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