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