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