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