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