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