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