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