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