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