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