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