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