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