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