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