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