machdep.c revision 26812
1/*-
2 * Copyright (c) 1992 Terrence R. Lambert.
3 * Copyright (c) 1982, 1987, 1990 The Regents of the University of California.
4 * All rights reserved.
5 *
6 * This code is derived from software contributed to Berkeley by
7 * William Jolitz.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 *    must display the following acknowledgement:
19 *	This product includes software developed by the University of
20 *	California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 *    may be used to endorse or promote products derived from this software
23 *    without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * SUCH DAMAGE.
36 *
37 *	from: @(#)machdep.c	7.4 (Berkeley) 6/3/91
38 *	$Id: machdep.c,v 1.250 1997/06/22 15:47:07 peter Exp $
39 */
40
41#include "apm.h"
42#include "npx.h"
43#include "opt_sysvipc.h"
44#include "opt_ddb.h"
45#include "opt_bounce.h"
46#include "opt_machdep.h"
47#include "opt_perfmon.h"
48#include "opt_smp.h"
49#include "opt_userconfig.h"
50
51#include <sys/param.h>
52#include <sys/systm.h>
53#include <sys/sysproto.h>
54#include <sys/signalvar.h>
55#include <sys/kernel.h>
56#include <sys/proc.h>
57#include <sys/buf.h>
58#include <sys/reboot.h>
59#include <sys/conf.h>
60#include <sys/file.h>
61#include <sys/callout.h>
62#include <sys/malloc.h>
63#include <sys/mbuf.h>
64#include <sys/mount.h>
65#include <sys/msgbuf.h>
66#include <sys/sysent.h>
67#include <sys/tty.h>
68#include <sys/sysctl.h>
69#include <sys/vmmeter.h>
70
71#ifdef SYSVSHM
72#include <sys/shm.h>
73#endif
74
75#ifdef SYSVMSG
76#include <sys/msg.h>
77#endif
78
79#ifdef SYSVSEM
80#include <sys/sem.h>
81#endif
82
83#include <vm/vm.h>
84#include <vm/vm_param.h>
85#include <vm/vm_prot.h>
86#include <sys/lock.h>
87#include <vm/vm_kern.h>
88#include <vm/vm_object.h>
89#include <vm/vm_page.h>
90#include <vm/vm_map.h>
91#include <vm/vm_pager.h>
92#include <vm/vm_extern.h>
93
94#include <sys/user.h>
95#include <sys/exec.h>
96#include <sys/vnode.h>
97
98#include <ddb/ddb.h>
99
100#include <net/netisr.h>
101
102#if NAPM > 0
103#include <machine/apm_bios.h>
104#endif
105#include <machine/cpu.h>
106#include <machine/npx.h>
107#include <machine/reg.h>
108#include <machine/psl.h>
109#include <machine/clock.h>
110#include <machine/specialreg.h>
111#include <machine/sysarch.h>
112#include <machine/cons.h>
113#include <machine/bootinfo.h>
114#include <machine/md_var.h>
115#ifdef SMP
116#include <machine/smp.h>
117#include <machine/smptests.h>	/** LATE_START */
118#endif
119#ifdef PERFMON
120#include <machine/perfmon.h>
121#endif
122
123#include <i386/isa/isa_device.h>
124#include <i386/isa/intr_machdep.h>
125#include <i386/isa/rtc.h>
126#include <machine/random.h>
127
128extern void init386 __P((int first));
129extern int ptrace_set_pc __P((struct proc *p, unsigned int addr));
130extern int ptrace_single_step __P((struct proc *p));
131extern int ptrace_write_u __P((struct proc *p, vm_offset_t off, int data));
132extern void dblfault_handler __P((void));
133
134extern void printcpuinfo(void);	/* XXX header file */
135extern void earlysetcpuclass(void);	/* same header file */
136extern void finishidentcpu(void);
137extern void panicifcpuunsupported(void);
138extern void initializecpu(void);
139
140static void cpu_startup __P((void *));
141SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL)
142
143
144#ifdef BOUNCE_BUFFERS
145extern char *bouncememory;
146extern int maxbkva;
147#ifdef BOUNCEPAGES
148int	bouncepages = BOUNCEPAGES;
149#else
150int	bouncepages = 0;
151#endif
152#endif	/* BOUNCE_BUFFERS */
153
154extern int freebufspace;
155int	msgbufmapped = 0;		/* set when safe to use msgbuf */
156int _udatasel, _ucodesel;
157u_int	atdevbase;
158
159
160int physmem = 0;
161int cold = 1;
162
163static int
164sysctl_hw_physmem SYSCTL_HANDLER_ARGS
165{
166	int error = sysctl_handle_int(oidp, 0, ctob(physmem), req);
167	return (error);
168}
169
170SYSCTL_PROC(_hw, HW_PHYSMEM, physmem, CTLTYPE_INT|CTLFLAG_RD,
171	0, 0, sysctl_hw_physmem, "I", "");
172
173static int
174sysctl_hw_usermem SYSCTL_HANDLER_ARGS
175{
176	int error = sysctl_handle_int(oidp, 0,
177		ctob(physmem - cnt.v_wire_count), req);
178	return (error);
179}
180
181SYSCTL_PROC(_hw, HW_USERMEM, usermem, CTLTYPE_INT|CTLFLAG_RD,
182	0, 0, sysctl_hw_usermem, "I", "");
183
184int boothowto = 0, bootverbose = 0, Maxmem = 0;
185static int	badpages = 0;
186long dumplo;
187extern int bootdev;
188
189vm_offset_t phys_avail[10];
190
191/* must be 2 less so 0 0 can signal end of chunks */
192#define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(vm_offset_t)) - 2)
193
194static void setup_netisrs __P((struct linker_set *)); /* XXX declare elsewhere */
195
196static vm_offset_t buffer_sva, buffer_eva;
197vm_offset_t clean_sva, clean_eva;
198static vm_offset_t pager_sva, pager_eva;
199extern struct linker_set netisr_set;
200
201#define offsetof(type, member)	((size_t)(&((type *)0)->member))
202
203static void
204cpu_startup(dummy)
205	void *dummy;
206{
207	register unsigned i;
208	register caddr_t v;
209	vm_offset_t maxaddr;
210	vm_size_t size = 0;
211	int firstaddr;
212	vm_offset_t minaddr;
213
214	if (boothowto & RB_VERBOSE)
215		bootverbose++;
216
217	/*
218	 * Good {morning,afternoon,evening,night}.
219	 */
220	printf(version);
221	earlysetcpuclass();
222	startrtclock();
223	printcpuinfo();
224	panicifcpuunsupported();
225#ifdef PERFMON
226	perfmon_init();
227#endif
228	printf("real memory  = %d (%dK bytes)\n", ptoa(Maxmem), ptoa(Maxmem) / 1024);
229	/*
230	 * Display any holes after the first chunk of extended memory.
231	 */
232	if (badpages != 0) {
233		int indx = 1;
234
235		/*
236		 * XXX skip reporting ISA hole & unmanaged kernel memory
237		 */
238		if (phys_avail[0] == PAGE_SIZE)
239			indx += 2;
240
241		printf("Physical memory hole(s):\n");
242		for (; phys_avail[indx + 1] != 0; indx += 2) {
243			int size = phys_avail[indx + 1] - phys_avail[indx];
244
245			printf("0x%08lx - 0x%08lx, %d bytes (%d pages)\n", phys_avail[indx],
246			    phys_avail[indx + 1] - 1, size, size / PAGE_SIZE);
247		}
248	}
249
250	/*
251	 * Quickly wire in netisrs.
252	 */
253	setup_netisrs(&netisr_set);
254
255	/*
256	 * Allocate space for system data structures.
257	 * The first available kernel virtual address is in "v".
258	 * As pages of kernel virtual memory are allocated, "v" is incremented.
259	 * As pages of memory are allocated and cleared,
260	 * "firstaddr" is incremented.
261	 * An index into the kernel page table corresponding to the
262	 * virtual memory address maintained in "v" is kept in "mapaddr".
263	 */
264
265	/*
266	 * Make two passes.  The first pass calculates how much memory is
267	 * needed and allocates it.  The second pass assigns virtual
268	 * addresses to the various data structures.
269	 */
270	firstaddr = 0;
271again:
272	v = (caddr_t)firstaddr;
273
274#define	valloc(name, type, num) \
275	    (name) = (type *)v; v = (caddr_t)((name)+(num))
276#define	valloclim(name, type, num, lim) \
277	    (name) = (type *)v; v = (caddr_t)((lim) = ((name)+(num)))
278	valloc(callout, struct callout, ncallout);
279#ifdef SYSVSHM
280	valloc(shmsegs, struct shmid_ds, shminfo.shmmni);
281#endif
282#ifdef SYSVSEM
283	valloc(sema, struct semid_ds, seminfo.semmni);
284	valloc(sem, struct sem, seminfo.semmns);
285	/* This is pretty disgusting! */
286	valloc(semu, int, (seminfo.semmnu * seminfo.semusz) / sizeof(int));
287#endif
288#ifdef SYSVMSG
289	valloc(msgpool, char, msginfo.msgmax);
290	valloc(msgmaps, struct msgmap, msginfo.msgseg);
291	valloc(msghdrs, struct msg, msginfo.msgtql);
292	valloc(msqids, struct msqid_ds, msginfo.msgmni);
293#endif
294
295	if (nbuf == 0) {
296		nbuf = 30;
297		if( physmem > 1024)
298			nbuf += min((physmem - 1024) / 8, 2048);
299	}
300	nswbuf = max(min(nbuf/4, 128), 16);
301
302	valloc(swbuf, struct buf, nswbuf);
303	valloc(buf, struct buf, nbuf);
304
305#ifdef BOUNCE_BUFFERS
306	/*
307	 * If there is more than 16MB of memory, allocate some bounce buffers
308	 */
309	if (Maxmem > 4096) {
310		if (bouncepages == 0) {
311			bouncepages = 64;
312			bouncepages += ((Maxmem - 4096) / 2048) * 32;
313			if (bouncepages > 128)
314				bouncepages = 128;
315		}
316		v = (caddr_t)((vm_offset_t)round_page(v));
317		valloc(bouncememory, char, bouncepages * PAGE_SIZE);
318	}
319#endif
320
321	/*
322	 * End of first pass, size has been calculated so allocate memory
323	 */
324	if (firstaddr == 0) {
325		size = (vm_size_t)(v - firstaddr);
326		firstaddr = (int)kmem_alloc(kernel_map, round_page(size));
327		if (firstaddr == 0)
328			panic("startup: no room for tables");
329		goto again;
330	}
331
332	/*
333	 * End of second pass, addresses have been assigned
334	 */
335	if ((vm_size_t)(v - firstaddr) != size)
336		panic("startup: table size inconsistency");
337
338#ifdef BOUNCE_BUFFERS
339	clean_map = kmem_suballoc(kernel_map, &clean_sva, &clean_eva,
340			(nbuf*BKVASIZE) + (nswbuf*MAXPHYS) +
341				maxbkva + pager_map_size, TRUE);
342	io_map = kmem_suballoc(clean_map, &minaddr, &maxaddr, maxbkva, FALSE);
343#else
344	clean_map = kmem_suballoc(kernel_map, &clean_sva, &clean_eva,
345			(nbuf*BKVASIZE) + (nswbuf*MAXPHYS) + pager_map_size, TRUE);
346#endif
347	buffer_map = kmem_suballoc(clean_map, &buffer_sva, &buffer_eva,
348				(nbuf*BKVASIZE), TRUE);
349	pager_map = kmem_suballoc(clean_map, &pager_sva, &pager_eva,
350				(nswbuf*MAXPHYS) + pager_map_size, TRUE);
351	exec_map = kmem_suballoc(kernel_map, &minaddr, &maxaddr,
352				(16*ARG_MAX), TRUE);
353	u_map = kmem_suballoc(kernel_map, &minaddr, &maxaddr,
354				(maxproc*UPAGES*PAGE_SIZE), FALSE);
355
356	/*
357	 * Finally, allocate mbuf pool.  Since mclrefcnt is an off-size
358	 * we use the more space efficient malloc in place of kmem_alloc.
359	 */
360	{
361		vm_offset_t mb_map_size;
362
363		mb_map_size = nmbufs * MSIZE + nmbclusters * MCLBYTES;
364		mb_map_size = roundup2(mb_map_size, max(MCLBYTES, PAGE_SIZE));
365		mclrefcnt = malloc(mb_map_size / MCLBYTES, M_MBUF, M_NOWAIT);
366		bzero(mclrefcnt, mb_map_size / MCLBYTES);
367		mb_map = kmem_suballoc(kmem_map, (vm_offset_t *)&mbutl, &maxaddr,
368			mb_map_size, FALSE);
369	}
370
371	/*
372	 * Initialize callouts
373	 */
374	callfree = callout;
375	for (i = 1; i < ncallout; i++)
376		callout[i-1].c_next = &callout[i];
377
378#if defined(USERCONFIG)
379#if defined(USERCONFIG_BOOT)
380	if (1) {
381#else
382        if (boothowto & RB_CONFIG) {
383#endif
384		userconfig();
385		cninit();	/* the preferred console may have changed */
386	}
387#endif
388
389#ifdef BOUNCE_BUFFERS
390	/*
391	 * init bounce buffers
392	 */
393	vm_bounce_init();
394#endif
395
396	printf("avail memory = %d (%dK bytes)\n", ptoa(cnt.v_free_count),
397	    ptoa(cnt.v_free_count) / 1024);
398
399#ifdef SMP
400	/*
401	 * OK, enough kmem_alloc/malloc state should be up, lets get on with it!
402	 */
403	mp_start();			/* fire up the APs and APICs */
404	mp_announce();
405#endif  /* SMP */
406
407	/*
408	 * Set up buffers, so they can be used to read disk labels.
409	 */
410	bufinit();
411	vm_pager_bufferinit();
412}
413
414int
415register_netisr(num, handler)
416	int num;
417	netisr_t *handler;
418{
419
420	if (num < 0 || num >= (sizeof(netisrs)/sizeof(*netisrs)) ) {
421		printf("register_netisr: bad isr number: %d\n", num);
422		return (EINVAL);
423	}
424	netisrs[num] = handler;
425	return (0);
426}
427
428static void
429setup_netisrs(ls)
430	struct linker_set *ls;
431{
432	int i;
433	const struct netisrtab *nit;
434
435	for(i = 0; ls->ls_items[i]; i++) {
436		nit = (const struct netisrtab *)ls->ls_items[i];
437		register_netisr(nit->nit_num, nit->nit_isr);
438	}
439}
440
441/*
442 * Send an interrupt to process.
443 *
444 * Stack is set up to allow sigcode stored
445 * at top to call routine, followed by kcall
446 * to sigreturn routine below.  After sigreturn
447 * resets the signal mask, the stack, and the
448 * frame pointer, it returns to the user
449 * specified pc, psl.
450 */
451void
452sendsig(catcher, sig, mask, code)
453	sig_t catcher;
454	int sig, mask;
455	u_long code;
456{
457	register struct proc *p = curproc;
458	register struct trapframe *regs;
459	register struct sigframe *fp;
460	struct sigframe sf;
461	struct sigacts *psp = p->p_sigacts;
462	int oonstack;
463
464	regs = p->p_md.md_regs;
465        oonstack = psp->ps_sigstk.ss_flags & SS_ONSTACK;
466	/*
467	 * Allocate and validate space for the signal handler context.
468	 */
469        if ((psp->ps_flags & SAS_ALTSTACK) && !oonstack &&
470	    (psp->ps_sigonstack & sigmask(sig))) {
471		fp = (struct sigframe *)(psp->ps_sigstk.ss_sp +
472		    psp->ps_sigstk.ss_size - sizeof(struct sigframe));
473		psp->ps_sigstk.ss_flags |= SS_ONSTACK;
474	} else {
475		fp = (struct sigframe *)regs->tf_esp - 1;
476	}
477
478	/*
479	 * grow() will return FALSE if the fp will not fit inside the stack
480	 *	and the stack can not be grown. useracc will return FALSE
481	 *	if access is denied.
482	 */
483	if ((grow(p, (int)fp) == FALSE) ||
484	    (useracc((caddr_t)fp, sizeof (struct sigframe), B_WRITE) == FALSE)) {
485		/*
486		 * Process has trashed its stack; give it an illegal
487		 * instruction to halt it in its tracks.
488		 */
489		SIGACTION(p, SIGILL) = SIG_DFL;
490		sig = sigmask(SIGILL);
491		p->p_sigignore &= ~sig;
492		p->p_sigcatch &= ~sig;
493		p->p_sigmask &= ~sig;
494		psignal(p, SIGILL);
495		return;
496	}
497
498	/*
499	 * Build the argument list for the signal handler.
500	 */
501	if (p->p_sysent->sv_sigtbl) {
502		if (sig < p->p_sysent->sv_sigsize)
503			sig = p->p_sysent->sv_sigtbl[sig];
504		else
505			sig = p->p_sysent->sv_sigsize + 1;
506	}
507	sf.sf_signum = sig;
508	sf.sf_code = code;
509	sf.sf_scp = &fp->sf_sc;
510	sf.sf_addr = (char *) regs->tf_err;
511	sf.sf_handler = catcher;
512
513	/* save scratch registers */
514	sf.sf_sc.sc_eax = regs->tf_eax;
515	sf.sf_sc.sc_ebx = regs->tf_ebx;
516	sf.sf_sc.sc_ecx = regs->tf_ecx;
517	sf.sf_sc.sc_edx = regs->tf_edx;
518	sf.sf_sc.sc_esi = regs->tf_esi;
519	sf.sf_sc.sc_edi = regs->tf_edi;
520	sf.sf_sc.sc_cs = regs->tf_cs;
521	sf.sf_sc.sc_ds = regs->tf_ds;
522	sf.sf_sc.sc_ss = regs->tf_ss;
523	sf.sf_sc.sc_es = regs->tf_es;
524	sf.sf_sc.sc_isp = regs->tf_isp;
525
526	/*
527	 * Build the signal context to be used by sigreturn.
528	 */
529	sf.sf_sc.sc_onstack = oonstack;
530	sf.sf_sc.sc_mask = mask;
531	sf.sf_sc.sc_sp = regs->tf_esp;
532	sf.sf_sc.sc_fp = regs->tf_ebp;
533	sf.sf_sc.sc_pc = regs->tf_eip;
534	sf.sf_sc.sc_ps = regs->tf_eflags;
535
536	/*
537	 * Copy the sigframe out to the user's stack.
538	 */
539	if (copyout(&sf, fp, sizeof(struct sigframe)) != 0) {
540		/*
541		 * Something is wrong with the stack pointer.
542		 * ...Kill the process.
543		 */
544		sigexit(p, SIGILL);
545	};
546
547	regs->tf_esp = (int)fp;
548	regs->tf_eip = (int)(((char *)PS_STRINGS) - *(p->p_sysent->sv_szsigcode));
549	regs->tf_eflags &= ~PSL_VM;
550	regs->tf_cs = _ucodesel;
551	regs->tf_ds = _udatasel;
552	regs->tf_es = _udatasel;
553	regs->tf_ss = _udatasel;
554}
555
556/*
557 * System call to cleanup state after a signal
558 * has been taken.  Reset signal mask and
559 * stack state from context left by sendsig (above).
560 * Return to previous pc and psl as specified by
561 * context left by sendsig. Check carefully to
562 * make sure that the user has not modified the
563 * state to gain improper privileges.
564 */
565int
566sigreturn(p, uap, retval)
567	struct proc *p;
568	struct sigreturn_args /* {
569		struct sigcontext *sigcntxp;
570	} */ *uap;
571	int *retval;
572{
573	register struct sigcontext *scp;
574	register struct sigframe *fp;
575	register struct trapframe *regs = p->p_md.md_regs;
576	int eflags;
577
578	/*
579	 * (XXX old comment) regs->tf_esp points to the return address.
580	 * The user scp pointer is above that.
581	 * The return address is faked in the signal trampoline code
582	 * for consistency.
583	 */
584	scp = uap->sigcntxp;
585	fp = (struct sigframe *)
586	     ((caddr_t)scp - offsetof(struct sigframe, sf_sc));
587
588	if (useracc((caddr_t)fp, sizeof (*fp), B_WRITE) == 0)
589		return(EFAULT);
590
591	/*
592	 * Don't allow users to change privileged or reserved flags.
593	 */
594#define	EFLAGS_SECURE(ef, oef)	((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
595	eflags = scp->sc_ps;
596	/*
597	 * XXX do allow users to change the privileged flag PSL_RF.  The
598	 * cpu sets PSL_RF in tf_eflags for faults.  Debuggers should
599	 * sometimes set it there too.  tf_eflags is kept in the signal
600	 * context during signal handling and there is no other place
601	 * to remember it, so the PSL_RF bit may be corrupted by the
602	 * signal handler without us knowing.  Corruption of the PSL_RF
603	 * bit at worst causes one more or one less debugger trap, so
604	 * allowing it is fairly harmless.
605	 */
606	if (!EFLAGS_SECURE(eflags & ~PSL_RF, regs->tf_eflags & ~PSL_RF)) {
607#ifdef DEBUG
608    		printf("sigreturn: eflags = 0x%x\n", eflags);
609#endif
610    		return(EINVAL);
611	}
612
613	/*
614	 * Don't allow users to load a valid privileged %cs.  Let the
615	 * hardware check for invalid selectors, excess privilege in
616	 * other selectors, invalid %eip's and invalid %esp's.
617	 */
618#define	CS_SECURE(cs)	(ISPL(cs) == SEL_UPL)
619	if (!CS_SECURE(scp->sc_cs)) {
620#ifdef DEBUG
621    		printf("sigreturn: cs = 0x%x\n", scp->sc_cs);
622#endif
623		trapsignal(p, SIGBUS, T_PROTFLT);
624		return(EINVAL);
625	}
626
627	/* restore scratch registers */
628	regs->tf_eax = scp->sc_eax;
629	regs->tf_ebx = scp->sc_ebx;
630	regs->tf_ecx = scp->sc_ecx;
631	regs->tf_edx = scp->sc_edx;
632	regs->tf_esi = scp->sc_esi;
633	regs->tf_edi = scp->sc_edi;
634	regs->tf_cs = scp->sc_cs;
635	regs->tf_ds = scp->sc_ds;
636	regs->tf_es = scp->sc_es;
637	regs->tf_ss = scp->sc_ss;
638	regs->tf_isp = scp->sc_isp;
639
640	if (useracc((caddr_t)scp, sizeof (*scp), B_WRITE) == 0)
641		return(EINVAL);
642
643	if (scp->sc_onstack & 01)
644		p->p_sigacts->ps_sigstk.ss_flags |= SS_ONSTACK;
645	else
646		p->p_sigacts->ps_sigstk.ss_flags &= ~SS_ONSTACK;
647	p->p_sigmask = scp->sc_mask & ~sigcantmask;
648	regs->tf_ebp = scp->sc_fp;
649	regs->tf_esp = scp->sc_sp;
650	regs->tf_eip = scp->sc_pc;
651	regs->tf_eflags = eflags;
652	return(EJUSTRETURN);
653}
654
655/*
656 * Machine dependent boot() routine
657 *
658 * I haven't seen anything to put here yet
659 * Possibly some stuff might be grafted back here from boot()
660 */
661void
662cpu_boot(int howto)
663{
664}
665
666/*
667 * Shutdown the CPU as much as possible
668 */
669void
670cpu_halt(void)
671{
672	for (;;)
673		__asm__ ("hlt");
674}
675
676/*
677 * Turn the power off.
678 */
679void
680cpu_power_down(void)
681{
682#if NAPM > 0
683	apm_power_off();
684#endif
685}
686
687/*
688 * Clear registers on exec
689 */
690void
691setregs(p, entry, stack)
692	struct proc *p;
693	u_long entry;
694	u_long stack;
695{
696	struct trapframe *regs = p->p_md.md_regs;
697
698#ifdef USER_LDT
699	struct pcb *pcb = &p->p_addr->u_pcb;
700
701	/* was i386_user_cleanup() in NetBSD */
702	if (pcb->pcb_ldt) {
703		if (pcb == curpcb)
704			lldt(GSEL(GUSERLDT_SEL, SEL_KPL));
705		kmem_free(kernel_map, (vm_offset_t)pcb->pcb_ldt,
706			pcb->pcb_ldt_len * sizeof(union descriptor));
707		pcb->pcb_ldt_len = (int)pcb->pcb_ldt = 0;
708 	}
709#endif
710
711	bzero((char *)regs, sizeof(struct trapframe));
712	regs->tf_eip = entry;
713	regs->tf_esp = stack;
714	regs->tf_eflags = PSL_USER | (regs->tf_eflags & PSL_T);
715	regs->tf_ss = _udatasel;
716	regs->tf_ds = _udatasel;
717	regs->tf_es = _udatasel;
718	regs->tf_cs = _ucodesel;
719
720	/*
721	 * Initialize the math emulator (if any) for the current process.
722	 * Actually, just clear the bit that says that the emulator has
723	 * been initialized.  Initialization is delayed until the process
724	 * traps to the emulator (if it is done at all) mainly because
725	 * emulators don't provide an entry point for initialization.
726	 */
727	p->p_addr->u_pcb.pcb_flags &= ~FP_SOFTFP;
728
729	/*
730	 * Arrange to trap the next npx or `fwait' instruction (see npx.c
731	 * for why fwait must be trapped at least if there is an npx or an
732	 * emulator).  This is mainly to handle the case where npx0 is not
733	 * configured, since the npx routines normally set up the trap
734	 * otherwise.  It should be done only at boot time, but doing it
735	 * here allows modifying `npx_exists' for testing the emulator on
736	 * systems with an npx.
737	 */
738	load_cr0(rcr0() | CR0_MP | CR0_TS);
739
740#if NNPX > 0
741	/* Initialize the npx (if any) for the current process. */
742	npxinit(__INITIAL_NPXCW__);
743#endif
744}
745
746static int
747sysctl_machdep_adjkerntz SYSCTL_HANDLER_ARGS
748{
749	int error;
750	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
751		req);
752	if (!error && req->newptr)
753		resettodr();
754	return (error);
755}
756
757SYSCTL_PROC(_machdep, CPU_ADJKERNTZ, adjkerntz, CTLTYPE_INT|CTLFLAG_RW,
758	&adjkerntz, 0, sysctl_machdep_adjkerntz, "I", "");
759
760SYSCTL_INT(_machdep, CPU_DISRTCSET, disable_rtc_set,
761	CTLFLAG_RW, &disable_rtc_set, 0, "");
762
763SYSCTL_STRUCT(_machdep, CPU_BOOTINFO, bootinfo,
764	CTLFLAG_RD, &bootinfo, bootinfo, "");
765
766SYSCTL_INT(_machdep, CPU_WALLCLOCK, wall_cmos_clock,
767	CTLFLAG_RW, &wall_cmos_clock, 0, "");
768
769/*
770 * Initialize 386 and configure to run kernel
771 */
772
773/*
774 * Initialize segments & interrupt table
775 */
776
777int currentldt;
778int _default_ldt;
779#ifdef SMP
780union descriptor gdt[NGDT + NCPU];		/* global descriptor table */
781#else
782union descriptor gdt[NGDT];		/* global descriptor table */
783#endif
784struct gate_descriptor idt[NIDT];	/* interrupt descriptor table */
785union descriptor ldt[NLDT];		/* local descriptor table */
786#ifdef SMP
787/* table descriptors - used to load tables by microp */
788struct region_descriptor r_gdt, r_idt;
789#endif
790
791#ifdef SMP
792extern struct i386tss common_tss;	/* One tss per cpu */
793#else
794struct i386tss common_tss;
795#endif
796
797static struct i386tss dblfault_tss;
798static char dblfault_stack[PAGE_SIZE];
799
800extern  struct user *proc0paddr;
801
802#ifdef TSS_IS_CACHED			/* cpu_switch helper */
803struct segment_descriptor *tssptr;
804int gsel_tss;
805#endif
806
807/* software prototypes -- in more palatable form */
808struct soft_segment_descriptor gdt_segs[
809#ifdef SMP
810					NGDT + NCPU
811#endif
812						   ] = {
813/* GNULL_SEL	0 Null Descriptor */
814{	0x0,			/* segment base address  */
815	0x0,			/* length */
816	0,			/* segment type */
817	0,			/* segment descriptor priority level */
818	0,			/* segment descriptor present */
819	0, 0,
820	0,			/* default 32 vs 16 bit size */
821	0  			/* limit granularity (byte/page units)*/ },
822/* GCODE_SEL	1 Code Descriptor for kernel */
823{	0x0,			/* segment base address  */
824	0xfffff,		/* length - all address space */
825	SDT_MEMERA,		/* segment type */
826	0,			/* segment descriptor priority level */
827	1,			/* segment descriptor present */
828	0, 0,
829	1,			/* default 32 vs 16 bit size */
830	1  			/* limit granularity (byte/page units)*/ },
831/* GDATA_SEL	2 Data Descriptor for kernel */
832{	0x0,			/* segment base address  */
833	0xfffff,		/* length - all address space */
834	SDT_MEMRWA,		/* segment type */
835	0,			/* segment descriptor priority level */
836	1,			/* segment descriptor present */
837	0, 0,
838	1,			/* default 32 vs 16 bit size */
839	1  			/* limit granularity (byte/page units)*/ },
840/* GLDT_SEL	3 LDT Descriptor */
841{	(int) ldt,		/* segment base address  */
842	sizeof(ldt)-1,		/* length - all address space */
843	SDT_SYSLDT,		/* segment type */
844	SEL_UPL,		/* segment descriptor priority level */
845	1,			/* segment descriptor present */
846	0, 0,
847	0,			/* unused - default 32 vs 16 bit size */
848	0  			/* limit granularity (byte/page units)*/ },
849/* GTGATE_SEL	4 Null Descriptor - Placeholder */
850{	0x0,			/* segment base address  */
851	0x0,			/* length - all address space */
852	0,			/* segment type */
853	0,			/* segment descriptor priority level */
854	0,			/* segment descriptor present */
855	0, 0,
856	0,			/* default 32 vs 16 bit size */
857	0  			/* limit granularity (byte/page units)*/ },
858/* GPANIC_SEL	5 Panic Tss Descriptor */
859{	(int) &dblfault_tss,	/* segment base address  */
860	sizeof(struct i386tss)-1,/* length - all address space */
861	SDT_SYS386TSS,		/* segment type */
862	0,			/* segment descriptor priority level */
863	1,			/* segment descriptor present */
864	0, 0,
865	0,			/* unused - default 32 vs 16 bit size */
866	0  			/* limit granularity (byte/page units)*/ },
867/* GPROC0_SEL	6 Proc 0 Tss Descriptor */
868{
869	(int) &common_tss,	/* segment base address */
870	sizeof(struct i386tss)-1,/* length - all address space */
871	SDT_SYS386TSS,		/* segment type */
872	0,			/* segment descriptor priority level */
873	1,			/* segment descriptor present */
874	0, 0,
875	0,			/* unused - default 32 vs 16 bit size */
876	0  			/* limit granularity (byte/page units)*/ },
877/* GUSERLDT_SEL	7 User LDT Descriptor per process */
878{	(int) ldt,		/* segment base address  */
879	(512 * sizeof(union descriptor)-1),		/* length */
880	SDT_SYSLDT,		/* segment type */
881	0,			/* segment descriptor priority level */
882	1,			/* segment descriptor present */
883	0, 0,
884	0,			/* unused - default 32 vs 16 bit size */
885	0  			/* limit granularity (byte/page units)*/ },
886/* GAPMCODE32_SEL 8 APM BIOS 32-bit interface (32bit Code) */
887{	0,			/* segment base address (overwritten by APM)  */
888	0xfffff,		/* length */
889	SDT_MEMERA,		/* segment type */
890	0,			/* segment descriptor priority level */
891	1,			/* segment descriptor present */
892	0, 0,
893	1,			/* default 32 vs 16 bit size */
894	1  			/* limit granularity (byte/page units)*/ },
895/* GAPMCODE16_SEL 9 APM BIOS 32-bit interface (16bit Code) */
896{	0,			/* segment base address (overwritten by APM)  */
897	0xfffff,		/* length */
898	SDT_MEMERA,		/* segment type */
899	0,			/* segment descriptor priority level */
900	1,			/* segment descriptor present */
901	0, 0,
902	0,			/* default 32 vs 16 bit size */
903	1  			/* limit granularity (byte/page units)*/ },
904/* GAPMDATA_SEL	10 APM BIOS 32-bit interface (Data) */
905{	0,			/* segment base address (overwritten by APM) */
906	0xfffff,		/* length */
907	SDT_MEMRWA,		/* segment type */
908	0,			/* segment descriptor priority level */
909	1,			/* segment descriptor present */
910	0, 0,
911	1,			/* default 32 vs 16 bit size */
912	1  			/* limit granularity (byte/page units)*/ },
913};
914
915static struct soft_segment_descriptor ldt_segs[] = {
916	/* Null Descriptor - overwritten by call gate */
917{	0x0,			/* segment base address  */
918	0x0,			/* length - all address space */
919	0,			/* segment type */
920	0,			/* segment descriptor priority level */
921	0,			/* segment descriptor present */
922	0, 0,
923	0,			/* default 32 vs 16 bit size */
924	0  			/* limit granularity (byte/page units)*/ },
925	/* Null Descriptor - overwritten by call gate */
926{	0x0,			/* segment base address  */
927	0x0,			/* length - all address space */
928	0,			/* segment type */
929	0,			/* segment descriptor priority level */
930	0,			/* segment descriptor present */
931	0, 0,
932	0,			/* default 32 vs 16 bit size */
933	0  			/* limit granularity (byte/page units)*/ },
934	/* Null Descriptor - overwritten by call gate */
935{	0x0,			/* segment base address  */
936	0x0,			/* length - all address space */
937	0,			/* segment type */
938	0,			/* segment descriptor priority level */
939	0,			/* segment descriptor present */
940	0, 0,
941	0,			/* default 32 vs 16 bit size */
942	0  			/* limit granularity (byte/page units)*/ },
943	/* Code Descriptor for user */
944{	0x0,			/* segment base address  */
945	0xfffff,		/* length - all address space */
946	SDT_MEMERA,		/* segment type */
947	SEL_UPL,		/* segment descriptor priority level */
948	1,			/* segment descriptor present */
949	0, 0,
950	1,			/* default 32 vs 16 bit size */
951	1  			/* limit granularity (byte/page units)*/ },
952	/* Data Descriptor for user */
953{	0x0,			/* segment base address  */
954	0xfffff,		/* length - all address space */
955	SDT_MEMRWA,		/* segment type */
956	SEL_UPL,		/* segment descriptor priority level */
957	1,			/* segment descriptor present */
958	0, 0,
959	1,			/* default 32 vs 16 bit size */
960	1  			/* limit granularity (byte/page units)*/ },
961};
962
963void
964setidt(idx, func, typ, dpl, selec)
965	int idx;
966	inthand_t *func;
967	int typ;
968	int dpl;
969	int selec;
970{
971	struct gate_descriptor *ip = idt + idx;
972
973	ip->gd_looffset = (int)func;
974	ip->gd_selector = selec;
975	ip->gd_stkcpy = 0;
976	ip->gd_xx = 0;
977	ip->gd_type = typ;
978	ip->gd_dpl = dpl;
979	ip->gd_p = 1;
980	ip->gd_hioffset = ((int)func)>>16 ;
981}
982
983#define	IDTVEC(name)	__CONCAT(X,name)
984
985extern inthand_t
986	IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
987	IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
988	IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
989	IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
990	IDTVEC(syscall), IDTVEC(int0x80_syscall);
991
992void
993sdtossd(sd, ssd)
994	struct segment_descriptor *sd;
995	struct soft_segment_descriptor *ssd;
996{
997	ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
998	ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
999	ssd->ssd_type  = sd->sd_type;
1000	ssd->ssd_dpl   = sd->sd_dpl;
1001	ssd->ssd_p     = sd->sd_p;
1002	ssd->ssd_def32 = sd->sd_def32;
1003	ssd->ssd_gran  = sd->sd_gran;
1004}
1005
1006void
1007init386(first)
1008	int first;
1009{
1010	int x;
1011	unsigned biosbasemem, biosextmem;
1012	struct gate_descriptor *gdp;
1013#ifndef TSS_IS_CACHED
1014	int gsel_tss;
1015#endif
1016	struct isa_device *idp;
1017#ifndef SMP
1018	/* table descriptors - used to load tables by microp */
1019	struct region_descriptor r_gdt, r_idt;
1020#endif
1021	int	pagesinbase, pagesinext;
1022	int	target_page, pa_indx;
1023	int	off;
1024
1025	proc0.p_addr = proc0paddr;
1026
1027	atdevbase = ISA_HOLE_START + KERNBASE;
1028
1029	/*
1030	 * Initialize the console before we print anything out.
1031	 */
1032	cninit();
1033
1034	/*
1035	 * make gdt memory segments, the code segment goes up to end of the
1036	 * page with etext in it, the data segment goes to the end of
1037	 * the address space
1038	 */
1039	/*
1040	 * XXX text protection is temporarily (?) disabled.  The limit was
1041	 * i386_btop(round_page(etext)) - 1.
1042	 */
1043	gdt_segs[GCODE_SEL].ssd_limit = i386_btop(0) - 1;
1044	gdt_segs[GDATA_SEL].ssd_limit = i386_btop(0) - 1;
1045#ifdef BDE_DEBUGGER
1046#define	NGDT1	8		/* avoid overwriting db entries with APM ones */
1047#else
1048#define	NGDT1	(sizeof gdt_segs / sizeof gdt_segs[0])
1049#endif
1050	for (x = 0; x < NGDT1; x++)
1051		ssdtosd(&gdt_segs[x], &gdt[x].sd);
1052
1053#ifdef SMP
1054	/*
1055	 * Spin these up now.  init_secondary() grabs them.  We could use
1056	 * #for(x,y,z) / #endfor cpp directives if they existed.
1057	 */
1058	for (x = 0; x < NCPU; x++) {
1059		gdt_segs[NGDT + x] = gdt_segs[GPROC0_SEL];
1060		ssdtosd(&gdt_segs[NGDT + x], &gdt[NGDT + x].sd);
1061	}
1062#endif
1063
1064	/* make ldt memory segments */
1065	/*
1066	 * The data segment limit must not cover the user area because we
1067	 * don't want the user area to be writable in copyout() etc. (page
1068	 * level protection is lost in kernel mode on 386's).  Also, we
1069	 * don't want the user area to be writable directly (page level
1070	 * protection of the user area is not available on 486's with
1071	 * CR0_WP set, because there is no user-read/kernel-write mode).
1072	 *
1073	 * XXX - VM_MAXUSER_ADDRESS is an end address, not a max.  And it
1074	 * should be spelled ...MAX_USER...
1075	 */
1076#define VM_END_USER_RW_ADDRESS	VM_MAXUSER_ADDRESS
1077	/*
1078	 * The code segment limit has to cover the user area until we move
1079	 * the signal trampoline out of the user area.  This is safe because
1080	 * the code segment cannot be written to directly.
1081	 */
1082#define VM_END_USER_R_ADDRESS	(VM_END_USER_RW_ADDRESS + UPAGES * PAGE_SIZE)
1083	ldt_segs[LUCODE_SEL].ssd_limit = i386_btop(VM_END_USER_R_ADDRESS) - 1;
1084	ldt_segs[LUDATA_SEL].ssd_limit = i386_btop(VM_END_USER_RW_ADDRESS) - 1;
1085	for (x = 0; x < sizeof ldt_segs / sizeof ldt_segs[0]; x++)
1086		ssdtosd(&ldt_segs[x], &ldt[x].sd);
1087
1088	/* exceptions */
1089	for (x = 0; x < NIDT; x++)
1090		setidt(x, &IDTVEC(rsvd), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1091	setidt(0, &IDTVEC(div),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1092	setidt(1, &IDTVEC(dbg),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1093	setidt(2, &IDTVEC(nmi),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1094 	setidt(3, &IDTVEC(bpt),  SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1095	setidt(4, &IDTVEC(ofl),  SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1096	setidt(5, &IDTVEC(bnd),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1097	setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1098	setidt(7, &IDTVEC(dna),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1099	setidt(8, 0,  SDT_SYSTASKGT, SEL_KPL, GSEL(GPANIC_SEL, SEL_KPL));
1100	setidt(9, &IDTVEC(fpusegm),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1101	setidt(10, &IDTVEC(tss),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1102	setidt(11, &IDTVEC(missing),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1103	setidt(12, &IDTVEC(stk),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1104	setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1105	setidt(14, &IDTVEC(page),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1106	setidt(15, &IDTVEC(rsvd),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1107	setidt(16, &IDTVEC(fpu),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1108	setidt(17, &IDTVEC(align), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1109	setidt(18, &IDTVEC(mchk),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1110 	setidt(0x80, &IDTVEC(int0x80_syscall),
1111			SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1112
1113#include	"isa.h"
1114#if	NISA >0
1115	isa_defaultirq();
1116#endif
1117	rand_initialize();
1118
1119	r_gdt.rd_limit = sizeof(gdt) - 1;
1120	r_gdt.rd_base =  (int) gdt;
1121	lgdt(&r_gdt);
1122
1123	r_idt.rd_limit = sizeof(idt) - 1;
1124	r_idt.rd_base = (int) idt;
1125	lidt(&r_idt);
1126
1127	_default_ldt = GSEL(GLDT_SEL, SEL_KPL);
1128	lldt(_default_ldt);
1129	currentldt = _default_ldt;
1130
1131#ifdef DDB
1132	kdb_init();
1133	if (boothowto & RB_KDB)
1134		Debugger("Boot flags requested debugger");
1135#endif
1136
1137	finishidentcpu();	/* Final stage of CPU initialization */
1138	setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1139	initializecpu();	/* Initialize CPU registers */
1140
1141	/* Use BIOS values stored in RTC CMOS RAM, since probing
1142	 * breaks certain 386 AT relics.
1143	 */
1144	biosbasemem = rtcin(RTC_BASELO)+ (rtcin(RTC_BASEHI)<<8);
1145	biosextmem = rtcin(RTC_EXTLO)+ (rtcin(RTC_EXTHI)<<8);
1146
1147	/*
1148	 * If BIOS tells us that it has more than 640k in the basemem,
1149	 *	don't believe it - set it to 640k.
1150	 */
1151	if (biosbasemem > 640) {
1152		printf("Preposterous RTC basemem of %dK, truncating to 640K\n",
1153		       biosbasemem);
1154		biosbasemem = 640;
1155	}
1156	if (bootinfo.bi_memsizes_valid && bootinfo.bi_basemem > 640) {
1157		printf("Preposterous BIOS basemem of %dK, truncating to 640K\n",
1158		       bootinfo.bi_basemem);
1159		bootinfo.bi_basemem = 640;
1160	}
1161
1162	/*
1163	 * Warn if the official BIOS interface disagrees with the RTC
1164	 * interface used above about the amount of base memory or the
1165	 * amount of extended memory.  Prefer the BIOS value for the base
1166	 * memory.  This is necessary for machines that `steal' base
1167	 * memory for use as BIOS memory, at least if we are going to use
1168	 * the BIOS for apm.  Prefer the RTC value for extended memory.
1169	 * Eventually the hackish interface shouldn't even be looked at.
1170	 */
1171	if (bootinfo.bi_memsizes_valid) {
1172		if (bootinfo.bi_basemem != biosbasemem) {
1173			vm_offset_t pa;
1174
1175			printf(
1176	"BIOS basemem (%ldK) != RTC basemem (%dK), setting to BIOS value\n",
1177			       bootinfo.bi_basemem, biosbasemem);
1178			biosbasemem = bootinfo.bi_basemem;
1179
1180			/*
1181			 * XXX if biosbasemem is now < 640, there is `hole'
1182			 * between the end of base memory and the start of
1183			 * ISA memory.  The hole may be empty or it may
1184			 * contain BIOS code or data.  Map it read/write so
1185			 * that the BIOS can write to it.  (Memory from 0 to
1186			 * the physical end of the kernel is mapped read-only
1187			 * to begin with and then parts of it are remapped.
1188			 * The parts that aren't remapped form holes that
1189			 * remain read-only and are unused by the kernel.
1190			 * The base memory area is below the physical end of
1191			 * the kernel and right now forms a read-only hole.
1192			 * The part of it from 0 to
1193			 * (trunc_page(biosbasemem * 1024) - 1) will be
1194			 * remapped and used by the kernel later.)
1195			 *
1196			 * This code is similar to the code used in
1197			 * pmap_mapdev, but since no memory needs to be
1198			 * allocated we simply change the mapping.
1199			 */
1200			for (pa = trunc_page(biosbasemem * 1024);
1201			     pa < ISA_HOLE_START; pa += PAGE_SIZE) {
1202				unsigned *pte;
1203
1204				pte = (unsigned *)vtopte(pa + KERNBASE);
1205				*pte = pa | PG_RW | PG_V;
1206			}
1207		}
1208		if (bootinfo.bi_extmem != biosextmem)
1209			printf("BIOS extmem (%ldK) != RTC extmem (%dK)\n",
1210			       bootinfo.bi_extmem, biosextmem);
1211	}
1212
1213#ifdef SMP
1214	/* make hole for AP bootstrap code */
1215	pagesinbase = mp_bootaddress(biosbasemem) / PAGE_SIZE;
1216#else
1217	pagesinbase = biosbasemem * 1024 / PAGE_SIZE;
1218#endif
1219
1220	pagesinext = biosextmem * 1024 / PAGE_SIZE;
1221
1222	/*
1223	 * Special hack for chipsets that still remap the 384k hole when
1224	 *	there's 16MB of memory - this really confuses people that
1225	 *	are trying to use bus mastering ISA controllers with the
1226	 *	"16MB limit"; they only have 16MB, but the remapping puts
1227	 *	them beyond the limit.
1228	 */
1229	/*
1230	 * If extended memory is between 15-16MB (16-17MB phys address range),
1231	 *	chop it to 15MB.
1232	 */
1233	if ((pagesinext > 3840) && (pagesinext < 4096))
1234		pagesinext = 3840;
1235
1236	/*
1237	 * Maxmem isn't the "maximum memory", it's one larger than the
1238	 * highest page of the physical address space.  It should be
1239	 * called something like "Maxphyspage".
1240	 */
1241	Maxmem = pagesinext + 0x100000/PAGE_SIZE;
1242
1243#ifdef MAXMEM
1244	Maxmem = MAXMEM/4;
1245#endif
1246
1247#if NNPX > 0
1248	idp = find_isadev(isa_devtab_null, &npxdriver, 0);
1249	if (idp != NULL && idp->id_msize != 0)
1250		Maxmem = idp->id_msize / 4;
1251#endif
1252
1253#ifdef SMP
1254	/* look for the MP hardware - needed for apic addresses */
1255	mp_probe();
1256#endif
1257
1258	/* call pmap initialization to make new kernel address space */
1259	pmap_bootstrap (first, 0);
1260
1261	/*
1262	 * Size up each available chunk of physical memory.
1263	 */
1264
1265	/*
1266	 * We currently don't bother testing base memory.
1267	 * XXX  ...but we probably should.
1268	 */
1269	pa_indx = 0;
1270	badpages = 0;
1271	if (pagesinbase > 1) {
1272		phys_avail[pa_indx++] = PAGE_SIZE;	/* skip first page of memory */
1273		phys_avail[pa_indx] = ptoa(pagesinbase);/* memory up to the ISA hole */
1274		physmem = pagesinbase - 1;
1275	} else {
1276		/* point at first chunk end */
1277		pa_indx++;
1278	}
1279
1280	for (target_page = avail_start; target_page < ptoa(Maxmem); target_page += PAGE_SIZE) {
1281		int tmp, page_bad = FALSE;
1282
1283		/*
1284		 * map page into kernel: valid, read/write, non-cacheable
1285		 */
1286		*(int *)CMAP1 = PG_V | PG_RW | PG_N | target_page;
1287		invltlb();
1288
1289		tmp = *(int *)CADDR1;
1290		/*
1291		 * Test for alternating 1's and 0's
1292		 */
1293		*(volatile int *)CADDR1 = 0xaaaaaaaa;
1294		if (*(volatile int *)CADDR1 != 0xaaaaaaaa) {
1295			page_bad = TRUE;
1296		}
1297		/*
1298		 * Test for alternating 0's and 1's
1299		 */
1300		*(volatile int *)CADDR1 = 0x55555555;
1301		if (*(volatile int *)CADDR1 != 0x55555555) {
1302			page_bad = TRUE;
1303		}
1304		/*
1305		 * Test for all 1's
1306		 */
1307		*(volatile int *)CADDR1 = 0xffffffff;
1308		if (*(volatile int *)CADDR1 != 0xffffffff) {
1309			page_bad = TRUE;
1310		}
1311		/*
1312		 * Test for all 0's
1313		 */
1314		*(volatile int *)CADDR1 = 0x0;
1315		if (*(volatile int *)CADDR1 != 0x0) {
1316			/*
1317			 * test of page failed
1318			 */
1319			page_bad = TRUE;
1320		}
1321		/*
1322		 * Restore original value.
1323		 */
1324		*(int *)CADDR1 = tmp;
1325
1326		/*
1327		 * Adjust array of valid/good pages.
1328		 */
1329		if (page_bad == FALSE) {
1330			/*
1331			 * If this good page is a continuation of the
1332			 * previous set of good pages, then just increase
1333			 * the end pointer. Otherwise start a new chunk.
1334			 * Note that "end" points one higher than end,
1335			 * making the range >= start and < end.
1336			 */
1337			if (phys_avail[pa_indx] == target_page) {
1338				phys_avail[pa_indx] += PAGE_SIZE;
1339			} else {
1340				pa_indx++;
1341				if (pa_indx == PHYS_AVAIL_ARRAY_END) {
1342					printf("Too many holes in the physical address space, giving up\n");
1343					pa_indx--;
1344					break;
1345				}
1346				phys_avail[pa_indx++] = target_page;	/* start */
1347				phys_avail[pa_indx] = target_page + PAGE_SIZE;	/* end */
1348			}
1349			physmem++;
1350		} else {
1351			badpages++;
1352			page_bad = FALSE;
1353		}
1354	}
1355
1356	*(int *)CMAP1 = 0;
1357	invltlb();
1358
1359	/*
1360	 * XXX
1361	 * The last chunk must contain at least one page plus the message
1362	 * buffer to avoid complicating other code (message buffer address
1363	 * calculation, etc.).
1364	 */
1365	while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1366	    round_page(sizeof(struct msgbuf)) >= phys_avail[pa_indx]) {
1367		physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1368		phys_avail[pa_indx--] = 0;
1369		phys_avail[pa_indx--] = 0;
1370	}
1371
1372	Maxmem = atop(phys_avail[pa_indx]);
1373
1374	/* Trim off space for the message buffer. */
1375	phys_avail[pa_indx] -= round_page(sizeof(struct msgbuf));
1376
1377	avail_end = phys_avail[pa_indx];
1378
1379	/* now running on new page tables, configured,and u/iom is accessible */
1380
1381	/* Map the message buffer. */
1382	for (off = 0; off < round_page(sizeof(struct msgbuf)); off += PAGE_SIZE)
1383		pmap_enter(kernel_pmap, (vm_offset_t)msgbufp + off,
1384			   avail_end + off, VM_PROT_ALL, TRUE);
1385	msgbufmapped = 1;
1386
1387	/* make an initial tss so cpu can get interrupt stack on syscall! */
1388	common_tss.tss_esp0 = (int) proc0.p_addr + UPAGES*PAGE_SIZE;
1389	common_tss.tss_ss0 = GSEL(GDATA_SEL, SEL_KPL) ;
1390	common_tss.tss_ioopt = (sizeof common_tss) << 16;
1391	gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1392	ltr(gsel_tss);
1393
1394	dblfault_tss.tss_esp = dblfault_tss.tss_esp0 = dblfault_tss.tss_esp1 =
1395	    dblfault_tss.tss_esp2 = (int) &dblfault_stack[sizeof(dblfault_stack)];
1396	dblfault_tss.tss_ss = dblfault_tss.tss_ss0 = dblfault_tss.tss_ss1 =
1397	    dblfault_tss.tss_ss2 = GSEL(GDATA_SEL, SEL_KPL);
1398	dblfault_tss.tss_cr3 = (int)IdlePTD;
1399	dblfault_tss.tss_eip = (int) dblfault_handler;
1400	dblfault_tss.tss_eflags = PSL_KERNEL;
1401	dblfault_tss.tss_ds = dblfault_tss.tss_es = dblfault_tss.tss_fs =
1402	    dblfault_tss.tss_gs = GSEL(GDATA_SEL, SEL_KPL);
1403	dblfault_tss.tss_cs = GSEL(GCODE_SEL, SEL_KPL);
1404	dblfault_tss.tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
1405
1406#ifdef TSS_IS_CACHED			/* cpu_switch helper */
1407	tssptr = &gdt[GPROC0_SEL].sd;
1408#endif
1409
1410	/* make a call gate to reenter kernel with */
1411	gdp = &ldt[LSYS5CALLS_SEL].gd;
1412
1413	x = (int) &IDTVEC(syscall);
1414	gdp->gd_looffset = x++;
1415	gdp->gd_selector = GSEL(GCODE_SEL,SEL_KPL);
1416	gdp->gd_stkcpy = 1;
1417	gdp->gd_type = SDT_SYS386CGT;
1418	gdp->gd_dpl = SEL_UPL;
1419	gdp->gd_p = 1;
1420	gdp->gd_hioffset = ((int) &IDTVEC(syscall)) >>16;
1421
1422	/* XXX does this work? */
1423	ldt[LBSDICALLS_SEL] = ldt[LSYS5CALLS_SEL];
1424
1425	/* transfer to user mode */
1426
1427	_ucodesel = LSEL(LUCODE_SEL, SEL_UPL);
1428	_udatasel = LSEL(LUDATA_SEL, SEL_UPL);
1429
1430	/* setup proc 0's pcb */
1431	proc0.p_addr->u_pcb.pcb_flags = 0;
1432	proc0.p_addr->u_pcb.pcb_cr3 = (int)IdlePTD;
1433	proc0.p_addr->u_pcb.pcb_mpnest = 1;
1434}
1435
1436int
1437ptrace_set_pc(p, addr)
1438	struct proc *p;
1439	unsigned int addr;
1440{
1441	p->p_md.md_regs->tf_eip = addr;
1442	return (0);
1443}
1444
1445int
1446ptrace_single_step(p)
1447	struct proc *p;
1448{
1449	p->p_md.md_regs->tf_eflags |= PSL_T;
1450	return (0);
1451}
1452
1453int ptrace_write_u(p, off, data)
1454	struct proc *p;
1455	vm_offset_t off;
1456	int data;
1457{
1458	struct trapframe frame_copy;
1459	vm_offset_t min;
1460	struct trapframe *tp;
1461
1462	/*
1463	 * Privileged kernel state is scattered all over the user area.
1464	 * Only allow write access to parts of regs and to fpregs.
1465	 */
1466	min = (char *)p->p_md.md_regs - (char *)p->p_addr;
1467	if (off >= min && off <= min + sizeof(struct trapframe) - sizeof(int)) {
1468		tp = p->p_md.md_regs;
1469		frame_copy = *tp;
1470		*(int *)((char *)&frame_copy + (off - min)) = data;
1471		if (!EFLAGS_SECURE(frame_copy.tf_eflags, tp->tf_eflags) ||
1472		    !CS_SECURE(frame_copy.tf_cs))
1473			return (EINVAL);
1474		*(int*)((char *)p->p_addr + off) = data;
1475		return (0);
1476	}
1477	min = offsetof(struct user, u_pcb) + offsetof(struct pcb, pcb_savefpu);
1478	if (off >= min && off <= min + sizeof(struct save87) - sizeof(int)) {
1479		*(int*)((char *)p->p_addr + off) = data;
1480		return (0);
1481	}
1482	return (EFAULT);
1483}
1484
1485int
1486fill_regs(p, regs)
1487	struct proc *p;
1488	struct reg *regs;
1489{
1490	struct pcb *pcb;
1491	struct trapframe *tp;
1492
1493	tp = p->p_md.md_regs;
1494	regs->r_es = tp->tf_es;
1495	regs->r_ds = tp->tf_ds;
1496	regs->r_edi = tp->tf_edi;
1497	regs->r_esi = tp->tf_esi;
1498	regs->r_ebp = tp->tf_ebp;
1499	regs->r_ebx = tp->tf_ebx;
1500	regs->r_edx = tp->tf_edx;
1501	regs->r_ecx = tp->tf_ecx;
1502	regs->r_eax = tp->tf_eax;
1503	regs->r_eip = tp->tf_eip;
1504	regs->r_cs = tp->tf_cs;
1505	regs->r_eflags = tp->tf_eflags;
1506	regs->r_esp = tp->tf_esp;
1507	regs->r_ss = tp->tf_ss;
1508	pcb = &p->p_addr->u_pcb;
1509	regs->r_fs = pcb->pcb_fs;
1510	regs->r_gs = pcb->pcb_gs;
1511	return (0);
1512}
1513
1514int
1515set_regs(p, regs)
1516	struct proc *p;
1517	struct reg *regs;
1518{
1519	struct pcb *pcb;
1520	struct trapframe *tp;
1521
1522	tp = p->p_md.md_regs;
1523	if (!EFLAGS_SECURE(regs->r_eflags, tp->tf_eflags) ||
1524	    !CS_SECURE(regs->r_cs))
1525		return (EINVAL);
1526	tp->tf_es = regs->r_es;
1527	tp->tf_ds = regs->r_ds;
1528	tp->tf_edi = regs->r_edi;
1529	tp->tf_esi = regs->r_esi;
1530	tp->tf_ebp = regs->r_ebp;
1531	tp->tf_ebx = regs->r_ebx;
1532	tp->tf_edx = regs->r_edx;
1533	tp->tf_ecx = regs->r_ecx;
1534	tp->tf_eax = regs->r_eax;
1535	tp->tf_eip = regs->r_eip;
1536	tp->tf_cs = regs->r_cs;
1537	tp->tf_eflags = regs->r_eflags;
1538	tp->tf_esp = regs->r_esp;
1539	tp->tf_ss = regs->r_ss;
1540	pcb = &p->p_addr->u_pcb;
1541	pcb->pcb_fs = regs->r_fs;
1542	pcb->pcb_gs = regs->r_gs;
1543	return (0);
1544}
1545
1546#ifndef DDB
1547void
1548Debugger(const char *msg)
1549{
1550	printf("Debugger(\"%s\") called.\n", msg);
1551}
1552#endif /* no DDB */
1553
1554#include <sys/disklabel.h>
1555
1556/*
1557 * Determine the size of the transfer, and make sure it is
1558 * within the boundaries of the partition. Adjust transfer
1559 * if needed, and signal errors or early completion.
1560 */
1561int
1562bounds_check_with_label(struct buf *bp, struct disklabel *lp, int wlabel)
1563{
1564        struct partition *p = lp->d_partitions + dkpart(bp->b_dev);
1565        int labelsect = lp->d_partitions[0].p_offset;
1566        int maxsz = p->p_size,
1567                sz = (bp->b_bcount + DEV_BSIZE - 1) >> DEV_BSHIFT;
1568
1569        /* overwriting disk label ? */
1570        /* XXX should also protect bootstrap in first 8K */
1571        if (bp->b_blkno + p->p_offset <= LABELSECTOR + labelsect &&
1572#if LABELSECTOR != 0
1573            bp->b_blkno + p->p_offset + sz > LABELSECTOR + labelsect &&
1574#endif
1575            (bp->b_flags & B_READ) == 0 && wlabel == 0) {
1576                bp->b_error = EROFS;
1577                goto bad;
1578        }
1579
1580#if     defined(DOSBBSECTOR) && defined(notyet)
1581        /* overwriting master boot record? */
1582        if (bp->b_blkno + p->p_offset <= DOSBBSECTOR &&
1583            (bp->b_flags & B_READ) == 0 && wlabel == 0) {
1584                bp->b_error = EROFS;
1585                goto bad;
1586        }
1587#endif
1588
1589        /* beyond partition? */
1590        if (bp->b_blkno < 0 || bp->b_blkno + sz > maxsz) {
1591                /* if exactly at end of disk, return an EOF */
1592                if (bp->b_blkno == maxsz) {
1593                        bp->b_resid = bp->b_bcount;
1594                        return(0);
1595                }
1596                /* or truncate if part of it fits */
1597                sz = maxsz - bp->b_blkno;
1598                if (sz <= 0) {
1599                        bp->b_error = EINVAL;
1600                        goto bad;
1601                }
1602                bp->b_bcount = sz << DEV_BSHIFT;
1603        }
1604
1605        bp->b_pblkno = bp->b_blkno + p->p_offset;
1606        return(1);
1607
1608bad:
1609        bp->b_flags |= B_ERROR;
1610        return(-1);
1611}
1612
1613#ifdef DDB
1614
1615/*
1616 * Provide inb() and outb() as functions.  They are normally only
1617 * available as macros calling inlined functions, thus cannot be
1618 * called inside DDB.
1619 *
1620 * The actual code is stolen from <machine/cpufunc.h>, and de-inlined.
1621 */
1622
1623#undef inb
1624#undef outb
1625
1626/* silence compiler warnings */
1627u_char inb(u_int);
1628void outb(u_int, u_char);
1629
1630u_char
1631inb(u_int port)
1632{
1633	u_char	data;
1634	/*
1635	 * We use %%dx and not %1 here because i/o is done at %dx and not at
1636	 * %edx, while gcc generates inferior code (movw instead of movl)
1637	 * if we tell it to load (u_short) port.
1638	 */
1639	__asm __volatile("inb %%dx,%0" : "=a" (data) : "d" (port));
1640	return (data);
1641}
1642
1643void
1644outb(u_int port, u_char data)
1645{
1646	u_char	al;
1647	/*
1648	 * Use an unnecessary assignment to help gcc's register allocator.
1649	 * This make a large difference for gcc-1.40 and a tiny difference
1650	 * for gcc-2.6.0.  For gcc-1.40, al had to be ``asm("ax")'' for
1651	 * best results.  gcc-2.6.0 can't handle this.
1652	 */
1653	al = data;
1654	__asm __volatile("outb %0,%%dx" : : "a" (al), "d" (port));
1655}
1656
1657#endif /* DDB */
1658