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