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