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