machdep.c revision 290731
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: stable/10/sys/i386/i386/machdep.c 290731 2015-11-12 23:49:47Z jhb $");
42
43#include "opt_apic.h"
44#include "opt_atalk.h"
45#include "opt_atpic.h"
46#include "opt_compat.h"
47#include "opt_cpu.h"
48#include "opt_ddb.h"
49#include "opt_inet.h"
50#include "opt_ipx.h"
51#include "opt_isa.h"
52#include "opt_kstack_pages.h"
53#include "opt_maxmem.h"
54#include "opt_mp_watchdog.h"
55#include "opt_npx.h"
56#include "opt_perfmon.h"
57#include "opt_platform.h"
58#include "opt_xbox.h"
59#include "opt_kdtrace.h"
60
61#include <sys/param.h>
62#include <sys/proc.h>
63#include <sys/systm.h>
64#include <sys/bio.h>
65#include <sys/buf.h>
66#include <sys/bus.h>
67#include <sys/callout.h>
68#include <sys/cons.h>
69#include <sys/cpu.h>
70#include <sys/eventhandler.h>
71#include <sys/exec.h>
72#include <sys/imgact.h>
73#include <sys/kdb.h>
74#include <sys/kernel.h>
75#include <sys/ktr.h>
76#include <sys/linker.h>
77#include <sys/lock.h>
78#include <sys/malloc.h>
79#include <sys/memrange.h>
80#include <sys/msgbuf.h>
81#include <sys/mutex.h>
82#include <sys/pcpu.h>
83#include <sys/ptrace.h>
84#include <sys/reboot.h>
85#include <sys/rwlock.h>
86#include <sys/sched.h>
87#include <sys/signalvar.h>
88#ifdef SMP
89#include <sys/smp.h>
90#endif
91#include <sys/syscallsubr.h>
92#include <sys/sysctl.h>
93#include <sys/sysent.h>
94#include <sys/sysproto.h>
95#include <sys/ucontext.h>
96#include <sys/vmmeter.h>
97
98#include <vm/vm.h>
99#include <vm/vm_extern.h>
100#include <vm/vm_kern.h>
101#include <vm/vm_page.h>
102#include <vm/vm_map.h>
103#include <vm/vm_object.h>
104#include <vm/vm_pager.h>
105#include <vm/vm_param.h>
106
107#ifdef DDB
108#ifndef KDB
109#error KDB must be enabled in order for DDB to work!
110#endif
111#include <ddb/ddb.h>
112#include <ddb/db_sym.h>
113#endif
114
115#ifdef PC98
116#include <pc98/pc98/pc98_machdep.h>
117#else
118#include <isa/rtc.h>
119#endif
120
121#include <net/netisr.h>
122
123#include <machine/bootinfo.h>
124#include <machine/clock.h>
125#include <machine/cpu.h>
126#include <machine/cputypes.h>
127#include <machine/intr_machdep.h>
128#include <x86/mca.h>
129#include <machine/md_var.h>
130#include <machine/metadata.h>
131#include <machine/mp_watchdog.h>
132#include <machine/pc/bios.h>
133#include <machine/pcb.h>
134#include <machine/pcb_ext.h>
135#include <machine/proc.h>
136#include <machine/reg.h>
137#include <machine/sigframe.h>
138#include <machine/specialreg.h>
139#include <machine/vm86.h>
140#ifdef PERFMON
141#include <machine/perfmon.h>
142#endif
143#ifdef SMP
144#include <machine/smp.h>
145#endif
146#ifdef FDT
147#include <x86/fdt.h>
148#endif
149
150#ifdef DEV_APIC
151#include <machine/apicvar.h>
152#endif
153
154#ifdef DEV_ISA
155#include <x86/isa/icu.h>
156#endif
157
158#ifdef XBOX
159#include <machine/xbox.h>
160
161int arch_i386_is_xbox = 0;
162uint32_t arch_i386_xbox_memsize = 0;
163#endif
164
165#ifdef XEN
166/* XEN includes */
167#include <xen/xen-os.h>
168#include <xen/hypervisor.h>
169#include <machine/xen/xenvar.h>
170#include <machine/xen/xenfunc.h>
171#include <xen/xen_intr.h>
172
173void Xhypervisor_callback(void);
174void failsafe_callback(void);
175
176extern trap_info_t trap_table[];
177struct proc_ldt default_proc_ldt;
178extern int init_first;
179int running_xen = 1;
180extern unsigned long physfree;
181#endif /* XEN */
182
183/* Sanity check for __curthread() */
184CTASSERT(offsetof(struct pcpu, pc_curthread) == 0);
185
186extern register_t init386(int first);
187extern void dblfault_handler(void);
188
189#define	CS_SECURE(cs)		(ISPL(cs) == SEL_UPL)
190#define	EFL_SECURE(ef, oef)	((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
191
192#if !defined(CPU_DISABLE_SSE) && defined(I686_CPU)
193#define CPU_ENABLE_SSE
194#endif
195
196static void cpu_startup(void *);
197static void fpstate_drop(struct thread *td);
198static void get_fpcontext(struct thread *td, mcontext_t *mcp,
199    char *xfpusave, size_t xfpusave_len);
200static int  set_fpcontext(struct thread *td, mcontext_t *mcp,
201    char *xfpustate, size_t xfpustate_len);
202#ifdef CPU_ENABLE_SSE
203static void set_fpregs_xmm(struct save87 *, struct savexmm *);
204static void fill_fpregs_xmm(struct savexmm *, struct save87 *);
205#endif /* CPU_ENABLE_SSE */
206SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
207
208#ifdef DDB
209extern vm_offset_t ksym_start, ksym_end;
210#endif
211
212/* Intel ICH registers */
213#define ICH_PMBASE	0x400
214#define ICH_SMI_EN	ICH_PMBASE + 0x30
215
216int	_udatasel, _ucodesel;
217u_int	basemem;
218
219#ifdef PC98
220int	need_pre_dma_flush;	/* If 1, use wbinvd befor DMA transfer. */
221int	need_post_dma_flush;	/* If 1, use invd after DMA transfer. */
222
223static int	ispc98 = 1;
224SYSCTL_INT(_machdep, OID_AUTO, ispc98, CTLFLAG_RD, &ispc98, 0, "");
225#endif
226
227int cold = 1;
228
229#ifdef COMPAT_43
230static void osendsig(sig_t catcher, ksiginfo_t *, sigset_t *mask);
231#endif
232#ifdef COMPAT_FREEBSD4
233static void freebsd4_sendsig(sig_t catcher, ksiginfo_t *, sigset_t *mask);
234#endif
235
236long Maxmem = 0;
237long realmem = 0;
238
239#ifdef PAE
240FEATURE(pae, "Physical Address Extensions");
241#endif
242
243/*
244 * The number of PHYSMAP entries must be one less than the number of
245 * PHYSSEG entries because the PHYSMAP entry that spans the largest
246 * physical address that is accessible by ISA DMA is split into two
247 * PHYSSEG entries.
248 */
249#define	PHYSMAP_SIZE	(2 * (VM_PHYSSEG_MAX - 1))
250
251vm_paddr_t phys_avail[PHYSMAP_SIZE + 2];
252vm_paddr_t dump_avail[PHYSMAP_SIZE + 2];
253
254/* must be 2 less so 0 0 can signal end of chunks */
255#define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(phys_avail[0])) - 2)
256#define DUMP_AVAIL_ARRAY_END ((sizeof(dump_avail) / sizeof(dump_avail[0])) - 2)
257
258struct kva_md_info kmi;
259
260static struct trapframe proc0_tf;
261struct pcpu __pcpu[MAXCPU];
262
263struct mtx icu_lock;
264
265struct mem_range_softc mem_range_softc;
266
267static void
268cpu_startup(dummy)
269	void *dummy;
270{
271	uintmax_t memsize;
272	char *sysenv;
273
274#ifndef PC98
275	/*
276	 * On MacBooks, we need to disallow the legacy USB circuit to
277	 * generate an SMI# because this can cause several problems,
278	 * namely: incorrect CPU frequency detection and failure to
279	 * start the APs.
280	 * We do this by disabling a bit in the SMI_EN (SMI Control and
281	 * Enable register) of the Intel ICH LPC Interface Bridge.
282	 */
283	sysenv = getenv("smbios.system.product");
284	if (sysenv != NULL) {
285		if (strncmp(sysenv, "MacBook1,1", 10) == 0 ||
286		    strncmp(sysenv, "MacBook3,1", 10) == 0 ||
287		    strncmp(sysenv, "MacBook4,1", 10) == 0 ||
288		    strncmp(sysenv, "MacBookPro1,1", 13) == 0 ||
289		    strncmp(sysenv, "MacBookPro1,2", 13) == 0 ||
290		    strncmp(sysenv, "MacBookPro3,1", 13) == 0 ||
291		    strncmp(sysenv, "MacBookPro4,1", 13) == 0 ||
292		    strncmp(sysenv, "Macmini1,1", 10) == 0) {
293			if (bootverbose)
294				printf("Disabling LEGACY_USB_EN bit on "
295				    "Intel ICH.\n");
296			outl(ICH_SMI_EN, inl(ICH_SMI_EN) & ~0x8);
297		}
298		freeenv(sysenv);
299	}
300#endif /* !PC98 */
301
302	/*
303	 * Good {morning,afternoon,evening,night}.
304	 */
305	startrtclock();
306	printcpuinfo();
307	panicifcpuunsupported();
308#ifdef PERFMON
309	perfmon_init();
310#endif
311
312	/*
313	 * Display physical memory if SMBIOS reports reasonable amount.
314	 */
315	memsize = 0;
316	sysenv = getenv("smbios.memory.enabled");
317	if (sysenv != NULL) {
318		memsize = (uintmax_t)strtoul(sysenv, (char **)NULL, 10) << 10;
319		freeenv(sysenv);
320	}
321	if (memsize < ptoa((uintmax_t)cnt.v_free_count))
322		memsize = ptoa((uintmax_t)Maxmem);
323	printf("real memory  = %ju (%ju MB)\n", memsize, memsize >> 20);
324	realmem = atop(memsize);
325
326	/*
327	 * Display any holes after the first chunk of extended memory.
328	 */
329	if (bootverbose) {
330		int indx;
331
332		printf("Physical memory chunk(s):\n");
333		for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
334			vm_paddr_t size;
335
336			size = phys_avail[indx + 1] - phys_avail[indx];
337			printf(
338			    "0x%016jx - 0x%016jx, %ju bytes (%ju pages)\n",
339			    (uintmax_t)phys_avail[indx],
340			    (uintmax_t)phys_avail[indx + 1] - 1,
341			    (uintmax_t)size, (uintmax_t)size / PAGE_SIZE);
342		}
343	}
344
345	vm_ksubmap_init(&kmi);
346
347	printf("avail memory = %ju (%ju MB)\n",
348	    ptoa((uintmax_t)cnt.v_free_count),
349	    ptoa((uintmax_t)cnt.v_free_count) / 1048576);
350
351	/*
352	 * Set up buffers, so they can be used to read disk labels.
353	 */
354	bufinit();
355	vm_pager_bufferinit();
356#ifndef XEN
357	cpu_setregs();
358#endif
359}
360
361/*
362 * Send an interrupt to process.
363 *
364 * Stack is set up to allow sigcode stored
365 * at top to call routine, followed by call
366 * to sigreturn routine below.  After sigreturn
367 * resets the signal mask, the stack, and the
368 * frame pointer, it returns to the user
369 * specified pc, psl.
370 */
371#ifdef COMPAT_43
372static void
373osendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
374{
375	struct osigframe sf, *fp;
376	struct proc *p;
377	struct thread *td;
378	struct sigacts *psp;
379	struct trapframe *regs;
380	int sig;
381	int oonstack;
382
383	td = curthread;
384	p = td->td_proc;
385	PROC_LOCK_ASSERT(p, MA_OWNED);
386	sig = ksi->ksi_signo;
387	psp = p->p_sigacts;
388	mtx_assert(&psp->ps_mtx, MA_OWNED);
389	regs = td->td_frame;
390	oonstack = sigonstack(regs->tf_esp);
391
392	/* Allocate space for the signal handler context. */
393	if ((td->td_pflags & TDP_ALTSTACK) && !oonstack &&
394	    SIGISMEMBER(psp->ps_sigonstack, sig)) {
395		fp = (struct osigframe *)(td->td_sigstk.ss_sp +
396		    td->td_sigstk.ss_size - sizeof(struct osigframe));
397#if defined(COMPAT_43)
398		td->td_sigstk.ss_flags |= SS_ONSTACK;
399#endif
400	} else
401		fp = (struct osigframe *)regs->tf_esp - 1;
402
403	/* Translate the signal if appropriate. */
404	if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
405		sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
406
407	/* Build the argument list for the signal handler. */
408	sf.sf_signum = sig;
409	sf.sf_scp = (register_t)&fp->sf_siginfo.si_sc;
410	bzero(&sf.sf_siginfo, sizeof(sf.sf_siginfo));
411	if (SIGISMEMBER(psp->ps_siginfo, sig)) {
412		/* Signal handler installed with SA_SIGINFO. */
413		sf.sf_arg2 = (register_t)&fp->sf_siginfo;
414		sf.sf_siginfo.si_signo = sig;
415		sf.sf_siginfo.si_code = ksi->ksi_code;
416		sf.sf_ahu.sf_action = (__osiginfohandler_t *)catcher;
417		sf.sf_addr = 0;
418	} else {
419		/* Old FreeBSD-style arguments. */
420		sf.sf_arg2 = ksi->ksi_code;
421		sf.sf_addr = (register_t)ksi->ksi_addr;
422		sf.sf_ahu.sf_handler = catcher;
423	}
424	mtx_unlock(&psp->ps_mtx);
425	PROC_UNLOCK(p);
426
427	/* Save most if not all of trap frame. */
428	sf.sf_siginfo.si_sc.sc_eax = regs->tf_eax;
429	sf.sf_siginfo.si_sc.sc_ebx = regs->tf_ebx;
430	sf.sf_siginfo.si_sc.sc_ecx = regs->tf_ecx;
431	sf.sf_siginfo.si_sc.sc_edx = regs->tf_edx;
432	sf.sf_siginfo.si_sc.sc_esi = regs->tf_esi;
433	sf.sf_siginfo.si_sc.sc_edi = regs->tf_edi;
434	sf.sf_siginfo.si_sc.sc_cs = regs->tf_cs;
435	sf.sf_siginfo.si_sc.sc_ds = regs->tf_ds;
436	sf.sf_siginfo.si_sc.sc_ss = regs->tf_ss;
437	sf.sf_siginfo.si_sc.sc_es = regs->tf_es;
438	sf.sf_siginfo.si_sc.sc_fs = regs->tf_fs;
439	sf.sf_siginfo.si_sc.sc_gs = rgs();
440	sf.sf_siginfo.si_sc.sc_isp = regs->tf_isp;
441
442	/* Build the signal context to be used by osigreturn(). */
443	sf.sf_siginfo.si_sc.sc_onstack = (oonstack) ? 1 : 0;
444	SIG2OSIG(*mask, sf.sf_siginfo.si_sc.sc_mask);
445	sf.sf_siginfo.si_sc.sc_sp = regs->tf_esp;
446	sf.sf_siginfo.si_sc.sc_fp = regs->tf_ebp;
447	sf.sf_siginfo.si_sc.sc_pc = regs->tf_eip;
448	sf.sf_siginfo.si_sc.sc_ps = regs->tf_eflags;
449	sf.sf_siginfo.si_sc.sc_trapno = regs->tf_trapno;
450	sf.sf_siginfo.si_sc.sc_err = regs->tf_err;
451
452	/*
453	 * If we're a vm86 process, we want to save the segment registers.
454	 * We also change eflags to be our emulated eflags, not the actual
455	 * eflags.
456	 */
457	if (regs->tf_eflags & PSL_VM) {
458		/* XXX confusing names: `tf' isn't a trapframe; `regs' is. */
459		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
460		struct vm86_kernel *vm86 = &td->td_pcb->pcb_ext->ext_vm86;
461
462		sf.sf_siginfo.si_sc.sc_gs = tf->tf_vm86_gs;
463		sf.sf_siginfo.si_sc.sc_fs = tf->tf_vm86_fs;
464		sf.sf_siginfo.si_sc.sc_es = tf->tf_vm86_es;
465		sf.sf_siginfo.si_sc.sc_ds = tf->tf_vm86_ds;
466
467		if (vm86->vm86_has_vme == 0)
468			sf.sf_siginfo.si_sc.sc_ps =
469			    (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
470			    (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
471
472		/* See sendsig() for comments. */
473		tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_VIF | PSL_VIP);
474	}
475
476	/*
477	 * Copy the sigframe out to the user's stack.
478	 */
479	if (copyout(&sf, fp, sizeof(*fp)) != 0) {
480#ifdef DEBUG
481		printf("process %ld has trashed its stack\n", (long)p->p_pid);
482#endif
483		PROC_LOCK(p);
484		sigexit(td, SIGILL);
485	}
486
487	regs->tf_esp = (int)fp;
488	if (p->p_sysent->sv_sigcode_base != 0) {
489		regs->tf_eip = p->p_sysent->sv_sigcode_base + szsigcode -
490		    szosigcode;
491	} else {
492		/* a.out sysentvec does not use shared page */
493		regs->tf_eip = p->p_sysent->sv_psstrings - szosigcode;
494	}
495	regs->tf_eflags &= ~(PSL_T | PSL_D);
496	regs->tf_cs = _ucodesel;
497	regs->tf_ds = _udatasel;
498	regs->tf_es = _udatasel;
499	regs->tf_fs = _udatasel;
500	load_gs(_udatasel);
501	regs->tf_ss = _udatasel;
502	PROC_LOCK(p);
503	mtx_lock(&psp->ps_mtx);
504}
505#endif /* COMPAT_43 */
506
507#ifdef COMPAT_FREEBSD4
508static void
509freebsd4_sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
510{
511	struct sigframe4 sf, *sfp;
512	struct proc *p;
513	struct thread *td;
514	struct sigacts *psp;
515	struct trapframe *regs;
516	int sig;
517	int oonstack;
518
519	td = curthread;
520	p = td->td_proc;
521	PROC_LOCK_ASSERT(p, MA_OWNED);
522	sig = ksi->ksi_signo;
523	psp = p->p_sigacts;
524	mtx_assert(&psp->ps_mtx, MA_OWNED);
525	regs = td->td_frame;
526	oonstack = sigonstack(regs->tf_esp);
527
528	/* Save user context. */
529	bzero(&sf, sizeof(sf));
530	sf.sf_uc.uc_sigmask = *mask;
531	sf.sf_uc.uc_stack = td->td_sigstk;
532	sf.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
533	    ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
534	sf.sf_uc.uc_mcontext.mc_onstack = (oonstack) ? 1 : 0;
535	sf.sf_uc.uc_mcontext.mc_gs = rgs();
536	bcopy(regs, &sf.sf_uc.uc_mcontext.mc_fs, sizeof(*regs));
537	bzero(sf.sf_uc.uc_mcontext.mc_fpregs,
538	    sizeof(sf.sf_uc.uc_mcontext.mc_fpregs));
539	bzero(sf.sf_uc.uc_mcontext.__spare__,
540	    sizeof(sf.sf_uc.uc_mcontext.__spare__));
541	bzero(sf.sf_uc.__spare__, sizeof(sf.sf_uc.__spare__));
542
543	/* Allocate space for the signal handler context. */
544	if ((td->td_pflags & TDP_ALTSTACK) != 0 && !oonstack &&
545	    SIGISMEMBER(psp->ps_sigonstack, sig)) {
546		sfp = (struct sigframe4 *)(td->td_sigstk.ss_sp +
547		    td->td_sigstk.ss_size - sizeof(struct sigframe4));
548#if defined(COMPAT_43)
549		td->td_sigstk.ss_flags |= SS_ONSTACK;
550#endif
551	} else
552		sfp = (struct sigframe4 *)regs->tf_esp - 1;
553
554	/* Translate the signal if appropriate. */
555	if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
556		sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
557
558	/* Build the argument list for the signal handler. */
559	sf.sf_signum = sig;
560	sf.sf_ucontext = (register_t)&sfp->sf_uc;
561	bzero(&sf.sf_si, sizeof(sf.sf_si));
562	if (SIGISMEMBER(psp->ps_siginfo, sig)) {
563		/* Signal handler installed with SA_SIGINFO. */
564		sf.sf_siginfo = (register_t)&sfp->sf_si;
565		sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
566
567		/* Fill in POSIX parts */
568		sf.sf_si.si_signo = sig;
569		sf.sf_si.si_code = ksi->ksi_code;
570		sf.sf_si.si_addr = ksi->ksi_addr;
571	} else {
572		/* Old FreeBSD-style arguments. */
573		sf.sf_siginfo = ksi->ksi_code;
574		sf.sf_addr = (register_t)ksi->ksi_addr;
575		sf.sf_ahu.sf_handler = catcher;
576	}
577	mtx_unlock(&psp->ps_mtx);
578	PROC_UNLOCK(p);
579
580	/*
581	 * If we're a vm86 process, we want to save the segment registers.
582	 * We also change eflags to be our emulated eflags, not the actual
583	 * eflags.
584	 */
585	if (regs->tf_eflags & PSL_VM) {
586		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
587		struct vm86_kernel *vm86 = &td->td_pcb->pcb_ext->ext_vm86;
588
589		sf.sf_uc.uc_mcontext.mc_gs = tf->tf_vm86_gs;
590		sf.sf_uc.uc_mcontext.mc_fs = tf->tf_vm86_fs;
591		sf.sf_uc.uc_mcontext.mc_es = tf->tf_vm86_es;
592		sf.sf_uc.uc_mcontext.mc_ds = tf->tf_vm86_ds;
593
594		if (vm86->vm86_has_vme == 0)
595			sf.sf_uc.uc_mcontext.mc_eflags =
596			    (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
597			    (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
598
599		/*
600		 * Clear PSL_NT to inhibit T_TSSFLT faults on return from
601		 * syscalls made by the signal handler.  This just avoids
602		 * wasting time for our lazy fixup of such faults.  PSL_NT
603		 * does nothing in vm86 mode, but vm86 programs can set it
604		 * almost legitimately in probes for old cpu types.
605		 */
606		tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_VIF | PSL_VIP);
607	}
608
609	/*
610	 * Copy the sigframe out to the user's stack.
611	 */
612	if (copyout(&sf, sfp, sizeof(*sfp)) != 0) {
613#ifdef DEBUG
614		printf("process %ld has trashed its stack\n", (long)p->p_pid);
615#endif
616		PROC_LOCK(p);
617		sigexit(td, SIGILL);
618	}
619
620	regs->tf_esp = (int)sfp;
621	regs->tf_eip = p->p_sysent->sv_sigcode_base + szsigcode -
622	    szfreebsd4_sigcode;
623	regs->tf_eflags &= ~(PSL_T | PSL_D);
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#endif	/* COMPAT_FREEBSD4 */
633
634void
635sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
636{
637	struct sigframe sf, *sfp;
638	struct proc *p;
639	struct thread *td;
640	struct sigacts *psp;
641	char *sp;
642	struct trapframe *regs;
643	struct segment_descriptor *sdp;
644	char *xfpusave;
645	size_t xfpusave_len;
646	int sig;
647	int oonstack;
648
649	td = curthread;
650	p = td->td_proc;
651	PROC_LOCK_ASSERT(p, MA_OWNED);
652	sig = ksi->ksi_signo;
653	psp = p->p_sigacts;
654	mtx_assert(&psp->ps_mtx, MA_OWNED);
655#ifdef COMPAT_FREEBSD4
656	if (SIGISMEMBER(psp->ps_freebsd4, sig)) {
657		freebsd4_sendsig(catcher, ksi, mask);
658		return;
659	}
660#endif
661#ifdef COMPAT_43
662	if (SIGISMEMBER(psp->ps_osigset, sig)) {
663		osendsig(catcher, ksi, mask);
664		return;
665	}
666#endif
667	regs = td->td_frame;
668	oonstack = sigonstack(regs->tf_esp);
669
670#ifdef CPU_ENABLE_SSE
671	if (cpu_max_ext_state_size > sizeof(union savefpu) && use_xsave) {
672		xfpusave_len = cpu_max_ext_state_size - sizeof(union savefpu);
673		xfpusave = __builtin_alloca(xfpusave_len);
674	} else {
675#else
676	{
677#endif
678		xfpusave_len = 0;
679		xfpusave = NULL;
680	}
681
682	/* Save user context. */
683	bzero(&sf, sizeof(sf));
684	sf.sf_uc.uc_sigmask = *mask;
685	sf.sf_uc.uc_stack = td->td_sigstk;
686	sf.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
687	    ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
688	sf.sf_uc.uc_mcontext.mc_onstack = (oonstack) ? 1 : 0;
689	sf.sf_uc.uc_mcontext.mc_gs = rgs();
690	bcopy(regs, &sf.sf_uc.uc_mcontext.mc_fs, sizeof(*regs));
691	sf.sf_uc.uc_mcontext.mc_len = sizeof(sf.sf_uc.uc_mcontext); /* magic */
692	get_fpcontext(td, &sf.sf_uc.uc_mcontext, xfpusave, xfpusave_len);
693	fpstate_drop(td);
694	/*
695	 * Unconditionally fill the fsbase and gsbase into the mcontext.
696	 */
697	sdp = &td->td_pcb->pcb_fsd;
698	sf.sf_uc.uc_mcontext.mc_fsbase = sdp->sd_hibase << 24 |
699	    sdp->sd_lobase;
700	sdp = &td->td_pcb->pcb_gsd;
701	sf.sf_uc.uc_mcontext.mc_gsbase = sdp->sd_hibase << 24 |
702	    sdp->sd_lobase;
703	bzero(sf.sf_uc.uc_mcontext.mc_spare2,
704	    sizeof(sf.sf_uc.uc_mcontext.mc_spare2));
705	bzero(sf.sf_uc.__spare__, sizeof(sf.sf_uc.__spare__));
706
707	/* Allocate space for the signal handler context. */
708	if ((td->td_pflags & TDP_ALTSTACK) != 0 && !oonstack &&
709	    SIGISMEMBER(psp->ps_sigonstack, sig)) {
710		sp = td->td_sigstk.ss_sp + td->td_sigstk.ss_size;
711#if defined(COMPAT_43)
712		td->td_sigstk.ss_flags |= SS_ONSTACK;
713#endif
714	} else
715		sp = (char *)regs->tf_esp - 128;
716	if (xfpusave != NULL) {
717		sp -= xfpusave_len;
718		sp = (char *)((unsigned int)sp & ~0x3F);
719		sf.sf_uc.uc_mcontext.mc_xfpustate = (register_t)sp;
720	}
721	sp -= sizeof(struct sigframe);
722
723	/* Align to 16 bytes. */
724	sfp = (struct sigframe *)((unsigned int)sp & ~0xF);
725
726	/* Translate the signal if appropriate. */
727	if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
728		sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
729
730	/* Build the argument list for the signal handler. */
731	sf.sf_signum = sig;
732	sf.sf_ucontext = (register_t)&sfp->sf_uc;
733	bzero(&sf.sf_si, sizeof(sf.sf_si));
734	if (SIGISMEMBER(psp->ps_siginfo, sig)) {
735		/* Signal handler installed with SA_SIGINFO. */
736		sf.sf_siginfo = (register_t)&sfp->sf_si;
737		sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
738
739		/* Fill in POSIX parts */
740		sf.sf_si = ksi->ksi_info;
741		sf.sf_si.si_signo = sig; /* maybe a translated signal */
742	} else {
743		/* Old FreeBSD-style arguments. */
744		sf.sf_siginfo = ksi->ksi_code;
745		sf.sf_addr = (register_t)ksi->ksi_addr;
746		sf.sf_ahu.sf_handler = catcher;
747	}
748	mtx_unlock(&psp->ps_mtx);
749	PROC_UNLOCK(p);
750
751	/*
752	 * If we're a vm86 process, we want to save the segment registers.
753	 * We also change eflags to be our emulated eflags, not the actual
754	 * eflags.
755	 */
756	if (regs->tf_eflags & PSL_VM) {
757		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
758		struct vm86_kernel *vm86 = &td->td_pcb->pcb_ext->ext_vm86;
759
760		sf.sf_uc.uc_mcontext.mc_gs = tf->tf_vm86_gs;
761		sf.sf_uc.uc_mcontext.mc_fs = tf->tf_vm86_fs;
762		sf.sf_uc.uc_mcontext.mc_es = tf->tf_vm86_es;
763		sf.sf_uc.uc_mcontext.mc_ds = tf->tf_vm86_ds;
764
765		if (vm86->vm86_has_vme == 0)
766			sf.sf_uc.uc_mcontext.mc_eflags =
767			    (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
768			    (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
769
770		/*
771		 * Clear PSL_NT to inhibit T_TSSFLT faults on return from
772		 * syscalls made by the signal handler.  This just avoids
773		 * wasting time for our lazy fixup of such faults.  PSL_NT
774		 * does nothing in vm86 mode, but vm86 programs can set it
775		 * almost legitimately in probes for old cpu types.
776		 */
777		tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_VIF | PSL_VIP);
778	}
779
780	/*
781	 * Copy the sigframe out to the user's stack.
782	 */
783	if (copyout(&sf, sfp, sizeof(*sfp)) != 0 ||
784	    (xfpusave != NULL && copyout(xfpusave,
785	    (void *)sf.sf_uc.uc_mcontext.mc_xfpustate, xfpusave_len)
786	    != 0)) {
787#ifdef DEBUG
788		printf("process %ld has trashed its stack\n", (long)p->p_pid);
789#endif
790		PROC_LOCK(p);
791		sigexit(td, SIGILL);
792	}
793
794	regs->tf_esp = (int)sfp;
795	regs->tf_eip = p->p_sysent->sv_sigcode_base;
796	if (regs->tf_eip == 0)
797		regs->tf_eip = p->p_sysent->sv_psstrings - szsigcode;
798	regs->tf_eflags &= ~(PSL_T | PSL_D);
799	regs->tf_cs = _ucodesel;
800	regs->tf_ds = _udatasel;
801	regs->tf_es = _udatasel;
802	regs->tf_fs = _udatasel;
803	regs->tf_ss = _udatasel;
804	PROC_LOCK(p);
805	mtx_lock(&psp->ps_mtx);
806}
807
808/*
809 * System call to cleanup state after a signal
810 * has been taken.  Reset signal mask and
811 * stack state from context left by sendsig (above).
812 * Return to previous pc and psl as specified by
813 * context left by sendsig. Check carefully to
814 * make sure that the user has not modified the
815 * state to gain improper privileges.
816 *
817 * MPSAFE
818 */
819#ifdef COMPAT_43
820int
821osigreturn(td, uap)
822	struct thread *td;
823	struct osigreturn_args /* {
824		struct osigcontext *sigcntxp;
825	} */ *uap;
826{
827	struct osigcontext sc;
828	struct trapframe *regs;
829	struct osigcontext *scp;
830	int eflags, error;
831	ksiginfo_t ksi;
832
833	regs = td->td_frame;
834	error = copyin(uap->sigcntxp, &sc, sizeof(sc));
835	if (error != 0)
836		return (error);
837	scp = &sc;
838	eflags = scp->sc_ps;
839	if (eflags & PSL_VM) {
840		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
841		struct vm86_kernel *vm86;
842
843		/*
844		 * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
845		 * set up the vm86 area, and we can't enter vm86 mode.
846		 */
847		if (td->td_pcb->pcb_ext == 0)
848			return (EINVAL);
849		vm86 = &td->td_pcb->pcb_ext->ext_vm86;
850		if (vm86->vm86_inited == 0)
851			return (EINVAL);
852
853		/* Go back to user mode if both flags are set. */
854		if ((eflags & PSL_VIP) && (eflags & PSL_VIF)) {
855			ksiginfo_init_trap(&ksi);
856			ksi.ksi_signo = SIGBUS;
857			ksi.ksi_code = BUS_OBJERR;
858			ksi.ksi_addr = (void *)regs->tf_eip;
859			trapsignal(td, &ksi);
860		}
861
862		if (vm86->vm86_has_vme) {
863			eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
864			    (eflags & VME_USERCHANGE) | PSL_VM;
865		} else {
866			vm86->vm86_eflags = eflags;	/* save VIF, VIP */
867			eflags = (tf->tf_eflags & ~VM_USERCHANGE) |
868			    (eflags & VM_USERCHANGE) | PSL_VM;
869		}
870		tf->tf_vm86_ds = scp->sc_ds;
871		tf->tf_vm86_es = scp->sc_es;
872		tf->tf_vm86_fs = scp->sc_fs;
873		tf->tf_vm86_gs = scp->sc_gs;
874		tf->tf_ds = _udatasel;
875		tf->tf_es = _udatasel;
876		tf->tf_fs = _udatasel;
877	} else {
878		/*
879		 * Don't allow users to change privileged or reserved flags.
880		 */
881		if (!EFL_SECURE(eflags, regs->tf_eflags)) {
882	    		return (EINVAL);
883		}
884
885		/*
886		 * Don't allow users to load a valid privileged %cs.  Let the
887		 * hardware check for invalid selectors, excess privilege in
888		 * other selectors, invalid %eip's and invalid %esp's.
889		 */
890		if (!CS_SECURE(scp->sc_cs)) {
891			ksiginfo_init_trap(&ksi);
892			ksi.ksi_signo = SIGBUS;
893			ksi.ksi_code = BUS_OBJERR;
894			ksi.ksi_trapno = T_PROTFLT;
895			ksi.ksi_addr = (void *)regs->tf_eip;
896			trapsignal(td, &ksi);
897			return (EINVAL);
898		}
899		regs->tf_ds = scp->sc_ds;
900		regs->tf_es = scp->sc_es;
901		regs->tf_fs = scp->sc_fs;
902	}
903
904	/* Restore remaining registers. */
905	regs->tf_eax = scp->sc_eax;
906	regs->tf_ebx = scp->sc_ebx;
907	regs->tf_ecx = scp->sc_ecx;
908	regs->tf_edx = scp->sc_edx;
909	regs->tf_esi = scp->sc_esi;
910	regs->tf_edi = scp->sc_edi;
911	regs->tf_cs = scp->sc_cs;
912	regs->tf_ss = scp->sc_ss;
913	regs->tf_isp = scp->sc_isp;
914	regs->tf_ebp = scp->sc_fp;
915	regs->tf_esp = scp->sc_sp;
916	regs->tf_eip = scp->sc_pc;
917	regs->tf_eflags = eflags;
918
919#if defined(COMPAT_43)
920	if (scp->sc_onstack & 1)
921		td->td_sigstk.ss_flags |= SS_ONSTACK;
922	else
923		td->td_sigstk.ss_flags &= ~SS_ONSTACK;
924#endif
925	kern_sigprocmask(td, SIG_SETMASK, (sigset_t *)&scp->sc_mask, NULL,
926	    SIGPROCMASK_OLD);
927	return (EJUSTRETURN);
928}
929#endif /* COMPAT_43 */
930
931#ifdef COMPAT_FREEBSD4
932/*
933 * MPSAFE
934 */
935int
936freebsd4_sigreturn(td, uap)
937	struct thread *td;
938	struct freebsd4_sigreturn_args /* {
939		const ucontext4 *sigcntxp;
940	} */ *uap;
941{
942	struct ucontext4 uc;
943	struct trapframe *regs;
944	struct ucontext4 *ucp;
945	int cs, eflags, error;
946	ksiginfo_t ksi;
947
948	error = copyin(uap->sigcntxp, &uc, sizeof(uc));
949	if (error != 0)
950		return (error);
951	ucp = &uc;
952	regs = td->td_frame;
953	eflags = ucp->uc_mcontext.mc_eflags;
954	if (eflags & PSL_VM) {
955		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
956		struct vm86_kernel *vm86;
957
958		/*
959		 * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
960		 * set up the vm86 area, and we can't enter vm86 mode.
961		 */
962		if (td->td_pcb->pcb_ext == 0)
963			return (EINVAL);
964		vm86 = &td->td_pcb->pcb_ext->ext_vm86;
965		if (vm86->vm86_inited == 0)
966			return (EINVAL);
967
968		/* Go back to user mode if both flags are set. */
969		if ((eflags & PSL_VIP) && (eflags & PSL_VIF)) {
970			ksiginfo_init_trap(&ksi);
971			ksi.ksi_signo = SIGBUS;
972			ksi.ksi_code = BUS_OBJERR;
973			ksi.ksi_addr = (void *)regs->tf_eip;
974			trapsignal(td, &ksi);
975		}
976		if (vm86->vm86_has_vme) {
977			eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
978			    (eflags & VME_USERCHANGE) | PSL_VM;
979		} else {
980			vm86->vm86_eflags = eflags;	/* save VIF, VIP */
981			eflags = (tf->tf_eflags & ~VM_USERCHANGE) |
982			    (eflags & VM_USERCHANGE) | PSL_VM;
983		}
984		bcopy(&ucp->uc_mcontext.mc_fs, tf, sizeof(struct trapframe));
985		tf->tf_eflags = eflags;
986		tf->tf_vm86_ds = tf->tf_ds;
987		tf->tf_vm86_es = tf->tf_es;
988		tf->tf_vm86_fs = tf->tf_fs;
989		tf->tf_vm86_gs = ucp->uc_mcontext.mc_gs;
990		tf->tf_ds = _udatasel;
991		tf->tf_es = _udatasel;
992		tf->tf_fs = _udatasel;
993	} else {
994		/*
995		 * Don't allow users to change privileged or reserved flags.
996		 */
997		if (!EFL_SECURE(eflags, regs->tf_eflags)) {
998			uprintf("pid %d (%s): freebsd4_sigreturn eflags = 0x%x\n",
999			    td->td_proc->p_pid, td->td_name, eflags);
1000	    		return (EINVAL);
1001		}
1002
1003		/*
1004		 * Don't allow users to load a valid privileged %cs.  Let the
1005		 * hardware check for invalid selectors, excess privilege in
1006		 * other selectors, invalid %eip's and invalid %esp's.
1007		 */
1008		cs = ucp->uc_mcontext.mc_cs;
1009		if (!CS_SECURE(cs)) {
1010			uprintf("pid %d (%s): freebsd4_sigreturn cs = 0x%x\n",
1011			    td->td_proc->p_pid, td->td_name, cs);
1012			ksiginfo_init_trap(&ksi);
1013			ksi.ksi_signo = SIGBUS;
1014			ksi.ksi_code = BUS_OBJERR;
1015			ksi.ksi_trapno = T_PROTFLT;
1016			ksi.ksi_addr = (void *)regs->tf_eip;
1017			trapsignal(td, &ksi);
1018			return (EINVAL);
1019		}
1020
1021		bcopy(&ucp->uc_mcontext.mc_fs, regs, sizeof(*regs));
1022	}
1023
1024#if defined(COMPAT_43)
1025	if (ucp->uc_mcontext.mc_onstack & 1)
1026		td->td_sigstk.ss_flags |= SS_ONSTACK;
1027	else
1028		td->td_sigstk.ss_flags &= ~SS_ONSTACK;
1029#endif
1030	kern_sigprocmask(td, SIG_SETMASK, &ucp->uc_sigmask, NULL, 0);
1031	return (EJUSTRETURN);
1032}
1033#endif	/* COMPAT_FREEBSD4 */
1034
1035/*
1036 * MPSAFE
1037 */
1038int
1039sys_sigreturn(td, uap)
1040	struct thread *td;
1041	struct sigreturn_args /* {
1042		const struct __ucontext *sigcntxp;
1043	} */ *uap;
1044{
1045	ucontext_t uc;
1046	struct proc *p;
1047	struct trapframe *regs;
1048	ucontext_t *ucp;
1049	char *xfpustate;
1050	size_t xfpustate_len;
1051	int cs, eflags, error, ret;
1052	ksiginfo_t ksi;
1053
1054	p = td->td_proc;
1055
1056	error = copyin(uap->sigcntxp, &uc, sizeof(uc));
1057	if (error != 0)
1058		return (error);
1059	ucp = &uc;
1060	if ((ucp->uc_mcontext.mc_flags & ~_MC_FLAG_MASK) != 0) {
1061		uprintf("pid %d (%s): sigreturn mc_flags %x\n", p->p_pid,
1062		    td->td_name, ucp->uc_mcontext.mc_flags);
1063		return (EINVAL);
1064	}
1065	regs = td->td_frame;
1066	eflags = ucp->uc_mcontext.mc_eflags;
1067	if (eflags & PSL_VM) {
1068		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
1069		struct vm86_kernel *vm86;
1070
1071		/*
1072		 * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
1073		 * set up the vm86 area, and we can't enter vm86 mode.
1074		 */
1075		if (td->td_pcb->pcb_ext == 0)
1076			return (EINVAL);
1077		vm86 = &td->td_pcb->pcb_ext->ext_vm86;
1078		if (vm86->vm86_inited == 0)
1079			return (EINVAL);
1080
1081		/* Go back to user mode if both flags are set. */
1082		if ((eflags & PSL_VIP) && (eflags & PSL_VIF)) {
1083			ksiginfo_init_trap(&ksi);
1084			ksi.ksi_signo = SIGBUS;
1085			ksi.ksi_code = BUS_OBJERR;
1086			ksi.ksi_addr = (void *)regs->tf_eip;
1087			trapsignal(td, &ksi);
1088		}
1089
1090		if (vm86->vm86_has_vme) {
1091			eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
1092			    (eflags & VME_USERCHANGE) | PSL_VM;
1093		} else {
1094			vm86->vm86_eflags = eflags;	/* save VIF, VIP */
1095			eflags = (tf->tf_eflags & ~VM_USERCHANGE) |
1096			    (eflags & VM_USERCHANGE) | PSL_VM;
1097		}
1098		bcopy(&ucp->uc_mcontext.mc_fs, tf, sizeof(struct trapframe));
1099		tf->tf_eflags = eflags;
1100		tf->tf_vm86_ds = tf->tf_ds;
1101		tf->tf_vm86_es = tf->tf_es;
1102		tf->tf_vm86_fs = tf->tf_fs;
1103		tf->tf_vm86_gs = ucp->uc_mcontext.mc_gs;
1104		tf->tf_ds = _udatasel;
1105		tf->tf_es = _udatasel;
1106		tf->tf_fs = _udatasel;
1107	} else {
1108		/*
1109		 * Don't allow users to change privileged or reserved flags.
1110		 */
1111		if (!EFL_SECURE(eflags, regs->tf_eflags)) {
1112			uprintf("pid %d (%s): sigreturn eflags = 0x%x\n",
1113			    td->td_proc->p_pid, td->td_name, eflags);
1114	    		return (EINVAL);
1115		}
1116
1117		/*
1118		 * Don't allow users to load a valid privileged %cs.  Let the
1119		 * hardware check for invalid selectors, excess privilege in
1120		 * other selectors, invalid %eip's and invalid %esp's.
1121		 */
1122		cs = ucp->uc_mcontext.mc_cs;
1123		if (!CS_SECURE(cs)) {
1124			uprintf("pid %d (%s): sigreturn cs = 0x%x\n",
1125			    td->td_proc->p_pid, td->td_name, cs);
1126			ksiginfo_init_trap(&ksi);
1127			ksi.ksi_signo = SIGBUS;
1128			ksi.ksi_code = BUS_OBJERR;
1129			ksi.ksi_trapno = T_PROTFLT;
1130			ksi.ksi_addr = (void *)regs->tf_eip;
1131			trapsignal(td, &ksi);
1132			return (EINVAL);
1133		}
1134
1135		if ((uc.uc_mcontext.mc_flags & _MC_HASFPXSTATE) != 0) {
1136			xfpustate_len = uc.uc_mcontext.mc_xfpustate_len;
1137			if (xfpustate_len > cpu_max_ext_state_size -
1138			    sizeof(union savefpu)) {
1139				uprintf(
1140			    "pid %d (%s): sigreturn xfpusave_len = 0x%zx\n",
1141				    p->p_pid, td->td_name, xfpustate_len);
1142				return (EINVAL);
1143			}
1144			xfpustate = __builtin_alloca(xfpustate_len);
1145			error = copyin((const void *)uc.uc_mcontext.mc_xfpustate,
1146			    xfpustate, xfpustate_len);
1147			if (error != 0) {
1148				uprintf(
1149	"pid %d (%s): sigreturn copying xfpustate failed\n",
1150				    p->p_pid, td->td_name);
1151				return (error);
1152			}
1153		} else {
1154			xfpustate = NULL;
1155			xfpustate_len = 0;
1156		}
1157		ret = set_fpcontext(td, &ucp->uc_mcontext, xfpustate,
1158		    xfpustate_len);
1159		if (ret != 0)
1160			return (ret);
1161		bcopy(&ucp->uc_mcontext.mc_fs, regs, sizeof(*regs));
1162	}
1163
1164#if defined(COMPAT_43)
1165	if (ucp->uc_mcontext.mc_onstack & 1)
1166		td->td_sigstk.ss_flags |= SS_ONSTACK;
1167	else
1168		td->td_sigstk.ss_flags &= ~SS_ONSTACK;
1169#endif
1170
1171	kern_sigprocmask(td, SIG_SETMASK, &ucp->uc_sigmask, NULL, 0);
1172	return (EJUSTRETURN);
1173}
1174
1175/*
1176 * Machine dependent boot() routine
1177 *
1178 * I haven't seen anything to put here yet
1179 * Possibly some stuff might be grafted back here from boot()
1180 */
1181void
1182cpu_boot(int howto)
1183{
1184}
1185
1186/*
1187 * Flush the D-cache for non-DMA I/O so that the I-cache can
1188 * be made coherent later.
1189 */
1190void
1191cpu_flush_dcache(void *ptr, size_t len)
1192{
1193	/* Not applicable */
1194}
1195
1196/* Get current clock frequency for the given cpu id. */
1197int
1198cpu_est_clockrate(int cpu_id, uint64_t *rate)
1199{
1200	uint64_t tsc1, tsc2;
1201	uint64_t acnt, mcnt, perf;
1202	register_t reg;
1203
1204	if (pcpu_find(cpu_id) == NULL || rate == NULL)
1205		return (EINVAL);
1206	if ((cpu_feature & CPUID_TSC) == 0)
1207		return (EOPNOTSUPP);
1208
1209	/*
1210	 * If TSC is P-state invariant and APERF/MPERF MSRs do not exist,
1211	 * DELAY(9) based logic fails.
1212	 */
1213	if (tsc_is_invariant && !tsc_perf_stat)
1214		return (EOPNOTSUPP);
1215
1216#ifdef SMP
1217	if (smp_cpus > 1) {
1218		/* Schedule ourselves on the indicated cpu. */
1219		thread_lock(curthread);
1220		sched_bind(curthread, cpu_id);
1221		thread_unlock(curthread);
1222	}
1223#endif
1224
1225	/* Calibrate by measuring a short delay. */
1226	reg = intr_disable();
1227	if (tsc_is_invariant) {
1228		wrmsr(MSR_MPERF, 0);
1229		wrmsr(MSR_APERF, 0);
1230		tsc1 = rdtsc();
1231		DELAY(1000);
1232		mcnt = rdmsr(MSR_MPERF);
1233		acnt = rdmsr(MSR_APERF);
1234		tsc2 = rdtsc();
1235		intr_restore(reg);
1236		perf = 1000 * acnt / mcnt;
1237		*rate = (tsc2 - tsc1) * perf;
1238	} else {
1239		tsc1 = rdtsc();
1240		DELAY(1000);
1241		tsc2 = rdtsc();
1242		intr_restore(reg);
1243		*rate = (tsc2 - tsc1) * 1000;
1244	}
1245
1246#ifdef SMP
1247	if (smp_cpus > 1) {
1248		thread_lock(curthread);
1249		sched_unbind(curthread);
1250		thread_unlock(curthread);
1251	}
1252#endif
1253
1254	return (0);
1255}
1256
1257#ifdef XEN
1258
1259static void
1260idle_block(void)
1261{
1262
1263	HYPERVISOR_sched_op(SCHEDOP_block, 0);
1264}
1265
1266void
1267cpu_halt(void)
1268{
1269	HYPERVISOR_shutdown(SHUTDOWN_poweroff);
1270}
1271
1272int scheduler_running;
1273
1274static void
1275cpu_idle_hlt(sbintime_t sbt)
1276{
1277
1278	scheduler_running = 1;
1279	enable_intr();
1280	idle_block();
1281}
1282
1283#else
1284/*
1285 * Shutdown the CPU as much as possible
1286 */
1287void
1288cpu_halt(void)
1289{
1290	for (;;)
1291		halt();
1292}
1293
1294#endif
1295
1296void (*cpu_idle_hook)(sbintime_t) = NULL;	/* ACPI idle hook. */
1297static int	cpu_ident_amdc1e = 0;	/* AMD C1E supported. */
1298static int	idle_mwait = 1;		/* Use MONITOR/MWAIT for short idle. */
1299TUNABLE_INT("machdep.idle_mwait", &idle_mwait);
1300SYSCTL_INT(_machdep, OID_AUTO, idle_mwait, CTLFLAG_RW, &idle_mwait,
1301    0, "Use MONITOR/MWAIT for short idle");
1302
1303#define	STATE_RUNNING	0x0
1304#define	STATE_MWAIT	0x1
1305#define	STATE_SLEEPING	0x2
1306
1307#ifndef PC98
1308static void
1309cpu_idle_acpi(sbintime_t sbt)
1310{
1311	int *state;
1312
1313	state = (int *)PCPU_PTR(monitorbuf);
1314	*state = STATE_SLEEPING;
1315
1316	/* See comments in cpu_idle_hlt(). */
1317	disable_intr();
1318	if (sched_runnable())
1319		enable_intr();
1320	else if (cpu_idle_hook)
1321		cpu_idle_hook(sbt);
1322	else
1323		__asm __volatile("sti; hlt");
1324	*state = STATE_RUNNING;
1325}
1326#endif /* !PC98 */
1327
1328#ifndef XEN
1329static void
1330cpu_idle_hlt(sbintime_t sbt)
1331{
1332	int *state;
1333
1334	state = (int *)PCPU_PTR(monitorbuf);
1335	*state = STATE_SLEEPING;
1336
1337	/*
1338	 * Since we may be in a critical section from cpu_idle(), if
1339	 * an interrupt fires during that critical section we may have
1340	 * a pending preemption.  If the CPU halts, then that thread
1341	 * may not execute until a later interrupt awakens the CPU.
1342	 * To handle this race, check for a runnable thread after
1343	 * disabling interrupts and immediately return if one is
1344	 * found.  Also, we must absolutely guarentee that hlt is
1345	 * the next instruction after sti.  This ensures that any
1346	 * interrupt that fires after the call to disable_intr() will
1347	 * immediately awaken the CPU from hlt.  Finally, please note
1348	 * that on x86 this works fine because of interrupts enabled only
1349	 * after the instruction following sti takes place, while IF is set
1350	 * to 1 immediately, allowing hlt instruction to acknowledge the
1351	 * interrupt.
1352	 */
1353	disable_intr();
1354	if (sched_runnable())
1355		enable_intr();
1356	else
1357		__asm __volatile("sti; hlt");
1358	*state = STATE_RUNNING;
1359}
1360#endif
1361
1362static void
1363cpu_idle_mwait(sbintime_t sbt)
1364{
1365	int *state;
1366
1367	state = (int *)PCPU_PTR(monitorbuf);
1368	*state = STATE_MWAIT;
1369
1370	/* See comments in cpu_idle_hlt(). */
1371	disable_intr();
1372	if (sched_runnable()) {
1373		enable_intr();
1374		*state = STATE_RUNNING;
1375		return;
1376	}
1377	cpu_monitor(state, 0, 0);
1378	if (*state == STATE_MWAIT)
1379		__asm __volatile("sti; mwait" : : "a" (MWAIT_C1), "c" (0));
1380	else
1381		enable_intr();
1382	*state = STATE_RUNNING;
1383}
1384
1385static void
1386cpu_idle_spin(sbintime_t sbt)
1387{
1388	int *state;
1389	int i;
1390
1391	state = (int *)PCPU_PTR(monitorbuf);
1392	*state = STATE_RUNNING;
1393
1394	/*
1395	 * The sched_runnable() call is racy but as long as there is
1396	 * a loop missing it one time will have just a little impact if any
1397	 * (and it is much better than missing the check at all).
1398	 */
1399	for (i = 0; i < 1000; i++) {
1400		if (sched_runnable())
1401			return;
1402		cpu_spinwait();
1403	}
1404}
1405
1406/*
1407 * C1E renders the local APIC timer dead, so we disable it by
1408 * reading the Interrupt Pending Message register and clearing
1409 * both C1eOnCmpHalt (bit 28) and SmiOnCmpHalt (bit 27).
1410 *
1411 * Reference:
1412 *   "BIOS and Kernel Developer's Guide for AMD NPT Family 0Fh Processors"
1413 *   #32559 revision 3.00+
1414 */
1415#define	MSR_AMDK8_IPM		0xc0010055
1416#define	AMDK8_SMIONCMPHALT	(1ULL << 27)
1417#define	AMDK8_C1EONCMPHALT	(1ULL << 28)
1418#define	AMDK8_CMPHALT		(AMDK8_SMIONCMPHALT | AMDK8_C1EONCMPHALT)
1419
1420static void
1421cpu_probe_amdc1e(void)
1422{
1423
1424	/*
1425	 * Detect the presence of C1E capability mostly on latest
1426	 * dual-cores (or future) k8 family.
1427	 */
1428	if (cpu_vendor_id == CPU_VENDOR_AMD &&
1429	    (cpu_id & 0x00000f00) == 0x00000f00 &&
1430	    (cpu_id & 0x0fff0000) >=  0x00040000) {
1431		cpu_ident_amdc1e = 1;
1432	}
1433}
1434
1435#if defined(PC98) || defined(XEN)
1436void (*cpu_idle_fn)(sbintime_t) = cpu_idle_hlt;
1437#else
1438void (*cpu_idle_fn)(sbintime_t) = cpu_idle_acpi;
1439#endif
1440
1441void
1442cpu_idle(int busy)
1443{
1444#ifndef XEN
1445	uint64_t msr;
1446#endif
1447	sbintime_t sbt = -1;
1448
1449	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d",
1450	    busy, curcpu);
1451#if defined(MP_WATCHDOG) && !defined(XEN)
1452	ap_watchdog(PCPU_GET(cpuid));
1453#endif
1454#ifndef XEN
1455	/* If we are busy - try to use fast methods. */
1456	if (busy) {
1457		if ((cpu_feature2 & CPUID2_MON) && idle_mwait) {
1458			cpu_idle_mwait(busy);
1459			goto out;
1460		}
1461	}
1462#endif
1463
1464	/* If we have time - switch timers into idle mode. */
1465	if (!busy) {
1466		critical_enter();
1467		sbt = cpu_idleclock();
1468	}
1469
1470#ifndef XEN
1471	/* Apply AMD APIC timer C1E workaround. */
1472	if (cpu_ident_amdc1e && cpu_disable_c3_sleep) {
1473		msr = rdmsr(MSR_AMDK8_IPM);
1474		if (msr & AMDK8_CMPHALT)
1475			wrmsr(MSR_AMDK8_IPM, msr & ~AMDK8_CMPHALT);
1476	}
1477#endif
1478
1479	/* Call main idle method. */
1480	cpu_idle_fn(sbt);
1481
1482	/* Switch timers mack into active mode. */
1483	if (!busy) {
1484		cpu_activeclock();
1485		critical_exit();
1486	}
1487#ifndef XEN
1488out:
1489#endif
1490	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done",
1491	    busy, curcpu);
1492}
1493
1494int
1495cpu_idle_wakeup(int cpu)
1496{
1497	struct pcpu *pcpu;
1498	int *state;
1499
1500	pcpu = pcpu_find(cpu);
1501	state = (int *)pcpu->pc_monitorbuf;
1502	/*
1503	 * This doesn't need to be atomic since missing the race will
1504	 * simply result in unnecessary IPIs.
1505	 */
1506	if (*state == STATE_SLEEPING)
1507		return (0);
1508	if (*state == STATE_MWAIT)
1509		*state = STATE_RUNNING;
1510	return (1);
1511}
1512
1513/*
1514 * Ordered by speed/power consumption.
1515 */
1516struct {
1517	void	*id_fn;
1518	char	*id_name;
1519} idle_tbl[] = {
1520	{ cpu_idle_spin, "spin" },
1521	{ cpu_idle_mwait, "mwait" },
1522	{ cpu_idle_hlt, "hlt" },
1523#ifndef PC98
1524	{ cpu_idle_acpi, "acpi" },
1525#endif
1526	{ NULL, NULL }
1527};
1528
1529static int
1530idle_sysctl_available(SYSCTL_HANDLER_ARGS)
1531{
1532	char *avail, *p;
1533	int error;
1534	int i;
1535
1536	avail = malloc(256, M_TEMP, M_WAITOK);
1537	p = avail;
1538	for (i = 0; idle_tbl[i].id_name != NULL; i++) {
1539		if (strstr(idle_tbl[i].id_name, "mwait") &&
1540		    (cpu_feature2 & CPUID2_MON) == 0)
1541			continue;
1542#ifndef PC98
1543		if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
1544		    cpu_idle_hook == NULL)
1545			continue;
1546#endif
1547		p += sprintf(p, "%s%s", p != avail ? ", " : "",
1548		    idle_tbl[i].id_name);
1549	}
1550	error = sysctl_handle_string(oidp, avail, 0, req);
1551	free(avail, M_TEMP);
1552	return (error);
1553}
1554
1555SYSCTL_PROC(_machdep, OID_AUTO, idle_available, CTLTYPE_STRING | CTLFLAG_RD,
1556    0, 0, idle_sysctl_available, "A", "list of available idle functions");
1557
1558static int
1559idle_sysctl(SYSCTL_HANDLER_ARGS)
1560{
1561	char buf[16];
1562	int error;
1563	char *p;
1564	int i;
1565
1566	p = "unknown";
1567	for (i = 0; idle_tbl[i].id_name != NULL; i++) {
1568		if (idle_tbl[i].id_fn == cpu_idle_fn) {
1569			p = idle_tbl[i].id_name;
1570			break;
1571		}
1572	}
1573	strncpy(buf, p, sizeof(buf));
1574	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
1575	if (error != 0 || req->newptr == NULL)
1576		return (error);
1577	for (i = 0; idle_tbl[i].id_name != NULL; i++) {
1578		if (strstr(idle_tbl[i].id_name, "mwait") &&
1579		    (cpu_feature2 & CPUID2_MON) == 0)
1580			continue;
1581#ifndef PC98
1582		if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
1583		    cpu_idle_hook == NULL)
1584			continue;
1585#endif
1586		if (strcmp(idle_tbl[i].id_name, buf))
1587			continue;
1588		cpu_idle_fn = idle_tbl[i].id_fn;
1589		return (0);
1590	}
1591	return (EINVAL);
1592}
1593
1594SYSCTL_PROC(_machdep, OID_AUTO, idle, CTLTYPE_STRING | CTLFLAG_RW, 0, 0,
1595    idle_sysctl, "A", "currently selected idle function");
1596
1597/*
1598 * Reset registers to default values on exec.
1599 */
1600void
1601exec_setregs(struct thread *td, struct image_params *imgp, u_long stack)
1602{
1603	struct trapframe *regs = td->td_frame;
1604	struct pcb *pcb = td->td_pcb;
1605
1606	/* Reset pc->pcb_gs and %gs before possibly invalidating it. */
1607	pcb->pcb_gs = _udatasel;
1608	load_gs(_udatasel);
1609
1610	mtx_lock_spin(&dt_lock);
1611	if (td->td_proc->p_md.md_ldt)
1612		user_ldt_free(td);
1613	else
1614		mtx_unlock_spin(&dt_lock);
1615
1616	bzero((char *)regs, sizeof(struct trapframe));
1617	regs->tf_eip = imgp->entry_addr;
1618	regs->tf_esp = stack;
1619	regs->tf_eflags = PSL_USER | (regs->tf_eflags & PSL_T);
1620	regs->tf_ss = _udatasel;
1621	regs->tf_ds = _udatasel;
1622	regs->tf_es = _udatasel;
1623	regs->tf_fs = _udatasel;
1624	regs->tf_cs = _ucodesel;
1625
1626	/* PS_STRINGS value for BSD/OS binaries.  It is 0 for non-BSD/OS. */
1627	regs->tf_ebx = imgp->ps_strings;
1628
1629        /*
1630         * Reset the hardware debug registers if they were in use.
1631         * They won't have any meaning for the newly exec'd process.
1632         */
1633        if (pcb->pcb_flags & PCB_DBREGS) {
1634                pcb->pcb_dr0 = 0;
1635                pcb->pcb_dr1 = 0;
1636                pcb->pcb_dr2 = 0;
1637                pcb->pcb_dr3 = 0;
1638                pcb->pcb_dr6 = 0;
1639                pcb->pcb_dr7 = 0;
1640                if (pcb == curpcb) {
1641		        /*
1642			 * Clear the debug registers on the running
1643			 * CPU, otherwise they will end up affecting
1644			 * the next process we switch to.
1645			 */
1646		        reset_dbregs();
1647                }
1648		pcb->pcb_flags &= ~PCB_DBREGS;
1649        }
1650
1651	pcb->pcb_initial_npxcw = __INITIAL_NPXCW__;
1652
1653	/*
1654	 * Drop the FP state if we hold it, so that the process gets a
1655	 * clean FP state if it uses the FPU again.
1656	 */
1657	fpstate_drop(td);
1658
1659	/*
1660	 * XXX - Linux emulator
1661	 * Make sure sure edx is 0x0 on entry. Linux binaries depend
1662	 * on it.
1663	 */
1664	td->td_retval[1] = 0;
1665}
1666
1667void
1668cpu_setregs(void)
1669{
1670	unsigned int cr0;
1671
1672	cr0 = rcr0();
1673
1674	/*
1675	 * CR0_MP, CR0_NE and CR0_TS are set for NPX (FPU) support:
1676	 *
1677	 * Prepare to trap all ESC (i.e., NPX) instructions and all WAIT
1678	 * instructions.  We must set the CR0_MP bit and use the CR0_TS
1679	 * bit to control the trap, because setting the CR0_EM bit does
1680	 * not cause WAIT instructions to trap.  It's important to trap
1681	 * WAIT instructions - otherwise the "wait" variants of no-wait
1682	 * control instructions would degenerate to the "no-wait" variants
1683	 * after FP context switches but work correctly otherwise.  It's
1684	 * particularly important to trap WAITs when there is no NPX -
1685	 * otherwise the "wait" variants would always degenerate.
1686	 *
1687	 * Try setting CR0_NE to get correct error reporting on 486DX's.
1688	 * Setting it should fail or do nothing on lesser processors.
1689	 */
1690	cr0 |= CR0_MP | CR0_NE | CR0_TS | CR0_WP | CR0_AM;
1691	load_cr0(cr0);
1692	load_gs(_udatasel);
1693}
1694
1695u_long bootdev;		/* not a struct cdev *- encoding is different */
1696SYSCTL_ULONG(_machdep, OID_AUTO, guessed_bootdev,
1697	CTLFLAG_RD, &bootdev, 0, "Maybe the Boot device (not in struct cdev *format)");
1698
1699static char bootmethod[16] = "BIOS";
1700SYSCTL_STRING(_machdep, OID_AUTO, bootmethod, CTLFLAG_RD, bootmethod, 0,
1701    "System firmware boot method");
1702
1703/*
1704 * Initialize 386 and configure to run kernel
1705 */
1706
1707/*
1708 * Initialize segments & interrupt table
1709 */
1710
1711int _default_ldt;
1712
1713#ifdef XEN
1714union descriptor *gdt;
1715union descriptor *ldt;
1716#else
1717union descriptor gdt[NGDT * MAXCPU];	/* global descriptor table */
1718union descriptor ldt[NLDT];		/* local descriptor table */
1719#endif
1720static struct gate_descriptor idt0[NIDT];
1721struct gate_descriptor *idt = &idt0[0];	/* interrupt descriptor table */
1722struct region_descriptor r_gdt, r_idt;	/* table descriptors */
1723struct mtx dt_lock;			/* lock for GDT and LDT */
1724
1725static struct i386tss dblfault_tss;
1726static char dblfault_stack[PAGE_SIZE];
1727
1728extern  vm_offset_t	proc0kstack;
1729
1730
1731/*
1732 * software prototypes -- in more palatable form.
1733 *
1734 * GCODE_SEL through GUDATA_SEL must be in this order for syscall/sysret
1735 * GUFS_SEL and GUGS_SEL must be in this order (swtch.s knows it)
1736 */
1737struct soft_segment_descriptor gdt_segs[] = {
1738/* GNULL_SEL	0 Null Descriptor */
1739{	.ssd_base = 0x0,
1740	.ssd_limit = 0x0,
1741	.ssd_type = 0,
1742	.ssd_dpl = SEL_KPL,
1743	.ssd_p = 0,
1744	.ssd_xx = 0, .ssd_xx1 = 0,
1745	.ssd_def32 = 0,
1746	.ssd_gran = 0		},
1747/* GPRIV_SEL	1 SMP Per-Processor Private Data Descriptor */
1748{	.ssd_base = 0x0,
1749	.ssd_limit = 0xfffff,
1750	.ssd_type = SDT_MEMRWA,
1751	.ssd_dpl = SEL_KPL,
1752	.ssd_p = 1,
1753	.ssd_xx = 0, .ssd_xx1 = 0,
1754	.ssd_def32 = 1,
1755	.ssd_gran = 1		},
1756/* GUFS_SEL	2 %fs Descriptor for user */
1757{	.ssd_base = 0x0,
1758	.ssd_limit = 0xfffff,
1759	.ssd_type = SDT_MEMRWA,
1760	.ssd_dpl = SEL_UPL,
1761	.ssd_p = 1,
1762	.ssd_xx = 0, .ssd_xx1 = 0,
1763	.ssd_def32 = 1,
1764	.ssd_gran = 1		},
1765/* GUGS_SEL	3 %gs Descriptor for user */
1766{	.ssd_base = 0x0,
1767	.ssd_limit = 0xfffff,
1768	.ssd_type = SDT_MEMRWA,
1769	.ssd_dpl = SEL_UPL,
1770	.ssd_p = 1,
1771	.ssd_xx = 0, .ssd_xx1 = 0,
1772	.ssd_def32 = 1,
1773	.ssd_gran = 1		},
1774/* GCODE_SEL	4 Code Descriptor for kernel */
1775{	.ssd_base = 0x0,
1776	.ssd_limit = 0xfffff,
1777	.ssd_type = SDT_MEMERA,
1778	.ssd_dpl = SEL_KPL,
1779	.ssd_p = 1,
1780	.ssd_xx = 0, .ssd_xx1 = 0,
1781	.ssd_def32 = 1,
1782	.ssd_gran = 1		},
1783/* GDATA_SEL	5 Data Descriptor for kernel */
1784{	.ssd_base = 0x0,
1785	.ssd_limit = 0xfffff,
1786	.ssd_type = SDT_MEMRWA,
1787	.ssd_dpl = SEL_KPL,
1788	.ssd_p = 1,
1789	.ssd_xx = 0, .ssd_xx1 = 0,
1790	.ssd_def32 = 1,
1791	.ssd_gran = 1		},
1792/* GUCODE_SEL	6 Code Descriptor for user */
1793{	.ssd_base = 0x0,
1794	.ssd_limit = 0xfffff,
1795	.ssd_type = SDT_MEMERA,
1796	.ssd_dpl = SEL_UPL,
1797	.ssd_p = 1,
1798	.ssd_xx = 0, .ssd_xx1 = 0,
1799	.ssd_def32 = 1,
1800	.ssd_gran = 1		},
1801/* GUDATA_SEL	7 Data Descriptor for user */
1802{	.ssd_base = 0x0,
1803	.ssd_limit = 0xfffff,
1804	.ssd_type = SDT_MEMRWA,
1805	.ssd_dpl = SEL_UPL,
1806	.ssd_p = 1,
1807	.ssd_xx = 0, .ssd_xx1 = 0,
1808	.ssd_def32 = 1,
1809	.ssd_gran = 1		},
1810/* GBIOSLOWMEM_SEL 8 BIOS access to realmode segment 0x40, must be #8 in GDT */
1811{	.ssd_base = 0x400,
1812	.ssd_limit = 0xfffff,
1813	.ssd_type = SDT_MEMRWA,
1814	.ssd_dpl = SEL_KPL,
1815	.ssd_p = 1,
1816	.ssd_xx = 0, .ssd_xx1 = 0,
1817	.ssd_def32 = 1,
1818	.ssd_gran = 1		},
1819#ifndef XEN
1820/* GPROC0_SEL	9 Proc 0 Tss Descriptor */
1821{
1822	.ssd_base = 0x0,
1823	.ssd_limit = sizeof(struct i386tss)-1,
1824	.ssd_type = SDT_SYS386TSS,
1825	.ssd_dpl = 0,
1826	.ssd_p = 1,
1827	.ssd_xx = 0, .ssd_xx1 = 0,
1828	.ssd_def32 = 0,
1829	.ssd_gran = 0		},
1830/* GLDT_SEL	10 LDT Descriptor */
1831{	.ssd_base = (int) ldt,
1832	.ssd_limit = sizeof(ldt)-1,
1833	.ssd_type = SDT_SYSLDT,
1834	.ssd_dpl = SEL_UPL,
1835	.ssd_p = 1,
1836	.ssd_xx = 0, .ssd_xx1 = 0,
1837	.ssd_def32 = 0,
1838	.ssd_gran = 0		},
1839/* GUSERLDT_SEL	11 User LDT Descriptor per process */
1840{	.ssd_base = (int) ldt,
1841	.ssd_limit = (512 * sizeof(union descriptor)-1),
1842	.ssd_type = SDT_SYSLDT,
1843	.ssd_dpl = 0,
1844	.ssd_p = 1,
1845	.ssd_xx = 0, .ssd_xx1 = 0,
1846	.ssd_def32 = 0,
1847	.ssd_gran = 0		},
1848/* GPANIC_SEL	12 Panic Tss Descriptor */
1849{	.ssd_base = (int) &dblfault_tss,
1850	.ssd_limit = sizeof(struct i386tss)-1,
1851	.ssd_type = SDT_SYS386TSS,
1852	.ssd_dpl = 0,
1853	.ssd_p = 1,
1854	.ssd_xx = 0, .ssd_xx1 = 0,
1855	.ssd_def32 = 0,
1856	.ssd_gran = 0		},
1857/* GBIOSCODE32_SEL 13 BIOS 32-bit interface (32bit Code) */
1858{	.ssd_base = 0,
1859	.ssd_limit = 0xfffff,
1860	.ssd_type = SDT_MEMERA,
1861	.ssd_dpl = 0,
1862	.ssd_p = 1,
1863	.ssd_xx = 0, .ssd_xx1 = 0,
1864	.ssd_def32 = 0,
1865	.ssd_gran = 1		},
1866/* GBIOSCODE16_SEL 14 BIOS 32-bit interface (16bit Code) */
1867{	.ssd_base = 0,
1868	.ssd_limit = 0xfffff,
1869	.ssd_type = SDT_MEMERA,
1870	.ssd_dpl = 0,
1871	.ssd_p = 1,
1872	.ssd_xx = 0, .ssd_xx1 = 0,
1873	.ssd_def32 = 0,
1874	.ssd_gran = 1		},
1875/* GBIOSDATA_SEL 15 BIOS 32-bit interface (Data) */
1876{	.ssd_base = 0,
1877	.ssd_limit = 0xfffff,
1878	.ssd_type = SDT_MEMRWA,
1879	.ssd_dpl = 0,
1880	.ssd_p = 1,
1881	.ssd_xx = 0, .ssd_xx1 = 0,
1882	.ssd_def32 = 1,
1883	.ssd_gran = 1		},
1884/* GBIOSUTIL_SEL 16 BIOS 16-bit interface (Utility) */
1885{	.ssd_base = 0,
1886	.ssd_limit = 0xfffff,
1887	.ssd_type = SDT_MEMRWA,
1888	.ssd_dpl = 0,
1889	.ssd_p = 1,
1890	.ssd_xx = 0, .ssd_xx1 = 0,
1891	.ssd_def32 = 0,
1892	.ssd_gran = 1		},
1893/* GBIOSARGS_SEL 17 BIOS 16-bit interface (Arguments) */
1894{	.ssd_base = 0,
1895	.ssd_limit = 0xfffff,
1896	.ssd_type = SDT_MEMRWA,
1897	.ssd_dpl = 0,
1898	.ssd_p = 1,
1899	.ssd_xx = 0, .ssd_xx1 = 0,
1900	.ssd_def32 = 0,
1901	.ssd_gran = 1		},
1902/* GNDIS_SEL	18 NDIS Descriptor */
1903{	.ssd_base = 0x0,
1904	.ssd_limit = 0x0,
1905	.ssd_type = 0,
1906	.ssd_dpl = 0,
1907	.ssd_p = 0,
1908	.ssd_xx = 0, .ssd_xx1 = 0,
1909	.ssd_def32 = 0,
1910	.ssd_gran = 0		},
1911#endif /* !XEN */
1912};
1913
1914static struct soft_segment_descriptor ldt_segs[] = {
1915	/* Null Descriptor - overwritten by call gate */
1916{	.ssd_base = 0x0,
1917	.ssd_limit = 0x0,
1918	.ssd_type = 0,
1919	.ssd_dpl = 0,
1920	.ssd_p = 0,
1921	.ssd_xx = 0, .ssd_xx1 = 0,
1922	.ssd_def32 = 0,
1923	.ssd_gran = 0		},
1924	/* Null Descriptor - overwritten by call gate */
1925{	.ssd_base = 0x0,
1926	.ssd_limit = 0x0,
1927	.ssd_type = 0,
1928	.ssd_dpl = 0,
1929	.ssd_p = 0,
1930	.ssd_xx = 0, .ssd_xx1 = 0,
1931	.ssd_def32 = 0,
1932	.ssd_gran = 0		},
1933	/* Null Descriptor - overwritten by call gate */
1934{	.ssd_base = 0x0,
1935	.ssd_limit = 0x0,
1936	.ssd_type = 0,
1937	.ssd_dpl = 0,
1938	.ssd_p = 0,
1939	.ssd_xx = 0, .ssd_xx1 = 0,
1940	.ssd_def32 = 0,
1941	.ssd_gran = 0		},
1942	/* Code Descriptor for user */
1943{	.ssd_base = 0x0,
1944	.ssd_limit = 0xfffff,
1945	.ssd_type = SDT_MEMERA,
1946	.ssd_dpl = SEL_UPL,
1947	.ssd_p = 1,
1948	.ssd_xx = 0, .ssd_xx1 = 0,
1949	.ssd_def32 = 1,
1950	.ssd_gran = 1		},
1951	/* Null Descriptor - overwritten by call gate */
1952{	.ssd_base = 0x0,
1953	.ssd_limit = 0x0,
1954	.ssd_type = 0,
1955	.ssd_dpl = 0,
1956	.ssd_p = 0,
1957	.ssd_xx = 0, .ssd_xx1 = 0,
1958	.ssd_def32 = 0,
1959	.ssd_gran = 0		},
1960	/* Data Descriptor for user */
1961{	.ssd_base = 0x0,
1962	.ssd_limit = 0xfffff,
1963	.ssd_type = SDT_MEMRWA,
1964	.ssd_dpl = SEL_UPL,
1965	.ssd_p = 1,
1966	.ssd_xx = 0, .ssd_xx1 = 0,
1967	.ssd_def32 = 1,
1968	.ssd_gran = 1		},
1969};
1970
1971void
1972setidt(idx, func, typ, dpl, selec)
1973	int idx;
1974	inthand_t *func;
1975	int typ;
1976	int dpl;
1977	int selec;
1978{
1979	struct gate_descriptor *ip;
1980
1981	ip = idt + idx;
1982	ip->gd_looffset = (int)func;
1983	ip->gd_selector = selec;
1984	ip->gd_stkcpy = 0;
1985	ip->gd_xx = 0;
1986	ip->gd_type = typ;
1987	ip->gd_dpl = dpl;
1988	ip->gd_p = 1;
1989	ip->gd_hioffset = ((int)func)>>16 ;
1990}
1991
1992extern inthand_t
1993	IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
1994	IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
1995	IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
1996	IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
1997	IDTVEC(xmm),
1998#ifdef KDTRACE_HOOKS
1999	IDTVEC(dtrace_ret),
2000#endif
2001#ifdef XENHVM
2002	IDTVEC(xen_intr_upcall),
2003#endif
2004	IDTVEC(lcall_syscall), IDTVEC(int0x80_syscall);
2005
2006#ifdef DDB
2007/*
2008 * Display the index and function name of any IDT entries that don't use
2009 * the default 'rsvd' entry point.
2010 */
2011DB_SHOW_COMMAND(idt, db_show_idt)
2012{
2013	struct gate_descriptor *ip;
2014	int idx;
2015	uintptr_t func;
2016
2017	ip = idt;
2018	for (idx = 0; idx < NIDT && !db_pager_quit; idx++) {
2019		func = (ip->gd_hioffset << 16 | ip->gd_looffset);
2020		if (func != (uintptr_t)&IDTVEC(rsvd)) {
2021			db_printf("%3d\t", idx);
2022			db_printsym(func, DB_STGY_PROC);
2023			db_printf("\n");
2024		}
2025		ip++;
2026	}
2027}
2028
2029/* Show privileged registers. */
2030DB_SHOW_COMMAND(sysregs, db_show_sysregs)
2031{
2032	uint64_t idtr, gdtr;
2033
2034	idtr = ridt();
2035	db_printf("idtr\t0x%08x/%04x\n",
2036	    (u_int)(idtr >> 16), (u_int)idtr & 0xffff);
2037	gdtr = rgdt();
2038	db_printf("gdtr\t0x%08x/%04x\n",
2039	    (u_int)(gdtr >> 16), (u_int)gdtr & 0xffff);
2040	db_printf("ldtr\t0x%04x\n", rldt());
2041	db_printf("tr\t0x%04x\n", rtr());
2042	db_printf("cr0\t0x%08x\n", rcr0());
2043	db_printf("cr2\t0x%08x\n", rcr2());
2044	db_printf("cr3\t0x%08x\n", rcr3());
2045	db_printf("cr4\t0x%08x\n", rcr4());
2046	if (rcr4() & CR4_XSAVE)
2047		db_printf("xcr0\t0x%016llx\n", rxcr(0));
2048	if (amd_feature & (AMDID_NX | AMDID_LM))
2049		db_printf("EFER\t0x%016llx\n", rdmsr(MSR_EFER));
2050	if (cpu_feature2 & (CPUID2_VMX | CPUID2_SMX))
2051		db_printf("FEATURES_CTL\t0x%016llx\n",
2052		    rdmsr(MSR_IA32_FEATURE_CONTROL));
2053	if ((cpu_vendor_id == CPU_VENDOR_INTEL ||
2054	    cpu_vendor_id == CPU_VENDOR_AMD) && CPUID_TO_FAMILY(cpu_id) >= 6)
2055		db_printf("DEBUG_CTL\t0x%016llx\n", rdmsr(MSR_DEBUGCTLMSR));
2056	if (cpu_feature & CPUID_PAT)
2057		db_printf("PAT\t0x%016llx\n", rdmsr(MSR_PAT));
2058}
2059
2060DB_SHOW_COMMAND(dbregs, db_show_dbregs)
2061{
2062
2063	db_printf("dr0\t0x%08x\n", rdr0());
2064	db_printf("dr1\t0x%08x\n", rdr1());
2065	db_printf("dr2\t0x%08x\n", rdr2());
2066	db_printf("dr3\t0x%08x\n", rdr3());
2067	db_printf("dr6\t0x%08x\n", rdr6());
2068	db_printf("dr7\t0x%08x\n", rdr7());
2069}
2070#endif
2071
2072void
2073sdtossd(sd, ssd)
2074	struct segment_descriptor *sd;
2075	struct soft_segment_descriptor *ssd;
2076{
2077	ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
2078	ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
2079	ssd->ssd_type  = sd->sd_type;
2080	ssd->ssd_dpl   = sd->sd_dpl;
2081	ssd->ssd_p     = sd->sd_p;
2082	ssd->ssd_def32 = sd->sd_def32;
2083	ssd->ssd_gran  = sd->sd_gran;
2084}
2085
2086#if !defined(PC98) && !defined(XEN)
2087static int
2088add_smap_entry(struct bios_smap *smap, vm_paddr_t *physmap, int *physmap_idxp)
2089{
2090	int i, insert_idx, physmap_idx;
2091
2092	physmap_idx = *physmap_idxp;
2093
2094	if (boothowto & RB_VERBOSE)
2095		printf("SMAP type=%02x base=%016llx len=%016llx\n",
2096		    smap->type, smap->base, smap->length);
2097
2098	if (smap->type != SMAP_TYPE_MEMORY)
2099		return (1);
2100
2101	if (smap->length == 0)
2102		return (1);
2103
2104#ifndef PAE
2105	if (smap->base > 0xffffffff) {
2106		printf("%uK of memory above 4GB ignored\n",
2107		    (u_int)(smap->length / 1024));
2108		return (1);
2109	}
2110#endif
2111
2112	/*
2113	 * Find insertion point while checking for overlap.  Start off by
2114	 * assuming the new entry will be added to the end.
2115	 */
2116	insert_idx = physmap_idx + 2;
2117	for (i = 0; i <= physmap_idx; i += 2) {
2118		if (smap->base < physmap[i + 1]) {
2119			if (smap->base + smap->length <= physmap[i]) {
2120				insert_idx = i;
2121				break;
2122			}
2123			if (boothowto & RB_VERBOSE)
2124				printf(
2125		    "Overlapping memory regions, ignoring second region\n");
2126			return (1);
2127		}
2128	}
2129
2130	/* See if we can prepend to the next entry. */
2131	if (insert_idx <= physmap_idx &&
2132	    smap->base + smap->length == physmap[insert_idx]) {
2133		physmap[insert_idx] = smap->base;
2134		return (1);
2135	}
2136
2137	/* See if we can append to the previous entry. */
2138	if (insert_idx > 0 && smap->base == physmap[insert_idx - 1]) {
2139		physmap[insert_idx - 1] += smap->length;
2140		return (1);
2141	}
2142
2143	physmap_idx += 2;
2144	*physmap_idxp = physmap_idx;
2145	if (physmap_idx == PHYSMAP_SIZE) {
2146		printf(
2147		"Too many segments in the physical address map, giving up\n");
2148		return (0);
2149	}
2150
2151	/*
2152	 * Move the last 'N' entries down to make room for the new
2153	 * entry if needed.
2154	 */
2155	for (i = physmap_idx; i > insert_idx; i -= 2) {
2156		physmap[i] = physmap[i - 2];
2157		physmap[i + 1] = physmap[i - 1];
2158	}
2159
2160	/* Insert the new entry. */
2161	physmap[insert_idx] = smap->base;
2162	physmap[insert_idx + 1] = smap->base + smap->length;
2163	return (1);
2164}
2165#endif /* !PC98 && !XEN */
2166
2167#ifndef XEN
2168static void
2169basemem_setup(void)
2170{
2171	vm_paddr_t pa;
2172	pt_entry_t *pte;
2173	int i;
2174
2175	if (basemem > 640) {
2176		printf("Preposterous BIOS basemem of %uK, truncating to 640K\n",
2177			basemem);
2178		basemem = 640;
2179	}
2180
2181	/*
2182	 * XXX if biosbasemem is now < 640, there is a `hole'
2183	 * between the end of base memory and the start of
2184	 * ISA memory.  The hole may be empty or it may
2185	 * contain BIOS code or data.  Map it read/write so
2186	 * that the BIOS can write to it.  (Memory from 0 to
2187	 * the physical end of the kernel is mapped read-only
2188	 * to begin with and then parts of it are remapped.
2189	 * The parts that aren't remapped form holes that
2190	 * remain read-only and are unused by the kernel.
2191	 * The base memory area is below the physical end of
2192	 * the kernel and right now forms a read-only hole.
2193	 * The part of it from PAGE_SIZE to
2194	 * (trunc_page(biosbasemem * 1024) - 1) will be
2195	 * remapped and used by the kernel later.)
2196	 *
2197	 * This code is similar to the code used in
2198	 * pmap_mapdev, but since no memory needs to be
2199	 * allocated we simply change the mapping.
2200	 */
2201	for (pa = trunc_page(basemem * 1024);
2202	     pa < ISA_HOLE_START; pa += PAGE_SIZE)
2203		pmap_kenter(KERNBASE + pa, pa);
2204
2205	/*
2206	 * Map pages between basemem and ISA_HOLE_START, if any, r/w into
2207	 * the vm86 page table so that vm86 can scribble on them using
2208	 * the vm86 map too.  XXX: why 2 ways for this and only 1 way for
2209	 * page 0, at least as initialized here?
2210	 */
2211	pte = (pt_entry_t *)vm86paddr;
2212	for (i = basemem / 4; i < 160; i++)
2213		pte[i] = (i << PAGE_SHIFT) | PG_V | PG_RW | PG_U;
2214}
2215#endif /* !XEN */
2216
2217/*
2218 * Populate the (physmap) array with base/bound pairs describing the
2219 * available physical memory in the system, then test this memory and
2220 * build the phys_avail array describing the actually-available memory.
2221 *
2222 * If we cannot accurately determine the physical memory map, then use
2223 * value from the 0xE801 call, and failing that, the RTC.
2224 *
2225 * Total memory size may be set by the kernel environment variable
2226 * hw.physmem or the compile-time define MAXMEM.
2227 *
2228 * XXX first should be vm_paddr_t.
2229 */
2230#ifdef PC98
2231static void
2232getmemsize(int first)
2233{
2234	int off, physmap_idx, pa_indx, da_indx;
2235	u_long physmem_tunable, memtest;
2236	vm_paddr_t physmap[PHYSMAP_SIZE];
2237	pt_entry_t *pte;
2238	quad_t dcons_addr, dcons_size;
2239	int i;
2240	int pg_n;
2241	u_int extmem;
2242	u_int under16;
2243	vm_paddr_t pa;
2244
2245	bzero(physmap, sizeof(physmap));
2246
2247	/* XXX - some of EPSON machines can't use PG_N */
2248	pg_n = PG_N;
2249	if (pc98_machine_type & M_EPSON_PC98) {
2250		switch (epson_machine_id) {
2251#ifdef WB_CACHE
2252		default:
2253#endif
2254		case EPSON_PC486_HX:
2255		case EPSON_PC486_HG:
2256		case EPSON_PC486_HA:
2257			pg_n = 0;
2258			break;
2259		}
2260	}
2261
2262	under16 = pc98_getmemsize(&basemem, &extmem);
2263	basemem_setup();
2264
2265	physmap[0] = 0;
2266	physmap[1] = basemem * 1024;
2267	physmap_idx = 2;
2268	physmap[physmap_idx] = 0x100000;
2269	physmap[physmap_idx + 1] = physmap[physmap_idx] + extmem * 1024;
2270
2271	/*
2272	 * Now, physmap contains a map of physical memory.
2273	 */
2274
2275#ifdef SMP
2276	/* make hole for AP bootstrap code */
2277	physmap[1] = mp_bootaddress(physmap[1]);
2278#endif
2279
2280	/*
2281	 * Maxmem isn't the "maximum memory", it's one larger than the
2282	 * highest page of the physical address space.  It should be
2283	 * called something like "Maxphyspage".  We may adjust this
2284	 * based on ``hw.physmem'' and the results of the memory test.
2285	 */
2286	Maxmem = atop(physmap[physmap_idx + 1]);
2287
2288#ifdef MAXMEM
2289	Maxmem = MAXMEM / 4;
2290#endif
2291
2292	if (TUNABLE_ULONG_FETCH("hw.physmem", &physmem_tunable))
2293		Maxmem = atop(physmem_tunable);
2294
2295	/*
2296	 * By default keep the memtest enabled.  Use a general name so that
2297	 * one could eventually do more with the code than just disable it.
2298	 */
2299	memtest = 1;
2300	TUNABLE_ULONG_FETCH("hw.memtest.tests", &memtest);
2301
2302	if (atop(physmap[physmap_idx + 1]) != Maxmem &&
2303	    (boothowto & RB_VERBOSE))
2304		printf("Physical memory use set to %ldK\n", Maxmem * 4);
2305
2306	/*
2307	 * If Maxmem has been increased beyond what the system has detected,
2308	 * extend the last memory segment to the new limit.
2309	 */
2310	if (atop(physmap[physmap_idx + 1]) < Maxmem)
2311		physmap[physmap_idx + 1] = ptoa((vm_paddr_t)Maxmem);
2312
2313	/*
2314	 * We need to divide chunk if Maxmem is larger than 16MB and
2315	 * under 16MB area is not full of memory.
2316	 * (1) system area (15-16MB region) is cut off
2317	 * (2) extended memory is only over 16MB area (ex. Melco "HYPERMEMORY")
2318	 */
2319	if ((under16 != 16 * 1024) && (extmem > 15 * 1024)) {
2320		/* 15M - 16M region is cut off, so need to divide chunk */
2321		physmap[physmap_idx + 1] = under16 * 1024;
2322		physmap_idx += 2;
2323		physmap[physmap_idx] = 0x1000000;
2324		physmap[physmap_idx + 1] = physmap[2] + extmem * 1024;
2325	}
2326
2327	/* call pmap initialization to make new kernel address space */
2328	pmap_bootstrap(first);
2329
2330	/*
2331	 * Size up each available chunk of physical memory.
2332	 */
2333	physmap[0] = PAGE_SIZE;		/* mask off page 0 */
2334	pa_indx = 0;
2335	da_indx = 1;
2336	phys_avail[pa_indx++] = physmap[0];
2337	phys_avail[pa_indx] = physmap[0];
2338	dump_avail[da_indx] = physmap[0];
2339	pte = CMAP3;
2340
2341	/*
2342	 * Get dcons buffer address
2343	 */
2344	if (getenv_quad("dcons.addr", &dcons_addr) == 0 ||
2345	    getenv_quad("dcons.size", &dcons_size) == 0)
2346		dcons_addr = 0;
2347
2348	/*
2349	 * physmap is in bytes, so when converting to page boundaries,
2350	 * round up the start address and round down the end address.
2351	 */
2352	for (i = 0; i <= physmap_idx; i += 2) {
2353		vm_paddr_t end;
2354
2355		end = ptoa((vm_paddr_t)Maxmem);
2356		if (physmap[i + 1] < end)
2357			end = trunc_page(physmap[i + 1]);
2358		for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
2359			int tmp, page_bad, full;
2360			int *ptr = (int *)CADDR3;
2361
2362			full = FALSE;
2363			/*
2364			 * block out kernel memory as not available.
2365			 */
2366			if (pa >= KERNLOAD && pa < first)
2367				goto do_dump_avail;
2368
2369			/*
2370			 * block out dcons buffer
2371			 */
2372			if (dcons_addr > 0
2373			    && pa >= trunc_page(dcons_addr)
2374			    && pa < dcons_addr + dcons_size)
2375				goto do_dump_avail;
2376
2377			page_bad = FALSE;
2378			if (memtest == 0)
2379				goto skip_memtest;
2380
2381			/*
2382			 * map page into kernel: valid, read/write,non-cacheable
2383			 */
2384			*pte = pa | PG_V | PG_RW | pg_n;
2385			invltlb();
2386
2387			tmp = *(int *)ptr;
2388			/*
2389			 * Test for alternating 1's and 0's
2390			 */
2391			*(volatile int *)ptr = 0xaaaaaaaa;
2392			if (*(volatile int *)ptr != 0xaaaaaaaa)
2393				page_bad = TRUE;
2394			/*
2395			 * Test for alternating 0's and 1's
2396			 */
2397			*(volatile int *)ptr = 0x55555555;
2398			if (*(volatile int *)ptr != 0x55555555)
2399				page_bad = TRUE;
2400			/*
2401			 * Test for all 1's
2402			 */
2403			*(volatile int *)ptr = 0xffffffff;
2404			if (*(volatile int *)ptr != 0xffffffff)
2405				page_bad = TRUE;
2406			/*
2407			 * Test for all 0's
2408			 */
2409			*(volatile int *)ptr = 0x0;
2410			if (*(volatile int *)ptr != 0x0)
2411				page_bad = TRUE;
2412			/*
2413			 * Restore original value.
2414			 */
2415			*(int *)ptr = tmp;
2416
2417skip_memtest:
2418			/*
2419			 * Adjust array of valid/good pages.
2420			 */
2421			if (page_bad == TRUE)
2422				continue;
2423			/*
2424			 * If this good page is a continuation of the
2425			 * previous set of good pages, then just increase
2426			 * the end pointer. Otherwise start a new chunk.
2427			 * Note that "end" points one higher than end,
2428			 * making the range >= start and < end.
2429			 * If we're also doing a speculative memory
2430			 * test and we at or past the end, bump up Maxmem
2431			 * so that we keep going. The first bad page
2432			 * will terminate the loop.
2433			 */
2434			if (phys_avail[pa_indx] == pa) {
2435				phys_avail[pa_indx] += PAGE_SIZE;
2436			} else {
2437				pa_indx++;
2438				if (pa_indx == PHYS_AVAIL_ARRAY_END) {
2439					printf(
2440		"Too many holes in the physical address space, giving up\n");
2441					pa_indx--;
2442					full = TRUE;
2443					goto do_dump_avail;
2444				}
2445				phys_avail[pa_indx++] = pa;	/* start */
2446				phys_avail[pa_indx] = pa + PAGE_SIZE; /* end */
2447			}
2448			physmem++;
2449do_dump_avail:
2450			if (dump_avail[da_indx] == pa) {
2451				dump_avail[da_indx] += PAGE_SIZE;
2452			} else {
2453				da_indx++;
2454				if (da_indx == DUMP_AVAIL_ARRAY_END) {
2455					da_indx--;
2456					goto do_next;
2457				}
2458				dump_avail[da_indx++] = pa;	/* start */
2459				dump_avail[da_indx] = pa + PAGE_SIZE; /* end */
2460			}
2461do_next:
2462			if (full)
2463				break;
2464		}
2465	}
2466	*pte = 0;
2467	invltlb();
2468
2469	/*
2470	 * XXX
2471	 * The last chunk must contain at least one page plus the message
2472	 * buffer to avoid complicating other code (message buffer address
2473	 * calculation, etc.).
2474	 */
2475	while (phys_avail[pa_indx - 1] + PAGE_SIZE +
2476	    round_page(msgbufsize) >= phys_avail[pa_indx]) {
2477		physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
2478		phys_avail[pa_indx--] = 0;
2479		phys_avail[pa_indx--] = 0;
2480	}
2481
2482	Maxmem = atop(phys_avail[pa_indx]);
2483
2484	/* Trim off space for the message buffer. */
2485	phys_avail[pa_indx] -= round_page(msgbufsize);
2486
2487	/* Map the message buffer. */
2488	for (off = 0; off < round_page(msgbufsize); off += PAGE_SIZE)
2489		pmap_kenter((vm_offset_t)msgbufp + off, phys_avail[pa_indx] +
2490		    off);
2491
2492	PT_UPDATES_FLUSH();
2493}
2494#else /* PC98 */
2495static void
2496getmemsize(int first)
2497{
2498	int has_smap, off, physmap_idx, pa_indx, da_indx;
2499	u_long physmem_tunable, memtest;
2500	vm_paddr_t physmap[PHYSMAP_SIZE];
2501	pt_entry_t *pte;
2502	quad_t dcons_addr, dcons_size;
2503#ifndef XEN
2504	int hasbrokenint12, i, res;
2505	u_int extmem;
2506	struct vm86frame vmf;
2507	struct vm86context vmc;
2508	vm_paddr_t pa;
2509	struct bios_smap *smap, *smapbase, *smapend;
2510	u_int32_t smapsize;
2511	caddr_t kmdp;
2512#endif
2513
2514	has_smap = 0;
2515#if defined(XEN)
2516	Maxmem = xen_start_info->nr_pages - init_first;
2517	physmem = Maxmem;
2518	basemem = 0;
2519	physmap[0] = init_first << PAGE_SHIFT;
2520	physmap[1] = ptoa(Maxmem) - round_page(msgbufsize);
2521	physmap_idx = 0;
2522#else
2523#ifdef XBOX
2524	if (arch_i386_is_xbox) {
2525		/*
2526		 * We queried the memory size before, so chop off 4MB for
2527		 * the framebuffer and inform the OS of this.
2528		 */
2529		physmap[0] = 0;
2530		physmap[1] = (arch_i386_xbox_memsize * 1024 * 1024) - XBOX_FB_SIZE;
2531		physmap_idx = 0;
2532		goto physmap_done;
2533	}
2534#endif
2535	bzero(&vmf, sizeof(vmf));
2536	bzero(physmap, sizeof(physmap));
2537	basemem = 0;
2538
2539	/*
2540	 * Check if the loader supplied an SMAP memory map.  If so,
2541	 * use that and do not make any VM86 calls.
2542	 */
2543	physmap_idx = 0;
2544	smapbase = NULL;
2545	kmdp = preload_search_by_type("elf kernel");
2546	if (kmdp == NULL)
2547		kmdp = preload_search_by_type("elf32 kernel");
2548	if (kmdp != NULL)
2549		smapbase = (struct bios_smap *)preload_search_info(kmdp,
2550		    MODINFO_METADATA | MODINFOMD_SMAP);
2551	if (smapbase != NULL) {
2552		/*
2553		 * subr_module.c says:
2554		 * "Consumer may safely assume that size value precedes data."
2555		 * ie: an int32_t immediately precedes SMAP.
2556		 */
2557		smapsize = *((u_int32_t *)smapbase - 1);
2558		smapend = (struct bios_smap *)((uintptr_t)smapbase + smapsize);
2559		has_smap = 1;
2560
2561		for (smap = smapbase; smap < smapend; smap++)
2562			if (!add_smap_entry(smap, physmap, &physmap_idx))
2563				break;
2564		goto have_smap;
2565	}
2566
2567	/*
2568	 * Some newer BIOSes have a broken INT 12H implementation
2569	 * which causes a kernel panic immediately.  In this case, we
2570	 * need use the SMAP to determine the base memory size.
2571	 */
2572	hasbrokenint12 = 0;
2573	TUNABLE_INT_FETCH("hw.hasbrokenint12", &hasbrokenint12);
2574	if (hasbrokenint12 == 0) {
2575		/* Use INT12 to determine base memory size. */
2576		vm86_intcall(0x12, &vmf);
2577		basemem = vmf.vmf_ax;
2578		basemem_setup();
2579	}
2580
2581	/*
2582	 * Fetch the memory map with INT 15:E820.  Map page 1 R/W into
2583	 * the kernel page table so we can use it as a buffer.  The
2584	 * kernel will unmap this page later.
2585	 */
2586	pmap_kenter(KERNBASE + (1 << PAGE_SHIFT), 1 << PAGE_SHIFT);
2587	vmc.npages = 0;
2588	smap = (void *)vm86_addpage(&vmc, 1, KERNBASE + (1 << PAGE_SHIFT));
2589	res = vm86_getptr(&vmc, (vm_offset_t)smap, &vmf.vmf_es, &vmf.vmf_di);
2590	KASSERT(res != 0, ("vm86_getptr() failed: address not found"));
2591
2592	vmf.vmf_ebx = 0;
2593	do {
2594		vmf.vmf_eax = 0xE820;
2595		vmf.vmf_edx = SMAP_SIG;
2596		vmf.vmf_ecx = sizeof(struct bios_smap);
2597		i = vm86_datacall(0x15, &vmf, &vmc);
2598		if (i || vmf.vmf_eax != SMAP_SIG)
2599			break;
2600		has_smap = 1;
2601		if (!add_smap_entry(smap, physmap, &physmap_idx))
2602			break;
2603	} while (vmf.vmf_ebx != 0);
2604
2605have_smap:
2606	/*
2607	 * If we didn't fetch the "base memory" size from INT12,
2608	 * figure it out from the SMAP (or just guess).
2609	 */
2610	if (basemem == 0) {
2611		for (i = 0; i <= physmap_idx; i += 2) {
2612			if (physmap[i] == 0x00000000) {
2613				basemem = physmap[i + 1] / 1024;
2614				break;
2615			}
2616		}
2617
2618		/* XXX: If we couldn't find basemem from SMAP, just guess. */
2619		if (basemem == 0)
2620			basemem = 640;
2621		basemem_setup();
2622	}
2623
2624	if (physmap[1] != 0)
2625		goto physmap_done;
2626
2627	/*
2628	 * If we failed to find an SMAP, figure out the extended
2629	 * memory size.  We will then build a simple memory map with
2630	 * two segments, one for "base memory" and the second for
2631	 * "extended memory".  Note that "extended memory" starts at a
2632	 * physical address of 1MB and that both basemem and extmem
2633	 * are in units of 1KB.
2634	 *
2635	 * First, try to fetch the extended memory size via INT 15:E801.
2636	 */
2637	vmf.vmf_ax = 0xE801;
2638	if (vm86_intcall(0x15, &vmf) == 0) {
2639		extmem = vmf.vmf_cx + vmf.vmf_dx * 64;
2640	} else {
2641		/*
2642		 * If INT15:E801 fails, this is our last ditch effort
2643		 * to determine the extended memory size.  Currently
2644		 * we prefer the RTC value over INT15:88.
2645		 */
2646#if 0
2647		vmf.vmf_ah = 0x88;
2648		vm86_intcall(0x15, &vmf);
2649		extmem = vmf.vmf_ax;
2650#else
2651		extmem = rtcin(RTC_EXTLO) + (rtcin(RTC_EXTHI) << 8);
2652#endif
2653	}
2654
2655	/*
2656	 * Special hack for chipsets that still remap the 384k hole when
2657	 * there's 16MB of memory - this really confuses people that
2658	 * are trying to use bus mastering ISA controllers with the
2659	 * "16MB limit"; they only have 16MB, but the remapping puts
2660	 * them beyond the limit.
2661	 *
2662	 * If extended memory is between 15-16MB (16-17MB phys address range),
2663	 *	chop it to 15MB.
2664	 */
2665	if ((extmem > 15 * 1024) && (extmem < 16 * 1024))
2666		extmem = 15 * 1024;
2667
2668	physmap[0] = 0;
2669	physmap[1] = basemem * 1024;
2670	physmap_idx = 2;
2671	physmap[physmap_idx] = 0x100000;
2672	physmap[physmap_idx + 1] = physmap[physmap_idx] + extmem * 1024;
2673
2674physmap_done:
2675#endif
2676	/*
2677	 * Now, physmap contains a map of physical memory.
2678	 */
2679
2680#ifdef SMP
2681	/* make hole for AP bootstrap code */
2682	physmap[1] = mp_bootaddress(physmap[1]);
2683#endif
2684
2685	/*
2686	 * Maxmem isn't the "maximum memory", it's one larger than the
2687	 * highest page of the physical address space.  It should be
2688	 * called something like "Maxphyspage".  We may adjust this
2689	 * based on ``hw.physmem'' and the results of the memory test.
2690	 */
2691	Maxmem = atop(physmap[physmap_idx + 1]);
2692
2693#ifdef MAXMEM
2694	Maxmem = MAXMEM / 4;
2695#endif
2696
2697	if (TUNABLE_ULONG_FETCH("hw.physmem", &physmem_tunable))
2698		Maxmem = atop(physmem_tunable);
2699
2700	/*
2701	 * If we have an SMAP, don't allow MAXMEM or hw.physmem to extend
2702	 * the amount of memory in the system.
2703	 */
2704	if (has_smap && Maxmem > atop(physmap[physmap_idx + 1]))
2705		Maxmem = atop(physmap[physmap_idx + 1]);
2706
2707	/*
2708	 * By default enable the memory test on real hardware, and disable
2709	 * it if we appear to be running in a VM.  This avoids touching all
2710	 * pages unnecessarily, which doesn't matter on real hardware but is
2711	 * bad for shared VM hosts.  Use a general name so that
2712	 * one could eventually do more with the code than just disable it.
2713	 */
2714	memtest = (vm_guest > VM_GUEST_NO) ? 0 : 1;
2715	TUNABLE_ULONG_FETCH("hw.memtest.tests", &memtest);
2716
2717	if (atop(physmap[physmap_idx + 1]) != Maxmem &&
2718	    (boothowto & RB_VERBOSE))
2719		printf("Physical memory use set to %ldK\n", Maxmem * 4);
2720
2721	/*
2722	 * If Maxmem has been increased beyond what the system has detected,
2723	 * extend the last memory segment to the new limit.
2724	 */
2725	if (atop(physmap[physmap_idx + 1]) < Maxmem)
2726		physmap[physmap_idx + 1] = ptoa((vm_paddr_t)Maxmem);
2727
2728	/* call pmap initialization to make new kernel address space */
2729	pmap_bootstrap(first);
2730
2731	/*
2732	 * Size up each available chunk of physical memory.
2733	 */
2734	physmap[0] = PAGE_SIZE;		/* mask off page 0 */
2735	pa_indx = 0;
2736	da_indx = 1;
2737	phys_avail[pa_indx++] = physmap[0];
2738	phys_avail[pa_indx] = physmap[0];
2739	dump_avail[da_indx] = physmap[0];
2740	pte = CMAP3;
2741
2742	/*
2743	 * Get dcons buffer address
2744	 */
2745	if (getenv_quad("dcons.addr", &dcons_addr) == 0 ||
2746	    getenv_quad("dcons.size", &dcons_size) == 0)
2747		dcons_addr = 0;
2748
2749#ifndef XEN
2750	/*
2751	 * physmap is in bytes, so when converting to page boundaries,
2752	 * round up the start address and round down the end address.
2753	 */
2754	for (i = 0; i <= physmap_idx; i += 2) {
2755		vm_paddr_t end;
2756
2757		end = ptoa((vm_paddr_t)Maxmem);
2758		if (physmap[i + 1] < end)
2759			end = trunc_page(physmap[i + 1]);
2760		for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
2761			int tmp, page_bad, full;
2762			int *ptr = (int *)CADDR3;
2763
2764			full = FALSE;
2765			/*
2766			 * block out kernel memory as not available.
2767			 */
2768			if (pa >= KERNLOAD && pa < first)
2769				goto do_dump_avail;
2770
2771			/*
2772			 * block out dcons buffer
2773			 */
2774			if (dcons_addr > 0
2775			    && pa >= trunc_page(dcons_addr)
2776			    && pa < dcons_addr + dcons_size)
2777				goto do_dump_avail;
2778
2779			page_bad = FALSE;
2780			if (memtest == 0)
2781				goto skip_memtest;
2782
2783			/*
2784			 * map page into kernel: valid, read/write,non-cacheable
2785			 */
2786			*pte = pa | PG_V | PG_RW | PG_N;
2787			invltlb();
2788
2789			tmp = *(int *)ptr;
2790			/*
2791			 * Test for alternating 1's and 0's
2792			 */
2793			*(volatile int *)ptr = 0xaaaaaaaa;
2794			if (*(volatile int *)ptr != 0xaaaaaaaa)
2795				page_bad = TRUE;
2796			/*
2797			 * Test for alternating 0's and 1's
2798			 */
2799			*(volatile int *)ptr = 0x55555555;
2800			if (*(volatile int *)ptr != 0x55555555)
2801				page_bad = TRUE;
2802			/*
2803			 * Test for all 1's
2804			 */
2805			*(volatile int *)ptr = 0xffffffff;
2806			if (*(volatile int *)ptr != 0xffffffff)
2807				page_bad = TRUE;
2808			/*
2809			 * Test for all 0's
2810			 */
2811			*(volatile int *)ptr = 0x0;
2812			if (*(volatile int *)ptr != 0x0)
2813				page_bad = TRUE;
2814			/*
2815			 * Restore original value.
2816			 */
2817			*(int *)ptr = tmp;
2818
2819skip_memtest:
2820			/*
2821			 * Adjust array of valid/good pages.
2822			 */
2823			if (page_bad == TRUE)
2824				continue;
2825			/*
2826			 * If this good page is a continuation of the
2827			 * previous set of good pages, then just increase
2828			 * the end pointer. Otherwise start a new chunk.
2829			 * Note that "end" points one higher than end,
2830			 * making the range >= start and < end.
2831			 * If we're also doing a speculative memory
2832			 * test and we at or past the end, bump up Maxmem
2833			 * so that we keep going. The first bad page
2834			 * will terminate the loop.
2835			 */
2836			if (phys_avail[pa_indx] == pa) {
2837				phys_avail[pa_indx] += PAGE_SIZE;
2838			} else {
2839				pa_indx++;
2840				if (pa_indx == PHYS_AVAIL_ARRAY_END) {
2841					printf(
2842		"Too many holes in the physical address space, giving up\n");
2843					pa_indx--;
2844					full = TRUE;
2845					goto do_dump_avail;
2846				}
2847				phys_avail[pa_indx++] = pa;	/* start */
2848				phys_avail[pa_indx] = pa + PAGE_SIZE; /* end */
2849			}
2850			physmem++;
2851do_dump_avail:
2852			if (dump_avail[da_indx] == pa) {
2853				dump_avail[da_indx] += PAGE_SIZE;
2854			} else {
2855				da_indx++;
2856				if (da_indx == DUMP_AVAIL_ARRAY_END) {
2857					da_indx--;
2858					goto do_next;
2859				}
2860				dump_avail[da_indx++] = pa;	/* start */
2861				dump_avail[da_indx] = pa + PAGE_SIZE; /* end */
2862			}
2863do_next:
2864			if (full)
2865				break;
2866		}
2867	}
2868	*pte = 0;
2869	invltlb();
2870#else
2871	phys_avail[0] = physfree;
2872	phys_avail[1] = xen_start_info->nr_pages*PAGE_SIZE;
2873	dump_avail[0] = 0;
2874	dump_avail[1] = xen_start_info->nr_pages*PAGE_SIZE;
2875
2876#endif
2877
2878	/*
2879	 * XXX
2880	 * The last chunk must contain at least one page plus the message
2881	 * buffer to avoid complicating other code (message buffer address
2882	 * calculation, etc.).
2883	 */
2884	while (phys_avail[pa_indx - 1] + PAGE_SIZE +
2885	    round_page(msgbufsize) >= phys_avail[pa_indx]) {
2886		physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
2887		phys_avail[pa_indx--] = 0;
2888		phys_avail[pa_indx--] = 0;
2889	}
2890
2891	Maxmem = atop(phys_avail[pa_indx]);
2892
2893	/* Trim off space for the message buffer. */
2894	phys_avail[pa_indx] -= round_page(msgbufsize);
2895
2896	/* Map the message buffer. */
2897	for (off = 0; off < round_page(msgbufsize); off += PAGE_SIZE)
2898		pmap_kenter((vm_offset_t)msgbufp + off, phys_avail[pa_indx] +
2899		    off);
2900
2901	PT_UPDATES_FLUSH();
2902}
2903#endif /* PC98 */
2904
2905#ifdef XEN
2906#define MTOPSIZE (1<<(14 + PAGE_SHIFT))
2907
2908register_t
2909init386(first)
2910	int first;
2911{
2912	unsigned long gdtmachpfn;
2913	int error, gsel_tss, metadata_missing, x, pa;
2914	struct pcpu *pc;
2915#ifdef CPU_ENABLE_SSE
2916	struct xstate_hdr *xhdr;
2917#endif
2918	struct callback_register event = {
2919		.type = CALLBACKTYPE_event,
2920		.address = {GSEL(GCODE_SEL, SEL_KPL), (unsigned long)Xhypervisor_callback },
2921	};
2922	struct callback_register failsafe = {
2923		.type = CALLBACKTYPE_failsafe,
2924		.address = {GSEL(GCODE_SEL, SEL_KPL), (unsigned long)failsafe_callback },
2925	};
2926
2927	thread0.td_kstack = proc0kstack;
2928	thread0.td_kstack_pages = KSTACK_PAGES;
2929
2930	/*
2931 	 * This may be done better later if it gets more high level
2932 	 * components in it. If so just link td->td_proc here.
2933	 */
2934	proc_linkup0(&proc0, &thread0);
2935
2936	metadata_missing = 0;
2937	if (xen_start_info->mod_start) {
2938		preload_metadata = (caddr_t)xen_start_info->mod_start;
2939		preload_bootstrap_relocate(KERNBASE);
2940	} else {
2941		metadata_missing = 1;
2942	}
2943	if (envmode == 1)
2944		kern_envp = static_env;
2945	else if ((caddr_t)xen_start_info->cmd_line)
2946	        kern_envp = xen_setbootenv((caddr_t)xen_start_info->cmd_line);
2947
2948	boothowto |= xen_boothowto(kern_envp);
2949
2950	/* Init basic tunables, hz etc */
2951	init_param1();
2952
2953	/*
2954	 * XEN occupies a portion of the upper virtual address space
2955	 * At its base it manages an array mapping machine page frames
2956	 * to physical page frames - hence we need to be able to
2957	 * access 4GB - (64MB  - 4MB + 64k)
2958	 */
2959	gdt_segs[GPRIV_SEL].ssd_limit = atop(HYPERVISOR_VIRT_START + MTOPSIZE);
2960	gdt_segs[GUFS_SEL].ssd_limit = atop(HYPERVISOR_VIRT_START + MTOPSIZE);
2961	gdt_segs[GUGS_SEL].ssd_limit = atop(HYPERVISOR_VIRT_START + MTOPSIZE);
2962	gdt_segs[GCODE_SEL].ssd_limit = atop(HYPERVISOR_VIRT_START + MTOPSIZE);
2963	gdt_segs[GDATA_SEL].ssd_limit = atop(HYPERVISOR_VIRT_START + MTOPSIZE);
2964	gdt_segs[GUCODE_SEL].ssd_limit = atop(HYPERVISOR_VIRT_START + MTOPSIZE);
2965	gdt_segs[GUDATA_SEL].ssd_limit = atop(HYPERVISOR_VIRT_START + MTOPSIZE);
2966	gdt_segs[GBIOSLOWMEM_SEL].ssd_limit = atop(HYPERVISOR_VIRT_START + MTOPSIZE);
2967
2968	pc = &__pcpu[0];
2969	gdt_segs[GPRIV_SEL].ssd_base = (int) pc;
2970	gdt_segs[GPROC0_SEL].ssd_base = (int) &pc->pc_common_tss;
2971
2972	PT_SET_MA(gdt, xpmap_ptom(VTOP(gdt)) | PG_V | PG_RW);
2973	bzero(gdt, PAGE_SIZE);
2974	for (x = 0; x < NGDT; x++)
2975		ssdtosd(&gdt_segs[x], &gdt[x].sd);
2976
2977	mtx_init(&dt_lock, "descriptor tables", NULL, MTX_SPIN);
2978
2979	gdtmachpfn = vtomach(gdt) >> PAGE_SHIFT;
2980	PT_SET_MA(gdt, xpmap_ptom(VTOP(gdt)) | PG_V);
2981	PANIC_IF(HYPERVISOR_set_gdt(&gdtmachpfn, 512) != 0);
2982	lgdt(&r_gdt);
2983	gdtset = 1;
2984
2985	if ((error = HYPERVISOR_set_trap_table(trap_table)) != 0) {
2986		panic("set_trap_table failed - error %d\n", error);
2987	}
2988
2989	error = HYPERVISOR_callback_op(CALLBACKOP_register, &event);
2990	if (error == 0)
2991		error = HYPERVISOR_callback_op(CALLBACKOP_register, &failsafe);
2992#if	CONFIG_XEN_COMPAT <= 0x030002
2993	if (error == -ENOXENSYS)
2994		HYPERVISOR_set_callbacks(GSEL(GCODE_SEL, SEL_KPL),
2995		    (unsigned long)Xhypervisor_callback,
2996		    GSEL(GCODE_SEL, SEL_KPL), (unsigned long)failsafe_callback);
2997#endif
2998	pcpu_init(pc, 0, sizeof(struct pcpu));
2999	for (pa = first; pa < first + DPCPU_SIZE; pa += PAGE_SIZE)
3000		pmap_kenter(pa + KERNBASE, pa);
3001	dpcpu_init((void *)(first + KERNBASE), 0);
3002	first += DPCPU_SIZE;
3003	physfree += DPCPU_SIZE;
3004	init_first += DPCPU_SIZE / PAGE_SIZE;
3005
3006	PCPU_SET(prvspace, pc);
3007	PCPU_SET(curthread, &thread0);
3008
3009	/*
3010	 * Initialize mutexes.
3011	 *
3012	 * icu_lock: in order to allow an interrupt to occur in a critical
3013	 * 	     section, to set pcpu->ipending (etc...) properly, we
3014	 *	     must be able to get the icu lock, so it can't be
3015	 *	     under witness.
3016	 */
3017	mutex_init();
3018	mtx_init(&icu_lock, "icu", NULL, MTX_SPIN | MTX_NOWITNESS | MTX_NOPROFILE);
3019
3020	/* make ldt memory segments */
3021	PT_SET_MA(ldt, xpmap_ptom(VTOP(ldt)) | PG_V | PG_RW);
3022	bzero(ldt, PAGE_SIZE);
3023	ldt_segs[LUCODE_SEL].ssd_limit = atop(0 - 1);
3024	ldt_segs[LUDATA_SEL].ssd_limit = atop(0 - 1);
3025	for (x = 0; x < sizeof ldt_segs / sizeof ldt_segs[0]; x++)
3026		ssdtosd(&ldt_segs[x], &ldt[x].sd);
3027
3028	default_proc_ldt.ldt_base = (caddr_t)ldt;
3029	default_proc_ldt.ldt_len = 6;
3030	_default_ldt = (int)&default_proc_ldt;
3031	PCPU_SET(currentldt, _default_ldt);
3032	PT_SET_MA(ldt, *vtopte((unsigned long)ldt) & ~PG_RW);
3033	xen_set_ldt((unsigned long) ldt, (sizeof ldt_segs / sizeof ldt_segs[0]));
3034
3035#if defined(XEN_PRIVILEGED)
3036	/*
3037	 * Initialize the i8254 before the console so that console
3038	 * initialization can use DELAY().
3039	 */
3040	i8254_init();
3041#endif
3042
3043	/*
3044	 * Initialize the console before we print anything out.
3045	 */
3046	cninit();
3047
3048	if (metadata_missing)
3049		printf("WARNING: loader(8) metadata is missing!\n");
3050
3051#ifdef DEV_ISA
3052#ifdef DEV_ATPIC
3053	elcr_probe();
3054	atpic_startup();
3055#else
3056	/* Reset and mask the atpics and leave them shut down. */
3057	atpic_reset();
3058
3059	/*
3060	 * Point the ICU spurious interrupt vectors at the APIC spurious
3061	 * interrupt handler.
3062	 */
3063	setidt(IDT_IO_INTS + 7, IDTVEC(spuriousint), SDT_SYS386IGT, SEL_KPL,
3064	    GSEL(GCODE_SEL, SEL_KPL));
3065	setidt(IDT_IO_INTS + 15, IDTVEC(spuriousint), SDT_SYS386IGT, SEL_KPL,
3066	    GSEL(GCODE_SEL, SEL_KPL));
3067#endif
3068#endif
3069
3070#ifdef DDB
3071	ksym_start = bootinfo.bi_symtab;
3072	ksym_end = bootinfo.bi_esymtab;
3073#endif
3074
3075	kdb_init();
3076
3077#ifdef KDB
3078	if (boothowto & RB_KDB)
3079		kdb_enter(KDB_WHY_BOOTFLAGS, "Boot flags requested debugger");
3080#endif
3081
3082	finishidentcpu();	/* Final stage of CPU initialization */
3083	setidt(IDT_UD, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL,
3084	    GSEL(GCODE_SEL, SEL_KPL));
3085	setidt(IDT_GP, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL,
3086	    GSEL(GCODE_SEL, SEL_KPL));
3087	initializecpu();	/* Initialize CPU registers */
3088	initializecpucache();
3089
3090	/* pointer to selector slot for %fs/%gs */
3091	PCPU_SET(fsgs_gdt, &gdt[GUFS_SEL].sd);
3092
3093	dblfault_tss.tss_esp = dblfault_tss.tss_esp0 = dblfault_tss.tss_esp1 =
3094	    dblfault_tss.tss_esp2 = (int)&dblfault_stack[sizeof(dblfault_stack)];
3095	dblfault_tss.tss_ss = dblfault_tss.tss_ss0 = dblfault_tss.tss_ss1 =
3096	    dblfault_tss.tss_ss2 = GSEL(GDATA_SEL, SEL_KPL);
3097#if defined(PAE) || defined(PAE_TABLES)
3098	dblfault_tss.tss_cr3 = (int)IdlePDPT;
3099#else
3100	dblfault_tss.tss_cr3 = (int)IdlePTD;
3101#endif
3102	dblfault_tss.tss_eip = (int)dblfault_handler;
3103	dblfault_tss.tss_eflags = PSL_KERNEL;
3104	dblfault_tss.tss_ds = dblfault_tss.tss_es =
3105	    dblfault_tss.tss_gs = GSEL(GDATA_SEL, SEL_KPL);
3106	dblfault_tss.tss_fs = GSEL(GPRIV_SEL, SEL_KPL);
3107	dblfault_tss.tss_cs = GSEL(GCODE_SEL, SEL_KPL);
3108	dblfault_tss.tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
3109
3110	vm86_initialize();
3111	getmemsize(first);
3112	init_param2(physmem);
3113
3114	/* now running on new page tables, configured,and u/iom is accessible */
3115
3116	msgbufinit(msgbufp, msgbufsize);
3117#ifdef DEV_NPX
3118	npxinit(true);
3119#endif
3120	/*
3121	 * Set up thread0 pcb after npxinit calculated pcb + fpu save
3122	 * area size.  Zero out the extended state header in fpu save
3123	 * area.
3124	 */
3125	thread0.td_pcb = get_pcb_td(&thread0);
3126	bzero(get_pcb_user_save_td(&thread0), cpu_max_ext_state_size);
3127#ifdef CPU_ENABLE_SSE
3128	if (use_xsave) {
3129		xhdr = (struct xstate_hdr *)(get_pcb_user_save_td(&thread0) +
3130		    1);
3131		xhdr->xstate_bv = xsave_mask;
3132	}
3133#endif
3134	PCPU_SET(curpcb, thread0.td_pcb);
3135	/* make an initial tss so cpu can get interrupt stack on syscall! */
3136	/* Note: -16 is so we can grow the trapframe if we came from vm86 */
3137	PCPU_SET(common_tss.tss_esp0, (vm_offset_t)thread0.td_pcb - 16);
3138	PCPU_SET(common_tss.tss_ss0, GSEL(GDATA_SEL, SEL_KPL));
3139	gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
3140	HYPERVISOR_stack_switch(GSEL(GDATA_SEL, SEL_KPL),
3141	    PCPU_GET(common_tss.tss_esp0));
3142
3143	/* transfer to user mode */
3144
3145	_ucodesel = GSEL(GUCODE_SEL, SEL_UPL);
3146	_udatasel = GSEL(GUDATA_SEL, SEL_UPL);
3147
3148	/* setup proc 0's pcb */
3149	thread0.td_pcb->pcb_flags = 0;
3150#if defined(PAE) || defined(PAE_TABLES)
3151	thread0.td_pcb->pcb_cr3 = (int)IdlePDPT;
3152#else
3153	thread0.td_pcb->pcb_cr3 = (int)IdlePTD;
3154#endif
3155	thread0.td_pcb->pcb_ext = 0;
3156	thread0.td_frame = &proc0_tf;
3157	thread0.td_pcb->pcb_fsd = PCPU_GET(fsgs_gdt)[0];
3158	thread0.td_pcb->pcb_gsd = PCPU_GET(fsgs_gdt)[1];
3159
3160	cpu_probe_amdc1e();
3161
3162	/* Location of kernel stack for locore */
3163	return ((register_t)thread0.td_pcb);
3164}
3165
3166#else
3167register_t
3168init386(first)
3169	int first;
3170{
3171	struct gate_descriptor *gdp;
3172	int gsel_tss, metadata_missing, x, pa;
3173	struct pcpu *pc;
3174#ifdef CPU_ENABLE_SSE
3175	struct xstate_hdr *xhdr;
3176#endif
3177
3178	thread0.td_kstack = proc0kstack;
3179	thread0.td_kstack_pages = TD0_KSTACK_PAGES;
3180
3181	/*
3182 	 * This may be done better later if it gets more high level
3183 	 * components in it. If so just link td->td_proc here.
3184	 */
3185	proc_linkup0(&proc0, &thread0);
3186
3187#ifdef PC98
3188	/*
3189	 * Initialize DMAC
3190	 */
3191	pc98_init_dmac();
3192#endif
3193
3194	metadata_missing = 0;
3195	if (bootinfo.bi_modulep) {
3196		preload_metadata = (caddr_t)bootinfo.bi_modulep + KERNBASE;
3197		preload_bootstrap_relocate(KERNBASE);
3198	} else {
3199		metadata_missing = 1;
3200	}
3201	if (envmode == 1)
3202		kern_envp = static_env;
3203	else if (bootinfo.bi_envp)
3204		kern_envp = (caddr_t)bootinfo.bi_envp + KERNBASE;
3205
3206	/* Init basic tunables, hz etc */
3207	init_param1();
3208
3209	/*
3210	 * Make gdt memory segments.  All segments cover the full 4GB
3211	 * of address space and permissions are enforced at page level.
3212	 */
3213	gdt_segs[GCODE_SEL].ssd_limit = atop(0 - 1);
3214	gdt_segs[GDATA_SEL].ssd_limit = atop(0 - 1);
3215	gdt_segs[GUCODE_SEL].ssd_limit = atop(0 - 1);
3216	gdt_segs[GUDATA_SEL].ssd_limit = atop(0 - 1);
3217	gdt_segs[GUFS_SEL].ssd_limit = atop(0 - 1);
3218	gdt_segs[GUGS_SEL].ssd_limit = atop(0 - 1);
3219
3220	pc = &__pcpu[0];
3221	gdt_segs[GPRIV_SEL].ssd_limit = atop(0 - 1);
3222	gdt_segs[GPRIV_SEL].ssd_base = (int) pc;
3223	gdt_segs[GPROC0_SEL].ssd_base = (int) &pc->pc_common_tss;
3224
3225	for (x = 0; x < NGDT; x++)
3226		ssdtosd(&gdt_segs[x], &gdt[x].sd);
3227
3228	r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
3229	r_gdt.rd_base =  (int) gdt;
3230	mtx_init(&dt_lock, "descriptor tables", NULL, MTX_SPIN);
3231	lgdt(&r_gdt);
3232
3233	pcpu_init(pc, 0, sizeof(struct pcpu));
3234	for (pa = first; pa < first + DPCPU_SIZE; pa += PAGE_SIZE)
3235		pmap_kenter(pa + KERNBASE, pa);
3236	dpcpu_init((void *)(first + KERNBASE), 0);
3237	first += DPCPU_SIZE;
3238	PCPU_SET(prvspace, pc);
3239	PCPU_SET(curthread, &thread0);
3240
3241	/*
3242	 * Initialize mutexes.
3243	 *
3244	 * icu_lock: in order to allow an interrupt to occur in a critical
3245	 * 	     section, to set pcpu->ipending (etc...) properly, we
3246	 *	     must be able to get the icu lock, so it can't be
3247	 *	     under witness.
3248	 */
3249	mutex_init();
3250	mtx_init(&icu_lock, "icu", NULL, MTX_SPIN | MTX_NOWITNESS | MTX_NOPROFILE);
3251
3252	/* make ldt memory segments */
3253	ldt_segs[LUCODE_SEL].ssd_limit = atop(0 - 1);
3254	ldt_segs[LUDATA_SEL].ssd_limit = atop(0 - 1);
3255	for (x = 0; x < sizeof ldt_segs / sizeof ldt_segs[0]; x++)
3256		ssdtosd(&ldt_segs[x], &ldt[x].sd);
3257
3258	_default_ldt = GSEL(GLDT_SEL, SEL_KPL);
3259	lldt(_default_ldt);
3260	PCPU_SET(currentldt, _default_ldt);
3261
3262	/* exceptions */
3263	for (x = 0; x < NIDT; x++)
3264		setidt(x, &IDTVEC(rsvd), SDT_SYS386TGT, SEL_KPL,
3265		    GSEL(GCODE_SEL, SEL_KPL));
3266	setidt(IDT_DE, &IDTVEC(div),  SDT_SYS386TGT, SEL_KPL,
3267	    GSEL(GCODE_SEL, SEL_KPL));
3268	setidt(IDT_DB, &IDTVEC(dbg),  SDT_SYS386IGT, SEL_KPL,
3269	    GSEL(GCODE_SEL, SEL_KPL));
3270	setidt(IDT_NMI, &IDTVEC(nmi),  SDT_SYS386IGT, SEL_KPL,
3271	    GSEL(GCODE_SEL, SEL_KPL));
3272 	setidt(IDT_BP, &IDTVEC(bpt),  SDT_SYS386IGT, SEL_UPL,
3273	    GSEL(GCODE_SEL, SEL_KPL));
3274	setidt(IDT_OF, &IDTVEC(ofl),  SDT_SYS386TGT, SEL_UPL,
3275	    GSEL(GCODE_SEL, SEL_KPL));
3276	setidt(IDT_BR, &IDTVEC(bnd),  SDT_SYS386TGT, SEL_KPL,
3277	    GSEL(GCODE_SEL, SEL_KPL));
3278	setidt(IDT_UD, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL,
3279	    GSEL(GCODE_SEL, SEL_KPL));
3280	setidt(IDT_NM, &IDTVEC(dna),  SDT_SYS386TGT, SEL_KPL
3281	    , GSEL(GCODE_SEL, SEL_KPL));
3282	setidt(IDT_DF, 0,  SDT_SYSTASKGT, SEL_KPL, GSEL(GPANIC_SEL, SEL_KPL));
3283	setidt(IDT_FPUGP, &IDTVEC(fpusegm),  SDT_SYS386TGT, SEL_KPL,
3284	    GSEL(GCODE_SEL, SEL_KPL));
3285	setidt(IDT_TS, &IDTVEC(tss),  SDT_SYS386TGT, SEL_KPL,
3286	    GSEL(GCODE_SEL, SEL_KPL));
3287	setidt(IDT_NP, &IDTVEC(missing),  SDT_SYS386TGT, SEL_KPL,
3288	    GSEL(GCODE_SEL, SEL_KPL));
3289	setidt(IDT_SS, &IDTVEC(stk),  SDT_SYS386TGT, SEL_KPL,
3290	    GSEL(GCODE_SEL, SEL_KPL));
3291	setidt(IDT_GP, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL,
3292	    GSEL(GCODE_SEL, SEL_KPL));
3293	setidt(IDT_PF, &IDTVEC(page),  SDT_SYS386IGT, SEL_KPL,
3294	    GSEL(GCODE_SEL, SEL_KPL));
3295	setidt(IDT_MF, &IDTVEC(fpu),  SDT_SYS386TGT, SEL_KPL,
3296	    GSEL(GCODE_SEL, SEL_KPL));
3297	setidt(IDT_AC, &IDTVEC(align), SDT_SYS386TGT, SEL_KPL,
3298	    GSEL(GCODE_SEL, SEL_KPL));
3299	setidt(IDT_MC, &IDTVEC(mchk),  SDT_SYS386TGT, SEL_KPL,
3300	    GSEL(GCODE_SEL, SEL_KPL));
3301	setidt(IDT_XF, &IDTVEC(xmm), SDT_SYS386TGT, SEL_KPL,
3302	    GSEL(GCODE_SEL, SEL_KPL));
3303 	setidt(IDT_SYSCALL, &IDTVEC(int0x80_syscall), SDT_SYS386TGT, SEL_UPL,
3304	    GSEL(GCODE_SEL, SEL_KPL));
3305#ifdef KDTRACE_HOOKS
3306	setidt(IDT_DTRACE_RET, &IDTVEC(dtrace_ret), SDT_SYS386TGT, SEL_UPL,
3307	    GSEL(GCODE_SEL, SEL_KPL));
3308#endif
3309#ifdef XENHVM
3310	setidt(IDT_EVTCHN, &IDTVEC(xen_intr_upcall), SDT_SYS386IGT, SEL_UPL,
3311	    GSEL(GCODE_SEL, SEL_KPL));
3312#endif
3313
3314	r_idt.rd_limit = sizeof(idt0) - 1;
3315	r_idt.rd_base = (int) idt;
3316	lidt(&r_idt);
3317
3318#ifdef XBOX
3319	/*
3320	 * The following code queries the PCI ID of 0:0:0. For the XBOX,
3321	 * This should be 0x10de / 0x02a5.
3322	 *
3323	 * This is exactly what Linux does.
3324	 */
3325	outl(0xcf8, 0x80000000);
3326	if (inl(0xcfc) == 0x02a510de) {
3327		arch_i386_is_xbox = 1;
3328		pic16l_setled(XBOX_LED_GREEN);
3329
3330		/*
3331		 * We are an XBOX, but we may have either 64MB or 128MB of
3332		 * memory. The PCI host bridge should be programmed for this,
3333		 * so we just query it.
3334		 */
3335		outl(0xcf8, 0x80000084);
3336		arch_i386_xbox_memsize = (inl(0xcfc) == 0x7FFFFFF) ? 128 : 64;
3337	}
3338#endif /* XBOX */
3339
3340	/*
3341	 * Initialize the i8254 before the console so that console
3342	 * initialization can use DELAY().
3343	 */
3344	i8254_init();
3345
3346	finishidentcpu();	/* Final stage of CPU initialization */
3347	setidt(IDT_UD, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL,
3348	    GSEL(GCODE_SEL, SEL_KPL));
3349	setidt(IDT_GP, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL,
3350	    GSEL(GCODE_SEL, SEL_KPL));
3351	initializecpu();	/* Initialize CPU registers */
3352	initializecpucache();
3353
3354	/* pointer to selector slot for %fs/%gs */
3355	PCPU_SET(fsgs_gdt, &gdt[GUFS_SEL].sd);
3356
3357	dblfault_tss.tss_esp = dblfault_tss.tss_esp0 = dblfault_tss.tss_esp1 =
3358	    dblfault_tss.tss_esp2 = (int)&dblfault_stack[sizeof(dblfault_stack)];
3359	dblfault_tss.tss_ss = dblfault_tss.tss_ss0 = dblfault_tss.tss_ss1 =
3360	    dblfault_tss.tss_ss2 = GSEL(GDATA_SEL, SEL_KPL);
3361#if defined(PAE) || defined(PAE_TABLES)
3362	dblfault_tss.tss_cr3 = (int)IdlePDPT;
3363#else
3364	dblfault_tss.tss_cr3 = (int)IdlePTD;
3365#endif
3366	dblfault_tss.tss_eip = (int)dblfault_handler;
3367	dblfault_tss.tss_eflags = PSL_KERNEL;
3368	dblfault_tss.tss_ds = dblfault_tss.tss_es =
3369	    dblfault_tss.tss_gs = GSEL(GDATA_SEL, SEL_KPL);
3370	dblfault_tss.tss_fs = GSEL(GPRIV_SEL, SEL_KPL);
3371	dblfault_tss.tss_cs = GSEL(GCODE_SEL, SEL_KPL);
3372	dblfault_tss.tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
3373
3374	vm86_initialize();
3375	getmemsize(first);
3376	init_param2(physmem);
3377
3378	/* now running on new page tables, configured,and u/iom is accessible */
3379
3380	/*
3381	 * Initialize the console before we print anything out.
3382	 */
3383	cninit();
3384
3385	if (metadata_missing)
3386		printf("WARNING: loader(8) metadata is missing!\n");
3387
3388#ifdef DEV_ISA
3389#ifdef DEV_ATPIC
3390#ifndef PC98
3391	elcr_probe();
3392#endif
3393	atpic_startup();
3394#else
3395	/* Reset and mask the atpics and leave them shut down. */
3396	atpic_reset();
3397
3398	/*
3399	 * Point the ICU spurious interrupt vectors at the APIC spurious
3400	 * interrupt handler.
3401	 */
3402	setidt(IDT_IO_INTS + 7, IDTVEC(spuriousint), SDT_SYS386IGT, SEL_KPL,
3403	    GSEL(GCODE_SEL, SEL_KPL));
3404	setidt(IDT_IO_INTS + 15, IDTVEC(spuriousint), SDT_SYS386IGT, SEL_KPL,
3405	    GSEL(GCODE_SEL, SEL_KPL));
3406#endif
3407#endif
3408
3409#ifdef DDB
3410	ksym_start = bootinfo.bi_symtab;
3411	ksym_end = bootinfo.bi_esymtab;
3412#endif
3413
3414	kdb_init();
3415
3416#ifdef KDB
3417	if (boothowto & RB_KDB)
3418		kdb_enter(KDB_WHY_BOOTFLAGS, "Boot flags requested debugger");
3419#endif
3420
3421	msgbufinit(msgbufp, msgbufsize);
3422#ifdef DEV_NPX
3423	npxinit(true);
3424#endif
3425	/*
3426	 * Set up thread0 pcb after npxinit calculated pcb + fpu save
3427	 * area size.  Zero out the extended state header in fpu save
3428	 * area.
3429	 */
3430	thread0.td_pcb = get_pcb_td(&thread0);
3431	bzero(get_pcb_user_save_td(&thread0), cpu_max_ext_state_size);
3432#ifdef CPU_ENABLE_SSE
3433	if (use_xsave) {
3434		xhdr = (struct xstate_hdr *)(get_pcb_user_save_td(&thread0) +
3435		    1);
3436		xhdr->xstate_bv = xsave_mask;
3437	}
3438#endif
3439	PCPU_SET(curpcb, thread0.td_pcb);
3440	/* make an initial tss so cpu can get interrupt stack on syscall! */
3441	/* Note: -16 is so we can grow the trapframe if we came from vm86 */
3442	PCPU_SET(common_tss.tss_esp0, (vm_offset_t)thread0.td_pcb - 16);
3443	PCPU_SET(common_tss.tss_ss0, GSEL(GDATA_SEL, SEL_KPL));
3444	gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
3445	PCPU_SET(tss_gdt, &gdt[GPROC0_SEL].sd);
3446	PCPU_SET(common_tssd, *PCPU_GET(tss_gdt));
3447	PCPU_SET(common_tss.tss_ioopt, (sizeof (struct i386tss)) << 16);
3448	ltr(gsel_tss);
3449
3450	/* make a call gate to reenter kernel with */
3451	gdp = &ldt[LSYS5CALLS_SEL].gd;
3452
3453	x = (int) &IDTVEC(lcall_syscall);
3454	gdp->gd_looffset = x;
3455	gdp->gd_selector = GSEL(GCODE_SEL,SEL_KPL);
3456	gdp->gd_stkcpy = 1;
3457	gdp->gd_type = SDT_SYS386CGT;
3458	gdp->gd_dpl = SEL_UPL;
3459	gdp->gd_p = 1;
3460	gdp->gd_hioffset = x >> 16;
3461
3462	/* XXX does this work? */
3463	/* XXX yes! */
3464	ldt[LBSDICALLS_SEL] = ldt[LSYS5CALLS_SEL];
3465	ldt[LSOL26CALLS_SEL] = ldt[LSYS5CALLS_SEL];
3466
3467	/* transfer to user mode */
3468
3469	_ucodesel = GSEL(GUCODE_SEL, SEL_UPL);
3470	_udatasel = GSEL(GUDATA_SEL, SEL_UPL);
3471
3472	/* setup proc 0's pcb */
3473	thread0.td_pcb->pcb_flags = 0;
3474#if defined(PAE) || defined(PAE_TABLES)
3475	thread0.td_pcb->pcb_cr3 = (int)IdlePDPT;
3476#else
3477	thread0.td_pcb->pcb_cr3 = (int)IdlePTD;
3478#endif
3479	thread0.td_pcb->pcb_ext = 0;
3480	thread0.td_frame = &proc0_tf;
3481
3482	cpu_probe_amdc1e();
3483
3484#ifdef FDT
3485	x86_init_fdt();
3486#endif
3487
3488	/* Location of kernel stack for locore */
3489	return ((register_t)thread0.td_pcb);
3490}
3491#endif
3492
3493void
3494cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
3495{
3496
3497	pcpu->pc_acpi_id = 0xffffffff;
3498}
3499
3500#ifndef PC98
3501static int
3502smap_sysctl_handler(SYSCTL_HANDLER_ARGS)
3503{
3504	struct bios_smap *smapbase;
3505	struct bios_smap_xattr smap;
3506	caddr_t kmdp;
3507	uint32_t *smapattr;
3508	int count, error, i;
3509
3510	/* Retrieve the system memory map from the loader. */
3511	kmdp = preload_search_by_type("elf kernel");
3512	if (kmdp == NULL)
3513		kmdp = preload_search_by_type("elf32 kernel");
3514	if (kmdp == NULL)
3515		return (0);
3516	smapbase = (struct bios_smap *)preload_search_info(kmdp,
3517	    MODINFO_METADATA | MODINFOMD_SMAP);
3518	if (smapbase == NULL)
3519		return (0);
3520	smapattr = (uint32_t *)preload_search_info(kmdp,
3521	    MODINFO_METADATA | MODINFOMD_SMAP_XATTR);
3522	count = *((u_int32_t *)smapbase - 1) / sizeof(*smapbase);
3523	error = 0;
3524	for (i = 0; i < count; i++) {
3525		smap.base = smapbase[i].base;
3526		smap.length = smapbase[i].length;
3527		smap.type = smapbase[i].type;
3528		if (smapattr != NULL)
3529			smap.xattr = smapattr[i];
3530		else
3531			smap.xattr = 0;
3532		error = SYSCTL_OUT(req, &smap, sizeof(smap));
3533	}
3534	return (error);
3535}
3536SYSCTL_PROC(_machdep, OID_AUTO, smap, CTLTYPE_OPAQUE|CTLFLAG_RD, NULL, 0,
3537    smap_sysctl_handler, "S,bios_smap_xattr", "Raw BIOS SMAP data");
3538#endif /* !PC98 */
3539
3540void
3541spinlock_enter(void)
3542{
3543	struct thread *td;
3544	register_t flags;
3545
3546	td = curthread;
3547	if (td->td_md.md_spinlock_count == 0) {
3548		flags = intr_disable();
3549		td->td_md.md_spinlock_count = 1;
3550		td->td_md.md_saved_flags = flags;
3551	} else
3552		td->td_md.md_spinlock_count++;
3553	critical_enter();
3554}
3555
3556void
3557spinlock_exit(void)
3558{
3559	struct thread *td;
3560	register_t flags;
3561
3562	td = curthread;
3563	critical_exit();
3564	flags = td->td_md.md_saved_flags;
3565	td->td_md.md_spinlock_count--;
3566	if (td->td_md.md_spinlock_count == 0)
3567		intr_restore(flags);
3568}
3569
3570#if defined(I586_CPU) && !defined(NO_F00F_HACK)
3571static void f00f_hack(void *unused);
3572SYSINIT(f00f_hack, SI_SUB_INTRINSIC, SI_ORDER_FIRST, f00f_hack, NULL);
3573
3574static void
3575f00f_hack(void *unused)
3576{
3577	struct gate_descriptor *new_idt;
3578	vm_offset_t tmp;
3579
3580	if (!has_f00f_bug)
3581		return;
3582
3583	GIANT_REQUIRED;
3584
3585	printf("Intel Pentium detected, installing workaround for F00F bug\n");
3586
3587	tmp = kmem_malloc(kernel_arena, PAGE_SIZE * 2, M_WAITOK | M_ZERO);
3588	if (tmp == 0)
3589		panic("kmem_malloc returned 0");
3590
3591	/* Put the problematic entry (#6) at the end of the lower page. */
3592	new_idt = (struct gate_descriptor*)
3593	    (tmp + PAGE_SIZE - 7 * sizeof(struct gate_descriptor));
3594	bcopy(idt, new_idt, sizeof(idt0));
3595	r_idt.rd_base = (u_int)new_idt;
3596	lidt(&r_idt);
3597	idt = new_idt;
3598	pmap_protect(kernel_pmap, tmp, tmp + PAGE_SIZE, VM_PROT_READ);
3599}
3600#endif /* defined(I586_CPU) && !NO_F00F_HACK */
3601
3602/*
3603 * Construct a PCB from a trapframe. This is called from kdb_trap() where
3604 * we want to start a backtrace from the function that caused us to enter
3605 * the debugger. We have the context in the trapframe, but base the trace
3606 * on the PCB. The PCB doesn't have to be perfect, as long as it contains
3607 * enough for a backtrace.
3608 */
3609void
3610makectx(struct trapframe *tf, struct pcb *pcb)
3611{
3612
3613	pcb->pcb_edi = tf->tf_edi;
3614	pcb->pcb_esi = tf->tf_esi;
3615	pcb->pcb_ebp = tf->tf_ebp;
3616	pcb->pcb_ebx = tf->tf_ebx;
3617	pcb->pcb_eip = tf->tf_eip;
3618	pcb->pcb_esp = (ISPL(tf->tf_cs)) ? tf->tf_esp : (int)(tf + 1) - 8;
3619}
3620
3621int
3622ptrace_set_pc(struct thread *td, u_long addr)
3623{
3624
3625	td->td_frame->tf_eip = addr;
3626	return (0);
3627}
3628
3629int
3630ptrace_single_step(struct thread *td)
3631{
3632	td->td_frame->tf_eflags |= PSL_T;
3633	return (0);
3634}
3635
3636int
3637ptrace_clear_single_step(struct thread *td)
3638{
3639	td->td_frame->tf_eflags &= ~PSL_T;
3640	return (0);
3641}
3642
3643int
3644fill_regs(struct thread *td, struct reg *regs)
3645{
3646	struct pcb *pcb;
3647	struct trapframe *tp;
3648
3649	tp = td->td_frame;
3650	pcb = td->td_pcb;
3651	regs->r_gs = pcb->pcb_gs;
3652	return (fill_frame_regs(tp, regs));
3653}
3654
3655int
3656fill_frame_regs(struct trapframe *tp, struct reg *regs)
3657{
3658	regs->r_fs = tp->tf_fs;
3659	regs->r_es = tp->tf_es;
3660	regs->r_ds = tp->tf_ds;
3661	regs->r_edi = tp->tf_edi;
3662	regs->r_esi = tp->tf_esi;
3663	regs->r_ebp = tp->tf_ebp;
3664	regs->r_ebx = tp->tf_ebx;
3665	regs->r_edx = tp->tf_edx;
3666	regs->r_ecx = tp->tf_ecx;
3667	regs->r_eax = tp->tf_eax;
3668	regs->r_eip = tp->tf_eip;
3669	regs->r_cs = tp->tf_cs;
3670	regs->r_eflags = tp->tf_eflags;
3671	regs->r_esp = tp->tf_esp;
3672	regs->r_ss = tp->tf_ss;
3673	return (0);
3674}
3675
3676int
3677set_regs(struct thread *td, struct reg *regs)
3678{
3679	struct pcb *pcb;
3680	struct trapframe *tp;
3681
3682	tp = td->td_frame;
3683	if (!EFL_SECURE(regs->r_eflags, tp->tf_eflags) ||
3684	    !CS_SECURE(regs->r_cs))
3685		return (EINVAL);
3686	pcb = td->td_pcb;
3687	tp->tf_fs = regs->r_fs;
3688	tp->tf_es = regs->r_es;
3689	tp->tf_ds = regs->r_ds;
3690	tp->tf_edi = regs->r_edi;
3691	tp->tf_esi = regs->r_esi;
3692	tp->tf_ebp = regs->r_ebp;
3693	tp->tf_ebx = regs->r_ebx;
3694	tp->tf_edx = regs->r_edx;
3695	tp->tf_ecx = regs->r_ecx;
3696	tp->tf_eax = regs->r_eax;
3697	tp->tf_eip = regs->r_eip;
3698	tp->tf_cs = regs->r_cs;
3699	tp->tf_eflags = regs->r_eflags;
3700	tp->tf_esp = regs->r_esp;
3701	tp->tf_ss = regs->r_ss;
3702	pcb->pcb_gs = regs->r_gs;
3703	return (0);
3704}
3705
3706#ifdef CPU_ENABLE_SSE
3707static void
3708fill_fpregs_xmm(sv_xmm, sv_87)
3709	struct savexmm *sv_xmm;
3710	struct save87 *sv_87;
3711{
3712	register struct env87 *penv_87 = &sv_87->sv_env;
3713	register struct envxmm *penv_xmm = &sv_xmm->sv_env;
3714	int i;
3715
3716	bzero(sv_87, sizeof(*sv_87));
3717
3718	/* FPU control/status */
3719	penv_87->en_cw = penv_xmm->en_cw;
3720	penv_87->en_sw = penv_xmm->en_sw;
3721	penv_87->en_tw = penv_xmm->en_tw;
3722	penv_87->en_fip = penv_xmm->en_fip;
3723	penv_87->en_fcs = penv_xmm->en_fcs;
3724	penv_87->en_opcode = penv_xmm->en_opcode;
3725	penv_87->en_foo = penv_xmm->en_foo;
3726	penv_87->en_fos = penv_xmm->en_fos;
3727
3728	/* FPU registers */
3729	for (i = 0; i < 8; ++i)
3730		sv_87->sv_ac[i] = sv_xmm->sv_fp[i].fp_acc;
3731}
3732
3733static void
3734set_fpregs_xmm(sv_87, sv_xmm)
3735	struct save87 *sv_87;
3736	struct savexmm *sv_xmm;
3737{
3738	register struct env87 *penv_87 = &sv_87->sv_env;
3739	register struct envxmm *penv_xmm = &sv_xmm->sv_env;
3740	int i;
3741
3742	/* FPU control/status */
3743	penv_xmm->en_cw = penv_87->en_cw;
3744	penv_xmm->en_sw = penv_87->en_sw;
3745	penv_xmm->en_tw = penv_87->en_tw;
3746	penv_xmm->en_fip = penv_87->en_fip;
3747	penv_xmm->en_fcs = penv_87->en_fcs;
3748	penv_xmm->en_opcode = penv_87->en_opcode;
3749	penv_xmm->en_foo = penv_87->en_foo;
3750	penv_xmm->en_fos = penv_87->en_fos;
3751
3752	/* FPU registers */
3753	for (i = 0; i < 8; ++i)
3754		sv_xmm->sv_fp[i].fp_acc = sv_87->sv_ac[i];
3755}
3756#endif /* CPU_ENABLE_SSE */
3757
3758int
3759fill_fpregs(struct thread *td, struct fpreg *fpregs)
3760{
3761
3762	KASSERT(td == curthread || TD_IS_SUSPENDED(td) ||
3763	    P_SHOULDSTOP(td->td_proc),
3764	    ("not suspended thread %p", td));
3765#ifdef DEV_NPX
3766	npxgetregs(td);
3767#else
3768	bzero(fpregs, sizeof(*fpregs));
3769#endif
3770#ifdef CPU_ENABLE_SSE
3771	if (cpu_fxsr)
3772		fill_fpregs_xmm(&get_pcb_user_save_td(td)->sv_xmm,
3773		    (struct save87 *)fpregs);
3774	else
3775#endif /* CPU_ENABLE_SSE */
3776		bcopy(&get_pcb_user_save_td(td)->sv_87, fpregs,
3777		    sizeof(*fpregs));
3778	return (0);
3779}
3780
3781int
3782set_fpregs(struct thread *td, struct fpreg *fpregs)
3783{
3784
3785#ifdef CPU_ENABLE_SSE
3786	if (cpu_fxsr)
3787		set_fpregs_xmm((struct save87 *)fpregs,
3788		    &get_pcb_user_save_td(td)->sv_xmm);
3789	else
3790#endif /* CPU_ENABLE_SSE */
3791		bcopy(fpregs, &get_pcb_user_save_td(td)->sv_87,
3792		    sizeof(*fpregs));
3793#ifdef DEV_NPX
3794	npxuserinited(td);
3795#endif
3796	return (0);
3797}
3798
3799/*
3800 * Get machine context.
3801 */
3802int
3803get_mcontext(struct thread *td, mcontext_t *mcp, int flags)
3804{
3805	struct trapframe *tp;
3806	struct segment_descriptor *sdp;
3807
3808	tp = td->td_frame;
3809
3810	PROC_LOCK(curthread->td_proc);
3811	mcp->mc_onstack = sigonstack(tp->tf_esp);
3812	PROC_UNLOCK(curthread->td_proc);
3813	mcp->mc_gs = td->td_pcb->pcb_gs;
3814	mcp->mc_fs = tp->tf_fs;
3815	mcp->mc_es = tp->tf_es;
3816	mcp->mc_ds = tp->tf_ds;
3817	mcp->mc_edi = tp->tf_edi;
3818	mcp->mc_esi = tp->tf_esi;
3819	mcp->mc_ebp = tp->tf_ebp;
3820	mcp->mc_isp = tp->tf_isp;
3821	mcp->mc_eflags = tp->tf_eflags;
3822	if (flags & GET_MC_CLEAR_RET) {
3823		mcp->mc_eax = 0;
3824		mcp->mc_edx = 0;
3825		mcp->mc_eflags &= ~PSL_C;
3826	} else {
3827		mcp->mc_eax = tp->tf_eax;
3828		mcp->mc_edx = tp->tf_edx;
3829	}
3830	mcp->mc_ebx = tp->tf_ebx;
3831	mcp->mc_ecx = tp->tf_ecx;
3832	mcp->mc_eip = tp->tf_eip;
3833	mcp->mc_cs = tp->tf_cs;
3834	mcp->mc_esp = tp->tf_esp;
3835	mcp->mc_ss = tp->tf_ss;
3836	mcp->mc_len = sizeof(*mcp);
3837	get_fpcontext(td, mcp, NULL, 0);
3838	sdp = &td->td_pcb->pcb_fsd;
3839	mcp->mc_fsbase = sdp->sd_hibase << 24 | sdp->sd_lobase;
3840	sdp = &td->td_pcb->pcb_gsd;
3841	mcp->mc_gsbase = sdp->sd_hibase << 24 | sdp->sd_lobase;
3842	mcp->mc_flags = 0;
3843	mcp->mc_xfpustate = 0;
3844	mcp->mc_xfpustate_len = 0;
3845	bzero(mcp->mc_spare2, sizeof(mcp->mc_spare2));
3846	return (0);
3847}
3848
3849/*
3850 * Set machine context.
3851 *
3852 * However, we don't set any but the user modifiable flags, and we won't
3853 * touch the cs selector.
3854 */
3855int
3856set_mcontext(struct thread *td, mcontext_t *mcp)
3857{
3858	struct trapframe *tp;
3859	char *xfpustate;
3860	int eflags, ret;
3861
3862	tp = td->td_frame;
3863	if (mcp->mc_len != sizeof(*mcp) ||
3864	    (mcp->mc_flags & ~_MC_FLAG_MASK) != 0)
3865		return (EINVAL);
3866	eflags = (mcp->mc_eflags & PSL_USERCHANGE) |
3867	    (tp->tf_eflags & ~PSL_USERCHANGE);
3868	if (mcp->mc_flags & _MC_HASFPXSTATE) {
3869		if (mcp->mc_xfpustate_len > cpu_max_ext_state_size -
3870		    sizeof(union savefpu))
3871			return (EINVAL);
3872		xfpustate = __builtin_alloca(mcp->mc_xfpustate_len);
3873		ret = copyin((void *)mcp->mc_xfpustate, xfpustate,
3874		    mcp->mc_xfpustate_len);
3875		if (ret != 0)
3876			return (ret);
3877	} else
3878		xfpustate = NULL;
3879	ret = set_fpcontext(td, mcp, xfpustate, mcp->mc_xfpustate_len);
3880	if (ret != 0)
3881		return (ret);
3882	tp->tf_fs = mcp->mc_fs;
3883	tp->tf_es = mcp->mc_es;
3884	tp->tf_ds = mcp->mc_ds;
3885	tp->tf_edi = mcp->mc_edi;
3886	tp->tf_esi = mcp->mc_esi;
3887	tp->tf_ebp = mcp->mc_ebp;
3888	tp->tf_ebx = mcp->mc_ebx;
3889	tp->tf_edx = mcp->mc_edx;
3890	tp->tf_ecx = mcp->mc_ecx;
3891	tp->tf_eax = mcp->mc_eax;
3892	tp->tf_eip = mcp->mc_eip;
3893	tp->tf_eflags = eflags;
3894	tp->tf_esp = mcp->mc_esp;
3895	tp->tf_ss = mcp->mc_ss;
3896	td->td_pcb->pcb_gs = mcp->mc_gs;
3897	return (0);
3898}
3899
3900static void
3901get_fpcontext(struct thread *td, mcontext_t *mcp, char *xfpusave,
3902    size_t xfpusave_len)
3903{
3904#ifdef CPU_ENABLE_SSE
3905	size_t max_len, len;
3906#endif
3907
3908#ifndef DEV_NPX
3909	mcp->mc_fpformat = _MC_FPFMT_NODEV;
3910	mcp->mc_ownedfp = _MC_FPOWNED_NONE;
3911	bzero(mcp->mc_fpstate, sizeof(mcp->mc_fpstate));
3912#else
3913	mcp->mc_ownedfp = npxgetregs(td);
3914	bcopy(get_pcb_user_save_td(td), &mcp->mc_fpstate[0],
3915	    sizeof(mcp->mc_fpstate));
3916	mcp->mc_fpformat = npxformat();
3917#ifdef CPU_ENABLE_SSE
3918	if (!use_xsave || xfpusave_len == 0)
3919		return;
3920	max_len = cpu_max_ext_state_size - sizeof(union savefpu);
3921	len = xfpusave_len;
3922	if (len > max_len) {
3923		len = max_len;
3924		bzero(xfpusave + max_len, len - max_len);
3925	}
3926	mcp->mc_flags |= _MC_HASFPXSTATE;
3927	mcp->mc_xfpustate_len = len;
3928	bcopy(get_pcb_user_save_td(td) + 1, xfpusave, len);
3929#endif
3930#endif
3931}
3932
3933static int
3934set_fpcontext(struct thread *td, mcontext_t *mcp, char *xfpustate,
3935    size_t xfpustate_len)
3936{
3937	union savefpu *fpstate;
3938	int error;
3939
3940	if (mcp->mc_fpformat == _MC_FPFMT_NODEV)
3941		return (0);
3942	else if (mcp->mc_fpformat != _MC_FPFMT_387 &&
3943	    mcp->mc_fpformat != _MC_FPFMT_XMM)
3944		return (EINVAL);
3945	else if (mcp->mc_ownedfp == _MC_FPOWNED_NONE) {
3946		/* We don't care what state is left in the FPU or PCB. */
3947		fpstate_drop(td);
3948		error = 0;
3949	} else if (mcp->mc_ownedfp == _MC_FPOWNED_FPU ||
3950	    mcp->mc_ownedfp == _MC_FPOWNED_PCB) {
3951#ifdef DEV_NPX
3952		fpstate = (union savefpu *)&mcp->mc_fpstate;
3953#ifdef CPU_ENABLE_SSE
3954		if (cpu_fxsr)
3955			fpstate->sv_xmm.sv_env.en_mxcsr &= cpu_mxcsr_mask;
3956#endif
3957		error = npxsetregs(td, fpstate, xfpustate, xfpustate_len);
3958#else
3959		error = EINVAL;
3960#endif
3961	} else
3962		return (EINVAL);
3963	return (error);
3964}
3965
3966static void
3967fpstate_drop(struct thread *td)
3968{
3969
3970	KASSERT(PCB_USER_FPU(td->td_pcb), ("fpstate_drop: kernel-owned fpu"));
3971	critical_enter();
3972#ifdef DEV_NPX
3973	if (PCPU_GET(fpcurthread) == td)
3974		npxdrop();
3975#endif
3976	/*
3977	 * XXX force a full drop of the npx.  The above only drops it if we
3978	 * owned it.  npxgetregs() has the same bug in the !cpu_fxsr case.
3979	 *
3980	 * XXX I don't much like npxgetregs()'s semantics of doing a full
3981	 * drop.  Dropping only to the pcb matches fnsave's behaviour.
3982	 * We only need to drop to !PCB_INITDONE in sendsig().  But
3983	 * sendsig() is the only caller of npxgetregs()... perhaps we just
3984	 * have too many layers.
3985	 */
3986	curthread->td_pcb->pcb_flags &= ~(PCB_NPXINITDONE |
3987	    PCB_NPXUSERINITDONE);
3988	critical_exit();
3989}
3990
3991int
3992fill_dbregs(struct thread *td, struct dbreg *dbregs)
3993{
3994	struct pcb *pcb;
3995
3996	if (td == NULL) {
3997		dbregs->dr[0] = rdr0();
3998		dbregs->dr[1] = rdr1();
3999		dbregs->dr[2] = rdr2();
4000		dbregs->dr[3] = rdr3();
4001		dbregs->dr[4] = rdr4();
4002		dbregs->dr[5] = rdr5();
4003		dbregs->dr[6] = rdr6();
4004		dbregs->dr[7] = rdr7();
4005	} else {
4006		pcb = td->td_pcb;
4007		dbregs->dr[0] = pcb->pcb_dr0;
4008		dbregs->dr[1] = pcb->pcb_dr1;
4009		dbregs->dr[2] = pcb->pcb_dr2;
4010		dbregs->dr[3] = pcb->pcb_dr3;
4011		dbregs->dr[4] = 0;
4012		dbregs->dr[5] = 0;
4013		dbregs->dr[6] = pcb->pcb_dr6;
4014		dbregs->dr[7] = pcb->pcb_dr7;
4015	}
4016	return (0);
4017}
4018
4019int
4020set_dbregs(struct thread *td, struct dbreg *dbregs)
4021{
4022	struct pcb *pcb;
4023	int i;
4024
4025	if (td == NULL) {
4026		load_dr0(dbregs->dr[0]);
4027		load_dr1(dbregs->dr[1]);
4028		load_dr2(dbregs->dr[2]);
4029		load_dr3(dbregs->dr[3]);
4030		load_dr4(dbregs->dr[4]);
4031		load_dr5(dbregs->dr[5]);
4032		load_dr6(dbregs->dr[6]);
4033		load_dr7(dbregs->dr[7]);
4034	} else {
4035		/*
4036		 * Don't let an illegal value for dr7 get set.	Specifically,
4037		 * check for undefined settings.  Setting these bit patterns
4038		 * result in undefined behaviour and can lead to an unexpected
4039		 * TRCTRAP.
4040		 */
4041		for (i = 0; i < 4; i++) {
4042			if (DBREG_DR7_ACCESS(dbregs->dr[7], i) == 0x02)
4043				return (EINVAL);
4044			if (DBREG_DR7_LEN(dbregs->dr[7], i) == 0x02)
4045				return (EINVAL);
4046		}
4047
4048		pcb = td->td_pcb;
4049
4050		/*
4051		 * Don't let a process set a breakpoint that is not within the
4052		 * process's address space.  If a process could do this, it
4053		 * could halt the system by setting a breakpoint in the kernel
4054		 * (if ddb was enabled).  Thus, we need to check to make sure
4055		 * that no breakpoints are being enabled for addresses outside
4056		 * process's address space.
4057		 *
4058		 * XXX - what about when the watched area of the user's
4059		 * address space is written into from within the kernel
4060		 * ... wouldn't that still cause a breakpoint to be generated
4061		 * from within kernel mode?
4062		 */
4063
4064		if (DBREG_DR7_ENABLED(dbregs->dr[7], 0)) {
4065			/* dr0 is enabled */
4066			if (dbregs->dr[0] >= VM_MAXUSER_ADDRESS)
4067				return (EINVAL);
4068		}
4069
4070		if (DBREG_DR7_ENABLED(dbregs->dr[7], 1)) {
4071			/* dr1 is enabled */
4072			if (dbregs->dr[1] >= VM_MAXUSER_ADDRESS)
4073				return (EINVAL);
4074		}
4075
4076		if (DBREG_DR7_ENABLED(dbregs->dr[7], 2)) {
4077			/* dr2 is enabled */
4078			if (dbregs->dr[2] >= VM_MAXUSER_ADDRESS)
4079				return (EINVAL);
4080		}
4081
4082		if (DBREG_DR7_ENABLED(dbregs->dr[7], 3)) {
4083			/* dr3 is enabled */
4084			if (dbregs->dr[3] >= VM_MAXUSER_ADDRESS)
4085				return (EINVAL);
4086		}
4087
4088		pcb->pcb_dr0 = dbregs->dr[0];
4089		pcb->pcb_dr1 = dbregs->dr[1];
4090		pcb->pcb_dr2 = dbregs->dr[2];
4091		pcb->pcb_dr3 = dbregs->dr[3];
4092		pcb->pcb_dr6 = dbregs->dr[6];
4093		pcb->pcb_dr7 = dbregs->dr[7];
4094
4095		pcb->pcb_flags |= PCB_DBREGS;
4096	}
4097
4098	return (0);
4099}
4100
4101/*
4102 * Return > 0 if a hardware breakpoint has been hit, and the
4103 * breakpoint was in user space.  Return 0, otherwise.
4104 */
4105int
4106user_dbreg_trap(void)
4107{
4108        u_int32_t dr7, dr6; /* debug registers dr6 and dr7 */
4109        u_int32_t bp;       /* breakpoint bits extracted from dr6 */
4110        int nbp;            /* number of breakpoints that triggered */
4111        caddr_t addr[4];    /* breakpoint addresses */
4112        int i;
4113
4114        dr7 = rdr7();
4115        if ((dr7 & 0x000000ff) == 0) {
4116                /*
4117                 * all GE and LE bits in the dr7 register are zero,
4118                 * thus the trap couldn't have been caused by the
4119                 * hardware debug registers
4120                 */
4121                return 0;
4122        }
4123
4124        nbp = 0;
4125        dr6 = rdr6();
4126        bp = dr6 & 0x0000000f;
4127
4128        if (!bp) {
4129                /*
4130                 * None of the breakpoint bits are set meaning this
4131                 * trap was not caused by any of the debug registers
4132                 */
4133                return 0;
4134        }
4135
4136        /*
4137         * at least one of the breakpoints were hit, check to see
4138         * which ones and if any of them are user space addresses
4139         */
4140
4141        if (bp & 0x01) {
4142                addr[nbp++] = (caddr_t)rdr0();
4143        }
4144        if (bp & 0x02) {
4145                addr[nbp++] = (caddr_t)rdr1();
4146        }
4147        if (bp & 0x04) {
4148                addr[nbp++] = (caddr_t)rdr2();
4149        }
4150        if (bp & 0x08) {
4151                addr[nbp++] = (caddr_t)rdr3();
4152        }
4153
4154        for (i = 0; i < nbp; i++) {
4155                if (addr[i] < (caddr_t)VM_MAXUSER_ADDRESS) {
4156                        /*
4157                         * addr[i] is in user space
4158                         */
4159                        return nbp;
4160                }
4161        }
4162
4163        /*
4164         * None of the breakpoints are in user space.
4165         */
4166        return 0;
4167}
4168
4169#ifdef KDB
4170
4171/*
4172 * Provide inb() and outb() as functions.  They are normally only available as
4173 * inline functions, thus cannot be called from the debugger.
4174 */
4175
4176/* silence compiler warnings */
4177u_char inb_(u_short);
4178void outb_(u_short, u_char);
4179
4180u_char
4181inb_(u_short port)
4182{
4183	return inb(port);
4184}
4185
4186void
4187outb_(u_short port, u_char data)
4188{
4189	outb(port, data);
4190}
4191
4192#endif /* KDB */
4193