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