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