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