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