i386 removal, part 11/x: Remove wrong machine/ setup in the boot Makefiles.
[dragonfly.git] / sys / platform / pc32 / 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  * $FreeBSD: src/sys/i386/i386/machdep.c,v 1.385.2.30 2003/05/31 08:48:05 alc Exp $
39  */
40
41 #include "use_npx.h"
42 #include "use_isa.h"
43 #include "opt_compat.h"
44 #include "opt_cpu.h"
45 #include "opt_ddb.h"
46 #include "opt_directio.h"
47 #include "opt_inet.h"
48 #include "opt_maxmem.h"
49 #include "opt_msgbuf.h"
50 #include "opt_perfmon.h"
51 #include "opt_swap.h"
52 #include "opt_userconfig.h"
53
54 #include <sys/param.h>
55 #include <sys/systm.h>
56 #include <sys/sysproto.h>
57 #include <sys/signalvar.h>
58 #include <sys/kernel.h>
59 #include <sys/linker.h>
60 #include <sys/malloc.h>
61 #include <sys/proc.h>
62 #include <sys/priv.h>
63 #include <sys/buf.h>
64 #include <sys/reboot.h>
65 #include <sys/mbuf.h>
66 #include <sys/msgbuf.h>
67 #include <sys/sysent.h>
68 #include <sys/sysctl.h>
69 #include <sys/vmmeter.h>
70 #include <sys/bus.h>
71 #include <sys/usched.h>
72 #include <sys/reg.h>
73
74 #include <vm/vm.h>
75 #include <vm/vm_param.h>
76 #include <sys/lock.h>
77 #include <vm/vm_kern.h>
78 #include <vm/vm_object.h>
79 #include <vm/vm_page.h>
80 #include <vm/vm_map.h>
81 #include <vm/vm_pager.h>
82 #include <vm/vm_extern.h>
83
84 #include <sys/thread2.h>
85 #include <sys/mplock2.h>
86 #include <sys/mutex2.h>
87
88 #include <sys/user.h>
89 #include <sys/exec.h>
90 #include <sys/cons.h>
91
92 #include <ddb/ddb.h>
93
94 #include <machine/cpu.h>
95 #include <machine/clock.h>
96 #include <machine/specialreg.h>
97 #include <machine/bootinfo.h>
98 #include <machine/md_var.h>
99 #include <machine/pc/bios.h>
100 #include <machine/pcb_ext.h>            /* pcb.h included via sys/user.h */
101 #include <machine/globaldata.h>         /* CPU_prvspace */
102 #include <machine/smp.h>
103 #ifdef PERFMON
104 #include <machine/perfmon.h>
105 #endif
106 #include <machine/cputypes.h>
107 #include <machine/intr_machdep.h>
108
109 #ifdef OLD_BUS_ARCH
110 #include <bus/isa/isa_device.h>
111 #endif
112 #include <machine_base/isa/isa_intr.h>
113 #include <bus/isa/rtc.h>
114 #include <machine/vm86.h>
115 #include <sys/random.h>
116 #include <sys/ptrace.h>
117 #include <machine/sigframe.h>
118
119 #include <sys/machintr.h>
120 #include <machine_base/icu/icu_abi.h>
121 #include <machine_base/icu/elcr_var.h>
122 #include <machine_base/apic/lapic.h>
123 #include <machine_base/apic/ioapic.h>
124 #include <machine_base/apic/ioapic_abi.h>
125 #include <machine/mptable.h>
126
127 #define PHYSMAP_ENTRIES         10
128
129 extern void init386(int first);
130 extern void dblfault_handler(void);
131
132 extern void printcpuinfo(void); /* XXX header file */
133 extern void finishidentcpu(void);
134 extern void panicifcpuunsupported(void);
135 extern void initializecpu(void);
136
137 static void cpu_startup(void *);
138 static void pic_finish(void *);
139 static void cpu_finish(void *);
140 #ifndef CPU_DISABLE_SSE
141 static void set_fpregs_xmm(struct save87 *, struct savexmm *);
142 static void fill_fpregs_xmm(struct savexmm *, struct save87 *);
143 #endif /* CPU_DISABLE_SSE */
144 #ifdef DIRECTIO
145 extern void ffs_rawread_setup(void);
146 #endif /* DIRECTIO */
147 static void init_locks(void);
148
149 SYSINIT(cpu, SI_BOOT2_START_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
150 SYSINIT(pic_finish, SI_BOOT2_FINISH_PIC, SI_ORDER_FIRST, pic_finish, NULL);
151 SYSINIT(cpu_finish, SI_BOOT2_FINISH_CPU, SI_ORDER_FIRST, cpu_finish, NULL);
152
153 int     _udatasel, _ucodesel;
154 u_int   atdevbase;
155 int64_t tsc_offsets[MAXCPU];
156 static int cpu_mwait_halt = 0;
157
158 #if defined(SWTCH_OPTIM_STATS)
159 extern int swtch_optim_stats;
160 SYSCTL_INT(_debug, OID_AUTO, swtch_optim_stats,
161         CTLFLAG_RD, &swtch_optim_stats, 0, "");
162 SYSCTL_INT(_debug, OID_AUTO, tlb_flush_count,
163         CTLFLAG_RD, &tlb_flush_count, 0, "");
164 #endif
165 SYSCTL_INT(_hw, OID_AUTO, cpu_mwait_halt,
166         CTLFLAG_RW, &cpu_mwait_halt, 0, "");
167 SYSCTL_INT(_hw, OID_AUTO, cpu_mwait_spin, CTLFLAG_RW, &cpu_mwait_spin, 0,
168     "monitor/mwait target state");
169
170 long physmem = 0;
171
172 u_long ebda_addr = 0;
173
174 int imcr_present = 0;
175
176 int naps = 0; /* # of Applications processors */
177 struct mtx dt_lock;             /* lock for GDT and LDT */
178
179 u_int base_memory;
180
181 static int
182 sysctl_hw_physmem(SYSCTL_HANDLER_ARGS)
183 {
184         u_long pmem = ctob(physmem);
185
186         int error = sysctl_handle_long(oidp, &pmem, 0, req);
187         return (error);
188 }
189
190 SYSCTL_PROC(_hw, HW_PHYSMEM, physmem, CTLTYPE_ULONG|CTLFLAG_RD,
191         0, 0, sysctl_hw_physmem, "LU", "Total system memory in bytes (number of pages * page size)");
192
193 static int
194 sysctl_hw_usermem(SYSCTL_HANDLER_ARGS)
195 {
196         int error = sysctl_handle_int(oidp, 0,
197                 ctob(physmem - vmstats.v_wire_count), req);
198         return (error);
199 }
200
201 SYSCTL_PROC(_hw, HW_USERMEM, usermem, CTLTYPE_INT|CTLFLAG_RD,
202         0, 0, sysctl_hw_usermem, "IU", "");
203
204 static int
205 sysctl_hw_availpages(SYSCTL_HANDLER_ARGS)
206 {
207         int error = sysctl_handle_int(oidp, 0,
208                 i386_btop(avail_end - avail_start), req);
209         return (error);
210 }
211
212 SYSCTL_PROC(_hw, OID_AUTO, availpages, CTLTYPE_INT|CTLFLAG_RD,
213         0, 0, sysctl_hw_availpages, "I", "");
214
215 vm_paddr_t Maxmem;
216 vm_paddr_t Realmem;
217
218 vm_paddr_t phys_avail[PHYSMAP_ENTRIES*2+2];
219 vm_paddr_t dump_avail[PHYSMAP_ENTRIES*2+2];
220
221
222 static vm_offset_t buffer_sva, buffer_eva;
223 vm_offset_t clean_sva, clean_eva;
224 static vm_offset_t pager_sva, pager_eva;
225 static struct trapframe proc0_tf;
226
227 static void
228 cpu_startup(void *dummy)
229 {
230         caddr_t v;
231         vm_size_t size = 0;
232         vm_offset_t firstaddr;
233
234         /*
235          * Good {morning,afternoon,evening,night}.
236          */
237         kprintf("%s", version);
238         startrtclock();
239         printcpuinfo();
240         panicifcpuunsupported();
241 #ifdef PERFMON
242         perfmon_init();
243 #endif
244         kprintf("real memory  = %ju (%ju MB)\n",
245                 (intmax_t)Realmem,
246                 (intmax_t)Realmem / 1024 / 1024);
247         /*
248          * Display any holes after the first chunk of extended memory.
249          */
250         if (bootverbose) {
251                 int indx;
252
253                 kprintf("Physical memory chunk(s):\n");
254                 for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
255                         vm_paddr_t size1 = phys_avail[indx + 1] - phys_avail[indx];
256
257                         kprintf("0x%08llx - 0x%08llx, %llu bytes (%llu pages)\n",
258                             phys_avail[indx], phys_avail[indx + 1] - 1, size1,
259                             size1 / PAGE_SIZE);
260                 }
261         }
262
263         /*
264          * Allocate space for system data structures.
265          * The first available kernel virtual address is in "v".
266          * As pages of kernel virtual memory are allocated, "v" is incremented.
267          * As pages of memory are allocated and cleared,
268          * "firstaddr" is incremented.
269          * An index into the kernel page table corresponding to the
270          * virtual memory address maintained in "v" is kept in "mapaddr".
271          */
272
273         /*
274          * Make two passes.  The first pass calculates how much memory is
275          * needed and allocates it.  The second pass assigns virtual
276          * addresses to the various data structures.
277          */
278         firstaddr = 0;
279 again:
280         v = (caddr_t)firstaddr;
281
282 #define valloc(name, type, num) \
283             (name) = (type *)v; v = (caddr_t)((name)+(num))
284 #define valloclim(name, type, num, lim) \
285             (name) = (type *)v; v = (caddr_t)((lim) = ((name)+(num)))
286
287         /*
288          * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
289          * For the first 64MB of ram nominally allocate sufficient buffers to
290          * cover 1/4 of our ram.  Beyond the first 64MB allocate additional
291          * buffers to cover 1/20 of our ram over 64MB.  When auto-sizing
292          * the buffer cache we limit the eventual kva reservation to
293          * maxbcache bytes.
294          *
295          * factor represents the 1/4 x ram conversion.
296          */
297         if (nbuf == 0) {
298                 int factor = 4 * BKVASIZE / 1024;
299                 int kbytes = physmem * (PAGE_SIZE / 1024);
300
301                 nbuf = 50;
302                 if (kbytes > 4096)
303                         nbuf += min((kbytes - 4096) / factor, 65536 / factor);
304                 if (kbytes > 65536)
305                         nbuf += (kbytes - 65536) * 2 / (factor * 5);
306                 if (maxbcache && nbuf > maxbcache / BKVASIZE)
307                         nbuf = maxbcache / BKVASIZE;
308         }
309
310         /*
311          * Do not allow the buffer_map to be more then 1/2 the size of the
312          * kernel_map.
313          */
314         if (nbuf > (virtual_end - virtual_start) / (BKVASIZE * 2)) {
315                 nbuf = (virtual_end - virtual_start) / (BKVASIZE * 2);
316                 kprintf("Warning: nbufs capped at %ld\n", nbuf);
317         }
318
319         /* limit to 128 on i386 */
320         nswbuf = lmax(lmin(nbuf / 4, 128), 16);
321 #ifdef NSWBUF_MIN
322         if (nswbuf < NSWBUF_MIN)
323                 nswbuf = NSWBUF_MIN;
324 #endif
325 #ifdef DIRECTIO
326         ffs_rawread_setup();
327 #endif
328
329         valloc(swbuf, struct buf, nswbuf);
330         valloc(buf, struct buf, nbuf);
331
332         /*
333          * End of first pass, size has been calculated so allocate memory
334          */
335         if (firstaddr == 0) {
336                 size = (vm_size_t)(v - firstaddr);
337                 firstaddr = kmem_alloc(&kernel_map, round_page(size));
338                 if (firstaddr == 0)
339                         panic("startup: no room for tables");
340                 goto again;
341         }
342
343         /*
344          * End of second pass, addresses have been assigned
345          */
346         if ((vm_size_t)(v - firstaddr) != size)
347                 panic("startup: table size inconsistency");
348
349         kmem_suballoc(&kernel_map, &clean_map, &clean_sva, &clean_eva,
350                       (nbuf*BKVASIZE) + (nswbuf*MAXPHYS) + pager_map_size);
351         kmem_suballoc(&clean_map, &buffer_map, &buffer_sva, &buffer_eva,
352                       (nbuf*BKVASIZE));
353         buffer_map.system_map = 1;
354         kmem_suballoc(&clean_map, &pager_map, &pager_sva, &pager_eva,
355                       (nswbuf*MAXPHYS) + pager_map_size);
356         pager_map.system_map = 1;
357
358 #if defined(USERCONFIG)
359         userconfig();
360         cninit();               /* the preferred console may have changed */
361 #endif
362
363         kprintf("avail memory = %ju (%ju MB)\n",
364                 (intmax_t)ptoa(vmstats.v_free_count + vmstats.v_dma_pages),
365                 (intmax_t)ptoa(vmstats.v_free_count + vmstats.v_dma_pages) /
366                 1024 / 1024);
367 }
368
369 static void
370 cpu_finish(void *dummy __unused)
371 {
372         cpu_setregs();
373 }
374
375 static void
376 pic_finish(void *dummy __unused)
377 {
378         /* Log ELCR information */
379         elcr_dump();
380
381         /* Log MPTABLE information */
382         mptable_pci_int_dump();
383
384         /* Finalize PIC */
385         MachIntrABI.finalize();
386 }
387
388 /*
389  * Send an interrupt to process.
390  *
391  * Stack is set up to allow sigcode stored
392  * at top to call routine, followed by kcall
393  * to sigreturn routine below.  After sigreturn
394  * resets the signal mask, the stack, and the
395  * frame pointer, it returns to the user
396  * specified pc, psl.
397  */
398 void
399 sendsig(sig_t catcher, int sig, sigset_t *mask, u_long code)
400 {
401         struct lwp *lp = curthread->td_lwp;
402         struct proc *p = lp->lwp_proc;
403         struct trapframe *regs;
404         struct sigacts *psp = p->p_sigacts;
405         struct sigframe sf, *sfp;
406         int oonstack;
407
408         regs = lp->lwp_md.md_regs;
409         oonstack = (lp->lwp_sigstk.ss_flags & SS_ONSTACK) ? 1 : 0;
410
411         /* save user context */
412         bzero(&sf, sizeof(struct sigframe));
413         sf.sf_uc.uc_sigmask = *mask;
414         sf.sf_uc.uc_stack = lp->lwp_sigstk;
415         sf.sf_uc.uc_mcontext.mc_onstack = oonstack;
416         bcopy(regs, &sf.sf_uc.uc_mcontext.mc_gs, sizeof(struct trapframe));
417
418         /* make the size of the saved context visible to userland */
419         sf.sf_uc.uc_mcontext.mc_len = sizeof(sf.sf_uc.uc_mcontext);
420
421         /* Allocate and validate space for the signal handler context. */
422         if ((lp->lwp_flags & LWP_ALTSTACK) != 0 && !oonstack &&
423             SIGISMEMBER(psp->ps_sigonstack, sig)) {
424                 sfp = (struct sigframe *)(lp->lwp_sigstk.ss_sp +
425                     lp->lwp_sigstk.ss_size - sizeof(struct sigframe));
426                 lp->lwp_sigstk.ss_flags |= SS_ONSTACK;
427         } else {
428                 sfp = (struct sigframe *)regs->tf_esp - 1;
429         }
430
431         /* Translate the signal is appropriate */
432         if (p->p_sysent->sv_sigtbl) {
433                 if (sig <= p->p_sysent->sv_sigsize)
434                         sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
435         }
436
437         /* Build the argument list for the signal handler. */
438         sf.sf_signum = sig;
439         sf.sf_ucontext = (register_t)&sfp->sf_uc;
440         if (SIGISMEMBER(psp->ps_siginfo, sig)) {
441                 /* Signal handler installed with SA_SIGINFO. */
442                 sf.sf_siginfo = (register_t)&sfp->sf_si;
443                 sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
444
445                 /* fill siginfo structure */
446                 sf.sf_si.si_signo = sig;
447                 sf.sf_si.si_code = code;
448                 sf.sf_si.si_addr = (void*)regs->tf_err;
449         }
450         else {
451                 /* Old FreeBSD-style arguments. */
452                 sf.sf_siginfo = code;
453                 sf.sf_addr = regs->tf_err;
454                 sf.sf_ahu.sf_handler = catcher;
455         }
456
457         /*
458          * If we're a vm86 process, we want to save the segment registers.
459          * We also change eflags to be our emulated eflags, not the actual
460          * eflags.
461          */
462         if (regs->tf_eflags & PSL_VM) {
463                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
464                 struct vm86_kernel *vm86 = &lp->lwp_thread->td_pcb->pcb_ext->ext_vm86;
465
466                 sf.sf_uc.uc_mcontext.mc_gs = tf->tf_vm86_gs;
467                 sf.sf_uc.uc_mcontext.mc_fs = tf->tf_vm86_fs;
468                 sf.sf_uc.uc_mcontext.mc_es = tf->tf_vm86_es;
469                 sf.sf_uc.uc_mcontext.mc_ds = tf->tf_vm86_ds;
470
471                 if (vm86->vm86_has_vme == 0)
472                         sf.sf_uc.uc_mcontext.mc_eflags =
473                             (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
474                             (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
475
476                 /*
477                  * Clear PSL_NT to inhibit T_TSSFLT faults on return from
478                  * syscalls made by the signal handler.  This just avoids
479                  * wasting time for our lazy fixup of such faults.  PSL_NT
480                  * does nothing in vm86 mode, but vm86 programs can set it
481                  * almost legitimately in probes for old cpu types.
482                  */
483                 tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_VIF | PSL_VIP);
484         }
485
486         /*
487          * Save the FPU state and reinit the FP unit
488          */
489         npxpush(&sf.sf_uc.uc_mcontext);
490
491         /*
492          * Copy the sigframe out to the user's stack.
493          */
494         if (copyout(&sf, sfp, sizeof(struct sigframe)) != 0) {
495                 /*
496                  * Something is wrong with the stack pointer.
497                  * ...Kill the process.
498                  */
499                 sigexit(lp, SIGILL);
500         }
501
502         regs->tf_esp = (int)sfp;
503         regs->tf_eip = PS_STRINGS - *(p->p_sysent->sv_szsigcode);
504
505         /*
506          * i386 abi specifies that the direction flag must be cleared
507          * on function entry
508          */
509         regs->tf_eflags &= ~(PSL_T|PSL_D);
510
511         regs->tf_cs = _ucodesel;
512         regs->tf_ds = _udatasel;
513         regs->tf_es = _udatasel;
514
515         /*
516          * Allow the signal handler to inherit %fs in addition to %gs as
517          * the userland program might be using both.
518          *
519          * However, if a T_PROTFLT occured the segment registers could be
520          * totally broken.  They must be reset in order to be able to
521          * return to userland.
522          */
523         if (regs->tf_trapno == T_PROTFLT) {
524                 regs->tf_fs = _udatasel;
525                 regs->tf_gs = _udatasel;
526         }
527         regs->tf_ss = _udatasel;
528 }
529
530 /*
531  * Sanitize the trapframe for a virtual kernel passing control to a custom
532  * VM context.  Remove any items that would otherwise create a privilage
533  * issue.
534  *
535  * XXX at the moment we allow userland to set the resume flag.  Is this a
536  * bad idea?
537  */
538 int
539 cpu_sanitize_frame(struct trapframe *frame)
540 {
541         frame->tf_cs = _ucodesel;
542         frame->tf_ds = _udatasel;
543         frame->tf_es = _udatasel;       /* XXX allow userland this one too? */
544 #if 0
545         frame->tf_fs = _udatasel;
546         frame->tf_gs = _udatasel;
547 #endif
548         frame->tf_ss = _udatasel;
549         frame->tf_eflags &= (PSL_RF | PSL_USERCHANGE);
550         frame->tf_eflags |= PSL_RESERVED_DEFAULT | PSL_I;
551         return(0);
552 }
553
554 int
555 cpu_sanitize_tls(struct savetls *tls)
556 {
557          struct segment_descriptor *desc;
558          int i;
559
560          for (i = 0; i < NGTLS; ++i) {
561                 desc = &tls->tls[i];
562                 if (desc->sd_dpl == 0 && desc->sd_type == 0)
563                         continue;
564                 if (desc->sd_def32 == 0)
565                         return(ENXIO);
566                 if (desc->sd_type != SDT_MEMRWA)
567                         return(ENXIO);
568                 if (desc->sd_dpl != SEL_UPL)
569                         return(ENXIO);
570                 if (desc->sd_xx != 0 || desc->sd_p != 1)
571                         return(ENXIO);
572          }
573          return(0);
574 }
575
576 /*
577  * sigreturn(ucontext_t *sigcntxp)
578  *
579  * System call to cleanup state after a signal
580  * has been taken.  Reset signal mask and
581  * stack state from context left by sendsig (above).
582  * Return to previous pc and psl as specified by
583  * context left by sendsig. Check carefully to
584  * make sure that the user has not modified the
585  * state to gain improper privileges.
586  *
587  * MPSAFE
588  */
589 #define EFL_SECURE(ef, oef)     ((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
590 #define CS_SECURE(cs)           (ISPL(cs) == SEL_UPL)
591
592 int
593 sys_sigreturn(struct sigreturn_args *uap)
594 {
595         struct lwp *lp = curthread->td_lwp;
596         struct trapframe *regs;
597         ucontext_t uc;
598         ucontext_t *ucp;
599         int cs;
600         int eflags;
601         int error;
602
603         /*
604          * We have to copy the information into kernel space so userland
605          * can't modify it while we are sniffing it.
606          */
607         regs = lp->lwp_md.md_regs;
608         error = copyin(uap->sigcntxp, &uc, sizeof(uc));
609         if (error)
610                 return (error);
611         ucp = &uc;
612         eflags = ucp->uc_mcontext.mc_eflags;
613
614         if (eflags & PSL_VM) {
615                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
616                 struct vm86_kernel *vm86;
617
618                 /*
619                  * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
620                  * set up the vm86 area, and we can't enter vm86 mode.
621                  */
622                 if (lp->lwp_thread->td_pcb->pcb_ext == 0)
623                         return (EINVAL);
624                 vm86 = &lp->lwp_thread->td_pcb->pcb_ext->ext_vm86;
625                 if (vm86->vm86_inited == 0)
626                         return (EINVAL);
627
628                 /* go back to user mode if both flags are set */
629                 if ((eflags & PSL_VIP) && (eflags & PSL_VIF))
630                         trapsignal(lp, SIGBUS, 0);
631
632                 if (vm86->vm86_has_vme) {
633                         eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
634                             (eflags & VME_USERCHANGE) | PSL_VM;
635                 } else {
636                         vm86->vm86_eflags = eflags;     /* save VIF, VIP */
637                         eflags = (tf->tf_eflags & ~VM_USERCHANGE) |
638                             (eflags & VM_USERCHANGE) | PSL_VM;
639                 }
640                 bcopy(&ucp->uc_mcontext.mc_gs, tf, sizeof(struct trapframe));
641                 tf->tf_eflags = eflags;
642                 tf->tf_vm86_ds = tf->tf_ds;
643                 tf->tf_vm86_es = tf->tf_es;
644                 tf->tf_vm86_fs = tf->tf_fs;
645                 tf->tf_vm86_gs = tf->tf_gs;
646                 tf->tf_ds = _udatasel;
647                 tf->tf_es = _udatasel;
648 #if 0
649                 tf->tf_fs = _udatasel;
650                 tf->tf_gs = _udatasel;
651 #endif
652         } else {
653                 /*
654                  * Don't allow users to change privileged or reserved flags.
655                  */
656                 /*
657                  * XXX do allow users to change the privileged flag PSL_RF.
658                  * The cpu sets PSL_RF in tf_eflags for faults.  Debuggers
659                  * should sometimes set it there too.  tf_eflags is kept in
660                  * the signal context during signal handling and there is no
661                  * other place to remember it, so the PSL_RF bit may be
662                  * corrupted by the signal handler without us knowing.
663                  * Corruption of the PSL_RF bit at worst causes one more or
664                  * one less debugger trap, so allowing it is fairly harmless.
665                  */
666                 if (!EFL_SECURE(eflags & ~PSL_RF, regs->tf_eflags & ~PSL_RF)) {
667                         kprintf("sigreturn: eflags = 0x%x\n", eflags);
668                         return(EINVAL);
669                 }
670
671                 /*
672                  * Don't allow users to load a valid privileged %cs.  Let the
673                  * hardware check for invalid selectors, excess privilege in
674                  * other selectors, invalid %eip's and invalid %esp's.
675                  */
676                 cs = ucp->uc_mcontext.mc_cs;
677                 if (!CS_SECURE(cs)) {
678                         kprintf("sigreturn: cs = 0x%x\n", cs);
679                         trapsignal(lp, SIGBUS, T_PROTFLT);
680                         return(EINVAL);
681                 }
682                 bcopy(&ucp->uc_mcontext.mc_gs, regs, sizeof(struct trapframe));
683         }
684
685         /*
686          * Restore the FPU state from the frame
687          */
688         crit_enter();
689         npxpop(&ucp->uc_mcontext);
690
691         if (ucp->uc_mcontext.mc_onstack & 1)
692                 lp->lwp_sigstk.ss_flags |= SS_ONSTACK;
693         else
694                 lp->lwp_sigstk.ss_flags &= ~SS_ONSTACK;
695
696         lp->lwp_sigmask = ucp->uc_sigmask;
697         SIG_CANTMASK(lp->lwp_sigmask);
698         crit_exit();
699         return(EJUSTRETURN);
700 }
701
702 /*
703  * Machine dependent boot() routine
704  *
705  * I haven't seen anything to put here yet
706  * Possibly some stuff might be grafted back here from boot()
707  */
708 void
709 cpu_boot(int howto)
710 {
711 }
712
713 /*
714  * Shutdown the CPU as much as possible
715  */
716 void
717 cpu_halt(void)
718 {
719         for (;;)
720                 __asm__ __volatile("hlt");
721 }
722
723 /*
724  * cpu_idle() represents the idle LWKT.  You cannot return from this function
725  * (unless you want to blow things up!).  Instead we look for runnable threads
726  * and loop or halt as appropriate.  Giant is not held on entry to the thread.
727  *
728  * The main loop is entered with a critical section held, we must release
729  * the critical section before doing anything else.  lwkt_switch() will
730  * check for pending interrupts due to entering and exiting its own 
731  * critical section.
732  *
733  * NOTE: On an SMP system we rely on a scheduler IPI to wake a HLTed cpu up.
734  */
735 static int      cpu_idle_hlt = 2;
736 static int      cpu_idle_hltcnt;
737 static int      cpu_idle_spincnt;
738 static u_int    cpu_idle_repeat = 750;
739 SYSCTL_INT(_machdep, OID_AUTO, cpu_idle_hlt, CTLFLAG_RW,
740     &cpu_idle_hlt, 0, "Idle loop HLT enable");
741 SYSCTL_INT(_machdep, OID_AUTO, cpu_idle_hltcnt, CTLFLAG_RW,
742     &cpu_idle_hltcnt, 0, "Idle loop entry halts");
743 SYSCTL_INT(_machdep, OID_AUTO, cpu_idle_spincnt, CTLFLAG_RW,
744     &cpu_idle_spincnt, 0, "Idle loop entry spins");
745 SYSCTL_INT(_machdep, OID_AUTO, cpu_idle_repeat, CTLFLAG_RW,
746     &cpu_idle_repeat, 0, "Idle entries before acpi hlt");
747
748 static void
749 cpu_idle_default_hook(void)
750 {
751         /*
752          * We must guarentee that hlt is exactly the instruction
753          * following the sti.
754          */
755         __asm __volatile("sti; hlt");
756 }
757
758 /* Other subsystems (e.g., ACPI) can hook this later. */
759 void (*cpu_idle_hook)(void) = cpu_idle_default_hook;
760
761 void
762 cpu_idle(void)
763 {
764         globaldata_t gd = mycpu;
765         struct thread *td __debugvar = gd->gd_curthread;
766         int reqflags;
767         int quick;
768
769         crit_exit();
770         KKASSERT(td->td_critcount == 0);
771         for (;;) {
772                 /*
773                  * See if there are any LWKTs ready to go.
774                  */
775                 lwkt_switch();
776
777                 /*
778                  * When halting inside a cli we must check for reqflags
779                  * races, particularly [re]schedule requests.  Running
780                  * splz() does the job.
781                  *
782                  * cpu_idle_hlt:
783                  *      0       Never halt, just spin
784                  *
785                  *      1       Always use HLT (or MONITOR/MWAIT if avail).
786                  *              This typically eats more power than the
787                  *              ACPI halt.
788                  *
789                  *      2       Use HLT/MONITOR/MWAIT up to a point and then
790                  *              use the ACPI halt (default).  This is a hybrid
791                  *              approach.  See machdep.cpu_idle_repeat.
792                  *
793                  *      3       Always use the ACPI halt.  This typically
794                  *              eats the least amount of power but the cpu
795                  *              will be slow waking up.  Slows down e.g.
796                  *              compiles and other pipe/event oriented stuff.
797                  *
798                  *
799                  * NOTE: Interrupts are enabled and we are not in a critical
800                  *       section.
801                  *
802                  * NOTE: Preemptions do not reset gd_idle_repeat.  Also we
803                  *       don't bother capping gd_idle_repeat, it is ok if
804                  *       it overflows.
805                  */
806                 ++gd->gd_idle_repeat;
807                 reqflags = gd->gd_reqflags;
808                 quick = (cpu_idle_hlt == 1) ||
809                         (cpu_idle_hlt < 3 &&
810                          gd->gd_idle_repeat < cpu_idle_repeat);
811
812                 if (quick && (cpu_mi_feature & CPU_MI_MONITOR) &&
813                     (reqflags & RQF_IDLECHECK_WK_MASK) == 0) {
814                         cpu_mmw_pause_int(&gd->gd_reqflags, reqflags,
815                                           cpu_mwait_halt, 0);
816                         ++cpu_idle_hltcnt;
817                 } else if (cpu_idle_hlt) {
818                         __asm __volatile("cli");
819                         splz();
820                         if ((gd->gd_reqflags & RQF_IDLECHECK_WK_MASK) == 0) {
821                                 if (quick)
822                                         cpu_idle_default_hook();
823                                 else
824                                         cpu_idle_hook();
825                         }
826                         __asm __volatile("sti");
827                         ++cpu_idle_hltcnt;
828                 } else {
829                         splz();
830                         __asm __volatile("sti");
831                         ++cpu_idle_spincnt;
832                 }
833         }
834 }
835
836 /*
837  * This routine is called if a spinlock has been held through the
838  * exponential backoff period and is seriously contested.  On a real cpu
839  * we let it spin.
840  */
841 void
842 cpu_spinlock_contested(void)
843 {
844         cpu_pause();
845 }
846
847 /*
848  * Clear registers on exec
849  */
850 void
851 exec_setregs(u_long entry, u_long stack, u_long ps_strings)
852 {
853         struct thread *td = curthread;
854         struct lwp *lp = td->td_lwp;
855         struct pcb *pcb = td->td_pcb;
856         struct trapframe *regs = lp->lwp_md.md_regs;
857
858         /* was i386_user_cleanup() in NetBSD */
859         user_ldt_free(pcb);
860   
861         bzero((char *)regs, sizeof(struct trapframe));
862         regs->tf_eip = entry;
863         regs->tf_esp = stack;
864         regs->tf_eflags = PSL_USER | (regs->tf_eflags & PSL_T);
865         regs->tf_ss = _udatasel;
866         regs->tf_ds = _udatasel;
867         regs->tf_es = _udatasel;
868         regs->tf_fs = _udatasel;
869         regs->tf_gs = _udatasel;
870         regs->tf_cs = _ucodesel;
871
872         /* PS_STRINGS value for BSD/OS binaries.  It is 0 for non-BSD/OS. */
873         regs->tf_ebx = ps_strings;
874
875         /*
876          * Reset the hardware debug registers if they were in use.
877          * They won't have any meaning for the newly exec'd process.  
878          */
879         if (pcb->pcb_flags & PCB_DBREGS) {
880                 pcb->pcb_dr0 = 0;
881                 pcb->pcb_dr1 = 0;
882                 pcb->pcb_dr2 = 0;
883                 pcb->pcb_dr3 = 0;
884                 pcb->pcb_dr6 = 0;
885                 pcb->pcb_dr7 = 0;
886                 if (pcb == td->td_pcb) {
887                         /*
888                          * Clear the debug registers on the running
889                          * CPU, otherwise they will end up affecting
890                          * the next process we switch to.
891                          */
892                         reset_dbregs();
893                 }
894                 pcb->pcb_flags &= ~PCB_DBREGS;
895         }
896
897         /*
898          * Initialize the math emulator (if any) for the current process.
899          * Actually, just clear the bit that says that the emulator has
900          * been initialized.  Initialization is delayed until the process
901          * traps to the emulator (if it is done at all) mainly because
902          * emulators don't provide an entry point for initialization.
903          */
904         pcb->pcb_flags &= ~FP_SOFTFP;
905
906         /*
907          * note: do not set CR0_TS here.  npxinit() must do it after clearing
908          * gd_npxthread.  Otherwise a preemptive interrupt thread may panic
909          * in npxdna().
910          */
911         crit_enter();
912         load_cr0(rcr0() | CR0_MP);
913
914 #if NNPX > 0
915         /* Initialize the npx (if any) for the current process. */
916         npxinit();
917 #endif
918         crit_exit();
919
920         /*
921          * note: linux emulator needs edx to be 0x0 on entry, which is
922          * handled in execve simply by setting the 64 bit syscall
923          * return value to 0.
924          */
925 }
926
927 void
928 cpu_setregs(void)
929 {
930         unsigned int cr0;
931
932         cr0 = rcr0();
933         cr0 |= CR0_NE;                  /* Done by npxinit() */
934         cr0 |= CR0_MP | CR0_TS;         /* Done at every execve() too. */
935         cr0 |= CR0_WP | CR0_AM;
936         load_cr0(cr0);
937         load_gs(_udatasel);
938 }
939
940 static int
941 sysctl_machdep_adjkerntz(SYSCTL_HANDLER_ARGS)
942 {
943         int error;
944         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
945                 req);
946         if (!error && req->newptr)
947                 resettodr();
948         return (error);
949 }
950
951 SYSCTL_PROC(_machdep, CPU_ADJKERNTZ, adjkerntz, CTLTYPE_INT|CTLFLAG_RW,
952         &adjkerntz, 0, sysctl_machdep_adjkerntz, "I", "");
953
954 SYSCTL_INT(_machdep, CPU_DISRTCSET, disable_rtc_set,
955         CTLFLAG_RW, &disable_rtc_set, 0, "");
956
957 SYSCTL_STRUCT(_machdep, CPU_BOOTINFO, bootinfo, 
958         CTLFLAG_RD, &bootinfo, bootinfo, "");
959
960 SYSCTL_INT(_machdep, CPU_WALLCLOCK, wall_cmos_clock,
961         CTLFLAG_RW, &wall_cmos_clock, 0, "");
962
963 extern u_long bootdev;          /* not a cdev_t - encoding is different */
964 SYSCTL_ULONG(_machdep, OID_AUTO, guessed_bootdev,
965         CTLFLAG_RD, &bootdev, 0, "Boot device (not in cdev_t format)");
966
967 /*
968  * Initialize 386 and configure to run kernel
969  */
970
971 /*
972  * Initialize segments & interrupt table
973  */
974
975 int _default_ldt;
976 union descriptor gdt[NGDT * MAXCPU];    /* global descriptor table */
977 static struct gate_descriptor idt0[NIDT];
978 struct gate_descriptor *idt = &idt0[0]; /* interrupt descriptor table */
979 union descriptor ldt[NLDT];             /* local descriptor table */
980
981 /* table descriptors - used to load tables by cpu */
982 struct region_descriptor r_gdt, r_idt;
983
984 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
985 extern int has_f00f_bug;
986 #endif
987
988 static struct i386tss dblfault_tss;
989 static char dblfault_stack[PAGE_SIZE];
990
991 extern  struct user *proc0paddr;
992
993
994 /* software prototypes -- in more palatable form */
995 struct soft_segment_descriptor gdt_segs[] = {
996 /* GNULL_SEL    0 Null Descriptor */
997 {       0x0,                    /* segment base address  */
998         0x0,                    /* length */
999         0,                      /* segment type */
1000         0,                      /* segment descriptor priority level */
1001         0,                      /* segment descriptor present */
1002         0, 0,
1003         0,                      /* default 32 vs 16 bit size */
1004         0                       /* limit granularity (byte/page units)*/ },
1005 /* GCODE_SEL    1 Code Descriptor for kernel */
1006 {       0x0,                    /* segment base address  */
1007         0xfffff,                /* length - all address space */
1008         SDT_MEMERA,             /* segment type */
1009         0,                      /* segment descriptor priority level */
1010         1,                      /* segment descriptor present */
1011         0, 0,
1012         1,                      /* default 32 vs 16 bit size */
1013         1                       /* limit granularity (byte/page units)*/ },
1014 /* GDATA_SEL    2 Data Descriptor for kernel */
1015 {       0x0,                    /* segment base address  */
1016         0xfffff,                /* length - all address space */
1017         SDT_MEMRWA,             /* segment type */
1018         0,                      /* segment descriptor priority level */
1019         1,                      /* segment descriptor present */
1020         0, 0,
1021         1,                      /* default 32 vs 16 bit size */
1022         1                       /* limit granularity (byte/page units)*/ },
1023 /* GPRIV_SEL    3 SMP Per-Processor Private Data Descriptor */
1024 {       0x0,                    /* segment base address  */
1025         0xfffff,                /* length - all address space */
1026         SDT_MEMRWA,             /* segment type */
1027         0,                      /* segment descriptor priority level */
1028         1,                      /* segment descriptor present */
1029         0, 0,
1030         1,                      /* default 32 vs 16 bit size */
1031         1                       /* limit granularity (byte/page units)*/ },
1032 /* GPROC0_SEL   4 Proc 0 Tss Descriptor */
1033 {
1034         0x0,                    /* segment base address */
1035         sizeof(struct i386tss)-1,/* length - all address space */
1036         SDT_SYS386TSS,          /* segment type */
1037         0,                      /* segment descriptor priority level */
1038         1,                      /* segment descriptor present */
1039         0, 0,
1040         0,                      /* unused - default 32 vs 16 bit size */
1041         0                       /* limit granularity (byte/page units)*/ },
1042 /* GLDT_SEL     5 LDT Descriptor */
1043 {       (int) ldt,              /* segment base address  */
1044         sizeof(ldt)-1,          /* length - all address space */
1045         SDT_SYSLDT,             /* segment type */
1046         SEL_UPL,                /* segment descriptor priority level */
1047         1,                      /* segment descriptor present */
1048         0, 0,
1049         0,                      /* unused - default 32 vs 16 bit size */
1050         0                       /* limit granularity (byte/page units)*/ },
1051 /* GUSERLDT_SEL 6 User LDT Descriptor per process */
1052 {       (int) ldt,              /* segment base address  */
1053         (512 * sizeof(union descriptor)-1),             /* length */
1054         SDT_SYSLDT,             /* segment type */
1055         0,                      /* segment descriptor priority level */
1056         1,                      /* segment descriptor present */
1057         0, 0,
1058         0,                      /* unused - default 32 vs 16 bit size */
1059         0                       /* limit granularity (byte/page units)*/ },
1060 /* GTGATE_SEL   7 Null Descriptor - Placeholder */
1061 {       0x0,                    /* segment base address  */
1062         0x0,                    /* length - all address space */
1063         0,                      /* segment type */
1064         0,                      /* segment descriptor priority level */
1065         0,                      /* segment descriptor present */
1066         0, 0,
1067         0,                      /* default 32 vs 16 bit size */
1068         0                       /* limit granularity (byte/page units)*/ },
1069 /* GBIOSLOWMEM_SEL 8 BIOS access to realmode segment 0x40, must be #8 in GDT */
1070 {       0x400,                  /* segment base address */
1071         0xfffff,                /* length */
1072         SDT_MEMRWA,             /* segment type */
1073         0,                      /* segment descriptor priority level */
1074         1,                      /* segment descriptor present */
1075         0, 0,
1076         1,                      /* default 32 vs 16 bit size */
1077         1                       /* limit granularity (byte/page units)*/ },
1078 /* GPANIC_SEL   9 Panic Tss Descriptor */
1079 {       (int) &dblfault_tss,    /* segment base address  */
1080         sizeof(struct i386tss)-1,/* length - all address space */
1081         SDT_SYS386TSS,          /* segment type */
1082         0,                      /* segment descriptor priority level */
1083         1,                      /* segment descriptor present */
1084         0, 0,
1085         0,                      /* unused - default 32 vs 16 bit size */
1086         0                       /* limit granularity (byte/page units)*/ },
1087 /* GBIOSCODE32_SEL 10 BIOS 32-bit interface (32bit Code) */
1088 {       0,                      /* segment base address (overwritten)  */
1089         0xfffff,                /* length */
1090         SDT_MEMERA,             /* segment type */
1091         0,                      /* segment descriptor priority level */
1092         1,                      /* segment descriptor present */
1093         0, 0,
1094         0,                      /* default 32 vs 16 bit size */
1095         1                       /* limit granularity (byte/page units)*/ },
1096 /* GBIOSCODE16_SEL 11 BIOS 32-bit interface (16bit Code) */
1097 {       0,                      /* segment base address (overwritten)  */
1098         0xfffff,                /* length */
1099         SDT_MEMERA,             /* segment type */
1100         0,                      /* segment descriptor priority level */
1101         1,                      /* segment descriptor present */
1102         0, 0,
1103         0,                      /* default 32 vs 16 bit size */
1104         1                       /* limit granularity (byte/page units)*/ },
1105 /* GBIOSDATA_SEL 12 BIOS 32-bit interface (Data) */
1106 {       0,                      /* segment base address (overwritten) */
1107         0xfffff,                /* length */
1108         SDT_MEMRWA,             /* segment type */
1109         0,                      /* segment descriptor priority level */
1110         1,                      /* segment descriptor present */
1111         0, 0,
1112         1,                      /* default 32 vs 16 bit size */
1113         1                       /* limit granularity (byte/page units)*/ },
1114 /* GBIOSUTIL_SEL 13 BIOS 16-bit interface (Utility) */
1115 {       0,                      /* segment base address (overwritten) */
1116         0xfffff,                /* length */
1117         SDT_MEMRWA,             /* segment type */
1118         0,                      /* segment descriptor priority level */
1119         1,                      /* segment descriptor present */
1120         0, 0,
1121         0,                      /* default 32 vs 16 bit size */
1122         1                       /* limit granularity (byte/page units)*/ },
1123 /* GBIOSARGS_SEL 14 BIOS 16-bit interface (Arguments) */
1124 {       0,                      /* segment base address (overwritten) */
1125         0xfffff,                /* length */
1126         SDT_MEMRWA,             /* segment type */
1127         0,                      /* segment descriptor priority level */
1128         1,                      /* segment descriptor present */
1129         0, 0,
1130         0,                      /* default 32 vs 16 bit size */
1131         1                       /* limit granularity (byte/page units)*/ },
1132 /* GTLS_START 15 TLS */
1133 {       0x0,                    /* segment base address  */
1134         0x0,                    /* length */
1135         0,                      /* segment type */
1136         0,                      /* segment descriptor priority level */
1137         0,                      /* segment descriptor present */
1138         0, 0,
1139         0,                      /* default 32 vs 16 bit size */
1140         0                       /* limit granularity (byte/page units)*/ },
1141 /* GTLS_START+1 16 TLS */
1142 {       0x0,                    /* segment base address  */
1143         0x0,                    /* length */
1144         0,                      /* segment type */
1145         0,                      /* segment descriptor priority level */
1146         0,                      /* segment descriptor present */
1147         0, 0,
1148         0,                      /* default 32 vs 16 bit size */
1149         0                       /* limit granularity (byte/page units)*/ },
1150 /* GTLS_END 17 TLS */
1151 {       0x0,                    /* segment base address  */
1152         0x0,                    /* length */
1153         0,                      /* segment type */
1154         0,                      /* segment descriptor priority level */
1155         0,                      /* segment descriptor present */
1156         0, 0,
1157         0,                      /* default 32 vs 16 bit size */
1158         0                       /* limit granularity (byte/page units)*/ },
1159 /* GNDIS_SEL    18 NDIS Descriptor */
1160 {       0x0,                    /* segment base address  */
1161         0x0,                    /* length */
1162         0,                      /* segment type */
1163         0,                      /* segment descriptor priority level */
1164         0,                      /* segment descriptor present */
1165         0, 0,
1166         0,                      /* default 32 vs 16 bit size */
1167         0                       /* limit granularity (byte/page units)*/ },
1168 };
1169
1170 static struct soft_segment_descriptor ldt_segs[] = {
1171         /* Null Descriptor - overwritten by call gate */
1172 {       0x0,                    /* segment base address  */
1173         0x0,                    /* length - all address space */
1174         0,                      /* segment type */
1175         0,                      /* segment descriptor priority level */
1176         0,                      /* segment descriptor present */
1177         0, 0,
1178         0,                      /* default 32 vs 16 bit size */
1179         0                       /* limit granularity (byte/page units)*/ },
1180         /* Null Descriptor - overwritten by call gate */
1181 {       0x0,                    /* segment base address  */
1182         0x0,                    /* length - all address space */
1183         0,                      /* segment type */
1184         0,                      /* segment descriptor priority level */
1185         0,                      /* segment descriptor present */
1186         0, 0,
1187         0,                      /* default 32 vs 16 bit size */
1188         0                       /* limit granularity (byte/page units)*/ },
1189         /* Null Descriptor - overwritten by call gate */
1190 {       0x0,                    /* segment base address  */
1191         0x0,                    /* length - all address space */
1192         0,                      /* segment type */
1193         0,                      /* segment descriptor priority level */
1194         0,                      /* segment descriptor present */
1195         0, 0,
1196         0,                      /* default 32 vs 16 bit size */
1197         0                       /* limit granularity (byte/page units)*/ },
1198         /* Code Descriptor for user */
1199 {       0x0,                    /* segment base address  */
1200         0xfffff,                /* length - all address space */
1201         SDT_MEMERA,             /* segment type */
1202         SEL_UPL,                /* segment descriptor priority level */
1203         1,                      /* segment descriptor present */
1204         0, 0,
1205         1,                      /* default 32 vs 16 bit size */
1206         1                       /* limit granularity (byte/page units)*/ },
1207         /* Null Descriptor - overwritten by call gate */
1208 {       0x0,                    /* segment base address  */
1209         0x0,                    /* length - all address space */
1210         0,                      /* segment type */
1211         0,                      /* segment descriptor priority level */
1212         0,                      /* segment descriptor present */
1213         0, 0,
1214         0,                      /* default 32 vs 16 bit size */
1215         0                       /* limit granularity (byte/page units)*/ },
1216         /* Data Descriptor for user */
1217 {       0x0,                    /* segment base address  */
1218         0xfffff,                /* length - all address space */
1219         SDT_MEMRWA,             /* segment type */
1220         SEL_UPL,                /* segment descriptor priority level */
1221         1,                      /* segment descriptor present */
1222         0, 0,
1223         1,                      /* default 32 vs 16 bit size */
1224         1                       /* limit granularity (byte/page units)*/ },
1225 };
1226
1227 void
1228 setidt(int idx, inthand_t *func, int typ, int dpl, int selec)
1229 {
1230         struct gate_descriptor *ip;
1231
1232         ip = idt + idx;
1233         ip->gd_looffset = (int)func;
1234         ip->gd_selector = selec;
1235         ip->gd_stkcpy = 0;
1236         ip->gd_xx = 0;
1237         ip->gd_type = typ;
1238         ip->gd_dpl = dpl;
1239         ip->gd_p = 1;
1240         ip->gd_hioffset = ((int)func)>>16 ;
1241 }
1242
1243 #define IDTVEC(name)    __CONCAT(X,name)
1244
1245 extern inthand_t
1246         IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
1247         IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
1248         IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
1249         IDTVEC(page), IDTVEC(mchk), IDTVEC(fpu), IDTVEC(align),
1250         IDTVEC(xmm), IDTVEC(syscall),
1251         IDTVEC(rsvd0);
1252 extern inthand_t
1253         IDTVEC(int0x80_syscall);
1254
1255 #ifdef DEBUG_INTERRUPTS
1256 extern inthand_t *Xrsvdary[256];
1257 #endif
1258
1259 void
1260 sdtossd(struct segment_descriptor *sd, struct soft_segment_descriptor *ssd)
1261 {
1262         ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
1263         ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
1264         ssd->ssd_type  = sd->sd_type;
1265         ssd->ssd_dpl   = sd->sd_dpl;
1266         ssd->ssd_p     = sd->sd_p;
1267         ssd->ssd_def32 = sd->sd_def32;
1268         ssd->ssd_gran  = sd->sd_gran;
1269 }
1270
1271 /*
1272  * Populate the (physmap) array with base/bound pairs describing the
1273  * available physical memory in the system, then test this memory and
1274  * build the phys_avail array describing the actually-available memory.
1275  *
1276  * If we cannot accurately determine the physical memory map, then use
1277  * value from the 0xE801 call, and failing that, the RTC.
1278  *
1279  * Total memory size may be set by the kernel environment variable
1280  * hw.physmem or the compile-time define MAXMEM.
1281  */
1282 static void
1283 getmemsize(int first)
1284 {
1285         int i, physmap_idx, pa_indx, da_indx;
1286         int hasbrokenint12;
1287         u_int basemem, extmem;
1288         struct vm86frame vmf;
1289         struct vm86context vmc;
1290         vm_offset_t pa;
1291         vm_offset_t physmap[PHYSMAP_ENTRIES*2];
1292         pt_entry_t *pte;
1293         quad_t maxmem;
1294         struct {
1295                 u_int64_t base;
1296                 u_int64_t length;
1297                 u_int32_t type;
1298         } *smap;
1299         quad_t dcons_addr, dcons_size;
1300
1301         bzero(&vmf, sizeof(struct vm86frame));
1302         bzero(physmap, sizeof(physmap));
1303         basemem = 0;
1304
1305         /*
1306          * Some newer BIOSes has broken INT 12H implementation which cause
1307          * kernel panic immediately. In this case, we need to scan SMAP
1308          * with INT 15:E820 first, then determine base memory size.
1309          */
1310         hasbrokenint12 = 0;
1311         TUNABLE_INT_FETCH("hw.hasbrokenint12", &hasbrokenint12);
1312         if (hasbrokenint12) {
1313                 goto int15e820;
1314         }
1315
1316         /*
1317          * Perform "base memory" related probes & setup.  If we get a crazy
1318          * value give the bios some scribble space just in case.
1319          */
1320         vm86_intcall(0x12, &vmf);
1321         basemem = vmf.vmf_ax;
1322         if (basemem > 640) {
1323                 kprintf("Preposterous BIOS basemem of %uK, "
1324                         "truncating to < 640K\n", basemem);
1325                 basemem = 636;
1326         }
1327
1328         /*
1329          * XXX if biosbasemem is now < 640, there is a `hole'
1330          * between the end of base memory and the start of
1331          * ISA memory.  The hole may be empty or it may
1332          * contain BIOS code or data.  Map it read/write so
1333          * that the BIOS can write to it.  (Memory from 0 to
1334          * the physical end of the kernel is mapped read-only
1335          * to begin with and then parts of it are remapped.
1336          * The parts that aren't remapped form holes that
1337          * remain read-only and are unused by the kernel.
1338          * The base memory area is below the physical end of
1339          * the kernel and right now forms a read-only hole.
1340          * The part of it from PAGE_SIZE to
1341          * (trunc_page(biosbasemem * 1024) - 1) will be
1342          * remapped and used by the kernel later.)
1343          *
1344          * This code is similar to the code used in
1345          * pmap_mapdev, but since no memory needs to be
1346          * allocated we simply change the mapping.
1347          */
1348         for (pa = trunc_page(basemem * 1024);
1349              pa < ISA_HOLE_START; pa += PAGE_SIZE) {
1350                 pte = vtopte(pa + KERNBASE);
1351                 *pte = pa | PG_RW | PG_V;
1352         }
1353
1354         /*
1355          * if basemem != 640, map pages r/w into vm86 page table so 
1356          * that the bios can scribble on it.
1357          */
1358         pte = vm86paddr;
1359         for (i = basemem / 4; i < 160; i++)
1360                 pte[i] = (i << PAGE_SHIFT) | PG_V | PG_RW | PG_U;
1361
1362 int15e820:
1363         /*
1364          * map page 1 R/W into the kernel page table so we can use it
1365          * as a buffer.  The kernel will unmap this page later.
1366          */
1367         pte = vtopte(KERNBASE + (1 << PAGE_SHIFT));
1368         *pte = (1 << PAGE_SHIFT) | PG_RW | PG_V;
1369
1370         /*
1371          * get memory map with INT 15:E820
1372          */
1373 #define SMAPSIZ         sizeof(*smap)
1374 #define SMAP_SIG        0x534D4150                      /* 'SMAP' */
1375
1376         vmc.npages = 0;
1377         smap = (void *)vm86_addpage(&vmc, 1, KERNBASE + (1 << PAGE_SHIFT));
1378         vm86_getptr(&vmc, (vm_offset_t)smap, &vmf.vmf_es, &vmf.vmf_di);
1379
1380         physmap_idx = 0;
1381         vmf.vmf_ebx = 0;
1382         do {
1383                 vmf.vmf_eax = 0xE820;
1384                 vmf.vmf_edx = SMAP_SIG;
1385                 vmf.vmf_ecx = SMAPSIZ;
1386                 i = vm86_datacall(0x15, &vmf, &vmc);
1387                 if (i || vmf.vmf_eax != SMAP_SIG)
1388                         break;
1389                 if (boothowto & RB_VERBOSE)
1390                         kprintf("SMAP type=%02x base=%08x %08x len=%08x %08x\n",
1391                                 smap->type,
1392                                 *(u_int32_t *)((char *)&smap->base + 4),
1393                                 (u_int32_t)smap->base,
1394                                 *(u_int32_t *)((char *)&smap->length + 4),
1395                                 (u_int32_t)smap->length);
1396
1397                 if (smap->type != SMAP_TYPE_MEMORY)
1398                         goto next_run;
1399
1400                 if (smap->length == 0)
1401                         goto next_run;
1402
1403                 Realmem += smap->length;
1404
1405                 if (smap->base >= 0xffffffffLLU) {
1406                         kprintf("%ju MB of memory above 4GB ignored\n",
1407                                 (uintmax_t)(smap->length / 1024 / 1024));
1408                         goto next_run;
1409                 }
1410
1411                 for (i = 0; i <= physmap_idx; i += 2) {
1412                         if (smap->base < physmap[i + 1]) {
1413                                 if (boothowto & RB_VERBOSE) {
1414                                         kprintf("Overlapping or non-montonic "
1415                                                 "memory region, ignoring "
1416                                                 "second region\n");
1417                                 }
1418                                 Realmem -= smap->length;
1419                                 goto next_run;
1420                         }
1421                 }
1422
1423                 if (smap->base == physmap[physmap_idx + 1]) {
1424                         physmap[physmap_idx + 1] += smap->length;
1425                         goto next_run;
1426                 }
1427
1428                 physmap_idx += 2;
1429                 if (physmap_idx == PHYSMAP_ENTRIES*2) {
1430                         kprintf("Too many segments in the physical "
1431                                 "address map, giving up\n");
1432                         break;
1433                 }
1434                 physmap[physmap_idx] = smap->base;
1435                 physmap[physmap_idx + 1] = smap->base + smap->length;
1436 next_run:
1437                 ; /* fix GCC3.x warning */
1438         } while (vmf.vmf_ebx != 0);
1439
1440         /*
1441          * Perform "base memory" related probes & setup based on SMAP
1442          */
1443         if (basemem == 0) {
1444                 for (i = 0; i <= physmap_idx; i += 2) {
1445                         if (physmap[i] == 0x00000000) {
1446                                 basemem = physmap[i + 1] / 1024;
1447                                 break;
1448                         }
1449                 }
1450
1451                 if (basemem == 0) {
1452                         basemem = 640;
1453                 }
1454
1455                 if (basemem > 640) {
1456                         kprintf("Preposterous BIOS basemem of %uK, "
1457                                 "truncating to 640K\n", basemem);
1458                         basemem = 640;
1459                 }
1460
1461                 for (pa = trunc_page(basemem * 1024);
1462                      pa < ISA_HOLE_START; pa += PAGE_SIZE) {
1463                         pte = vtopte(pa + KERNBASE);
1464                         *pte = pa | PG_RW | PG_V;
1465                 }
1466
1467                 pte = vm86paddr;
1468                 for (i = basemem / 4; i < 160; i++)
1469                         pte[i] = (i << PAGE_SHIFT) | PG_V | PG_RW | PG_U;
1470         }
1471
1472         if (physmap[1] != 0)
1473                 goto physmap_done;
1474
1475         /*
1476          * If we failed above, try memory map with INT 15:E801
1477          */
1478         vmf.vmf_ax = 0xE801;
1479         if (vm86_intcall(0x15, &vmf) == 0) {
1480                 extmem = vmf.vmf_cx + vmf.vmf_dx * 64;
1481         } else {
1482 #if 0
1483                 vmf.vmf_ah = 0x88;
1484                 vm86_intcall(0x15, &vmf);
1485                 extmem = vmf.vmf_ax;
1486 #else
1487                 /*
1488                  * Prefer the RTC value for extended memory.
1489                  */
1490                 extmem = rtcin(RTC_EXTLO) + (rtcin(RTC_EXTHI) << 8);
1491 #endif
1492         }
1493
1494         /*
1495          * Special hack for chipsets that still remap the 384k hole when
1496          * there's 16MB of memory - this really confuses people that
1497          * are trying to use bus mastering ISA controllers with the
1498          * "16MB limit"; they only have 16MB, but the remapping puts
1499          * them beyond the limit.
1500          *
1501          * If extended memory is between 15-16MB (16-17MB phys address range),
1502          *      chop it to 15MB.
1503          */
1504         if ((extmem > 15 * 1024) && (extmem < 16 * 1024))
1505                 extmem = 15 * 1024;
1506
1507         physmap[0] = 0;
1508         physmap[1] = basemem * 1024;
1509         physmap_idx = 2;
1510         physmap[physmap_idx] = 0x100000;
1511         physmap[physmap_idx + 1] = physmap[physmap_idx] + extmem * 1024;
1512
1513 physmap_done:
1514         /*
1515          * Now, physmap contains a map of physical memory.
1516          */
1517
1518         base_memory = physmap[1];
1519         /* make hole for AP bootstrap code YYY */
1520         physmap[1] = mp_bootaddress(base_memory);
1521
1522         /* Save EBDA address, if any */
1523         ebda_addr = (u_long)(*(u_short *)(KERNBASE + 0x40e));
1524         ebda_addr <<= 4;
1525
1526         /*
1527          * Maxmem isn't the "maximum memory", it's one larger than the
1528          * highest page of the physical address space.  It should be
1529          * called something like "Maxphyspage".  We may adjust this 
1530          * based on ``hw.physmem'' and the results of the memory test.
1531          */
1532         Maxmem = atop(physmap[physmap_idx + 1]);
1533
1534 #ifdef MAXMEM
1535         Maxmem = MAXMEM / 4;
1536 #endif
1537
1538         if (kgetenv_quad("hw.physmem", &maxmem))
1539                 Maxmem = atop(maxmem);
1540
1541         if (atop(physmap[physmap_idx + 1]) != Maxmem &&
1542             (boothowto & RB_VERBOSE))
1543                 kprintf("Physical memory use set to %lluK\n", Maxmem * 4);
1544
1545         /*
1546          * If Maxmem has been increased beyond what the system has detected,
1547          * extend the last memory segment to the new limit.
1548          */ 
1549         if (atop(physmap[physmap_idx + 1]) < Maxmem)
1550                 physmap[physmap_idx + 1] = ptoa(Maxmem);
1551
1552         /* call pmap initialization to make new kernel address space */
1553         pmap_bootstrap(first, 0);
1554
1555         /*
1556          * Size up each available chunk of physical memory.
1557          */
1558         physmap[0] = PAGE_SIZE;         /* mask off page 0 */
1559         pa_indx = 0;
1560         da_indx = 1;
1561         phys_avail[pa_indx++] = physmap[0];
1562         phys_avail[pa_indx] = physmap[0];
1563         dump_avail[da_indx] = physmap[0];
1564
1565         pte = CMAP1;
1566
1567         /*
1568          * Get dcons buffer address
1569          */
1570         if (kgetenv_quad("dcons.addr", &dcons_addr) == 0 ||
1571             kgetenv_quad("dcons.size", &dcons_size) == 0)
1572                 dcons_addr = 0;
1573
1574         /*
1575          * physmap is in bytes, so when converting to page boundaries,
1576          * round up the start address and round down the end address.
1577          */
1578         for (i = 0; i <= physmap_idx; i += 2) {
1579                 vm_offset_t end;
1580
1581                 end = ptoa(Maxmem);
1582                 if (physmap[i + 1] < end)
1583                         end = trunc_page(physmap[i + 1]);
1584                 for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
1585                         int tmp, page_bad, full;
1586 #if 0
1587                         int *ptr = 0;
1588 #else
1589                         int *ptr = (int *)CADDR1;
1590 #endif
1591                         full = FALSE;
1592
1593                         /*
1594                          * block out kernel memory as not available.
1595                          */
1596                         if (pa >= 0x100000 && pa < first)
1597                                 goto do_dump_avail;
1598         
1599                         /*
1600                          * block out dcons buffer
1601                          */
1602                         if (dcons_addr > 0
1603                             && pa >= trunc_page(dcons_addr)
1604                             && pa < dcons_addr + dcons_size)
1605                                 goto do_dump_avail;
1606
1607                         page_bad = FALSE;
1608
1609                         /*
1610                          * map page into kernel: valid, read/write,non-cacheable
1611                          */
1612                         *pte = pa | PG_V | PG_RW | PG_N;
1613                         cpu_invltlb();
1614
1615                         tmp = *(int *)ptr;
1616                         /*
1617                          * Test for alternating 1's and 0's
1618                          */
1619                         *(volatile int *)ptr = 0xaaaaaaaa;
1620                         if (*(volatile int *)ptr != 0xaaaaaaaa) {
1621                                 page_bad = TRUE;
1622                         }
1623                         /*
1624                          * Test for alternating 0's and 1's
1625                          */
1626                         *(volatile int *)ptr = 0x55555555;
1627                         if (*(volatile int *)ptr != 0x55555555) {
1628                         page_bad = TRUE;
1629                         }
1630                         /*
1631                          * Test for all 1's
1632                          */
1633                         *(volatile int *)ptr = 0xffffffff;
1634                         if (*(volatile int *)ptr != 0xffffffff) {
1635                                 page_bad = TRUE;
1636                         }
1637                         /*
1638                          * Test for all 0's
1639                          */
1640                         *(volatile int *)ptr = 0x0;
1641                         if (*(volatile int *)ptr != 0x0) {
1642                                 page_bad = TRUE;
1643                         }
1644                         /*
1645                          * Restore original value.
1646                          */
1647                         *(int *)ptr = tmp;
1648
1649                         /*
1650                          * Adjust array of valid/good pages.
1651                          */
1652                         if (page_bad == TRUE) {
1653                                 continue;
1654                         }
1655                         /*
1656                          * If this good page is a continuation of the
1657                          * previous set of good pages, then just increase
1658                          * the end pointer. Otherwise start a new chunk.
1659                          * Note that "end" points one higher than end,
1660                          * making the range >= start and < end.
1661                          * If we're also doing a speculative memory
1662                          * test and we at or past the end, bump up Maxmem
1663                          * so that we keep going. The first bad page
1664                          * will terminate the loop.
1665                          */
1666                         if (phys_avail[pa_indx] == pa) {
1667                                 phys_avail[pa_indx] += PAGE_SIZE;
1668                         } else {
1669                                 pa_indx++;
1670                                 if (pa_indx >= PHYSMAP_ENTRIES*2) {
1671                                         kprintf("Too many holes in the physical address space, giving up\n");
1672                                         pa_indx--;
1673                                         full = TRUE;
1674                                         goto do_dump_avail;
1675                                 }
1676                                 phys_avail[pa_indx++] = pa;     /* start */
1677                                 phys_avail[pa_indx] = pa + PAGE_SIZE;   /* end */
1678                         }
1679                         physmem++;
1680 do_dump_avail:
1681                         if (dump_avail[da_indx] == pa) {
1682                                 dump_avail[da_indx] += PAGE_SIZE;
1683                         } else {
1684                                 da_indx++;
1685                                 if (da_indx >= PHYSMAP_ENTRIES*2) {
1686                                         da_indx--;
1687                                         goto do_next;
1688                                 }
1689                                 dump_avail[da_indx++] = pa;     /* start */
1690                                 dump_avail[da_indx] = pa + PAGE_SIZE; /* end */
1691                         }
1692 do_next:
1693                         if (full)
1694                                 break;
1695
1696                 }
1697         }
1698         *pte = 0;
1699         cpu_invltlb();
1700
1701         /*
1702          * XXX
1703          * The last chunk must contain at least one page plus the message
1704          * buffer to avoid complicating other code (message buffer address
1705          * calculation, etc.).
1706          */
1707         while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1708             round_page(MSGBUF_SIZE) >= phys_avail[pa_indx]) {
1709                 physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1710                 phys_avail[pa_indx--] = 0;
1711                 phys_avail[pa_indx--] = 0;
1712         }
1713
1714         Maxmem = atop(phys_avail[pa_indx]);
1715
1716         /* Trim off space for the message buffer. */
1717         phys_avail[pa_indx] -= round_page(MSGBUF_SIZE);
1718
1719         avail_end = phys_avail[pa_indx];
1720 }
1721
1722 struct machintr_abi MachIntrABI;
1723
1724 /*
1725  * IDT VECTORS:
1726  *      0       Divide by zero
1727  *      1       Debug
1728  *      2       NMI
1729  *      3       BreakPoint
1730  *      4       OverFlow
1731  *      5       Bound-Range
1732  *      6       Invalid OpCode
1733  *      7       Device Not Available (x87)
1734  *      8       Double-Fault
1735  *      9       Coprocessor Segment overrun (unsupported, reserved)
1736  *      10      Invalid-TSS
1737  *      11      Segment not present
1738  *      12      Stack
1739  *      13      General Protection
1740  *      14      Page Fault
1741  *      15      Reserved
1742  *      16      x87 FP Exception pending
1743  *      17      Alignment Check
1744  *      18      Machine Check
1745  *      19      SIMD floating point
1746  *      20-31   reserved
1747  *      32-255  INTn/external sources
1748  */
1749 void
1750 init386(int first)
1751 {
1752         struct gate_descriptor *gdp;
1753         int gsel_tss, metadata_missing, off, x;
1754         struct mdglobaldata *gd;
1755
1756         /*
1757          * Prevent lowering of the ipl if we call tsleep() early.
1758          */
1759         gd = &CPU_prvspace[0].mdglobaldata;
1760         bzero(gd, sizeof(*gd));
1761
1762         gd->mi.gd_curthread = &thread0;
1763         thread0.td_gd = &gd->mi;
1764
1765         atdevbase = ISA_HOLE_START + KERNBASE;
1766
1767         metadata_missing = 0;
1768         if (bootinfo.bi_modulep) {
1769                 preload_metadata = (caddr_t)bootinfo.bi_modulep + KERNBASE;
1770                 preload_bootstrap_relocate(KERNBASE);
1771         } else {
1772                 metadata_missing = 1;
1773         }
1774         if (bootinfo.bi_envp)
1775                 kern_envp = (caddr_t)bootinfo.bi_envp + KERNBASE;
1776
1777         if (boothowto & RB_VERBOSE)
1778                 bootverbose++;
1779
1780         /*
1781          * Default MachIntrABI to ICU
1782          */
1783         MachIntrABI = MachIntrABI_ICU;
1784
1785         TUNABLE_INT_FETCH("hw.apic_io_enable", &ioapic_enable); /* for compat */
1786         TUNABLE_INT_FETCH("hw.ioapic_enable", &ioapic_enable);
1787         TUNABLE_INT_FETCH("hw.lapic_enable", &lapic_enable);
1788
1789         /*
1790          * Some of the virtual machines do not work w/ I/O APIC
1791          * enabled.  If the user does not explicitly enable or
1792          * disable the I/O APIC (ioapic_enable < 0), then we
1793          * disable I/O APIC on all virtual machines.
1794          */
1795         if (ioapic_enable < 0) {
1796                 if (cpu_feature2 & CPUID2_VMM)
1797                         ioapic_enable = 0;
1798                 else
1799                         ioapic_enable = 1;
1800         }
1801
1802         /*
1803          * start with one cpu.  Note: with one cpu, ncpus2_shift, ncpus2_mask,
1804          * and ncpus_fit_mask remain 0.
1805          */
1806         ncpus = 1;
1807         ncpus2 = 1;
1808         ncpus_fit = 1;
1809         /* Init basic tunables, hz etc */
1810         init_param1();
1811
1812         /*
1813          * make gdt memory segments, the code segment goes up to end of the
1814          * page with etext in it, the data segment goes to the end of
1815          * the address space
1816          */
1817         /*
1818          * XXX text protection is temporarily (?) disabled.  The limit was
1819          * i386_btop(round_page(etext)) - 1.
1820          */
1821         gdt_segs[GCODE_SEL].ssd_limit = atop(0 - 1);
1822         gdt_segs[GDATA_SEL].ssd_limit = atop(0 - 1);
1823
1824         gdt_segs[GPRIV_SEL].ssd_limit =
1825                 atop(sizeof(struct privatespace) - 1);
1826         gdt_segs[GPRIV_SEL].ssd_base = (int) &CPU_prvspace[0];
1827         gdt_segs[GPROC0_SEL].ssd_base =
1828                 (int) &CPU_prvspace[0].mdglobaldata.gd_common_tss;
1829
1830         gd->mi.gd_prvspace = &CPU_prvspace[0];
1831
1832         /*
1833          * Note: curthread must be set non-NULL
1834          * early in the boot sequence because the system assumes
1835          * that 'curthread' is never NULL.
1836          */
1837
1838         for (x = 0; x < NGDT; x++)
1839                 ssdtosd(&gdt_segs[x], &gdt[x].sd);
1840
1841         r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
1842         r_gdt.rd_base =  (int) gdt;
1843         lgdt(&r_gdt);
1844
1845         mi_gdinit(&gd->mi, 0);
1846         cpu_gdinit(gd, 0);
1847         mi_proc0init(&gd->mi, proc0paddr);
1848         safepri = TDPRI_MAX;
1849
1850         /* make ldt memory segments */
1851         /*
1852          * XXX - VM_MAX_USER_ADDRESS is an end address, not a max.  And it
1853          * should be spelled ...MAX_USER...
1854          */
1855         ldt_segs[LUCODE_SEL].ssd_limit = atop(VM_MAX_USER_ADDRESS - 1);
1856         ldt_segs[LUDATA_SEL].ssd_limit = atop(VM_MAX_USER_ADDRESS - 1);
1857         for (x = 0; x < NELEM(ldt_segs); x++)
1858                 ssdtosd(&ldt_segs[x], &ldt[x].sd);
1859
1860         _default_ldt = GSEL(GLDT_SEL, SEL_KPL);
1861         lldt(_default_ldt);
1862         gd->gd_currentldt = _default_ldt;
1863         /* spinlocks and the BGL */
1864         init_locks();
1865
1866         /*
1867          * Setup the hardware exception table.  Most exceptions use
1868          * SDT_SYS386TGT, known as a 'trap gate'.  Trap gates leave
1869          * interrupts enabled.  VM page faults use SDT_SYS386IGT, known as
1870          * an 'interrupt trap gate', which disables interrupts on entry,
1871          * in order to be able to poll the appropriate CRn register to
1872          * determine the fault address.
1873          */
1874         for (x = 0; x < NIDT; x++) {
1875 #ifdef DEBUG_INTERRUPTS
1876                 setidt(x, Xrsvdary[x], SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1877 #else
1878                 setidt(x, &IDTVEC(rsvd0), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1879 #endif
1880         }
1881         setidt(0, &IDTVEC(div),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1882         setidt(1, &IDTVEC(dbg),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1883         setidt(2, &IDTVEC(nmi),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1884         setidt(3, &IDTVEC(bpt),  SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1885         setidt(4, &IDTVEC(ofl),  SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1886         setidt(5, &IDTVEC(bnd),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1887         setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1888         setidt(7, &IDTVEC(dna),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1889         setidt(8, 0,  SDT_SYSTASKGT, SEL_KPL, GSEL(GPANIC_SEL, SEL_KPL));
1890         setidt(9, &IDTVEC(fpusegm),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1891         setidt(10, &IDTVEC(tss),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1892         setidt(11, &IDTVEC(missing),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1893         setidt(12, &IDTVEC(stk),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1894         setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1895         setidt(14, &IDTVEC(page),  SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1896         setidt(15, &IDTVEC(rsvd0),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1897         setidt(16, &IDTVEC(fpu),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1898         setidt(17, &IDTVEC(align), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1899         setidt(18, &IDTVEC(mchk),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1900         setidt(19, &IDTVEC(xmm), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1901         setidt(0x80, &IDTVEC(int0x80_syscall),
1902                         SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1903
1904         r_idt.rd_limit = sizeof(idt0) - 1;
1905         r_idt.rd_base = (int) idt;
1906         lidt(&r_idt);
1907
1908         /*
1909          * Initialize the console before we print anything out.
1910          */
1911         cninit();
1912
1913         if (metadata_missing)
1914                 kprintf("WARNING: loader(8) metadata is missing!\n");
1915
1916 #if     NISA >0
1917         elcr_probe();
1918         isa_defaultirq();
1919 #endif
1920         rand_initialize();
1921
1922         /*
1923          * Initialize IRQ mapping
1924          *
1925          * NOTE:
1926          * SHOULD be after elcr_probe()
1927          */
1928         MachIntrABI_ICU.initmap();
1929         MachIntrABI_IOAPIC.initmap();
1930
1931 #ifdef DDB
1932         kdb_init();
1933         if (boothowto & RB_KDB)
1934                 Debugger("Boot flags requested debugger");
1935 #endif
1936
1937         finishidentcpu();       /* Final stage of CPU initialization */
1938         setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1939         setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1940         initializecpu();        /* Initialize CPU registers */
1941
1942         /*
1943          * make an initial tss so cpu can get interrupt stack on syscall!
1944          * The 16 bytes is to save room for a VM86 context.
1945          */
1946         gd->gd_common_tss.tss_esp0 = (int) thread0.td_pcb - 16;
1947         gd->gd_common_tss.tss_ss0 = GSEL(GDATA_SEL, SEL_KPL) ;
1948         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1949         gd->gd_tss_gdt = &gdt[GPROC0_SEL].sd;
1950         gd->gd_common_tssd = *gd->gd_tss_gdt;
1951         gd->gd_common_tss.tss_ioopt = (sizeof gd->gd_common_tss) << 16;
1952         ltr(gsel_tss);
1953
1954         dblfault_tss.tss_esp = dblfault_tss.tss_esp0 = dblfault_tss.tss_esp1 =
1955             dblfault_tss.tss_esp2 = (int) &dblfault_stack[sizeof(dblfault_stack)];
1956         dblfault_tss.tss_ss = dblfault_tss.tss_ss0 = dblfault_tss.tss_ss1 =
1957             dblfault_tss.tss_ss2 = GSEL(GDATA_SEL, SEL_KPL);
1958         dblfault_tss.tss_cr3 = (int)IdlePTD;
1959         dblfault_tss.tss_eip = (int) dblfault_handler;
1960         dblfault_tss.tss_eflags = PSL_KERNEL;
1961         dblfault_tss.tss_ds = dblfault_tss.tss_es =
1962             dblfault_tss.tss_gs = GSEL(GDATA_SEL, SEL_KPL);
1963         dblfault_tss.tss_fs = GSEL(GPRIV_SEL, SEL_KPL);
1964         dblfault_tss.tss_cs = GSEL(GCODE_SEL, SEL_KPL);
1965         dblfault_tss.tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
1966
1967         vm86_initialize();
1968         getmemsize(first);
1969         init_param2(physmem);
1970
1971         /* now running on new page tables, configured,and u/iom is accessible */
1972
1973         /* Map the message buffer. */
1974         for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
1975                 pmap_kenter((vm_offset_t)msgbufp + off, avail_end + off);
1976
1977         msgbufinit(msgbufp, MSGBUF_SIZE);
1978
1979         /* make a call gate to reenter kernel with */
1980         gdp = &ldt[LSYS5CALLS_SEL].gd;
1981
1982         x = (int) &IDTVEC(syscall);
1983         gdp->gd_looffset = x++;
1984         gdp->gd_selector = GSEL(GCODE_SEL,SEL_KPL);
1985         gdp->gd_stkcpy = 1;
1986         gdp->gd_type = SDT_SYS386CGT;
1987         gdp->gd_dpl = SEL_UPL;
1988         gdp->gd_p = 1;
1989         gdp->gd_hioffset = ((int) &IDTVEC(syscall)) >>16;
1990
1991         /* XXX does this work? */
1992         ldt[LBSDICALLS_SEL] = ldt[LSYS5CALLS_SEL];
1993         ldt[LSOL26CALLS_SEL] = ldt[LSYS5CALLS_SEL];
1994
1995         /* transfer to user mode */
1996
1997         _ucodesel = LSEL(LUCODE_SEL, SEL_UPL);
1998         _udatasel = LSEL(LUDATA_SEL, SEL_UPL);
1999
2000         /* setup proc 0's pcb */
2001         thread0.td_pcb->pcb_flags = 0;
2002         thread0.td_pcb->pcb_cr3 = (int)IdlePTD; /* should already be setup */
2003         thread0.td_pcb->pcb_ext = NULL;
2004         lwp0.lwp_md.md_regs = &proc0_tf;
2005 }
2006
2007 /*
2008  * Initialize machine-dependant portions of the global data structure.
2009  * Note that the global data area and cpu0's idlestack in the private
2010  * data space were allocated in locore.
2011  *
2012  * Note: the idlethread's cpl is 0
2013  *
2014  * WARNING!  Called from early boot, 'mycpu' may not work yet.
2015  */
2016 void
2017 cpu_gdinit(struct mdglobaldata *gd, int cpu)
2018 {
2019         if (cpu)
2020                 gd->mi.gd_curthread = &gd->mi.gd_idlethread;
2021
2022         lwkt_init_thread(&gd->mi.gd_idlethread, 
2023                         gd->mi.gd_prvspace->idlestack, 
2024                         sizeof(gd->mi.gd_prvspace->idlestack), 
2025                         0, &gd->mi);
2026         lwkt_set_comm(&gd->mi.gd_idlethread, "idle_%d", cpu);
2027         gd->mi.gd_idlethread.td_switch = cpu_lwkt_switch;
2028         gd->mi.gd_idlethread.td_sp -= sizeof(void *);
2029         *(void **)gd->mi.gd_idlethread.td_sp = cpu_idle_restore;
2030 }
2031
2032 int
2033 is_globaldata_space(vm_offset_t saddr, vm_offset_t eaddr)
2034 {
2035         if (saddr >= (vm_offset_t)&CPU_prvspace[0] &&
2036             eaddr <= (vm_offset_t)&CPU_prvspace[MAXCPU]) {
2037                 return (TRUE);
2038         }
2039         return (FALSE);
2040 }
2041
2042 struct globaldata *
2043 globaldata_find(int cpu)
2044 {
2045         KKASSERT(cpu >= 0 && cpu < ncpus);
2046         return(&CPU_prvspace[cpu].mdglobaldata.mi);
2047 }
2048
2049 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
2050 static void f00f_hack(void *unused);
2051 SYSINIT(f00f_hack, SI_BOOT2_BIOS, SI_ORDER_ANY, f00f_hack, NULL);
2052
2053 static void
2054 f00f_hack(void *unused) 
2055 {
2056         struct gate_descriptor *new_idt;
2057         vm_offset_t tmp;
2058
2059         if (!has_f00f_bug)
2060                 return;
2061
2062         kprintf("Intel Pentium detected, installing workaround for F00F bug\n");
2063
2064         r_idt.rd_limit = sizeof(idt0) - 1;
2065
2066         tmp = kmem_alloc(&kernel_map, PAGE_SIZE * 2);
2067         if (tmp == 0)
2068                 panic("kmem_alloc returned 0");
2069         if (((unsigned int)tmp & (PAGE_SIZE-1)) != 0)
2070                 panic("kmem_alloc returned non-page-aligned memory");
2071         /* Put the first seven entries in the lower page */
2072         new_idt = (struct gate_descriptor*)(tmp + PAGE_SIZE - (7*8));
2073         bcopy(idt, new_idt, sizeof(idt0));
2074         r_idt.rd_base = (int)new_idt;
2075         lidt(&r_idt);
2076         idt = new_idt;
2077         if (vm_map_protect(&kernel_map, tmp, tmp + PAGE_SIZE,
2078                            VM_PROT_READ, FALSE) != KERN_SUCCESS)
2079                 panic("vm_map_protect failed");
2080         return;
2081 }
2082 #endif /* defined(I586_CPU) && !NO_F00F_HACK */
2083
2084 int
2085 ptrace_set_pc(struct lwp *lp, unsigned long addr)
2086 {
2087         lp->lwp_md.md_regs->tf_eip = addr;
2088         return (0);
2089 }
2090
2091 int
2092 ptrace_single_step(struct lwp *lp)
2093 {
2094         lp->lwp_md.md_regs->tf_eflags |= PSL_T;
2095         return (0);
2096 }
2097
2098 int
2099 fill_regs(struct lwp *lp, struct reg *regs)
2100 {
2101         struct trapframe *tp;
2102
2103         if ((tp = lp->lwp_md.md_regs) == NULL)
2104                 return EINVAL;
2105         regs->r_gs = tp->tf_gs;
2106         regs->r_fs = tp->tf_fs;
2107         regs->r_es = tp->tf_es;
2108         regs->r_ds = tp->tf_ds;
2109         regs->r_edi = tp->tf_edi;
2110         regs->r_esi = tp->tf_esi;
2111         regs->r_ebp = tp->tf_ebp;
2112         regs->r_ebx = tp->tf_ebx;
2113         regs->r_edx = tp->tf_edx;
2114         regs->r_ecx = tp->tf_ecx;
2115         regs->r_eax = tp->tf_eax;
2116         regs->r_eip = tp->tf_eip;
2117         regs->r_cs = tp->tf_cs;
2118         regs->r_eflags = tp->tf_eflags;
2119         regs->r_esp = tp->tf_esp;
2120         regs->r_ss = tp->tf_ss;
2121         return (0);
2122 }
2123
2124 int
2125 set_regs(struct lwp *lp, struct reg *regs)
2126 {
2127         struct trapframe *tp;
2128
2129         tp = lp->lwp_md.md_regs;
2130         if (!EFL_SECURE(regs->r_eflags, tp->tf_eflags) ||
2131             !CS_SECURE(regs->r_cs))
2132                 return (EINVAL);
2133         tp->tf_gs = regs->r_gs;
2134         tp->tf_fs = regs->r_fs;
2135         tp->tf_es = regs->r_es;
2136         tp->tf_ds = regs->r_ds;
2137         tp->tf_edi = regs->r_edi;
2138         tp->tf_esi = regs->r_esi;
2139         tp->tf_ebp = regs->r_ebp;
2140         tp->tf_ebx = regs->r_ebx;
2141         tp->tf_edx = regs->r_edx;
2142         tp->tf_ecx = regs->r_ecx;
2143         tp->tf_eax = regs->r_eax;
2144         tp->tf_eip = regs->r_eip;
2145         tp->tf_cs = regs->r_cs;
2146         tp->tf_eflags = regs->r_eflags;
2147         tp->tf_esp = regs->r_esp;
2148         tp->tf_ss = regs->r_ss;
2149         return (0);
2150 }
2151
2152 #ifndef CPU_DISABLE_SSE
2153 static void
2154 fill_fpregs_xmm(struct savexmm *sv_xmm, struct save87 *sv_87)
2155 {
2156         struct env87 *penv_87 = &sv_87->sv_env;
2157         struct envxmm *penv_xmm = &sv_xmm->sv_env;
2158         int i;
2159
2160         /* FPU control/status */
2161         penv_87->en_cw = penv_xmm->en_cw;
2162         penv_87->en_sw = penv_xmm->en_sw;
2163         penv_87->en_tw = penv_xmm->en_tw;
2164         penv_87->en_fip = penv_xmm->en_fip;
2165         penv_87->en_fcs = penv_xmm->en_fcs;
2166         penv_87->en_opcode = penv_xmm->en_opcode;
2167         penv_87->en_foo = penv_xmm->en_foo;
2168         penv_87->en_fos = penv_xmm->en_fos;
2169
2170         /* FPU registers */
2171         for (i = 0; i < 8; ++i)
2172                 sv_87->sv_ac[i] = sv_xmm->sv_fp[i].fp_acc;
2173 }
2174
2175 static void
2176 set_fpregs_xmm(struct save87 *sv_87, struct savexmm *sv_xmm)
2177 {
2178         struct env87 *penv_87 = &sv_87->sv_env;
2179         struct envxmm *penv_xmm = &sv_xmm->sv_env;
2180         int i;
2181
2182         /* FPU control/status */
2183         penv_xmm->en_cw = penv_87->en_cw;
2184         penv_xmm->en_sw = penv_87->en_sw;
2185         penv_xmm->en_tw = penv_87->en_tw;
2186         penv_xmm->en_fip = penv_87->en_fip;
2187         penv_xmm->en_fcs = penv_87->en_fcs;
2188         penv_xmm->en_opcode = penv_87->en_opcode;
2189         penv_xmm->en_foo = penv_87->en_foo;
2190         penv_xmm->en_fos = penv_87->en_fos;
2191
2192         /* FPU registers */
2193         for (i = 0; i < 8; ++i)
2194                 sv_xmm->sv_fp[i].fp_acc = sv_87->sv_ac[i];
2195 }
2196 #endif /* CPU_DISABLE_SSE */
2197
2198 int
2199 fill_fpregs(struct lwp *lp, struct fpreg *fpregs)
2200 {
2201         if (lp->lwp_thread == NULL || lp->lwp_thread->td_pcb == NULL)
2202                 return EINVAL;
2203 #ifndef CPU_DISABLE_SSE
2204         if (cpu_fxsr) {
2205                 fill_fpregs_xmm(&lp->lwp_thread->td_pcb->pcb_save.sv_xmm,
2206                                 (struct save87 *)fpregs);
2207                 return (0);
2208         }
2209 #endif /* CPU_DISABLE_SSE */
2210         bcopy(&lp->lwp_thread->td_pcb->pcb_save.sv_87, fpregs, sizeof *fpregs);
2211         return (0);
2212 }
2213
2214 int
2215 set_fpregs(struct lwp *lp, struct fpreg *fpregs)
2216 {
2217 #ifndef CPU_DISABLE_SSE
2218         if (cpu_fxsr) {
2219                 set_fpregs_xmm((struct save87 *)fpregs,
2220                                &lp->lwp_thread->td_pcb->pcb_save.sv_xmm);
2221                 return (0);
2222         }
2223 #endif /* CPU_DISABLE_SSE */
2224         bcopy(fpregs, &lp->lwp_thread->td_pcb->pcb_save.sv_87, sizeof *fpregs);
2225         return (0);
2226 }
2227
2228 int
2229 fill_dbregs(struct lwp *lp, struct dbreg *dbregs)
2230 {
2231         struct pcb *pcb;
2232
2233         if (lp == NULL) {
2234                 dbregs->dr0 = rdr0();
2235                 dbregs->dr1 = rdr1();
2236                 dbregs->dr2 = rdr2();
2237                 dbregs->dr3 = rdr3();
2238                 dbregs->dr4 = rdr4();
2239                 dbregs->dr5 = rdr5();
2240                 dbregs->dr6 = rdr6();
2241                 dbregs->dr7 = rdr7();
2242                 return (0);
2243         }
2244         if (lp->lwp_thread == NULL || (pcb = lp->lwp_thread->td_pcb) == NULL)
2245                 return EINVAL;
2246         dbregs->dr0 = pcb->pcb_dr0;
2247         dbregs->dr1 = pcb->pcb_dr1;
2248         dbregs->dr2 = pcb->pcb_dr2;
2249         dbregs->dr3 = pcb->pcb_dr3;
2250         dbregs->dr4 = 0;
2251         dbregs->dr5 = 0;
2252         dbregs->dr6 = pcb->pcb_dr6;
2253         dbregs->dr7 = pcb->pcb_dr7;
2254         return (0);
2255 }
2256
2257 int
2258 set_dbregs(struct lwp *lp, struct dbreg *dbregs)
2259 {
2260         if (lp == NULL) {
2261                 load_dr0(dbregs->dr0);
2262                 load_dr1(dbregs->dr1);
2263                 load_dr2(dbregs->dr2);
2264                 load_dr3(dbregs->dr3);
2265                 load_dr4(dbregs->dr4);
2266                 load_dr5(dbregs->dr5);
2267                 load_dr6(dbregs->dr6);
2268                 load_dr7(dbregs->dr7);
2269         } else {
2270                 struct pcb *pcb;
2271                 struct ucred *ucred;
2272                 int i;
2273                 uint32_t mask1, mask2;
2274
2275                 /*
2276                  * Don't let an illegal value for dr7 get set.  Specifically,
2277                  * check for undefined settings.  Setting these bit patterns
2278                  * result in undefined behaviour and can lead to an unexpected
2279                  * TRCTRAP.
2280                  */
2281                 for (i = 0, mask1 = 0x3<<16, mask2 = 0x2<<16; i < 8; 
2282                      i++, mask1 <<= 2, mask2 <<= 2)
2283                         if ((dbregs->dr7 & mask1) == mask2)
2284                                 return (EINVAL);
2285                 
2286                 pcb = lp->lwp_thread->td_pcb;
2287                 ucred = lp->lwp_proc->p_ucred;
2288
2289                 /*
2290                  * Don't let a process set a breakpoint that is not within the
2291                  * process's address space.  If a process could do this, it
2292                  * could halt the system by setting a breakpoint in the kernel
2293                  * (if ddb was enabled).  Thus, we need to check to make sure
2294                  * that no breakpoints are being enabled for addresses outside
2295                  * process's address space, unless, perhaps, we were called by
2296                  * uid 0.
2297                  *
2298                  * XXX - what about when the watched area of the user's
2299                  * address space is written into from within the kernel
2300                  * ... wouldn't that still cause a breakpoint to be generated
2301                  * from within kernel mode?
2302                  */
2303
2304                 if (priv_check_cred(ucred, PRIV_ROOT, 0) != 0) {
2305                         if (dbregs->dr7 & 0x3) {
2306                                 /* dr0 is enabled */
2307                                 if (dbregs->dr0 >= VM_MAX_USER_ADDRESS)
2308                                         return (EINVAL);
2309                         }
2310
2311                         if (dbregs->dr7 & (0x3<<2)) {
2312                                 /* dr1 is enabled */
2313                                 if (dbregs->dr1 >= VM_MAX_USER_ADDRESS)
2314                                         return (EINVAL);
2315                         }
2316
2317                         if (dbregs->dr7 & (0x3<<4)) {
2318                                 /* dr2 is enabled */
2319                                 if (dbregs->dr2 >= VM_MAX_USER_ADDRESS)
2320                                         return (EINVAL);
2321                         }
2322
2323                         if (dbregs->dr7 & (0x3<<6)) {
2324                                 /* dr3 is enabled */
2325                                 if (dbregs->dr3 >= VM_MAX_USER_ADDRESS)
2326                                         return (EINVAL);
2327                         }
2328                 }
2329
2330                 pcb->pcb_dr0 = dbregs->dr0;
2331                 pcb->pcb_dr1 = dbregs->dr1;
2332                 pcb->pcb_dr2 = dbregs->dr2;
2333                 pcb->pcb_dr3 = dbregs->dr3;
2334                 pcb->pcb_dr6 = dbregs->dr6;
2335                 pcb->pcb_dr7 = dbregs->dr7;
2336
2337                 pcb->pcb_flags |= PCB_DBREGS;
2338         }
2339
2340         return (0);
2341 }
2342
2343 /*
2344  * Return > 0 if a hardware breakpoint has been hit, and the
2345  * breakpoint was in user space.  Return 0, otherwise.
2346  */
2347 int
2348 user_dbreg_trap(void)
2349 {
2350         u_int32_t dr7, dr6; /* debug registers dr6 and dr7 */
2351         u_int32_t bp;       /* breakpoint bits extracted from dr6 */
2352         int nbp;            /* number of breakpoints that triggered */
2353         caddr_t addr[4];    /* breakpoint addresses */
2354         int i;
2355         
2356         dr7 = rdr7();
2357         if ((dr7 & 0x000000ff) == 0) {
2358                 /*
2359                  * all GE and LE bits in the dr7 register are zero,
2360                  * thus the trap couldn't have been caused by the
2361                  * hardware debug registers
2362                  */
2363                 return 0;
2364         }
2365
2366         nbp = 0;
2367         dr6 = rdr6();
2368         bp = dr6 & 0x0000000f;
2369
2370         if (!bp) {
2371                 /*
2372                  * None of the breakpoint bits are set meaning this
2373                  * trap was not caused by any of the debug registers
2374                  */
2375                 return 0;
2376         }
2377
2378         /*
2379          * at least one of the breakpoints were hit, check to see
2380          * which ones and if any of them are user space addresses
2381          */
2382
2383         if (bp & 0x01) {
2384                 addr[nbp++] = (caddr_t)rdr0();
2385         }
2386         if (bp & 0x02) {
2387                 addr[nbp++] = (caddr_t)rdr1();
2388         }
2389         if (bp & 0x04) {
2390                 addr[nbp++] = (caddr_t)rdr2();
2391         }
2392         if (bp & 0x08) {
2393                 addr[nbp++] = (caddr_t)rdr3();
2394         }
2395
2396         for (i=0; i<nbp; i++) {
2397                 if (addr[i] <
2398                     (caddr_t)VM_MAX_USER_ADDRESS) {
2399                         /*
2400                          * addr[i] is in user space
2401                          */
2402                         return nbp;
2403                 }
2404         }
2405
2406         /*
2407          * None of the breakpoints are in user space.
2408          */
2409         return 0;
2410 }
2411
2412
2413 #ifndef DDB
2414 void
2415 Debugger(const char *msg)
2416 {
2417         kprintf("Debugger(\"%s\") called.\n", msg);
2418 }
2419 #endif /* no DDB */
2420
2421 #ifdef DDB
2422
2423 /*
2424  * Provide inb() and outb() as functions.  They are normally only
2425  * available as macros calling inlined functions, thus cannot be
2426  * called inside DDB.
2427  *
2428  * The actual code is stolen from <machine/cpufunc.h>, and de-inlined.
2429  */
2430
2431 #undef inb
2432 #undef outb
2433
2434 /* silence compiler warnings */
2435 u_char inb(u_int);
2436 void outb(u_int, u_char);
2437
2438 u_char
2439 inb(u_int port)
2440 {
2441         u_char  data;
2442         /*
2443          * We use %%dx and not %1 here because i/o is done at %dx and not at
2444          * %edx, while gcc generates inferior code (movw instead of movl)
2445          * if we tell it to load (u_short) port.
2446          */
2447         __asm __volatile("inb %%dx,%0" : "=a" (data) : "d" (port));
2448         return (data);
2449 }
2450
2451 void
2452 outb(u_int port, u_char data)
2453 {
2454         u_char  al;
2455         /*
2456          * Use an unnecessary assignment to help gcc's register allocator.
2457          * This make a large difference for gcc-1.40 and a tiny difference
2458          * for gcc-2.6.0.  For gcc-1.40, al had to be ``asm("ax")'' for
2459          * best results.  gcc-2.6.0 can't handle this.
2460          */
2461         al = data;
2462         __asm __volatile("outb %0,%%dx" : : "a" (al), "d" (port));
2463 }
2464
2465 #endif /* DDB */
2466
2467
2468
2469 /*
2470  * initialize all the SMP locks
2471  */
2472
2473 /* critical region when masking or unmasking interupts */
2474 struct spinlock_deprecated imen_spinlock;
2475
2476 /* critical region for old style disable_intr/enable_intr */
2477 struct spinlock_deprecated mpintr_spinlock;
2478
2479 /* critical region around INTR() routines */
2480 struct spinlock_deprecated intr_spinlock;
2481
2482 /* lock region used by kernel profiling */
2483 struct spinlock_deprecated mcount_spinlock;
2484
2485 /* locks com (tty) data/hardware accesses: a FASTINTR() */
2486 struct spinlock_deprecated com_spinlock;
2487
2488 /* lock regions around the clock hardware */
2489 struct spinlock_deprecated clock_spinlock;
2490
2491 /* lock around the MP rendezvous */
2492 struct spinlock_deprecated smp_rv_spinlock;
2493
2494 static void
2495 init_locks(void)
2496 {
2497         /*
2498          * Get the initial mplock with a count of 1 for the BSP.
2499          * This uses a LOGICAL cpu ID, ie BSP == 0.
2500          */
2501         cpu_get_initial_mplock();
2502         /* DEPRECATED */
2503         spin_lock_init(&mcount_spinlock);
2504         spin_lock_init(&intr_spinlock);
2505         spin_lock_init(&mpintr_spinlock);
2506         spin_lock_init(&imen_spinlock);
2507         spin_lock_init(&smp_rv_spinlock);
2508         spin_lock_init(&com_spinlock);
2509         spin_lock_init(&clock_spinlock);
2510
2511         /* our token pool needs to work early */
2512         lwkt_token_pool_init();
2513 }