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