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