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