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