machdep.c revision 67265
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 * $FreeBSD: head/sys/amd64/amd64/machdep.c 67265 2000-10-17 23:10:23Z jhb $
39 */
40#include "apm.h"
41#include "npx.h"
42#include "opt_atalk.h"
43#include "opt_compat.h"
44#include "opt_cpu.h"
45#include "opt_ddb.h"
46#include "opt_inet.h"
47#include "opt_ipx.h"
48#include "opt_maxmem.h"
49#include "opt_msgbuf.h"
50#include "opt_perfmon.h"
51#include "opt_user_ldt.h"
52#include "opt_userconfig.h"
53
54#include <sys/param.h>
55#include <sys/systm.h>
56#include <sys/sysproto.h>
57#include <sys/signalvar.h>
58#include <sys/ipl.h>
59#include <sys/kernel.h>
60#include <sys/ktr.h>
61#include <sys/linker.h>
62#include <sys/malloc.h>
63#include <sys/proc.h>
64#include <sys/bio.h>
65#include <sys/buf.h>
66#include <sys/reboot.h>
67#include <sys/callout.h>
68#include <sys/mbuf.h>
69#include <sys/msgbuf.h>
70#include <sys/sysent.h>
71#include <sys/sysctl.h>
72#include <sys/vmmeter.h>
73#include <sys/bus.h>
74#include <sys/eventhandler.h>
75
76#include <vm/vm.h>
77#include <vm/vm_param.h>
78#include <sys/lock.h>
79#include <vm/vm_kern.h>
80#include <vm/vm_object.h>
81#include <vm/vm_page.h>
82#include <vm/vm_map.h>
83#include <vm/vm_pager.h>
84#include <vm/vm_extern.h>
85
86#include <sys/user.h>
87#include <sys/exec.h>
88#include <sys/cons.h>
89
90#include <ddb/ddb.h>
91
92#include <net/netisr.h>
93
94#include <machine/cpu.h>
95#include <machine/cputypes.h>
96#include <machine/reg.h>
97#include <machine/clock.h>
98#include <machine/specialreg.h>
99#include <machine/bootinfo.h>
100#include <machine/md_var.h>
101#include <machine/mutex.h>
102#include <machine/pc/bios.h>
103#include <machine/pcb_ext.h>		/* pcb.h included via sys/user.h */
104#include <machine/globaldata.h>
105#include <machine/globals.h>
106#ifdef SMP
107#include <machine/smp.h>
108#endif
109#ifdef PERFMON
110#include <machine/perfmon.h>
111#endif
112
113#ifdef OLD_BUS_ARCH
114#include <i386/isa/isa_device.h>
115#endif
116#include <i386/isa/icu.h>
117#include <i386/isa/intr_machdep.h>
118#include <isa/rtc.h>
119#include <machine/vm86.h>
120#include <sys/ptrace.h>
121#include <machine/sigframe.h>
122
123extern void init386 __P((int first));
124extern void dblfault_handler __P((void));
125
126extern void printcpuinfo(void);	/* XXX header file */
127extern void earlysetcpuclass(void);	/* same header file */
128extern void finishidentcpu(void);
129extern void panicifcpuunsupported(void);
130extern void initializecpu(void);
131
132#define	CS_SECURE(cs)		(ISPL(cs) == SEL_UPL)
133#define	EFL_SECURE(ef, oef)	((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
134
135static void cpu_startup __P((void *));
136SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL)
137
138int	_udatasel, _ucodesel;
139u_int	atdevbase;
140
141#if defined(SWTCH_OPTIM_STATS)
142extern int swtch_optim_stats;
143SYSCTL_INT(_debug, OID_AUTO, swtch_optim_stats,
144	CTLFLAG_RD, &swtch_optim_stats, 0, "");
145SYSCTL_INT(_debug, OID_AUTO, tlb_flush_count,
146	CTLFLAG_RD, &tlb_flush_count, 0, "");
147#endif
148
149#ifdef PC98
150static int	ispc98 = 1;
151#else
152static int	ispc98 = 0;
153#endif
154SYSCTL_INT(_machdep, OID_AUTO, ispc98, CTLFLAG_RD, &ispc98, 0, "");
155
156int physmem = 0;
157int cold = 1;
158
159static void osendsig __P((sig_t catcher, int sig, sigset_t *mask, u_long code));
160
161static int
162sysctl_hw_physmem(SYSCTL_HANDLER_ARGS)
163{
164	int error = sysctl_handle_int(oidp, 0, ctob(physmem), req);
165	return (error);
166}
167
168SYSCTL_PROC(_hw, HW_PHYSMEM, physmem, CTLTYPE_INT|CTLFLAG_RD,
169	0, 0, sysctl_hw_physmem, "I", "");
170
171static int
172sysctl_hw_usermem(SYSCTL_HANDLER_ARGS)
173{
174	int error = sysctl_handle_int(oidp, 0,
175		ctob(physmem - cnt.v_wire_count), req);
176	return (error);
177}
178
179SYSCTL_PROC(_hw, HW_USERMEM, usermem, CTLTYPE_INT|CTLFLAG_RD,
180	0, 0, sysctl_hw_usermem, "I", "");
181
182static int
183sysctl_hw_availpages(SYSCTL_HANDLER_ARGS)
184{
185	int error = sysctl_handle_int(oidp, 0,
186		i386_btop(avail_end - avail_start), req);
187	return (error);
188}
189
190SYSCTL_PROC(_hw, OID_AUTO, availpages, CTLTYPE_INT|CTLFLAG_RD,
191	0, 0, sysctl_hw_availpages, "I", "");
192
193static int
194sysctl_machdep_msgbuf(SYSCTL_HANDLER_ARGS)
195{
196	int error;
197
198	/* Unwind the buffer, so that it's linear (possibly starting with
199	 * some initial nulls).
200	 */
201	error=sysctl_handle_opaque(oidp,msgbufp->msg_ptr+msgbufp->msg_bufr,
202		msgbufp->msg_size-msgbufp->msg_bufr,req);
203	if(error) return(error);
204	if(msgbufp->msg_bufr>0) {
205		error=sysctl_handle_opaque(oidp,msgbufp->msg_ptr,
206			msgbufp->msg_bufr,req);
207	}
208	return(error);
209}
210
211SYSCTL_PROC(_machdep, OID_AUTO, msgbuf, CTLTYPE_STRING|CTLFLAG_RD,
212	0, 0, sysctl_machdep_msgbuf, "A","Contents of kernel message buffer");
213
214static int msgbuf_clear;
215
216static int
217sysctl_machdep_msgbuf_clear(SYSCTL_HANDLER_ARGS)
218{
219	int error;
220	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
221		req);
222	if (!error && req->newptr) {
223		/* Clear the buffer and reset write pointer */
224		bzero(msgbufp->msg_ptr,msgbufp->msg_size);
225		msgbufp->msg_bufr=msgbufp->msg_bufx=0;
226		msgbuf_clear=0;
227	}
228	return (error);
229}
230
231SYSCTL_PROC(_machdep, OID_AUTO, msgbuf_clear, CTLTYPE_INT|CTLFLAG_RW,
232	&msgbuf_clear, 0, sysctl_machdep_msgbuf_clear, "I",
233	"Clear kernel message buffer");
234
235int bootverbose = 0, Maxmem = 0;
236long dumplo;
237
238vm_offset_t phys_avail[10];
239
240/* must be 2 less so 0 0 can signal end of chunks */
241#define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(vm_offset_t)) - 2)
242
243static vm_offset_t buffer_sva, buffer_eva;
244vm_offset_t clean_sva, clean_eva;
245static vm_offset_t pager_sva, pager_eva;
246static struct trapframe proc0_tf;
247
248struct cpuhead cpuhead;
249
250struct mtx	sched_lock;
251struct mtx	Giant;
252
253#define offsetof(type, member)	((size_t)(&((type *)0)->member))
254
255static void
256cpu_startup(dummy)
257	void *dummy;
258{
259	register unsigned i;
260	register caddr_t v;
261	vm_offset_t maxaddr;
262	vm_size_t size = 0;
263	int firstaddr;
264	vm_offset_t minaddr;
265
266	if (boothowto & RB_VERBOSE)
267		bootverbose++;
268
269	/*
270	 * Good {morning,afternoon,evening,night}.
271	 */
272	printf("%s", version);
273	earlysetcpuclass();
274	startrtclock();
275	printcpuinfo();
276	panicifcpuunsupported();
277#ifdef PERFMON
278	perfmon_init();
279#endif
280	printf("real memory  = %u (%uK bytes)\n", ptoa(Maxmem), ptoa(Maxmem) / 1024);
281	/*
282	 * Display any holes after the first chunk of extended memory.
283	 */
284	if (bootverbose) {
285		int indx;
286
287		printf("Physical memory chunk(s):\n");
288		for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
289			unsigned int size1 = phys_avail[indx + 1] - phys_avail[indx];
290
291			printf("0x%08x - 0x%08x, %u bytes (%u pages)\n",
292			    phys_avail[indx], phys_avail[indx + 1] - 1, size1,
293			    size1 / PAGE_SIZE);
294		}
295	}
296
297	/*
298	 * Calculate callout wheel size
299	 */
300	for (callwheelsize = 1, callwheelbits = 0;
301	     callwheelsize < ncallout;
302	     callwheelsize <<= 1, ++callwheelbits)
303		;
304	callwheelmask = callwheelsize - 1;
305
306	/*
307	 * Allocate space for system data structures.
308	 * The first available kernel virtual address is in "v".
309	 * As pages of kernel virtual memory are allocated, "v" is incremented.
310	 * As pages of memory are allocated and cleared,
311	 * "firstaddr" is incremented.
312	 * An index into the kernel page table corresponding to the
313	 * virtual memory address maintained in "v" is kept in "mapaddr".
314	 */
315
316	/*
317	 * Make two passes.  The first pass calculates how much memory is
318	 * needed and allocates it.  The second pass assigns virtual
319	 * addresses to the various data structures.
320	 */
321	firstaddr = 0;
322again:
323	v = (caddr_t)firstaddr;
324
325#define	valloc(name, type, num) \
326	    (name) = (type *)v; v = (caddr_t)((name)+(num))
327#define	valloclim(name, type, num, lim) \
328	    (name) = (type *)v; v = (caddr_t)((lim) = ((name)+(num)))
329
330	valloc(callout, struct callout, ncallout);
331	valloc(callwheel, struct callout_tailq, callwheelsize);
332
333	/*
334	 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
335	 * For the first 64MB of ram nominally allocate sufficient buffers to
336	 * cover 1/4 of our ram.  Beyond the first 64MB allocate additional
337	 * buffers to cover 1/20 of our ram over 64MB.
338	 *
339	 * factor represents the 1/4 x ram conversion.
340	 */
341	if (nbuf == 0) {
342		int factor = 4 * BKVASIZE / PAGE_SIZE;
343
344		nbuf = 50;
345		if (physmem > 1024)
346			nbuf += min((physmem - 1024) / factor, 16384 / factor);
347		if (physmem > 16384)
348			nbuf += (physmem - 16384) * 2 / (factor * 5);
349	}
350
351	/*
352	 * Do not allow the buffer_map to be more then 1/2 the size of the
353	 * kernel_map.
354	 */
355	if (nbuf > (kernel_map->max_offset - kernel_map->min_offset) /
356	    (BKVASIZE * 2)) {
357		nbuf = (kernel_map->max_offset - kernel_map->min_offset) /
358		    (BKVASIZE * 2);
359		printf("Warning: nbufs capped at %d\n", nbuf);
360	}
361
362	nswbuf = max(min(nbuf/4, 256), 16);
363
364	valloc(swbuf, struct buf, nswbuf);
365	valloc(buf, struct buf, nbuf);
366	v = bufhashinit(v);
367
368	/*
369	 * End of first pass, size has been calculated so allocate memory
370	 */
371	if (firstaddr == 0) {
372		size = (vm_size_t)(v - firstaddr);
373		firstaddr = (int)kmem_alloc(kernel_map, round_page(size));
374		if (firstaddr == 0)
375			panic("startup: no room for tables");
376		goto again;
377	}
378
379	/*
380	 * End of second pass, addresses have been assigned
381	 */
382	if ((vm_size_t)(v - firstaddr) != size)
383		panic("startup: table size inconsistency");
384
385	clean_map = kmem_suballoc(kernel_map, &clean_sva, &clean_eva,
386			(nbuf*BKVASIZE) + (nswbuf*MAXPHYS) + pager_map_size);
387	buffer_map = kmem_suballoc(clean_map, &buffer_sva, &buffer_eva,
388				(nbuf*BKVASIZE));
389	pager_map = kmem_suballoc(clean_map, &pager_sva, &pager_eva,
390				(nswbuf*MAXPHYS) + pager_map_size);
391	pager_map->system_map = 1;
392	exec_map = kmem_suballoc(kernel_map, &minaddr, &maxaddr,
393				(16*(ARG_MAX+(PAGE_SIZE*3))));
394
395	/*
396	 * XXX: Mbuf system machine-specific initializations should
397	 *      go here, if anywhere.
398	 */
399
400	/*
401	 * Initialize callouts
402	 */
403	SLIST_INIT(&callfree);
404	for (i = 0; i < ncallout; i++) {
405		callout_init(&callout[i]);
406		callout[i].c_flags = CALLOUT_LOCAL_ALLOC;
407		SLIST_INSERT_HEAD(&callfree, &callout[i], c_links.sle);
408	}
409
410	for (i = 0; i < callwheelsize; i++) {
411		TAILQ_INIT(&callwheel[i]);
412	}
413
414#if defined(USERCONFIG)
415	userconfig();
416	cninit();		/* the preferred console may have changed */
417#endif
418
419	printf("avail memory = %u (%uK bytes)\n", ptoa(cnt.v_free_count),
420	    ptoa(cnt.v_free_count) / 1024);
421
422	/*
423	 * Set up buffers, so they can be used to read disk labels.
424	 */
425	bufinit();
426	vm_pager_bufferinit();
427
428	SLIST_INIT(&cpuhead);
429	SLIST_INSERT_HEAD(&cpuhead, GLOBALDATA, gd_allcpu);
430
431	mtx_init(&sched_lock, "sched lock", MTX_SPIN);
432
433#ifdef SMP
434	/*
435	 * OK, enough kmem_alloc/malloc state should be up, lets get on with it!
436	 */
437	mp_start();			/* fire up the APs and APICs */
438	mp_announce();
439#endif  /* SMP */
440	cpu_setregs();
441}
442
443int
444register_netisr(num, handler)
445	int num;
446	netisr_t *handler;
447{
448
449	if (num < 0 || num >= (sizeof(netisrs)/sizeof(*netisrs)) ) {
450		printf("register_netisr: bad isr number: %d\n", num);
451		return (EINVAL);
452	}
453	netisrs[num] = handler;
454	return (0);
455}
456
457int
458unregister_netisr(num)
459	int num;
460{
461
462	if (num < 0 || num >= (sizeof(netisrs)/sizeof(*netisrs)) ) {
463		printf("unregister_netisr: bad isr number: %d\n", num);
464		return (EINVAL);
465	}
466	netisrs[num] = NULL;
467	return (0);
468}
469
470/*
471 * Send an interrupt to process.
472 *
473 * Stack is set up to allow sigcode stored
474 * at top to call routine, followed by kcall
475 * to sigreturn routine below.  After sigreturn
476 * resets the signal mask, the stack, and the
477 * frame pointer, it returns to the user
478 * specified pc, psl.
479 */
480static void
481osendsig(catcher, sig, mask, code)
482	sig_t catcher;
483	int sig;
484	sigset_t *mask;
485	u_long code;
486{
487	struct osigframe sf;
488	struct osigframe *fp;
489	struct proc *p;
490	struct sigacts *psp;
491	struct trapframe *regs;
492	int oonstack;
493
494	p = curproc;
495	psp = p->p_sigacts;
496	regs = p->p_md.md_regs;
497	oonstack = p->p_sigstk.ss_flags & SS_ONSTACK;
498
499	/* Allocate and validate space for the signal handler context. */
500	if ((p->p_flag & P_ALTSTACK) && !oonstack &&
501	    SIGISMEMBER(psp->ps_sigonstack, sig)) {
502		fp = (struct osigframe *)(p->p_sigstk.ss_sp +
503		    p->p_sigstk.ss_size - sizeof(struct osigframe));
504		p->p_sigstk.ss_flags |= SS_ONSTACK;
505	} else
506		fp = (struct osigframe *)regs->tf_esp - 1;
507
508	/*
509	 * grow_stack() will return 0 if *fp does not fit inside the stack
510	 * and the stack can not be grown.
511	 * useracc() will return FALSE if access is denied.
512	 */
513	if (grow_stack(p, (int)fp) == 0 ||
514	    !useracc((caddr_t)fp, sizeof(*fp), VM_PROT_WRITE)) {
515		/*
516		 * Process has trashed its stack; give it an illegal
517		 * instruction to halt it in its tracks.
518		 */
519		SIGACTION(p, SIGILL) = SIG_DFL;
520		SIGDELSET(p->p_sigignore, SIGILL);
521		SIGDELSET(p->p_sigcatch, SIGILL);
522		SIGDELSET(p->p_sigmask, SIGILL);
523		psignal(p, SIGILL);
524		return;
525	}
526
527	/* Translate the signal if appropriate. */
528	if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
529		sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
530
531	/* Build the argument list for the signal handler. */
532	sf.sf_signum = sig;
533	sf.sf_scp = (register_t)&fp->sf_siginfo.si_sc;
534	if (SIGISMEMBER(p->p_sigacts->ps_siginfo, sig)) {
535		/* Signal handler installed with SA_SIGINFO. */
536		sf.sf_arg2 = (register_t)&fp->sf_siginfo;
537		sf.sf_siginfo.si_signo = sig;
538		sf.sf_siginfo.si_code = code;
539		sf.sf_ahu.sf_action = (__osiginfohandler_t *)catcher;
540	} else {
541		/* Old FreeBSD-style arguments. */
542		sf.sf_arg2 = code;
543		sf.sf_addr = regs->tf_err;
544		sf.sf_ahu.sf_handler = catcher;
545	}
546
547	/* Save most if not all of trap frame. */
548	sf.sf_siginfo.si_sc.sc_eax = regs->tf_eax;
549	sf.sf_siginfo.si_sc.sc_ebx = regs->tf_ebx;
550	sf.sf_siginfo.si_sc.sc_ecx = regs->tf_ecx;
551	sf.sf_siginfo.si_sc.sc_edx = regs->tf_edx;
552	sf.sf_siginfo.si_sc.sc_esi = regs->tf_esi;
553	sf.sf_siginfo.si_sc.sc_edi = regs->tf_edi;
554	sf.sf_siginfo.si_sc.sc_cs = regs->tf_cs;
555	sf.sf_siginfo.si_sc.sc_ds = regs->tf_ds;
556	sf.sf_siginfo.si_sc.sc_ss = regs->tf_ss;
557	sf.sf_siginfo.si_sc.sc_es = regs->tf_es;
558	sf.sf_siginfo.si_sc.sc_fs = regs->tf_fs;
559	sf.sf_siginfo.si_sc.sc_gs = rgs();
560	sf.sf_siginfo.si_sc.sc_isp = regs->tf_isp;
561
562	/* Build the signal context to be used by osigreturn(). */
563	sf.sf_siginfo.si_sc.sc_onstack = oonstack;
564	SIG2OSIG(*mask, sf.sf_siginfo.si_sc.sc_mask);
565	sf.sf_siginfo.si_sc.sc_sp = regs->tf_esp;
566	sf.sf_siginfo.si_sc.sc_fp = regs->tf_ebp;
567	sf.sf_siginfo.si_sc.sc_pc = regs->tf_eip;
568	sf.sf_siginfo.si_sc.sc_ps = regs->tf_eflags;
569	sf.sf_siginfo.si_sc.sc_trapno = regs->tf_trapno;
570	sf.sf_siginfo.si_sc.sc_err = regs->tf_err;
571
572	/*
573	 * If we're a vm86 process, we want to save the segment registers.
574	 * We also change eflags to be our emulated eflags, not the actual
575	 * eflags.
576	 */
577	if (regs->tf_eflags & PSL_VM) {
578		/* XXX confusing names: `tf' isn't a trapframe; `regs' is. */
579		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
580		struct vm86_kernel *vm86 = &p->p_addr->u_pcb.pcb_ext->ext_vm86;
581
582		sf.sf_siginfo.si_sc.sc_gs = tf->tf_vm86_gs;
583		sf.sf_siginfo.si_sc.sc_fs = tf->tf_vm86_fs;
584		sf.sf_siginfo.si_sc.sc_es = tf->tf_vm86_es;
585		sf.sf_siginfo.si_sc.sc_ds = tf->tf_vm86_ds;
586
587		if (vm86->vm86_has_vme == 0)
588			sf.sf_siginfo.si_sc.sc_ps =
589			    (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
590			    (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
591
592		/* See sendsig() for comments. */
593		tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_T | PSL_VIF | PSL_VIP);
594	}
595
596	/* Copy the sigframe out to the user's stack. */
597	if (copyout(&sf, fp, sizeof(*fp)) != 0) {
598		/*
599		 * Something is wrong with the stack pointer.
600		 * ...Kill the process.
601		 */
602		sigexit(p, SIGILL);
603	}
604
605	regs->tf_esp = (int)fp;
606	regs->tf_eip = PS_STRINGS - szosigcode;
607	regs->tf_cs = _ucodesel;
608	regs->tf_ds = _udatasel;
609	regs->tf_es = _udatasel;
610	regs->tf_fs = _udatasel;
611	load_gs(_udatasel);
612	regs->tf_ss = _udatasel;
613}
614
615void
616sendsig(catcher, sig, mask, code)
617	sig_t catcher;
618	int sig;
619	sigset_t *mask;
620	u_long code;
621{
622	struct sigframe sf;
623	struct proc *p;
624	struct sigacts *psp;
625	struct trapframe *regs;
626	struct sigframe *sfp;
627	int oonstack;
628
629	p = curproc;
630	psp = p->p_sigacts;
631	if (SIGISMEMBER(psp->ps_osigset, sig)) {
632		osendsig(catcher, sig, mask, code);
633		return;
634	}
635	regs = p->p_md.md_regs;
636	oonstack = p->p_sigstk.ss_flags & SS_ONSTACK;
637
638	/* Save user context. */
639	bzero(&sf, sizeof(sf));
640	sf.sf_uc.uc_sigmask = *mask;
641	sf.sf_uc.uc_stack = p->p_sigstk;
642	sf.sf_uc.uc_mcontext.mc_onstack = oonstack;
643	sf.sf_uc.uc_mcontext.mc_gs = rgs();
644	bcopy(regs, &sf.sf_uc.uc_mcontext.mc_fs, sizeof(*regs));
645
646	/* Allocate and validate space for the signal handler context. */
647	if ((p->p_flag & P_ALTSTACK) != 0 && !oonstack &&
648	    SIGISMEMBER(psp->ps_sigonstack, sig)) {
649		sfp = (struct sigframe *)(p->p_sigstk.ss_sp +
650		    p->p_sigstk.ss_size - sizeof(struct sigframe));
651		p->p_sigstk.ss_flags |= SS_ONSTACK;
652	} else
653		sfp = (struct sigframe *)regs->tf_esp - 1;
654
655	/*
656	 * grow_stack() will return 0 if *sfp does not fit inside the stack
657	 * and the stack can not be grown.
658	 * useracc() will return FALSE if access is denied.
659	 */
660	if (grow_stack(p, (int)sfp) == 0 ||
661	    !useracc((caddr_t)sfp, sizeof(*sfp), VM_PROT_WRITE)) {
662		/*
663		 * Process has trashed its stack; give it an illegal
664		 * instruction to halt it in its tracks.
665		 */
666#ifdef DEBUG
667		printf("process %d has trashed its stack\n", p->p_pid);
668#endif
669		SIGACTION(p, SIGILL) = SIG_DFL;
670		SIGDELSET(p->p_sigignore, SIGILL);
671		SIGDELSET(p->p_sigcatch, SIGILL);
672		SIGDELSET(p->p_sigmask, SIGILL);
673		psignal(p, SIGILL);
674		return;
675	}
676
677	/* Translate the signal if appropriate. */
678	if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
679		sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
680
681	/* Build the argument list for the signal handler. */
682	sf.sf_signum = sig;
683	sf.sf_ucontext = (register_t)&sfp->sf_uc;
684	if (SIGISMEMBER(p->p_sigacts->ps_siginfo, sig)) {
685		/* Signal handler installed with SA_SIGINFO. */
686		sf.sf_siginfo = (register_t)&sfp->sf_si;
687		sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
688
689		/* Fill siginfo structure. */
690		sf.sf_si.si_signo = sig;
691		sf.sf_si.si_code = code;
692		sf.sf_si.si_addr = (void *)regs->tf_err;
693	} else {
694		/* Old FreeBSD-style arguments. */
695		sf.sf_siginfo = code;
696		sf.sf_addr = regs->tf_err;
697		sf.sf_ahu.sf_handler = catcher;
698	}
699
700	/*
701	 * If we're a vm86 process, we want to save the segment registers.
702	 * We also change eflags to be our emulated eflags, not the actual
703	 * eflags.
704	 */
705	if (regs->tf_eflags & PSL_VM) {
706		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
707		struct vm86_kernel *vm86 = &p->p_addr->u_pcb.pcb_ext->ext_vm86;
708
709		sf.sf_uc.uc_mcontext.mc_gs = tf->tf_vm86_gs;
710		sf.sf_uc.uc_mcontext.mc_fs = tf->tf_vm86_fs;
711		sf.sf_uc.uc_mcontext.mc_es = tf->tf_vm86_es;
712		sf.sf_uc.uc_mcontext.mc_ds = tf->tf_vm86_ds;
713
714		if (vm86->vm86_has_vme == 0)
715			sf.sf_uc.uc_mcontext.mc_eflags =
716			    (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
717			    (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
718
719		/*
720		 * We should never have PSL_T set when returning from vm86
721		 * mode.  It may be set here if we deliver a signal before
722		 * getting to vm86 mode, so turn it off.
723		 *
724		 * Clear PSL_NT to inhibit T_TSSFLT faults on return from
725		 * syscalls made by the signal handler.  This just avoids
726		 * wasting time for our lazy fixup of such faults.  PSL_NT
727		 * does nothing in vm86 mode, but vm86 programs can set it
728		 * almost legitimately in probes for old cpu types.
729		 */
730		tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_T | PSL_VIF | PSL_VIP);
731	}
732
733	/* Copy the sigframe out to the user's stack. */
734	if (copyout(&sf, sfp, sizeof(*sfp)) != 0) {
735		/*
736		 * Something is wrong with the stack pointer.
737		 * ...Kill the process.
738		 */
739		sigexit(p, SIGILL);
740	}
741
742	regs->tf_esp = (int)sfp;
743	regs->tf_eip = PS_STRINGS - *(p->p_sysent->sv_szsigcode);
744	regs->tf_cs = _ucodesel;
745	regs->tf_ds = _udatasel;
746	regs->tf_es = _udatasel;
747	regs->tf_fs = _udatasel;
748	load_gs(_udatasel);
749	regs->tf_ss = _udatasel;
750}
751
752/*
753 * System call to cleanup state after a signal
754 * has been taken.  Reset signal mask and
755 * stack state from context left by sendsig (above).
756 * Return to previous pc and psl as specified by
757 * context left by sendsig. Check carefully to
758 * make sure that the user has not modified the
759 * state to gain improper privileges.
760 */
761int
762osigreturn(p, uap)
763	struct proc *p;
764	struct osigreturn_args /* {
765		struct osigcontext *sigcntxp;
766	} */ *uap;
767{
768	struct trapframe *regs;
769	struct osigcontext *scp;
770	int eflags;
771
772	regs = p->p_md.md_regs;
773	scp = uap->sigcntxp;
774	if (!useracc((caddr_t)scp, sizeof(*scp), VM_PROT_READ))
775		return (EFAULT);
776	eflags = scp->sc_ps;
777	if (eflags & PSL_VM) {
778		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
779		struct vm86_kernel *vm86;
780
781		/*
782		 * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
783		 * set up the vm86 area, and we can't enter vm86 mode.
784		 */
785		if (p->p_addr->u_pcb.pcb_ext == 0)
786			return (EINVAL);
787		vm86 = &p->p_addr->u_pcb.pcb_ext->ext_vm86;
788		if (vm86->vm86_inited == 0)
789			return (EINVAL);
790
791		/* Go back to user mode if both flags are set. */
792		if ((eflags & PSL_VIP) && (eflags & PSL_VIF))
793			trapsignal(p, SIGBUS, 0);
794
795		if (vm86->vm86_has_vme) {
796			eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
797			    (eflags & VME_USERCHANGE) | PSL_VM;
798		} else {
799			vm86->vm86_eflags = eflags;	/* save VIF, VIP */
800			eflags = (tf->tf_eflags & ~VM_USERCHANGE) |					    (eflags & VM_USERCHANGE) | PSL_VM;
801		}
802		tf->tf_vm86_ds = scp->sc_ds;
803		tf->tf_vm86_es = scp->sc_es;
804		tf->tf_vm86_fs = scp->sc_fs;
805		tf->tf_vm86_gs = scp->sc_gs;
806		tf->tf_ds = _udatasel;
807		tf->tf_es = _udatasel;
808		tf->tf_fs = _udatasel;
809	} else {
810		/*
811		 * Don't allow users to change privileged or reserved flags.
812		 */
813		/*
814		 * XXX do allow users to change the privileged flag PSL_RF.
815		 * The cpu sets PSL_RF in tf_eflags for faults.  Debuggers
816		 * should sometimes set it there too.  tf_eflags is kept in
817		 * the signal context during signal handling and there is no
818		 * other place to remember it, so the PSL_RF bit may be
819		 * corrupted by the signal handler without us knowing.
820		 * Corruption of the PSL_RF bit at worst causes one more or
821		 * one less debugger trap, so allowing it is fairly harmless.
822		 */
823		if (!EFL_SECURE(eflags & ~PSL_RF, regs->tf_eflags & ~PSL_RF)) {
824	    		return (EINVAL);
825		}
826
827		/*
828		 * Don't allow users to load a valid privileged %cs.  Let the
829		 * hardware check for invalid selectors, excess privilege in
830		 * other selectors, invalid %eip's and invalid %esp's.
831		 */
832		if (!CS_SECURE(scp->sc_cs)) {
833			trapsignal(p, SIGBUS, T_PROTFLT);
834			return (EINVAL);
835		}
836		regs->tf_ds = scp->sc_ds;
837		regs->tf_es = scp->sc_es;
838		regs->tf_fs = scp->sc_fs;
839	}
840
841	/* Restore remaining registers. */
842	regs->tf_eax = scp->sc_eax;
843	regs->tf_ebx = scp->sc_ebx;
844	regs->tf_ecx = scp->sc_ecx;
845	regs->tf_edx = scp->sc_edx;
846	regs->tf_esi = scp->sc_esi;
847	regs->tf_edi = scp->sc_edi;
848	regs->tf_cs = scp->sc_cs;
849	regs->tf_ss = scp->sc_ss;
850	regs->tf_isp = scp->sc_isp;
851
852	if (scp->sc_onstack & 01)
853		p->p_sigstk.ss_flags |= SS_ONSTACK;
854	else
855		p->p_sigstk.ss_flags &= ~SS_ONSTACK;
856	SIGSETOLD(p->p_sigmask, scp->sc_mask);
857	SIG_CANTMASK(p->p_sigmask);
858	regs->tf_ebp = scp->sc_fp;
859	regs->tf_esp = scp->sc_sp;
860	regs->tf_eip = scp->sc_pc;
861	regs->tf_eflags = eflags;
862	return (EJUSTRETURN);
863}
864
865int
866sigreturn(p, uap)
867	struct proc *p;
868	struct sigreturn_args /* {
869		ucontext_t *sigcntxp;
870	} */ *uap;
871{
872	struct trapframe *regs;
873	ucontext_t *ucp;
874	int cs, eflags;
875
876	ucp = uap->sigcntxp;
877	if (!useracc((caddr_t)ucp, sizeof(struct osigcontext), VM_PROT_READ))
878		return (EFAULT);
879	if (((struct osigcontext *)ucp)->sc_trapno == 0x01d516)
880		return (osigreturn(p, (struct osigreturn_args *)uap));
881
882	/*
883	 * Since ucp is not an osigcontext but a ucontext_t, we have to
884	 * check again if all of it is accessible.  A ucontext_t is
885	 * much larger, so instead of just checking for the pointer
886	 * being valid for the size of an osigcontext, now check for
887	 * it being valid for a whole, new-style ucontext_t.
888	 */
889	if (!useracc((caddr_t)ucp, sizeof(*ucp), VM_PROT_READ))
890		return (EFAULT);
891
892	regs = p->p_md.md_regs;
893	eflags = ucp->uc_mcontext.mc_eflags;
894	if (eflags & PSL_VM) {
895		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
896		struct vm86_kernel *vm86;
897
898		/*
899		 * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
900		 * set up the vm86 area, and we can't enter vm86 mode.
901		 */
902		if (p->p_addr->u_pcb.pcb_ext == 0)
903			return (EINVAL);
904		vm86 = &p->p_addr->u_pcb.pcb_ext->ext_vm86;
905		if (vm86->vm86_inited == 0)
906			return (EINVAL);
907
908		/* Go back to user mode if both flags are set. */
909		if ((eflags & PSL_VIP) && (eflags & PSL_VIF))
910			trapsignal(p, SIGBUS, 0);
911
912		if (vm86->vm86_has_vme) {
913			eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
914			    (eflags & VME_USERCHANGE) | PSL_VM;
915		} else {
916			vm86->vm86_eflags = eflags;	/* save VIF, VIP */
917			eflags = (tf->tf_eflags & ~VM_USERCHANGE) |					    (eflags & VM_USERCHANGE) | PSL_VM;
918		}
919		bcopy(&ucp->uc_mcontext.mc_fs, tf, sizeof(struct trapframe));
920		tf->tf_eflags = eflags;
921		tf->tf_vm86_ds = tf->tf_ds;
922		tf->tf_vm86_es = tf->tf_es;
923		tf->tf_vm86_fs = tf->tf_fs;
924		tf->tf_vm86_gs = ucp->uc_mcontext.mc_gs;
925		tf->tf_ds = _udatasel;
926		tf->tf_es = _udatasel;
927		tf->tf_fs = _udatasel;
928	} else {
929		/*
930		 * Don't allow users to change privileged or reserved flags.
931		 */
932		/*
933		 * XXX do allow users to change the privileged flag PSL_RF.
934		 * The cpu sets PSL_RF in tf_eflags for faults.  Debuggers
935		 * should sometimes set it there too.  tf_eflags is kept in
936		 * the signal context during signal handling and there is no
937		 * other place to remember it, so the PSL_RF bit may be
938		 * corrupted by the signal handler without us knowing.
939		 * Corruption of the PSL_RF bit at worst causes one more or
940		 * one less debugger trap, so allowing it is fairly harmless.
941		 */
942		if (!EFL_SECURE(eflags & ~PSL_RF, regs->tf_eflags & ~PSL_RF)) {
943			printf("sigreturn: eflags = 0x%x\n", eflags);
944	    		return (EINVAL);
945		}
946
947		/*
948		 * Don't allow users to load a valid privileged %cs.  Let the
949		 * hardware check for invalid selectors, excess privilege in
950		 * other selectors, invalid %eip's and invalid %esp's.
951		 */
952		cs = ucp->uc_mcontext.mc_cs;
953		if (!CS_SECURE(cs)) {
954			printf("sigreturn: cs = 0x%x\n", cs);
955			trapsignal(p, SIGBUS, T_PROTFLT);
956			return (EINVAL);
957		}
958
959		bcopy(&ucp->uc_mcontext.mc_fs, regs, sizeof(*regs));
960	}
961	if (ucp->uc_mcontext.mc_onstack & 1)
962		p->p_sigstk.ss_flags |= SS_ONSTACK;
963	else
964		p->p_sigstk.ss_flags &= ~SS_ONSTACK;
965
966	p->p_sigmask = ucp->uc_sigmask;
967	SIG_CANTMASK(p->p_sigmask);
968	return (EJUSTRETURN);
969}
970
971/*
972 * Machine dependent boot() routine
973 *
974 * I haven't seen anything to put here yet
975 * Possibly some stuff might be grafted back here from boot()
976 */
977void
978cpu_boot(int howto)
979{
980}
981
982/*
983 * Shutdown the CPU as much as possible
984 */
985void
986cpu_halt(void)
987{
988	for (;;)
989		__asm__ ("hlt");
990}
991
992/*
993 * Hook to idle the CPU when possible.  This currently only works in
994 * the !SMP case, as there is no clean way to ensure that a CPU will be
995 * woken when there is work available for it.
996 */
997#ifndef SMP
998static int	cpu_idle_hlt = 1;
999SYSCTL_INT(_machdep, OID_AUTO, cpu_idle_hlt, CTLFLAG_RW,
1000    &cpu_idle_hlt, 0, "Idle loop HLT enable");
1001
1002/*
1003 * Note that we have to be careful here to avoid a race between checking
1004 * procrunnable() and actually halting.  If we don't do this, we may waste
1005 * the time between calling hlt and the next interrupt even though there
1006 * is a runnable process.
1007 */
1008static void
1009cpu_idle(void *junk, int count)
1010{
1011	if (cpu_idle_hlt) {
1012		disable_intr();
1013  		if (procrunnable())
1014			enable_intr();
1015		else {
1016			enable_intr();
1017			__asm __volatile("hlt");
1018		}
1019	}
1020}
1021
1022static void cpu_idle_register(void *junk)
1023{
1024	EVENTHANDLER_FAST_REGISTER(idle_event, cpu_idle, NULL, IDLE_PRI_LAST);
1025}
1026SYSINIT(cpu_idle_register, SI_SUB_SCHED_IDLE, SI_ORDER_SECOND,
1027    cpu_idle_register, NULL)
1028#endif /* !SMP */
1029
1030/*
1031 * Clear registers on exec
1032 */
1033void
1034setregs(p, entry, stack, ps_strings)
1035	struct proc *p;
1036	u_long entry;
1037	u_long stack;
1038	u_long ps_strings;
1039{
1040	struct trapframe *regs = p->p_md.md_regs;
1041	struct pcb *pcb = &p->p_addr->u_pcb;
1042
1043#ifdef USER_LDT
1044	/* was i386_user_cleanup() in NetBSD */
1045	user_ldt_free(pcb);
1046#endif
1047
1048	bzero((char *)regs, sizeof(struct trapframe));
1049	regs->tf_eip = entry;
1050	regs->tf_esp = stack;
1051	regs->tf_eflags = PSL_USER | (regs->tf_eflags & PSL_T);
1052	regs->tf_ss = _udatasel;
1053	regs->tf_ds = _udatasel;
1054	regs->tf_es = _udatasel;
1055	regs->tf_fs = _udatasel;
1056	regs->tf_cs = _ucodesel;
1057
1058	/* PS_STRINGS value for BSD/OS binaries.  It is 0 for non-BSD/OS. */
1059	regs->tf_ebx = ps_strings;
1060
1061	/* reset %gs as well */
1062	if (pcb == curpcb)
1063		load_gs(_udatasel);
1064	else
1065		pcb->pcb_gs = _udatasel;
1066
1067        /*
1068         * Reset the hardware debug registers if they were in use.
1069         * They won't have any meaning for the newly exec'd process.
1070         */
1071        if (pcb->pcb_flags & PCB_DBREGS) {
1072                pcb->pcb_dr0 = 0;
1073                pcb->pcb_dr1 = 0;
1074                pcb->pcb_dr2 = 0;
1075                pcb->pcb_dr3 = 0;
1076                pcb->pcb_dr6 = 0;
1077                pcb->pcb_dr7 = 0;
1078                if (pcb == curpcb) {
1079		        /*
1080			 * Clear the debug registers on the running
1081			 * CPU, otherwise they will end up affecting
1082			 * the next process we switch to.
1083			 */
1084		        reset_dbregs();
1085                }
1086                pcb->pcb_flags &= ~PCB_DBREGS;
1087        }
1088
1089	/*
1090	 * Initialize the math emulator (if any) for the current process.
1091	 * Actually, just clear the bit that says that the emulator has
1092	 * been initialized.  Initialization is delayed until the process
1093	 * traps to the emulator (if it is done at all) mainly because
1094	 * emulators don't provide an entry point for initialization.
1095	 */
1096	p->p_addr->u_pcb.pcb_flags &= ~FP_SOFTFP;
1097
1098	/*
1099	 * Arrange to trap the next npx or `fwait' instruction (see npx.c
1100	 * for why fwait must be trapped at least if there is an npx or an
1101	 * emulator).  This is mainly to handle the case where npx0 is not
1102	 * configured, since the npx routines normally set up the trap
1103	 * otherwise.  It should be done only at boot time, but doing it
1104	 * here allows modifying `npx_exists' for testing the emulator on
1105	 * systems with an npx.
1106	 */
1107	load_cr0(rcr0() | CR0_MP | CR0_TS);
1108
1109#if NNPX > 0
1110	/* Initialize the npx (if any) for the current process. */
1111	npxinit(__INITIAL_NPXCW__);
1112#endif
1113
1114      /*
1115       * XXX - Linux emulator
1116       * Make sure sure edx is 0x0 on entry. Linux binaries depend
1117       * on it.
1118       */
1119      p->p_retval[1] = 0;
1120}
1121
1122void
1123cpu_setregs(void)
1124{
1125	unsigned int cr0;
1126
1127	cr0 = rcr0();
1128	cr0 |= CR0_NE;			/* Done by npxinit() */
1129	cr0 |= CR0_MP | CR0_TS;		/* Done at every execve() too. */
1130#ifdef I386_CPU
1131	if (cpu_class != CPUCLASS_386)
1132#endif
1133		cr0 |= CR0_WP | CR0_AM;
1134	load_cr0(cr0);
1135	load_gs(_udatasel);
1136}
1137
1138static int
1139sysctl_machdep_adjkerntz(SYSCTL_HANDLER_ARGS)
1140{
1141	int error;
1142	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
1143		req);
1144	if (!error && req->newptr)
1145		resettodr();
1146	return (error);
1147}
1148
1149SYSCTL_PROC(_machdep, CPU_ADJKERNTZ, adjkerntz, CTLTYPE_INT|CTLFLAG_RW,
1150	&adjkerntz, 0, sysctl_machdep_adjkerntz, "I", "");
1151
1152SYSCTL_INT(_machdep, CPU_DISRTCSET, disable_rtc_set,
1153	CTLFLAG_RW, &disable_rtc_set, 0, "");
1154
1155SYSCTL_STRUCT(_machdep, CPU_BOOTINFO, bootinfo,
1156	CTLFLAG_RD, &bootinfo, bootinfo, "");
1157
1158SYSCTL_INT(_machdep, CPU_WALLCLOCK, wall_cmos_clock,
1159	CTLFLAG_RW, &wall_cmos_clock, 0, "");
1160
1161/*
1162 * Initialize 386 and configure to run kernel
1163 */
1164
1165/*
1166 * Initialize segments & interrupt table
1167 */
1168
1169int _default_ldt;
1170union descriptor gdt[NGDT * MAXCPU];	/* global descriptor table */
1171static struct gate_descriptor idt0[NIDT];
1172struct gate_descriptor *idt = &idt0[0];	/* interrupt descriptor table */
1173union descriptor ldt[NLDT];		/* local descriptor table */
1174#ifdef SMP
1175/* table descriptors - used to load tables by microp */
1176struct region_descriptor r_gdt, r_idt;
1177#endif
1178
1179#ifndef SMP
1180extern struct segment_descriptor common_tssd, *tss_gdt;
1181#endif
1182int private_tss;			/* flag indicating private tss */
1183
1184#if defined(I586_CPU) && !defined(NO_F00F_HACK)
1185extern int has_f00f_bug;
1186#endif
1187
1188static struct i386tss dblfault_tss;
1189static char dblfault_stack[PAGE_SIZE];
1190
1191extern  struct user *proc0paddr;
1192
1193
1194/* software prototypes -- in more palatable form */
1195struct soft_segment_descriptor gdt_segs[] = {
1196/* GNULL_SEL	0 Null Descriptor */
1197{	0x0,			/* segment base address  */
1198	0x0,			/* length */
1199	0,			/* segment type */
1200	0,			/* segment descriptor priority level */
1201	0,			/* segment descriptor present */
1202	0, 0,
1203	0,			/* default 32 vs 16 bit size */
1204	0  			/* limit granularity (byte/page units)*/ },
1205/* GCODE_SEL	1 Code Descriptor for kernel */
1206{	0x0,			/* segment base address  */
1207	0xfffff,		/* length - all address space */
1208	SDT_MEMERA,		/* segment type */
1209	0,			/* segment descriptor priority level */
1210	1,			/* segment descriptor present */
1211	0, 0,
1212	1,			/* default 32 vs 16 bit size */
1213	1  			/* limit granularity (byte/page units)*/ },
1214/* GDATA_SEL	2 Data Descriptor for kernel */
1215{	0x0,			/* segment base address  */
1216	0xfffff,		/* length - all address space */
1217	SDT_MEMRWA,		/* segment type */
1218	0,			/* segment descriptor priority level */
1219	1,			/* segment descriptor present */
1220	0, 0,
1221	1,			/* default 32 vs 16 bit size */
1222	1  			/* limit granularity (byte/page units)*/ },
1223/* GPRIV_SEL	3 SMP Per-Processor Private Data Descriptor */
1224{	0x0,			/* segment base address  */
1225	0xfffff,		/* length - all address space */
1226	SDT_MEMRWA,		/* segment type */
1227	0,			/* segment descriptor priority level */
1228	1,			/* segment descriptor present */
1229	0, 0,
1230	1,			/* default 32 vs 16 bit size */
1231	1  			/* limit granularity (byte/page units)*/ },
1232/* GPROC0_SEL	4 Proc 0 Tss Descriptor */
1233{
1234	0x0,			/* segment base address */
1235	sizeof(struct i386tss)-1,/* length - all address space */
1236	SDT_SYS386TSS,		/* segment type */
1237	0,			/* segment descriptor priority level */
1238	1,			/* segment descriptor present */
1239	0, 0,
1240	0,			/* unused - default 32 vs 16 bit size */
1241	0  			/* limit granularity (byte/page units)*/ },
1242/* GLDT_SEL	5 LDT Descriptor */
1243{	(int) ldt,		/* segment base address  */
1244	sizeof(ldt)-1,		/* length - all address space */
1245	SDT_SYSLDT,		/* segment type */
1246	SEL_UPL,		/* segment descriptor priority level */
1247	1,			/* segment descriptor present */
1248	0, 0,
1249	0,			/* unused - default 32 vs 16 bit size */
1250	0  			/* limit granularity (byte/page units)*/ },
1251/* GUSERLDT_SEL	6 User LDT Descriptor per process */
1252{	(int) ldt,		/* segment base address  */
1253	(512 * sizeof(union descriptor)-1),		/* length */
1254	SDT_SYSLDT,		/* segment type */
1255	0,			/* segment descriptor priority level */
1256	1,			/* segment descriptor present */
1257	0, 0,
1258	0,			/* unused - default 32 vs 16 bit size */
1259	0  			/* limit granularity (byte/page units)*/ },
1260/* GTGATE_SEL	7 Null Descriptor - Placeholder */
1261{	0x0,			/* segment base address  */
1262	0x0,			/* length - all address space */
1263	0,			/* segment type */
1264	0,			/* segment descriptor priority level */
1265	0,			/* segment descriptor present */
1266	0, 0,
1267	0,			/* default 32 vs 16 bit size */
1268	0  			/* limit granularity (byte/page units)*/ },
1269/* GBIOSLOWMEM_SEL 8 BIOS access to realmode segment 0x40, must be #8 in GDT */
1270{	0x400,			/* segment base address */
1271	0xfffff,		/* length */
1272	SDT_MEMRWA,		/* segment type */
1273	0,			/* segment descriptor priority level */
1274	1,			/* segment descriptor present */
1275	0, 0,
1276	1,			/* default 32 vs 16 bit size */
1277	1  			/* limit granularity (byte/page units)*/ },
1278/* GPANIC_SEL	9 Panic Tss Descriptor */
1279{	(int) &dblfault_tss,	/* segment base address  */
1280	sizeof(struct i386tss)-1,/* length - all address space */
1281	SDT_SYS386TSS,		/* segment type */
1282	0,			/* segment descriptor priority level */
1283	1,			/* segment descriptor present */
1284	0, 0,
1285	0,			/* unused - default 32 vs 16 bit size */
1286	0  			/* limit granularity (byte/page units)*/ },
1287/* GBIOSCODE32_SEL 10 BIOS 32-bit interface (32bit Code) */
1288{	0,			/* segment base address (overwritten)  */
1289	0xfffff,		/* length */
1290	SDT_MEMERA,		/* segment type */
1291	0,			/* segment descriptor priority level */
1292	1,			/* segment descriptor present */
1293	0, 0,
1294	0,			/* default 32 vs 16 bit size */
1295	1  			/* limit granularity (byte/page units)*/ },
1296/* GBIOSCODE16_SEL 11 BIOS 32-bit interface (16bit Code) */
1297{	0,			/* segment base address (overwritten)  */
1298	0xfffff,		/* length */
1299	SDT_MEMERA,		/* segment type */
1300	0,			/* segment descriptor priority level */
1301	1,			/* segment descriptor present */
1302	0, 0,
1303	0,			/* default 32 vs 16 bit size */
1304	1  			/* limit granularity (byte/page units)*/ },
1305/* GBIOSDATA_SEL 12 BIOS 32-bit interface (Data) */
1306{	0,			/* segment base address (overwritten) */
1307	0xfffff,		/* length */
1308	SDT_MEMRWA,		/* segment type */
1309	0,			/* segment descriptor priority level */
1310	1,			/* segment descriptor present */
1311	0, 0,
1312	1,			/* default 32 vs 16 bit size */
1313	1  			/* limit granularity (byte/page units)*/ },
1314/* GBIOSUTIL_SEL 13 BIOS 16-bit interface (Utility) */
1315{	0,			/* segment base address (overwritten) */
1316	0xfffff,		/* length */
1317	SDT_MEMRWA,		/* segment type */
1318	0,			/* segment descriptor priority level */
1319	1,			/* segment descriptor present */
1320	0, 0,
1321	0,			/* default 32 vs 16 bit size */
1322	1  			/* limit granularity (byte/page units)*/ },
1323/* GBIOSARGS_SEL 14 BIOS 16-bit interface (Arguments) */
1324{	0,			/* segment base address (overwritten) */
1325	0xfffff,		/* length */
1326	SDT_MEMRWA,		/* segment type */
1327	0,			/* segment descriptor priority level */
1328	1,			/* segment descriptor present */
1329	0, 0,
1330	0,			/* default 32 vs 16 bit size */
1331	1  			/* limit granularity (byte/page units)*/ },
1332};
1333
1334static struct soft_segment_descriptor ldt_segs[] = {
1335	/* Null Descriptor - overwritten by call gate */
1336{	0x0,			/* segment base address  */
1337	0x0,			/* length - all address space */
1338	0,			/* segment type */
1339	0,			/* segment descriptor priority level */
1340	0,			/* segment descriptor present */
1341	0, 0,
1342	0,			/* default 32 vs 16 bit size */
1343	0  			/* limit granularity (byte/page units)*/ },
1344	/* Null Descriptor - overwritten by call gate */
1345{	0x0,			/* segment base address  */
1346	0x0,			/* length - all address space */
1347	0,			/* segment type */
1348	0,			/* segment descriptor priority level */
1349	0,			/* segment descriptor present */
1350	0, 0,
1351	0,			/* default 32 vs 16 bit size */
1352	0  			/* limit granularity (byte/page units)*/ },
1353	/* Null Descriptor - overwritten by call gate */
1354{	0x0,			/* segment base address  */
1355	0x0,			/* length - all address space */
1356	0,			/* segment type */
1357	0,			/* segment descriptor priority level */
1358	0,			/* segment descriptor present */
1359	0, 0,
1360	0,			/* default 32 vs 16 bit size */
1361	0  			/* limit granularity (byte/page units)*/ },
1362	/* Code Descriptor for user */
1363{	0x0,			/* segment base address  */
1364	0xfffff,		/* length - all address space */
1365	SDT_MEMERA,		/* segment type */
1366	SEL_UPL,		/* segment descriptor priority level */
1367	1,			/* segment descriptor present */
1368	0, 0,
1369	1,			/* default 32 vs 16 bit size */
1370	1  			/* limit granularity (byte/page units)*/ },
1371	/* Null Descriptor - overwritten by call gate */
1372{	0x0,			/* segment base address  */
1373	0x0,			/* length - all address space */
1374	0,			/* segment type */
1375	0,			/* segment descriptor priority level */
1376	0,			/* segment descriptor present */
1377	0, 0,
1378	0,			/* default 32 vs 16 bit size */
1379	0  			/* limit granularity (byte/page units)*/ },
1380	/* Data Descriptor for user */
1381{	0x0,			/* segment base address  */
1382	0xfffff,		/* length - all address space */
1383	SDT_MEMRWA,		/* segment type */
1384	SEL_UPL,		/* segment descriptor priority level */
1385	1,			/* segment descriptor present */
1386	0, 0,
1387	1,			/* default 32 vs 16 bit size */
1388	1  			/* limit granularity (byte/page units)*/ },
1389};
1390
1391void
1392setidt(idx, func, typ, dpl, selec)
1393	int idx;
1394	inthand_t *func;
1395	int typ;
1396	int dpl;
1397	int selec;
1398{
1399	struct gate_descriptor *ip;
1400
1401	ip = idt + idx;
1402	ip->gd_looffset = (int)func;
1403	ip->gd_selector = selec;
1404	ip->gd_stkcpy = 0;
1405	ip->gd_xx = 0;
1406	ip->gd_type = typ;
1407	ip->gd_dpl = dpl;
1408	ip->gd_p = 1;
1409	ip->gd_hioffset = ((int)func)>>16 ;
1410}
1411
1412#define	IDTVEC(name)	__CONCAT(X,name)
1413
1414extern inthand_t
1415	IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
1416	IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
1417	IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
1418	IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
1419	IDTVEC(syscall), IDTVEC(int0x80_syscall);
1420
1421void
1422sdtossd(sd, ssd)
1423	struct segment_descriptor *sd;
1424	struct soft_segment_descriptor *ssd;
1425{
1426	ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
1427	ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
1428	ssd->ssd_type  = sd->sd_type;
1429	ssd->ssd_dpl   = sd->sd_dpl;
1430	ssd->ssd_p     = sd->sd_p;
1431	ssd->ssd_def32 = sd->sd_def32;
1432	ssd->ssd_gran  = sd->sd_gran;
1433}
1434
1435#define PHYSMAP_SIZE	(2 * 8)
1436
1437/*
1438 * Populate the (physmap) array with base/bound pairs describing the
1439 * available physical memory in the system, then test this memory and
1440 * build the phys_avail array describing the actually-available memory.
1441 *
1442 * If we cannot accurately determine the physical memory map, then use
1443 * value from the 0xE801 call, and failing that, the RTC.
1444 *
1445 * Total memory size may be set by the kernel environment variable
1446 * hw.physmem or the compile-time define MAXMEM.
1447 */
1448static void
1449getmemsize(int first)
1450{
1451	int i, physmap_idx, pa_indx;
1452	u_int basemem, extmem;
1453	struct vm86frame vmf;
1454	struct vm86context vmc;
1455	vm_offset_t pa, physmap[PHYSMAP_SIZE];
1456	pt_entry_t pte;
1457	const char *cp;
1458	struct bios_smap *smap;
1459
1460	bzero(&vmf, sizeof(struct vm86frame));
1461	bzero(physmap, sizeof(physmap));
1462
1463	/*
1464	 * Perform "base memory" related probes & setup
1465	 */
1466	vm86_intcall(0x12, &vmf);
1467	basemem = vmf.vmf_ax;
1468	if (basemem > 640) {
1469		printf("Preposterous BIOS basemem of %uK, truncating to 640K\n",
1470			basemem);
1471		basemem = 640;
1472	}
1473
1474	/*
1475	 * XXX if biosbasemem is now < 640, there is a `hole'
1476	 * between the end of base memory and the start of
1477	 * ISA memory.  The hole may be empty or it may
1478	 * contain BIOS code or data.  Map it read/write so
1479	 * that the BIOS can write to it.  (Memory from 0 to
1480	 * the physical end of the kernel is mapped read-only
1481	 * to begin with and then parts of it are remapped.
1482	 * The parts that aren't remapped form holes that
1483	 * remain read-only and are unused by the kernel.
1484	 * The base memory area is below the physical end of
1485	 * the kernel and right now forms a read-only hole.
1486	 * The part of it from PAGE_SIZE to
1487	 * (trunc_page(biosbasemem * 1024) - 1) will be
1488	 * remapped and used by the kernel later.)
1489	 *
1490	 * This code is similar to the code used in
1491	 * pmap_mapdev, but since no memory needs to be
1492	 * allocated we simply change the mapping.
1493	 */
1494	for (pa = trunc_page(basemem * 1024);
1495	     pa < ISA_HOLE_START; pa += PAGE_SIZE) {
1496		pte = (pt_entry_t)vtopte(pa + KERNBASE);
1497		*pte = pa | PG_RW | PG_V;
1498	}
1499
1500	/*
1501	 * if basemem != 640, map pages r/w into vm86 page table so
1502	 * that the bios can scribble on it.
1503	 */
1504	pte = (pt_entry_t)vm86paddr;
1505	for (i = basemem / 4; i < 160; i++)
1506		pte[i] = (i << PAGE_SHIFT) | PG_V | PG_RW | PG_U;
1507
1508	/*
1509	 * map page 1 R/W into the kernel page table so we can use it
1510	 * as a buffer.  The kernel will unmap this page later.
1511	 */
1512	pte = (pt_entry_t)vtopte(KERNBASE + (1 << PAGE_SHIFT));
1513	*pte = (1 << PAGE_SHIFT) | PG_RW | PG_V;
1514
1515	/*
1516	 * get memory map with INT 15:E820
1517	 */
1518	vmc.npages = 0;
1519	smap = (void *)vm86_addpage(&vmc, 1, KERNBASE + (1 << PAGE_SHIFT));
1520	vm86_getptr(&vmc, (vm_offset_t)smap, &vmf.vmf_es, &vmf.vmf_di);
1521
1522	physmap_idx = 0;
1523	vmf.vmf_ebx = 0;
1524	do {
1525		vmf.vmf_eax = 0xE820;
1526		vmf.vmf_edx = SMAP_SIG;
1527		vmf.vmf_ecx = sizeof(struct bios_smap);
1528		i = vm86_datacall(0x15, &vmf, &vmc);
1529		if (i || vmf.vmf_eax != SMAP_SIG)
1530			break;
1531		if (boothowto & RB_VERBOSE)
1532			printf("SMAP type=%02x base=%08x %08x len=%08x %08x\n",
1533				smap->type,
1534				*(u_int32_t *)((char *)&smap->base + 4),
1535				(u_int32_t)smap->base,
1536				*(u_int32_t *)((char *)&smap->length + 4),
1537				(u_int32_t)smap->length);
1538
1539		if (smap->type != 0x01)
1540			goto next_run;
1541
1542		if (smap->length == 0)
1543			goto next_run;
1544
1545		if (smap->base >= 0xffffffff) {
1546			printf("%uK of memory above 4GB ignored\n",
1547			    (u_int)(smap->length / 1024));
1548			goto next_run;
1549		}
1550
1551		for (i = 0; i <= physmap_idx; i += 2) {
1552			if (smap->base < physmap[i + 1]) {
1553				if (boothowto & RB_VERBOSE)
1554					printf(
1555	"Overlapping or non-montonic memory region, ignoring second region\n");
1556				goto next_run;
1557			}
1558		}
1559
1560		if (smap->base == physmap[physmap_idx + 1]) {
1561			physmap[physmap_idx + 1] += smap->length;
1562			goto next_run;
1563		}
1564
1565		physmap_idx += 2;
1566		if (physmap_idx == PHYSMAP_SIZE) {
1567			printf(
1568		"Too many segments in the physical address map, giving up\n");
1569			break;
1570		}
1571		physmap[physmap_idx] = smap->base;
1572		physmap[physmap_idx + 1] = smap->base + smap->length;
1573next_run:
1574	} while (vmf.vmf_ebx != 0);
1575
1576	if (physmap[1] != 0)
1577		goto physmap_done;
1578
1579	/*
1580	 * If we failed above, try memory map with INT 15:E801
1581	 */
1582	vmf.vmf_ax = 0xE801;
1583	if (vm86_intcall(0x15, &vmf) == 0) {
1584		extmem = vmf.vmf_cx + vmf.vmf_dx * 64;
1585	} else {
1586#if 0
1587		vmf.vmf_ah = 0x88;
1588		vm86_intcall(0x15, &vmf);
1589		extmem = vmf.vmf_ax;
1590#else
1591		/*
1592		 * Prefer the RTC value for extended memory.
1593		 */
1594		extmem = rtcin(RTC_EXTLO) + (rtcin(RTC_EXTHI) << 8);
1595#endif
1596	}
1597
1598	/*
1599	 * Special hack for chipsets that still remap the 384k hole when
1600	 * there's 16MB of memory - this really confuses people that
1601	 * are trying to use bus mastering ISA controllers with the
1602	 * "16MB limit"; they only have 16MB, but the remapping puts
1603	 * them beyond the limit.
1604	 *
1605	 * If extended memory is between 15-16MB (16-17MB phys address range),
1606	 *	chop it to 15MB.
1607	 */
1608	if ((extmem > 15 * 1024) && (extmem < 16 * 1024))
1609		extmem = 15 * 1024;
1610
1611	physmap[0] = 0;
1612	physmap[1] = basemem * 1024;
1613	physmap_idx = 2;
1614	physmap[physmap_idx] = 0x100000;
1615	physmap[physmap_idx + 1] = physmap[physmap_idx] + extmem * 1024;
1616
1617physmap_done:
1618	/*
1619	 * Now, physmap contains a map of physical memory.
1620	 */
1621
1622#ifdef SMP
1623	/* make hole for AP bootstrap code */
1624	physmap[1] = mp_bootaddress(physmap[1] / 1024);
1625
1626	/* look for the MP hardware - needed for apic addresses */
1627	mp_probe();
1628#endif
1629
1630	/*
1631	 * Maxmem isn't the "maximum memory", it's one larger than the
1632	 * highest page of the physical address space.  It should be
1633	 * called something like "Maxphyspage".  We may adjust this
1634	 * based on ``hw.physmem'' and the results of the memory test.
1635	 */
1636	Maxmem = atop(physmap[physmap_idx + 1]);
1637
1638#ifdef MAXMEM
1639	Maxmem = MAXMEM / 4;
1640#endif
1641
1642	/*
1643	 * hw.maxmem is a size in bytes; we also allow k, m, and g suffixes
1644	 * for the appropriate modifiers.  This overrides MAXMEM.
1645	 */
1646	if ((cp = getenv("hw.physmem")) != NULL) {
1647		u_int64_t AllowMem, sanity;
1648		char *ep;
1649
1650		sanity = AllowMem = strtouq(cp, &ep, 0);
1651		if ((ep != cp) && (*ep != 0)) {
1652			switch(*ep) {
1653			case 'g':
1654			case 'G':
1655				AllowMem <<= 10;
1656			case 'm':
1657			case 'M':
1658				AllowMem <<= 10;
1659			case 'k':
1660			case 'K':
1661				AllowMem <<= 10;
1662				break;
1663			default:
1664				AllowMem = sanity = 0;
1665			}
1666			if (AllowMem < sanity)
1667				AllowMem = 0;
1668		}
1669		if (AllowMem == 0)
1670			printf("Ignoring invalid memory size of '%s'\n", cp);
1671		else
1672			Maxmem = atop(AllowMem);
1673	}
1674
1675	if (atop(physmap[physmap_idx + 1]) != Maxmem &&
1676	    (boothowto & RB_VERBOSE))
1677		printf("Physical memory use set to %uK\n", Maxmem * 4);
1678
1679	/*
1680	 * If Maxmem has been increased beyond what the system has detected,
1681	 * extend the last memory segment to the new limit.
1682	 */
1683	if (atop(physmap[physmap_idx + 1]) < Maxmem)
1684		physmap[physmap_idx + 1] = ptoa(Maxmem);
1685
1686	/* call pmap initialization to make new kernel address space */
1687	pmap_bootstrap(first, 0);
1688
1689	/*
1690	 * Size up each available chunk of physical memory.
1691	 */
1692	physmap[0] = PAGE_SIZE;		/* mask off page 0 */
1693	pa_indx = 0;
1694	phys_avail[pa_indx++] = physmap[0];
1695	phys_avail[pa_indx] = physmap[0];
1696#if 0
1697	pte = (pt_entry_t)vtopte(KERNBASE);
1698#else
1699	pte = (pt_entry_t)CMAP1;
1700#endif
1701
1702	/*
1703	 * physmap is in bytes, so when converting to page boundaries,
1704	 * round up the start address and round down the end address.
1705	 */
1706	for (i = 0; i <= physmap_idx; i += 2) {
1707		vm_offset_t end;
1708
1709		end = ptoa(Maxmem);
1710		if (physmap[i + 1] < end)
1711			end = trunc_page(physmap[i + 1]);
1712		for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
1713			int tmp, page_bad;
1714#if 0
1715			int *ptr = 0;
1716#else
1717			int *ptr = (int *)CADDR1;
1718#endif
1719
1720			/*
1721			 * block out kernel memory as not available.
1722			 */
1723			if (pa >= 0x100000 && pa < first)
1724				continue;
1725
1726			page_bad = FALSE;
1727
1728			/*
1729			 * map page into kernel: valid, read/write,non-cacheable
1730			 */
1731			*pte = pa | PG_V | PG_RW | PG_N;
1732			invltlb();
1733
1734			tmp = *(int *)ptr;
1735			/*
1736			 * Test for alternating 1's and 0's
1737			 */
1738			*(volatile int *)ptr = 0xaaaaaaaa;
1739			if (*(volatile int *)ptr != 0xaaaaaaaa) {
1740				page_bad = TRUE;
1741			}
1742			/*
1743			 * Test for alternating 0's and 1's
1744			 */
1745			*(volatile int *)ptr = 0x55555555;
1746			if (*(volatile int *)ptr != 0x55555555) {
1747			page_bad = TRUE;
1748			}
1749			/*
1750			 * Test for all 1's
1751			 */
1752			*(volatile int *)ptr = 0xffffffff;
1753			if (*(volatile int *)ptr != 0xffffffff) {
1754				page_bad = TRUE;
1755			}
1756			/*
1757			 * Test for all 0's
1758			 */
1759			*(volatile int *)ptr = 0x0;
1760			if (*(volatile int *)ptr != 0x0) {
1761				page_bad = TRUE;
1762			}
1763			/*
1764			 * Restore original value.
1765			 */
1766			*(int *)ptr = tmp;
1767
1768			/*
1769			 * Adjust array of valid/good pages.
1770			 */
1771			if (page_bad == TRUE) {
1772				continue;
1773			}
1774			/*
1775			 * If this good page is a continuation of the
1776			 * previous set of good pages, then just increase
1777			 * the end pointer. Otherwise start a new chunk.
1778			 * Note that "end" points one higher than end,
1779			 * making the range >= start and < end.
1780			 * If we're also doing a speculative memory
1781			 * test and we at or past the end, bump up Maxmem
1782			 * so that we keep going. The first bad page
1783			 * will terminate the loop.
1784			 */
1785			if (phys_avail[pa_indx] == pa) {
1786				phys_avail[pa_indx] += PAGE_SIZE;
1787			} else {
1788				pa_indx++;
1789				if (pa_indx == PHYS_AVAIL_ARRAY_END) {
1790					printf("Too many holes in the physical address space, giving up\n");
1791					pa_indx--;
1792					break;
1793				}
1794				phys_avail[pa_indx++] = pa;	/* start */
1795				phys_avail[pa_indx] = pa + PAGE_SIZE;	/* end */
1796			}
1797			physmem++;
1798		}
1799	}
1800	*pte = 0;
1801	invltlb();
1802
1803	/*
1804	 * XXX
1805	 * The last chunk must contain at least one page plus the message
1806	 * buffer to avoid complicating other code (message buffer address
1807	 * calculation, etc.).
1808	 */
1809	while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1810	    round_page(MSGBUF_SIZE) >= phys_avail[pa_indx]) {
1811		physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1812		phys_avail[pa_indx--] = 0;
1813		phys_avail[pa_indx--] = 0;
1814	}
1815
1816	Maxmem = atop(phys_avail[pa_indx]);
1817
1818	/* Trim off space for the message buffer. */
1819	phys_avail[pa_indx] -= round_page(MSGBUF_SIZE);
1820
1821	avail_end = phys_avail[pa_indx];
1822}
1823
1824void
1825init386(first)
1826	int first;
1827{
1828	int x;
1829	struct gate_descriptor *gdp;
1830	int gsel_tss;
1831#ifndef SMP
1832	/* table descriptors - used to load tables by microp */
1833	struct region_descriptor r_gdt, r_idt;
1834#endif
1835	int off;
1836
1837	proc0.p_addr = proc0paddr;
1838
1839	atdevbase = ISA_HOLE_START + KERNBASE;
1840
1841	if (bootinfo.bi_modulep) {
1842		preload_metadata = (caddr_t)bootinfo.bi_modulep + KERNBASE;
1843		preload_bootstrap_relocate(KERNBASE);
1844	} else {
1845		printf("WARNING: loader(8) metadata is missing!\n");
1846	}
1847	if (bootinfo.bi_envp)
1848		kern_envp = (caddr_t)bootinfo.bi_envp + KERNBASE;
1849
1850	/*
1851	 * make gdt memory segments, the code segment goes up to end of the
1852	 * page with etext in it, the data segment goes to the end of
1853	 * the address space
1854	 */
1855	/*
1856	 * XXX text protection is temporarily (?) disabled.  The limit was
1857	 * i386_btop(round_page(etext)) - 1.
1858	 */
1859	gdt_segs[GCODE_SEL].ssd_limit = i386_btop(0) - 1;
1860	gdt_segs[GDATA_SEL].ssd_limit = i386_btop(0) - 1;
1861#ifdef SMP
1862	gdt_segs[GPRIV_SEL].ssd_limit =
1863		i386_btop(sizeof(struct privatespace)) - 1;
1864	gdt_segs[GPRIV_SEL].ssd_base = (int) &SMP_prvspace[0];
1865	gdt_segs[GPROC0_SEL].ssd_base =
1866		(int) &SMP_prvspace[0].globaldata.gd_common_tss;
1867	SMP_prvspace[0].globaldata.gd_prvspace = &SMP_prvspace[0];
1868#else
1869	gdt_segs[GPRIV_SEL].ssd_limit = i386_btop(0) - 1;
1870	gdt_segs[GPROC0_SEL].ssd_base = (int) &common_tss;
1871#endif
1872
1873	for (x = 0; x < NGDT; x++) {
1874#ifdef BDE_DEBUGGER
1875		/* avoid overwriting db entries with APM ones */
1876		if (x >= GAPMCODE32_SEL && x <= GAPMDATA_SEL)
1877			continue;
1878#endif
1879		ssdtosd(&gdt_segs[x], &gdt[x].sd);
1880	}
1881
1882	r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
1883	r_gdt.rd_base =  (int) gdt;
1884	lgdt(&r_gdt);
1885
1886	/* setup curproc so that mutexes work */
1887	PCPU_SET(curproc, &proc0);
1888
1889	/* make ldt memory segments */
1890	/*
1891	 * The data segment limit must not cover the user area because we
1892	 * don't want the user area to be writable in copyout() etc. (page
1893	 * level protection is lost in kernel mode on 386's).  Also, we
1894	 * don't want the user area to be writable directly (page level
1895	 * protection of the user area is not available on 486's with
1896	 * CR0_WP set, because there is no user-read/kernel-write mode).
1897	 *
1898	 * XXX - VM_MAXUSER_ADDRESS is an end address, not a max.  And it
1899	 * should be spelled ...MAX_USER...
1900	 */
1901#define VM_END_USER_RW_ADDRESS	VM_MAXUSER_ADDRESS
1902	/*
1903	 * The code segment limit has to cover the user area until we move
1904	 * the signal trampoline out of the user area.  This is safe because
1905	 * the code segment cannot be written to directly.
1906	 */
1907#define VM_END_USER_R_ADDRESS	(VM_END_USER_RW_ADDRESS + UPAGES * PAGE_SIZE)
1908	ldt_segs[LUCODE_SEL].ssd_limit = i386_btop(VM_END_USER_R_ADDRESS) - 1;
1909	ldt_segs[LUDATA_SEL].ssd_limit = i386_btop(VM_END_USER_RW_ADDRESS) - 1;
1910	for (x = 0; x < sizeof ldt_segs / sizeof ldt_segs[0]; x++)
1911		ssdtosd(&ldt_segs[x], &ldt[x].sd);
1912
1913	_default_ldt = GSEL(GLDT_SEL, SEL_KPL);
1914	lldt(_default_ldt);
1915#ifdef USER_LDT
1916	PCPU_SET(currentldt, _default_ldt);
1917#endif
1918
1919	/* exceptions */
1920	for (x = 0; x < NIDT; x++)
1921		setidt(x, &IDTVEC(rsvd), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1922	setidt(0, &IDTVEC(div),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1923	setidt(1, &IDTVEC(dbg),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1924	setidt(2, &IDTVEC(nmi),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1925 	setidt(3, &IDTVEC(bpt),  SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1926	setidt(4, &IDTVEC(ofl),  SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1927	setidt(5, &IDTVEC(bnd),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1928	setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1929	setidt(7, &IDTVEC(dna),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1930	setidt(8, 0,  SDT_SYSTASKGT, SEL_KPL, GSEL(GPANIC_SEL, SEL_KPL));
1931	setidt(9, &IDTVEC(fpusegm),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1932	setidt(10, &IDTVEC(tss),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1933	setidt(11, &IDTVEC(missing),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1934	setidt(12, &IDTVEC(stk),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1935	setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1936	setidt(14, &IDTVEC(page),  SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1937	setidt(15, &IDTVEC(rsvd),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1938	setidt(16, &IDTVEC(fpu),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1939	setidt(17, &IDTVEC(align), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1940	setidt(18, &IDTVEC(mchk),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1941 	setidt(0x80, &IDTVEC(int0x80_syscall),
1942			SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1943
1944	r_idt.rd_limit = sizeof(idt0) - 1;
1945	r_idt.rd_base = (int) idt;
1946	lidt(&r_idt);
1947
1948	/*
1949	 * We need this mutex before the console probe.
1950	 */
1951	mtx_init(&clock_lock, "clk interrupt lock", MTX_SPIN);
1952
1953	/*
1954	 * Initialize the console before we print anything out.
1955	 */
1956	cninit();
1957
1958#include	"isa.h"
1959#if	NISA >0
1960	isa_defaultirq();
1961#endif
1962
1963	/*
1964	 * Giant is used early for at least debugger traps and unexpected traps.
1965	 */
1966	mtx_init(&Giant, "Giant", MTX_DEF);
1967
1968#ifdef DDB
1969	kdb_init();
1970	if (boothowto & RB_KDB)
1971		Debugger("Boot flags requested debugger");
1972#endif
1973
1974	finishidentcpu();	/* Final stage of CPU initialization */
1975	setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1976	setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1977	initializecpu();	/* Initialize CPU registers */
1978
1979	/* make an initial tss so cpu can get interrupt stack on syscall! */
1980	common_tss.tss_esp0 = (int) proc0.p_addr + UPAGES*PAGE_SIZE - 16;
1981	common_tss.tss_ss0 = GSEL(GDATA_SEL, SEL_KPL);
1982	gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1983	private_tss = 0;
1984	tss_gdt = &gdt[GPROC0_SEL].sd;
1985	common_tssd = *tss_gdt;
1986	common_tss.tss_ioopt = (sizeof common_tss) << 16;
1987	ltr(gsel_tss);
1988
1989	dblfault_tss.tss_esp = dblfault_tss.tss_esp0 = dblfault_tss.tss_esp1 =
1990	    dblfault_tss.tss_esp2 = (int) &dblfault_stack[sizeof(dblfault_stack)];
1991	dblfault_tss.tss_ss = dblfault_tss.tss_ss0 = dblfault_tss.tss_ss1 =
1992	    dblfault_tss.tss_ss2 = GSEL(GDATA_SEL, SEL_KPL);
1993	dblfault_tss.tss_cr3 = (int)IdlePTD;
1994	dblfault_tss.tss_eip = (int) dblfault_handler;
1995	dblfault_tss.tss_eflags = PSL_KERNEL;
1996	dblfault_tss.tss_ds = dblfault_tss.tss_es =
1997	    dblfault_tss.tss_gs = GSEL(GDATA_SEL, SEL_KPL);
1998	dblfault_tss.tss_fs = GSEL(GPRIV_SEL, SEL_KPL);
1999	dblfault_tss.tss_cs = GSEL(GCODE_SEL, SEL_KPL);
2000	dblfault_tss.tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
2001
2002	vm86_initialize();
2003	getmemsize(first);
2004
2005	/* now running on new page tables, configured,and u/iom is accessible */
2006
2007	/* Map the message buffer. */
2008	for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
2009		pmap_kenter((vm_offset_t)msgbufp + off, avail_end + off);
2010
2011	msgbufinit(msgbufp, MSGBUF_SIZE);
2012
2013	/* make a call gate to reenter kernel with */
2014	gdp = &ldt[LSYS5CALLS_SEL].gd;
2015
2016	x = (int) &IDTVEC(syscall);
2017	gdp->gd_looffset = x++;
2018	gdp->gd_selector = GSEL(GCODE_SEL,SEL_KPL);
2019	gdp->gd_stkcpy = 1;
2020	gdp->gd_type = SDT_SYS386CGT;
2021	gdp->gd_dpl = SEL_UPL;
2022	gdp->gd_p = 1;
2023	gdp->gd_hioffset = ((int) &IDTVEC(syscall)) >>16;
2024
2025	/* XXX does this work? */
2026	ldt[LBSDICALLS_SEL] = ldt[LSYS5CALLS_SEL];
2027	ldt[LSOL26CALLS_SEL] = ldt[LSYS5CALLS_SEL];
2028
2029	/* transfer to user mode */
2030
2031	_ucodesel = LSEL(LUCODE_SEL, SEL_UPL);
2032	_udatasel = LSEL(LUDATA_SEL, SEL_UPL);
2033
2034	/* setup proc 0's pcb */
2035	proc0.p_addr->u_pcb.pcb_flags = 0;
2036	proc0.p_addr->u_pcb.pcb_cr3 = (int)IdlePTD;
2037	proc0.p_addr->u_pcb.pcb_schednest = 0;
2038	proc0.p_addr->u_pcb.pcb_ext = 0;
2039	proc0.p_md.md_regs = &proc0_tf;
2040}
2041
2042#if defined(I586_CPU) && !defined(NO_F00F_HACK)
2043static void f00f_hack(void *unused);
2044SYSINIT(f00f_hack, SI_SUB_INTRINSIC, SI_ORDER_FIRST, f00f_hack, NULL);
2045
2046static void
2047f00f_hack(void *unused) {
2048	struct gate_descriptor *new_idt;
2049#ifndef SMP
2050	struct region_descriptor r_idt;
2051#endif
2052	vm_offset_t tmp;
2053
2054	if (!has_f00f_bug)
2055		return;
2056
2057	printf("Intel Pentium detected, installing workaround for F00F bug\n");
2058
2059	r_idt.rd_limit = sizeof(idt0) - 1;
2060
2061	tmp = kmem_alloc(kernel_map, PAGE_SIZE * 2);
2062	if (tmp == 0)
2063		panic("kmem_alloc returned 0");
2064	if (((unsigned int)tmp & (PAGE_SIZE-1)) != 0)
2065		panic("kmem_alloc returned non-page-aligned memory");
2066	/* Put the first seven entries in the lower page */
2067	new_idt = (struct gate_descriptor*)(tmp + PAGE_SIZE - (7*8));
2068	bcopy(idt, new_idt, sizeof(idt0));
2069	r_idt.rd_base = (int)new_idt;
2070	lidt(&r_idt);
2071	idt = new_idt;
2072	if (vm_map_protect(kernel_map, tmp, tmp + PAGE_SIZE,
2073			   VM_PROT_READ, FALSE) != KERN_SUCCESS)
2074		panic("vm_map_protect failed");
2075	return;
2076}
2077#endif /* defined(I586_CPU) && !NO_F00F_HACK */
2078
2079int
2080ptrace_set_pc(p, addr)
2081	struct proc *p;
2082	unsigned long addr;
2083{
2084	p->p_md.md_regs->tf_eip = addr;
2085	return (0);
2086}
2087
2088int
2089ptrace_single_step(p)
2090	struct proc *p;
2091{
2092	p->p_md.md_regs->tf_eflags |= PSL_T;
2093	return (0);
2094}
2095
2096int ptrace_read_u_check(p, addr, len)
2097	struct proc *p;
2098	vm_offset_t addr;
2099	size_t len;
2100{
2101	vm_offset_t gap;
2102
2103	if ((vm_offset_t) (addr + len) < addr)
2104		return EPERM;
2105	if ((vm_offset_t) (addr + len) <= sizeof(struct user))
2106		return 0;
2107
2108	gap = (char *) p->p_md.md_regs - (char *) p->p_addr;
2109
2110	if ((vm_offset_t) addr < gap)
2111		return EPERM;
2112	if ((vm_offset_t) (addr + len) <=
2113	    (vm_offset_t) (gap + sizeof(struct trapframe)))
2114		return 0;
2115	return EPERM;
2116}
2117
2118int ptrace_write_u(p, off, data)
2119	struct proc *p;
2120	vm_offset_t off;
2121	long data;
2122{
2123	struct trapframe frame_copy;
2124	vm_offset_t min;
2125	struct trapframe *tp;
2126
2127	/*
2128	 * Privileged kernel state is scattered all over the user area.
2129	 * Only allow write access to parts of regs and to fpregs.
2130	 */
2131	min = (char *)p->p_md.md_regs - (char *)p->p_addr;
2132	if (off >= min && off <= min + sizeof(struct trapframe) - sizeof(int)) {
2133		tp = p->p_md.md_regs;
2134		frame_copy = *tp;
2135		*(int *)((char *)&frame_copy + (off - min)) = data;
2136		if (!EFL_SECURE(frame_copy.tf_eflags, tp->tf_eflags) ||
2137		    !CS_SECURE(frame_copy.tf_cs))
2138			return (EINVAL);
2139		*(int*)((char *)p->p_addr + off) = data;
2140		return (0);
2141	}
2142	min = offsetof(struct user, u_pcb) + offsetof(struct pcb, pcb_savefpu);
2143	if (off >= min && off <= min + sizeof(struct save87) - sizeof(int)) {
2144		*(int*)((char *)p->p_addr + off) = data;
2145		return (0);
2146	}
2147	return (EFAULT);
2148}
2149
2150int
2151fill_regs(p, regs)
2152	struct proc *p;
2153	struct reg *regs;
2154{
2155	struct pcb *pcb;
2156	struct trapframe *tp;
2157
2158	tp = p->p_md.md_regs;
2159	regs->r_fs = tp->tf_fs;
2160	regs->r_es = tp->tf_es;
2161	regs->r_ds = tp->tf_ds;
2162	regs->r_edi = tp->tf_edi;
2163	regs->r_esi = tp->tf_esi;
2164	regs->r_ebp = tp->tf_ebp;
2165	regs->r_ebx = tp->tf_ebx;
2166	regs->r_edx = tp->tf_edx;
2167	regs->r_ecx = tp->tf_ecx;
2168	regs->r_eax = tp->tf_eax;
2169	regs->r_eip = tp->tf_eip;
2170	regs->r_cs = tp->tf_cs;
2171	regs->r_eflags = tp->tf_eflags;
2172	regs->r_esp = tp->tf_esp;
2173	regs->r_ss = tp->tf_ss;
2174	pcb = &p->p_addr->u_pcb;
2175	regs->r_gs = pcb->pcb_gs;
2176	return (0);
2177}
2178
2179int
2180set_regs(p, regs)
2181	struct proc *p;
2182	struct reg *regs;
2183{
2184	struct pcb *pcb;
2185	struct trapframe *tp;
2186
2187	tp = p->p_md.md_regs;
2188	if (!EFL_SECURE(regs->r_eflags, tp->tf_eflags) ||
2189	    !CS_SECURE(regs->r_cs))
2190		return (EINVAL);
2191	tp->tf_fs = regs->r_fs;
2192	tp->tf_es = regs->r_es;
2193	tp->tf_ds = regs->r_ds;
2194	tp->tf_edi = regs->r_edi;
2195	tp->tf_esi = regs->r_esi;
2196	tp->tf_ebp = regs->r_ebp;
2197	tp->tf_ebx = regs->r_ebx;
2198	tp->tf_edx = regs->r_edx;
2199	tp->tf_ecx = regs->r_ecx;
2200	tp->tf_eax = regs->r_eax;
2201	tp->tf_eip = regs->r_eip;
2202	tp->tf_cs = regs->r_cs;
2203	tp->tf_eflags = regs->r_eflags;
2204	tp->tf_esp = regs->r_esp;
2205	tp->tf_ss = regs->r_ss;
2206	pcb = &p->p_addr->u_pcb;
2207	pcb->pcb_gs = regs->r_gs;
2208	return (0);
2209}
2210
2211int
2212fill_fpregs(p, fpregs)
2213	struct proc *p;
2214	struct fpreg *fpregs;
2215{
2216	bcopy(&p->p_addr->u_pcb.pcb_savefpu, fpregs, sizeof *fpregs);
2217	return (0);
2218}
2219
2220int
2221set_fpregs(p, fpregs)
2222	struct proc *p;
2223	struct fpreg *fpregs;
2224{
2225	bcopy(fpregs, &p->p_addr->u_pcb.pcb_savefpu, sizeof *fpregs);
2226	return (0);
2227}
2228
2229int
2230fill_dbregs(p, dbregs)
2231	struct proc *p;
2232	struct dbreg *dbregs;
2233{
2234	struct pcb *pcb;
2235
2236	pcb = &p->p_addr->u_pcb;
2237	dbregs->dr0 = pcb->pcb_dr0;
2238	dbregs->dr1 = pcb->pcb_dr1;
2239	dbregs->dr2 = pcb->pcb_dr2;
2240	dbregs->dr3 = pcb->pcb_dr3;
2241	dbregs->dr4 = 0;
2242	dbregs->dr5 = 0;
2243	dbregs->dr6 = pcb->pcb_dr6;
2244	dbregs->dr7 = pcb->pcb_dr7;
2245	return (0);
2246}
2247
2248int
2249set_dbregs(p, dbregs)
2250	struct proc *p;
2251	struct dbreg *dbregs;
2252{
2253	struct pcb *pcb;
2254	int i;
2255	u_int32_t mask1, mask2;
2256
2257	/*
2258	 * Don't let an illegal value for dr7 get set.  Specifically,
2259	 * check for undefined settings.  Setting these bit patterns
2260	 * result in undefined behaviour and can lead to an unexpected
2261	 * TRCTRAP.
2262	 */
2263	for (i = 0, mask1 = 0x3<<16, mask2 = 0x2<<16; i < 8;
2264	     i++, mask1 <<= 2, mask2 <<= 2)
2265		if ((dbregs->dr7 & mask1) == mask2)
2266			return (EINVAL);
2267
2268	if (dbregs->dr7 & 0x0000fc00)
2269		return (EINVAL);
2270
2271
2272
2273	pcb = &p->p_addr->u_pcb;
2274
2275	/*
2276	 * Don't let a process set a breakpoint that is not within the
2277	 * process's address space.  If a process could do this, it
2278	 * could halt the system by setting a breakpoint in the kernel
2279	 * (if ddb was enabled).  Thus, we need to check to make sure
2280	 * that no breakpoints are being enabled for addresses outside
2281	 * process's address space, unless, perhaps, we were called by
2282	 * uid 0.
2283	 *
2284	 * XXX - what about when the watched area of the user's
2285	 * address space is written into from within the kernel
2286	 * ... wouldn't that still cause a breakpoint to be generated
2287	 * from within kernel mode?
2288	 */
2289
2290	if (p->p_ucred->cr_uid != 0) {
2291		if (dbregs->dr7 & 0x3) {
2292			/* dr0 is enabled */
2293			if (dbregs->dr0 >= VM_MAXUSER_ADDRESS)
2294				return (EINVAL);
2295		}
2296
2297		if (dbregs->dr7 & (0x3<<2)) {
2298			/* dr1 is enabled */
2299			if (dbregs->dr1 >= VM_MAXUSER_ADDRESS)
2300				return (EINVAL);
2301		}
2302
2303		if (dbregs->dr7 & (0x3<<4)) {
2304			/* dr2 is enabled */
2305			if (dbregs->dr2 >= VM_MAXUSER_ADDRESS)
2306       				return (EINVAL);
2307		}
2308
2309		if (dbregs->dr7 & (0x3<<6)) {
2310			/* dr3 is enabled */
2311			if (dbregs->dr3 >= VM_MAXUSER_ADDRESS)
2312				return (EINVAL);
2313		}
2314	}
2315
2316	pcb->pcb_dr0 = dbregs->dr0;
2317	pcb->pcb_dr1 = dbregs->dr1;
2318	pcb->pcb_dr2 = dbregs->dr2;
2319	pcb->pcb_dr3 = dbregs->dr3;
2320	pcb->pcb_dr6 = dbregs->dr6;
2321	pcb->pcb_dr7 = dbregs->dr7;
2322
2323	pcb->pcb_flags |= PCB_DBREGS;
2324
2325	return (0);
2326}
2327
2328/*
2329 * Return > 0 if a hardware breakpoint has been hit, and the
2330 * breakpoint was in user space.  Return 0, otherwise.
2331 */
2332int
2333user_dbreg_trap(void)
2334{
2335        u_int32_t dr7, dr6; /* debug registers dr6 and dr7 */
2336        u_int32_t bp;       /* breakpoint bits extracted from dr6 */
2337        int nbp;            /* number of breakpoints that triggered */
2338        caddr_t addr[4];    /* breakpoint addresses */
2339        int i;
2340
2341        dr7 = rdr7();
2342        if ((dr7 & 0x000000ff) == 0) {
2343                /*
2344                 * all GE and LE bits in the dr7 register are zero,
2345                 * thus the trap couldn't have been caused by the
2346                 * hardware debug registers
2347                 */
2348                return 0;
2349        }
2350
2351        nbp = 0;
2352        dr6 = rdr6();
2353        bp = dr6 & 0x0000000f;
2354
2355        if (!bp) {
2356                /*
2357                 * None of the breakpoint bits are set meaning this
2358                 * trap was not caused by any of the debug registers
2359                 */
2360                return 0;
2361        }
2362
2363        /*
2364         * at least one of the breakpoints were hit, check to see
2365         * which ones and if any of them are user space addresses
2366         */
2367
2368        if (bp & 0x01) {
2369                addr[nbp++] = (caddr_t)rdr0();
2370        }
2371        if (bp & 0x02) {
2372                addr[nbp++] = (caddr_t)rdr1();
2373        }
2374        if (bp & 0x04) {
2375                addr[nbp++] = (caddr_t)rdr2();
2376        }
2377        if (bp & 0x08) {
2378                addr[nbp++] = (caddr_t)rdr3();
2379        }
2380
2381        for (i=0; i<nbp; i++) {
2382                if (addr[i] <
2383                    (caddr_t)VM_MAXUSER_ADDRESS) {
2384                        /*
2385                         * addr[i] is in user space
2386                         */
2387                        return nbp;
2388                }
2389        }
2390
2391        /*
2392         * None of the breakpoints are in user space.
2393         */
2394        return 0;
2395}
2396
2397
2398#ifndef DDB
2399void
2400Debugger(const char *msg)
2401{
2402	printf("Debugger(\"%s\") called.\n", msg);
2403}
2404#endif /* no DDB */
2405
2406#include <sys/disklabel.h>
2407
2408/*
2409 * Determine the size of the transfer, and make sure it is
2410 * within the boundaries of the partition. Adjust transfer
2411 * if needed, and signal errors or early completion.
2412 */
2413int
2414bounds_check_with_label(struct bio *bp, struct disklabel *lp, int wlabel)
2415{
2416        struct partition *p = lp->d_partitions + dkpart(bp->bio_dev);
2417        int labelsect = lp->d_partitions[0].p_offset;
2418        int maxsz = p->p_size,
2419                sz = (bp->bio_bcount + DEV_BSIZE - 1) >> DEV_BSHIFT;
2420
2421        /* overwriting disk label ? */
2422        /* XXX should also protect bootstrap in first 8K */
2423        if (bp->bio_blkno + p->p_offset <= LABELSECTOR + labelsect &&
2424#if LABELSECTOR != 0
2425            bp->bio_blkno + p->p_offset + sz > LABELSECTOR + labelsect &&
2426#endif
2427            (bp->bio_cmd == BIO_WRITE) && wlabel == 0) {
2428                bp->bio_error = EROFS;
2429                goto bad;
2430        }
2431
2432#if     defined(DOSBBSECTOR) && defined(notyet)
2433        /* overwriting master boot record? */
2434        if (bp->bio_blkno + p->p_offset <= DOSBBSECTOR &&
2435            (bp->bio_cmd == BIO_WRITE) && wlabel == 0) {
2436                bp->bio_error = EROFS;
2437                goto bad;
2438        }
2439#endif
2440
2441        /* beyond partition? */
2442        if (bp->bio_blkno < 0 || bp->bio_blkno + sz > maxsz) {
2443                /* if exactly at end of disk, return an EOF */
2444                if (bp->bio_blkno == maxsz) {
2445                        bp->bio_resid = bp->bio_bcount;
2446                        return(0);
2447                }
2448                /* or truncate if part of it fits */
2449                sz = maxsz - bp->bio_blkno;
2450                if (sz <= 0) {
2451                        bp->bio_error = EINVAL;
2452                        goto bad;
2453                }
2454                bp->bio_bcount = sz << DEV_BSHIFT;
2455        }
2456
2457        bp->bio_pblkno = bp->bio_blkno + p->p_offset;
2458        return(1);
2459
2460bad:
2461        bp->bio_flags |= BIO_ERROR;
2462        return(-1);
2463}
2464
2465#ifdef DDB
2466
2467/*
2468 * Provide inb() and outb() as functions.  They are normally only
2469 * available as macros calling inlined functions, thus cannot be
2470 * called inside DDB.
2471 *
2472 * The actual code is stolen from <machine/cpufunc.h>, and de-inlined.
2473 */
2474
2475#undef inb
2476#undef outb
2477
2478/* silence compiler warnings */
2479u_char inb(u_int);
2480void outb(u_int, u_char);
2481
2482u_char
2483inb(u_int port)
2484{
2485	u_char	data;
2486	/*
2487	 * We use %%dx and not %1 here because i/o is done at %dx and not at
2488	 * %edx, while gcc generates inferior code (movw instead of movl)
2489	 * if we tell it to load (u_short) port.
2490	 */
2491	__asm __volatile("inb %%dx,%0" : "=a" (data) : "d" (port));
2492	return (data);
2493}
2494
2495void
2496outb(u_int port, u_char data)
2497{
2498	u_char	al;
2499	/*
2500	 * Use an unnecessary assignment to help gcc's register allocator.
2501	 * This make a large difference for gcc-1.40 and a tiny difference
2502	 * for gcc-2.6.0.  For gcc-1.40, al had to be ``asm("ax")'' for
2503	 * best results.  gcc-2.6.0 can't handle this.
2504	 */
2505	al = data;
2506	__asm __volatile("outb %0,%%dx" : : "a" (al), "d" (port));
2507}
2508
2509#endif /* DDB */
2510