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