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