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