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