Add threads to the process-retrieval sysctls so they show up in top, ps, etc.
[dragonfly.git] / sys / i386 / i386 / machdep.c
1 /*-
2  * Copyright (c) 1992 Terrence R. Lambert.
3  * Copyright (c) 1982, 1987, 1990 The Regents of the University of California.
4  * All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * William Jolitz.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *      This product includes software developed by the University of
20  *      California, Berkeley and its contributors.
21  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *      from: @(#)machdep.c     7.4 (Berkeley) 6/3/91
38  * $FreeBSD: src/sys/i386/i386/machdep.c,v 1.385.2.30 2003/05/31 08:48:05 alc Exp $
39  * $DragonFly: src/sys/i386/i386/Attic/machdep.c,v 1.19 2003/06/30 23:54:00 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  * The main loop is entered with a critical section held, we must release
948  * the critical section before doing anything else.
949  *
950  * Note on cpu_idle_hlt:  On an SMP system this may cause the system to 
951  * halt until the next clock tick, even if a thread is ready YYY
952  */
953 static int      cpu_idle_hlt = 1;
954 SYSCTL_INT(_machdep, OID_AUTO, cpu_idle_hlt, CTLFLAG_RW,
955     &cpu_idle_hlt, 0, "Idle loop HLT enable");
956
957 void
958 cpu_idle(void)
959 {
960         crit_exit();
961         for (;;) {
962                 lwkt_switch();
963                 __asm __volatile("cli");
964                 if (cpu_idle_hlt && !lwkt_runnable()) {
965                         /*
966                          * We must guarentee that hlt is exactly the instruction
967                          * following the sti.
968                          */
969                         __asm __volatile("sti; hlt");
970                 } else {
971                         __asm __volatile("sti");
972                 }
973         }
974 }
975
976 /*
977  * Clear registers on exec
978  */
979 void
980 setregs(p, entry, stack, ps_strings)
981         struct proc *p;
982         u_long entry;
983         u_long stack;
984         u_long ps_strings;
985 {
986         struct trapframe *regs = p->p_md.md_regs;
987         struct pcb *pcb = p->p_thread->td_pcb;
988
989         /* Reset pc->pcb_gs and %gs before possibly invalidating it. */
990         pcb->pcb_gs = _udatasel;
991         load_gs(_udatasel);
992
993 #ifdef USER_LDT
994         /* was i386_user_cleanup() in NetBSD */
995         user_ldt_free(pcb);
996 #endif
997   
998         bzero((char *)regs, sizeof(struct trapframe));
999         regs->tf_eip = entry;
1000         regs->tf_esp = stack;
1001         regs->tf_eflags = PSL_USER | (regs->tf_eflags & PSL_T);
1002         regs->tf_ss = _udatasel;
1003         regs->tf_ds = _udatasel;
1004         regs->tf_es = _udatasel;
1005         regs->tf_fs = _udatasel;
1006         regs->tf_cs = _ucodesel;
1007
1008         /* PS_STRINGS value for BSD/OS binaries.  It is 0 for non-BSD/OS. */
1009         regs->tf_ebx = ps_strings;
1010
1011         /*
1012          * Reset the hardware debug registers if they were in use.
1013          * They won't have any meaning for the newly exec'd process.  
1014          */
1015         if (pcb->pcb_flags & PCB_DBREGS) {
1016                 pcb->pcb_dr0 = 0;
1017                 pcb->pcb_dr1 = 0;
1018                 pcb->pcb_dr2 = 0;
1019                 pcb->pcb_dr3 = 0;
1020                 pcb->pcb_dr6 = 0;
1021                 pcb->pcb_dr7 = 0;
1022                 if (pcb == curthread->td_pcb) {
1023                         /*
1024                          * Clear the debug registers on the running
1025                          * CPU, otherwise they will end up affecting
1026                          * the next process we switch to.
1027                          */
1028                         reset_dbregs();
1029                 }
1030                 pcb->pcb_flags &= ~PCB_DBREGS;
1031         }
1032
1033         /*
1034          * Initialize the math emulator (if any) for the current process.
1035          * Actually, just clear the bit that says that the emulator has
1036          * been initialized.  Initialization is delayed until the process
1037          * traps to the emulator (if it is done at all) mainly because
1038          * emulators don't provide an entry point for initialization.
1039          */
1040         p->p_thread->td_pcb->pcb_flags &= ~FP_SOFTFP;
1041
1042         /*
1043          * Arrange to trap the next npx or `fwait' instruction (see npx.c
1044          * for why fwait must be trapped at least if there is an npx or an
1045          * emulator).  This is mainly to handle the case where npx0 is not
1046          * configured, since the npx routines normally set up the trap
1047          * otherwise.  It should be done only at boot time, but doing it
1048          * here allows modifying `npx_exists' for testing the emulator on
1049          * systems with an npx.
1050          */
1051         load_cr0(rcr0() | CR0_MP | CR0_TS);
1052
1053 #if NNPX > 0
1054         /* Initialize the npx (if any) for the current process. */
1055         npxinit(__INITIAL_NPXCW__);
1056 #endif
1057
1058       /*
1059        * XXX - Linux emulator
1060        * Make sure sure edx is 0x0 on entry. Linux binaries depend
1061        * on it.
1062        */
1063       p->p_retval[1] = 0;
1064 }
1065
1066 void
1067 cpu_setregs(void)
1068 {
1069         unsigned int cr0;
1070
1071         cr0 = rcr0();
1072         cr0 |= CR0_NE;                  /* Done by npxinit() */
1073         cr0 |= CR0_MP | CR0_TS;         /* Done at every execve() too. */
1074 #ifdef I386_CPU
1075         if (cpu_class != CPUCLASS_386)
1076 #endif
1077                 cr0 |= CR0_WP | CR0_AM;
1078         load_cr0(cr0);
1079         load_gs(_udatasel);
1080 }
1081
1082 static int
1083 sysctl_machdep_adjkerntz(SYSCTL_HANDLER_ARGS)
1084 {
1085         int error;
1086         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
1087                 req);
1088         if (!error && req->newptr)
1089                 resettodr();
1090         return (error);
1091 }
1092
1093 SYSCTL_PROC(_machdep, CPU_ADJKERNTZ, adjkerntz, CTLTYPE_INT|CTLFLAG_RW,
1094         &adjkerntz, 0, sysctl_machdep_adjkerntz, "I", "");
1095
1096 SYSCTL_INT(_machdep, CPU_DISRTCSET, disable_rtc_set,
1097         CTLFLAG_RW, &disable_rtc_set, 0, "");
1098
1099 SYSCTL_STRUCT(_machdep, CPU_BOOTINFO, bootinfo, 
1100         CTLFLAG_RD, &bootinfo, bootinfo, "");
1101
1102 SYSCTL_INT(_machdep, CPU_WALLCLOCK, wall_cmos_clock,
1103         CTLFLAG_RW, &wall_cmos_clock, 0, "");
1104
1105 extern u_long bootdev;          /* not a dev_t - encoding is different */
1106 SYSCTL_ULONG(_machdep, OID_AUTO, guessed_bootdev,
1107         CTLFLAG_RD, &bootdev, 0, "Boot device (not in dev_t format)");
1108
1109 /*
1110  * Initialize 386 and configure to run kernel
1111  */
1112
1113 /*
1114  * Initialize segments & interrupt table
1115  */
1116
1117 int _default_ldt;
1118 union descriptor gdt[NGDT * MAXCPU];    /* global descriptor table */
1119 static struct gate_descriptor idt0[NIDT];
1120 struct gate_descriptor *idt = &idt0[0]; /* interrupt descriptor table */
1121 union descriptor ldt[NLDT];             /* local descriptor table */
1122
1123 /* table descriptors - used to load tables by cpu */
1124 struct region_descriptor r_gdt, r_idt;
1125
1126 int private_tss;                        /* flag indicating private tss */
1127
1128 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
1129 extern int has_f00f_bug;
1130 #endif
1131
1132 static struct i386tss dblfault_tss;
1133 static char dblfault_stack[PAGE_SIZE];
1134
1135 extern  struct user *proc0paddr;
1136
1137
1138 /* software prototypes -- in more palatable form */
1139 struct soft_segment_descriptor gdt_segs[] = {
1140 /* GNULL_SEL    0 Null Descriptor */
1141 {       0x0,                    /* segment base address  */
1142         0x0,                    /* length */
1143         0,                      /* segment type */
1144         0,                      /* segment descriptor priority level */
1145         0,                      /* segment descriptor present */
1146         0, 0,
1147         0,                      /* default 32 vs 16 bit size */
1148         0                       /* limit granularity (byte/page units)*/ },
1149 /* GCODE_SEL    1 Code Descriptor for kernel */
1150 {       0x0,                    /* segment base address  */
1151         0xfffff,                /* length - all address space */
1152         SDT_MEMERA,             /* segment type */
1153         0,                      /* segment descriptor priority level */
1154         1,                      /* segment descriptor present */
1155         0, 0,
1156         1,                      /* default 32 vs 16 bit size */
1157         1                       /* limit granularity (byte/page units)*/ },
1158 /* GDATA_SEL    2 Data Descriptor for kernel */
1159 {       0x0,                    /* segment base address  */
1160         0xfffff,                /* length - all address space */
1161         SDT_MEMRWA,             /* segment type */
1162         0,                      /* segment descriptor priority level */
1163         1,                      /* segment descriptor present */
1164         0, 0,
1165         1,                      /* default 32 vs 16 bit size */
1166         1                       /* limit granularity (byte/page units)*/ },
1167 /* GPRIV_SEL    3 SMP Per-Processor Private Data Descriptor */
1168 {       0x0,                    /* segment base address  */
1169         0xfffff,                /* length - all address space */
1170         SDT_MEMRWA,             /* segment type */
1171         0,                      /* segment descriptor priority level */
1172         1,                      /* segment descriptor present */
1173         0, 0,
1174         1,                      /* default 32 vs 16 bit size */
1175         1                       /* limit granularity (byte/page units)*/ },
1176 /* GPROC0_SEL   4 Proc 0 Tss Descriptor */
1177 {
1178         0x0,                    /* segment base address */
1179         sizeof(struct i386tss)-1,/* length - all address space */
1180         SDT_SYS386TSS,          /* segment type */
1181         0,                      /* segment descriptor priority level */
1182         1,                      /* segment descriptor present */
1183         0, 0,
1184         0,                      /* unused - default 32 vs 16 bit size */
1185         0                       /* limit granularity (byte/page units)*/ },
1186 /* GLDT_SEL     5 LDT Descriptor */
1187 {       (int) ldt,              /* segment base address  */
1188         sizeof(ldt)-1,          /* length - all address space */
1189         SDT_SYSLDT,             /* segment type */
1190         SEL_UPL,                /* segment descriptor priority level */
1191         1,                      /* segment descriptor present */
1192         0, 0,
1193         0,                      /* unused - default 32 vs 16 bit size */
1194         0                       /* limit granularity (byte/page units)*/ },
1195 /* GUSERLDT_SEL 6 User LDT Descriptor per process */
1196 {       (int) ldt,              /* segment base address  */
1197         (512 * sizeof(union descriptor)-1),             /* length */
1198         SDT_SYSLDT,             /* segment type */
1199         0,                      /* segment descriptor priority level */
1200         1,                      /* segment descriptor present */
1201         0, 0,
1202         0,                      /* unused - default 32 vs 16 bit size */
1203         0                       /* limit granularity (byte/page units)*/ },
1204 /* GTGATE_SEL   7 Null Descriptor - Placeholder */
1205 {       0x0,                    /* segment base address  */
1206         0x0,                    /* length - all address space */
1207         0,                      /* segment type */
1208         0,                      /* segment descriptor priority level */
1209         0,                      /* segment descriptor present */
1210         0, 0,
1211         0,                      /* default 32 vs 16 bit size */
1212         0                       /* limit granularity (byte/page units)*/ },
1213 /* GBIOSLOWMEM_SEL 8 BIOS access to realmode segment 0x40, must be #8 in GDT */
1214 {       0x400,                  /* segment base address */
1215         0xfffff,                /* length */
1216         SDT_MEMRWA,             /* segment type */
1217         0,                      /* segment descriptor priority level */
1218         1,                      /* segment descriptor present */
1219         0, 0,
1220         1,                      /* default 32 vs 16 bit size */
1221         1                       /* limit granularity (byte/page units)*/ },
1222 /* GPANIC_SEL   9 Panic Tss Descriptor */
1223 {       (int) &dblfault_tss,    /* segment base address  */
1224         sizeof(struct i386tss)-1,/* length - all address space */
1225         SDT_SYS386TSS,          /* segment type */
1226         0,                      /* segment descriptor priority level */
1227         1,                      /* segment descriptor present */
1228         0, 0,
1229         0,                      /* unused - default 32 vs 16 bit size */
1230         0                       /* limit granularity (byte/page units)*/ },
1231 /* GBIOSCODE32_SEL 10 BIOS 32-bit interface (32bit Code) */
1232 {       0,                      /* segment base address (overwritten)  */
1233         0xfffff,                /* length */
1234         SDT_MEMERA,             /* segment type */
1235         0,                      /* segment descriptor priority level */
1236         1,                      /* segment descriptor present */
1237         0, 0,
1238         0,                      /* default 32 vs 16 bit size */
1239         1                       /* limit granularity (byte/page units)*/ },
1240 /* GBIOSCODE16_SEL 11 BIOS 32-bit interface (16bit Code) */
1241 {       0,                      /* segment base address (overwritten)  */
1242         0xfffff,                /* length */
1243         SDT_MEMERA,             /* segment type */
1244         0,                      /* segment descriptor priority level */
1245         1,                      /* segment descriptor present */
1246         0, 0,
1247         0,                      /* default 32 vs 16 bit size */
1248         1                       /* limit granularity (byte/page units)*/ },
1249 /* GBIOSDATA_SEL 12 BIOS 32-bit interface (Data) */
1250 {       0,                      /* segment base address (overwritten) */
1251         0xfffff,                /* length */
1252         SDT_MEMRWA,             /* segment type */
1253         0,                      /* segment descriptor priority level */
1254         1,                      /* segment descriptor present */
1255         0, 0,
1256         1,                      /* default 32 vs 16 bit size */
1257         1                       /* limit granularity (byte/page units)*/ },
1258 /* GBIOSUTIL_SEL 13 BIOS 16-bit interface (Utility) */
1259 {       0,                      /* segment base address (overwritten) */
1260         0xfffff,                /* length */
1261         SDT_MEMRWA,             /* segment type */
1262         0,                      /* segment descriptor priority level */
1263         1,                      /* segment descriptor present */
1264         0, 0,
1265         0,                      /* default 32 vs 16 bit size */
1266         1                       /* limit granularity (byte/page units)*/ },
1267 /* GBIOSARGS_SEL 14 BIOS 16-bit interface (Arguments) */
1268 {       0,                      /* segment base address (overwritten) */
1269         0xfffff,                /* length */
1270         SDT_MEMRWA,             /* segment type */
1271         0,                      /* segment descriptor priority level */
1272         1,                      /* segment descriptor present */
1273         0, 0,
1274         0,                      /* default 32 vs 16 bit size */
1275         1                       /* limit granularity (byte/page units)*/ },
1276 };
1277
1278 static struct soft_segment_descriptor ldt_segs[] = {
1279         /* Null Descriptor - overwritten by call gate */
1280 {       0x0,                    /* segment base address  */
1281         0x0,                    /* length - all address space */
1282         0,                      /* segment type */
1283         0,                      /* segment descriptor priority level */
1284         0,                      /* segment descriptor present */
1285         0, 0,
1286         0,                      /* default 32 vs 16 bit size */
1287         0                       /* limit granularity (byte/page units)*/ },
1288         /* Null Descriptor - overwritten by call gate */
1289 {       0x0,                    /* segment base address  */
1290         0x0,                    /* length - all address space */
1291         0,                      /* segment type */
1292         0,                      /* segment descriptor priority level */
1293         0,                      /* segment descriptor present */
1294         0, 0,
1295         0,                      /* default 32 vs 16 bit size */
1296         0                       /* limit granularity (byte/page units)*/ },
1297         /* Null Descriptor - overwritten by call gate */
1298 {       0x0,                    /* segment base address  */
1299         0x0,                    /* length - all address space */
1300         0,                      /* segment type */
1301         0,                      /* segment descriptor priority level */
1302         0,                      /* segment descriptor present */
1303         0, 0,
1304         0,                      /* default 32 vs 16 bit size */
1305         0                       /* limit granularity (byte/page units)*/ },
1306         /* Code Descriptor for user */
1307 {       0x0,                    /* segment base address  */
1308         0xfffff,                /* length - all address space */
1309         SDT_MEMERA,             /* segment type */
1310         SEL_UPL,                /* segment descriptor priority level */
1311         1,                      /* segment descriptor present */
1312         0, 0,
1313         1,                      /* default 32 vs 16 bit size */
1314         1                       /* limit granularity (byte/page units)*/ },
1315         /* Null Descriptor - overwritten by call gate */
1316 {       0x0,                    /* segment base address  */
1317         0x0,                    /* length - all address space */
1318         0,                      /* segment type */
1319         0,                      /* segment descriptor priority level */
1320         0,                      /* segment descriptor present */
1321         0, 0,
1322         0,                      /* default 32 vs 16 bit size */
1323         0                       /* limit granularity (byte/page units)*/ },
1324         /* Data Descriptor for user */
1325 {       0x0,                    /* segment base address  */
1326         0xfffff,                /* length - all address space */
1327         SDT_MEMRWA,             /* segment type */
1328         SEL_UPL,                /* segment descriptor priority level */
1329         1,                      /* segment descriptor present */
1330         0, 0,
1331         1,                      /* default 32 vs 16 bit size */
1332         1                       /* limit granularity (byte/page units)*/ },
1333 };
1334
1335 void
1336 setidt(idx, func, typ, dpl, selec)
1337         int idx;
1338         inthand_t *func;
1339         int typ;
1340         int dpl;
1341         int selec;
1342 {
1343         struct gate_descriptor *ip;
1344
1345         ip = idt + idx;
1346         ip->gd_looffset = (int)func;
1347         ip->gd_selector = selec;
1348         ip->gd_stkcpy = 0;
1349         ip->gd_xx = 0;
1350         ip->gd_type = typ;
1351         ip->gd_dpl = dpl;
1352         ip->gd_p = 1;
1353         ip->gd_hioffset = ((int)func)>>16 ;
1354 }
1355
1356 #define IDTVEC(name)    __CONCAT(X,name)
1357
1358 extern inthand_t
1359         IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
1360         IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
1361         IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
1362         IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
1363         IDTVEC(xmm), IDTVEC(syscall), IDTVEC(int0x80_syscall);
1364
1365 void
1366 sdtossd(sd, ssd)
1367         struct segment_descriptor *sd;
1368         struct soft_segment_descriptor *ssd;
1369 {
1370         ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
1371         ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
1372         ssd->ssd_type  = sd->sd_type;
1373         ssd->ssd_dpl   = sd->sd_dpl;
1374         ssd->ssd_p     = sd->sd_p;
1375         ssd->ssd_def32 = sd->sd_def32;
1376         ssd->ssd_gran  = sd->sd_gran;
1377 }
1378
1379 #define PHYSMAP_SIZE    (2 * 8)
1380
1381 /*
1382  * Populate the (physmap) array with base/bound pairs describing the
1383  * available physical memory in the system, then test this memory and
1384  * build the phys_avail array describing the actually-available memory.
1385  *
1386  * If we cannot accurately determine the physical memory map, then use
1387  * value from the 0xE801 call, and failing that, the RTC.
1388  *
1389  * Total memory size may be set by the kernel environment variable
1390  * hw.physmem or the compile-time define MAXMEM.
1391  */
1392 static void
1393 getmemsize(int first)
1394 {
1395         int i, physmap_idx, pa_indx;
1396         int hasbrokenint12;
1397         u_int basemem, extmem;
1398         struct vm86frame vmf;
1399         struct vm86context vmc;
1400         vm_offset_t pa, physmap[PHYSMAP_SIZE];
1401         pt_entry_t pte;
1402         const char *cp;
1403         struct {
1404                 u_int64_t base;
1405                 u_int64_t length;
1406                 u_int32_t type;
1407         } *smap;
1408
1409         hasbrokenint12 = 0;
1410         TUNABLE_INT_FETCH("hw.hasbrokenint12", &hasbrokenint12);
1411         bzero(&vmf, sizeof(struct vm86frame));
1412         bzero(physmap, sizeof(physmap));
1413         basemem = 0;
1414
1415         /*
1416          * Some newer BIOSes has broken INT 12H implementation which cause
1417          * kernel panic immediately. In this case, we need to scan SMAP
1418          * with INT 15:E820 first, then determine base memory size.
1419          */
1420         if (hasbrokenint12) {
1421                 goto int15e820;
1422         }
1423
1424         /*
1425          * Perform "base memory" related probes & setup
1426          */
1427         vm86_intcall(0x12, &vmf);
1428         basemem = vmf.vmf_ax;
1429         if (basemem > 640) {
1430                 printf("Preposterous BIOS basemem of %uK, truncating to 640K\n",
1431                         basemem);
1432                 basemem = 640;
1433         }
1434
1435         /*
1436          * XXX if biosbasemem is now < 640, there is a `hole'
1437          * between the end of base memory and the start of
1438          * ISA memory.  The hole may be empty or it may
1439          * contain BIOS code or data.  Map it read/write so
1440          * that the BIOS can write to it.  (Memory from 0 to
1441          * the physical end of the kernel is mapped read-only
1442          * to begin with and then parts of it are remapped.
1443          * The parts that aren't remapped form holes that
1444          * remain read-only and are unused by the kernel.
1445          * The base memory area is below the physical end of
1446          * the kernel and right now forms a read-only hole.
1447          * The part of it from PAGE_SIZE to
1448          * (trunc_page(biosbasemem * 1024) - 1) will be
1449          * remapped and used by the kernel later.)
1450          *
1451          * This code is similar to the code used in
1452          * pmap_mapdev, but since no memory needs to be
1453          * allocated we simply change the mapping.
1454          */
1455         for (pa = trunc_page(basemem * 1024);
1456              pa < ISA_HOLE_START; pa += PAGE_SIZE) {
1457                 pte = (pt_entry_t)vtopte(pa + KERNBASE);
1458                 *pte = pa | PG_RW | PG_V;
1459         }
1460
1461         /*
1462          * if basemem != 640, map pages r/w into vm86 page table so 
1463          * that the bios can scribble on it.
1464          */
1465         pte = (pt_entry_t)vm86paddr;
1466         for (i = basemem / 4; i < 160; i++)
1467                 pte[i] = (i << PAGE_SHIFT) | PG_V | PG_RW | PG_U;
1468
1469 int15e820:
1470         /*
1471          * map page 1 R/W into the kernel page table so we can use it
1472          * as a buffer.  The kernel will unmap this page later.
1473          */
1474         pte = (pt_entry_t)vtopte(KERNBASE + (1 << PAGE_SHIFT));
1475         *pte = (1 << PAGE_SHIFT) | PG_RW | PG_V;
1476
1477         /*
1478          * get memory map with INT 15:E820
1479          */
1480 #define SMAPSIZ         sizeof(*smap)
1481 #define SMAP_SIG        0x534D4150                      /* 'SMAP' */
1482
1483         vmc.npages = 0;
1484         smap = (void *)vm86_addpage(&vmc, 1, KERNBASE + (1 << PAGE_SHIFT));
1485         vm86_getptr(&vmc, (vm_offset_t)smap, &vmf.vmf_es, &vmf.vmf_di);
1486
1487         physmap_idx = 0;
1488         vmf.vmf_ebx = 0;
1489         do {
1490                 vmf.vmf_eax = 0xE820;
1491                 vmf.vmf_edx = SMAP_SIG;
1492                 vmf.vmf_ecx = SMAPSIZ;
1493                 i = vm86_datacall(0x15, &vmf, &vmc);
1494                 if (i || vmf.vmf_eax != SMAP_SIG)
1495                         break;
1496                 if (boothowto & RB_VERBOSE)
1497                         printf("SMAP type=%02x base=%08x %08x len=%08x %08x\n",
1498                                 smap->type,
1499                                 *(u_int32_t *)((char *)&smap->base + 4),
1500                                 (u_int32_t)smap->base,
1501                                 *(u_int32_t *)((char *)&smap->length + 4),
1502                                 (u_int32_t)smap->length);
1503
1504                 if (smap->type != 0x01)
1505                         goto next_run;
1506
1507                 if (smap->length == 0)
1508                         goto next_run;
1509
1510                 if (smap->base >= 0xffffffff) {
1511                         printf("%uK of memory above 4GB ignored\n",
1512                             (u_int)(smap->length / 1024));
1513                         goto next_run;
1514                 }
1515
1516                 for (i = 0; i <= physmap_idx; i += 2) {
1517                         if (smap->base < physmap[i + 1]) {
1518                                 if (boothowto & RB_VERBOSE)
1519                                         printf(
1520         "Overlapping or non-montonic memory region, ignoring second region\n");
1521                                 goto next_run;
1522                         }
1523                 }
1524
1525                 if (smap->base == physmap[physmap_idx + 1]) {
1526                         physmap[physmap_idx + 1] += smap->length;
1527                         goto next_run;
1528                 }
1529
1530                 physmap_idx += 2;
1531                 if (physmap_idx == PHYSMAP_SIZE) {
1532                         printf(
1533                 "Too many segments in the physical address map, giving up\n");
1534                         break;
1535                 }
1536                 physmap[physmap_idx] = smap->base;
1537                 physmap[physmap_idx + 1] = smap->base + smap->length;
1538 next_run:
1539         } while (vmf.vmf_ebx != 0);
1540
1541         /*
1542          * Perform "base memory" related probes & setup based on SMAP
1543          */
1544         if (basemem == 0) {
1545                 for (i = 0; i <= physmap_idx; i += 2) {
1546                         if (physmap[i] == 0x00000000) {
1547                                 basemem = physmap[i + 1] / 1024;
1548                                 break;
1549                         }
1550                 }
1551
1552                 if (basemem == 0) {
1553                         basemem = 640;
1554                 }
1555
1556                 if (basemem > 640) {
1557                         printf("Preposterous BIOS basemem of %uK, truncating to 640K\n",
1558                                 basemem);
1559                         basemem = 640;
1560                 }
1561
1562                 for (pa = trunc_page(basemem * 1024);
1563                      pa < ISA_HOLE_START; pa += PAGE_SIZE) {
1564                         pte = (pt_entry_t)vtopte(pa + KERNBASE);
1565                         *pte = pa | PG_RW | PG_V;
1566                 }
1567
1568                 pte = (pt_entry_t)vm86paddr;
1569                 for (i = basemem / 4; i < 160; i++)
1570                         pte[i] = (i << PAGE_SHIFT) | PG_V | PG_RW | PG_U;
1571         }
1572
1573         if (physmap[1] != 0)
1574                 goto physmap_done;
1575
1576         /*
1577          * If we failed above, try memory map with INT 15:E801
1578          */
1579         vmf.vmf_ax = 0xE801;
1580         if (vm86_intcall(0x15, &vmf) == 0) {
1581                 extmem = vmf.vmf_cx + vmf.vmf_dx * 64;
1582         } else {
1583 #if 0
1584                 vmf.vmf_ah = 0x88;
1585                 vm86_intcall(0x15, &vmf);
1586                 extmem = vmf.vmf_ax;
1587 #else
1588                 /*
1589                  * Prefer the RTC value for extended memory.
1590                  */
1591                 extmem = rtcin(RTC_EXTLO) + (rtcin(RTC_EXTHI) << 8);
1592 #endif
1593         }
1594
1595         /*
1596          * Special hack for chipsets that still remap the 384k hole when
1597          * there's 16MB of memory - this really confuses people that
1598          * are trying to use bus mastering ISA controllers with the
1599          * "16MB limit"; they only have 16MB, but the remapping puts
1600          * them beyond the limit.
1601          *
1602          * If extended memory is between 15-16MB (16-17MB phys address range),
1603          *      chop it to 15MB.
1604          */
1605         if ((extmem > 15 * 1024) && (extmem < 16 * 1024))
1606                 extmem = 15 * 1024;
1607
1608         physmap[0] = 0;
1609         physmap[1] = basemem * 1024;
1610         physmap_idx = 2;
1611         physmap[physmap_idx] = 0x100000;
1612         physmap[physmap_idx + 1] = physmap[physmap_idx] + extmem * 1024;
1613
1614 physmap_done:
1615         /*
1616          * Now, physmap contains a map of physical memory.
1617          */
1618
1619 #ifdef SMP
1620         /* make hole for AP bootstrap code YYY */
1621         physmap[1] = mp_bootaddress(physmap[1] / 1024);
1622
1623         /* look for the MP hardware - needed for apic addresses */
1624         mp_probe();
1625 #endif
1626
1627         /*
1628          * Maxmem isn't the "maximum memory", it's one larger than the
1629          * highest page of the physical address space.  It should be
1630          * called something like "Maxphyspage".  We may adjust this 
1631          * based on ``hw.physmem'' and the results of the memory test.
1632          */
1633         Maxmem = atop(physmap[physmap_idx + 1]);
1634
1635 #ifdef MAXMEM
1636         Maxmem = MAXMEM / 4;
1637 #endif
1638
1639         /*
1640          * hw.maxmem is a size in bytes; we also allow k, m, and g suffixes
1641          * for the appropriate modifiers.  This overrides MAXMEM.
1642          */
1643         if ((cp = getenv("hw.physmem")) != NULL) {
1644                 u_int64_t AllowMem, sanity;
1645                 char *ep;
1646
1647                 sanity = AllowMem = strtouq(cp, &ep, 0);
1648                 if ((ep != cp) && (*ep != 0)) {
1649                         switch(*ep) {
1650                         case 'g':
1651                         case 'G':
1652                                 AllowMem <<= 10;
1653                         case 'm':
1654                         case 'M':
1655                                 AllowMem <<= 10;
1656                         case 'k':
1657                         case 'K':
1658                                 AllowMem <<= 10;
1659                                 break;
1660                         default:
1661                                 AllowMem = sanity = 0;
1662                         }
1663                         if (AllowMem < sanity)
1664                                 AllowMem = 0;
1665                 }
1666                 if (AllowMem == 0)
1667                         printf("Ignoring invalid memory size of '%s'\n", cp);
1668                 else
1669                         Maxmem = atop(AllowMem);
1670         }
1671
1672         if (atop(physmap[physmap_idx + 1]) != Maxmem &&
1673             (boothowto & RB_VERBOSE))
1674                 printf("Physical memory use set to %uK\n", Maxmem * 4);
1675
1676         /*
1677          * If Maxmem has been increased beyond what the system has detected,
1678          * extend the last memory segment to the new limit.
1679          */ 
1680         if (atop(physmap[physmap_idx + 1]) < Maxmem)
1681                 physmap[physmap_idx + 1] = ptoa(Maxmem);
1682
1683         /* call pmap initialization to make new kernel address space */
1684         pmap_bootstrap(first, 0);
1685
1686         /*
1687          * Size up each available chunk of physical memory.
1688          */
1689         physmap[0] = PAGE_SIZE;         /* mask off page 0 */
1690         pa_indx = 0;
1691         phys_avail[pa_indx++] = physmap[0];
1692         phys_avail[pa_indx] = physmap[0];
1693 #if 0
1694         pte = (pt_entry_t)vtopte(KERNBASE);
1695 #else
1696         pte = (pt_entry_t)CMAP1;
1697 #endif
1698
1699         /*
1700          * physmap is in bytes, so when converting to page boundaries,
1701          * round up the start address and round down the end address.
1702          */
1703         for (i = 0; i <= physmap_idx; i += 2) {
1704                 vm_offset_t end;
1705
1706                 end = ptoa(Maxmem);
1707                 if (physmap[i + 1] < end)
1708                         end = trunc_page(physmap[i + 1]);
1709                 for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
1710                         int tmp, page_bad;
1711 #if 0
1712                         int *ptr = 0;
1713 #else
1714                         int *ptr = (int *)CADDR1;
1715 #endif
1716
1717                         /*
1718                          * block out kernel memory as not available.
1719                          */
1720                         if (pa >= 0x100000 && pa < first)
1721                                 continue;
1722         
1723                         page_bad = FALSE;
1724
1725                         /*
1726                          * map page into kernel: valid, read/write,non-cacheable
1727                          */
1728                         *pte = pa | PG_V | PG_RW | PG_N;
1729                         invltlb();
1730
1731                         tmp = *(int *)ptr;
1732                         /*
1733                          * Test for alternating 1's and 0's
1734                          */
1735                         *(volatile int *)ptr = 0xaaaaaaaa;
1736                         if (*(volatile int *)ptr != 0xaaaaaaaa) {
1737                                 page_bad = TRUE;
1738                         }
1739                         /*
1740                          * Test for alternating 0's and 1's
1741                          */
1742                         *(volatile int *)ptr = 0x55555555;
1743                         if (*(volatile int *)ptr != 0x55555555) {
1744                         page_bad = TRUE;
1745                         }
1746                         /*
1747                          * Test for all 1's
1748                          */
1749                         *(volatile int *)ptr = 0xffffffff;
1750                         if (*(volatile int *)ptr != 0xffffffff) {
1751                                 page_bad = TRUE;
1752                         }
1753                         /*
1754                          * Test for all 0's
1755                          */
1756                         *(volatile int *)ptr = 0x0;
1757                         if (*(volatile int *)ptr != 0x0) {
1758                                 page_bad = TRUE;
1759                         }
1760                         /*
1761                          * Restore original value.
1762                          */
1763                         *(int *)ptr = tmp;
1764
1765                         /*
1766                          * Adjust array of valid/good pages.
1767                          */
1768                         if (page_bad == TRUE) {
1769                                 continue;
1770                         }
1771                         /*
1772                          * If this good page is a continuation of the
1773                          * previous set of good pages, then just increase
1774                          * the end pointer. Otherwise start a new chunk.
1775                          * Note that "end" points one higher than end,
1776                          * making the range >= start and < end.
1777                          * If we're also doing a speculative memory
1778                          * test and we at or past the end, bump up Maxmem
1779                          * so that we keep going. The first bad page
1780                          * will terminate the loop.
1781                          */
1782                         if (phys_avail[pa_indx] == pa) {
1783                                 phys_avail[pa_indx] += PAGE_SIZE;
1784                         } else {
1785                                 pa_indx++;
1786                                 if (pa_indx == PHYS_AVAIL_ARRAY_END) {
1787                                         printf("Too many holes in the physical address space, giving up\n");
1788                                         pa_indx--;
1789                                         break;
1790                                 }
1791                                 phys_avail[pa_indx++] = pa;     /* start */
1792                                 phys_avail[pa_indx] = pa + PAGE_SIZE;   /* end */
1793                         }
1794                         physmem++;
1795                 }
1796         }
1797         *pte = 0;
1798         invltlb();
1799
1800         /*
1801          * XXX
1802          * The last chunk must contain at least one page plus the message
1803          * buffer to avoid complicating other code (message buffer address
1804          * calculation, etc.).
1805          */
1806         while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1807             round_page(MSGBUF_SIZE) >= phys_avail[pa_indx]) {
1808                 physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1809                 phys_avail[pa_indx--] = 0;
1810                 phys_avail[pa_indx--] = 0;
1811         }
1812
1813         Maxmem = atop(phys_avail[pa_indx]);
1814
1815         /* Trim off space for the message buffer. */
1816         phys_avail[pa_indx] -= round_page(MSGBUF_SIZE);
1817
1818         avail_end = phys_avail[pa_indx];
1819 }
1820
1821 void
1822 init386(int first)
1823 {
1824         struct gate_descriptor *gdp;
1825         int gsel_tss, metadata_missing, off, x;
1826         struct mdglobaldata *gd;
1827
1828         /*
1829          * Prevent lowering of the ipl if we call tsleep() early.
1830          */
1831         gd = &CPU_prvspace[0].mdglobaldata;
1832
1833         gd->mi.gd_curthread = &thread0;
1834
1835         atdevbase = ISA_HOLE_START + KERNBASE;
1836
1837         metadata_missing = 0;
1838         if (bootinfo.bi_modulep) {
1839                 preload_metadata = (caddr_t)bootinfo.bi_modulep + KERNBASE;
1840                 preload_bootstrap_relocate(KERNBASE);
1841         } else {
1842                 metadata_missing = 1;
1843         }
1844         if (bootinfo.bi_envp)
1845                 kern_envp = (caddr_t)bootinfo.bi_envp + KERNBASE;
1846
1847         /* Init basic tunables, hz etc */
1848         init_param1();
1849
1850         /*
1851          * make gdt memory segments, the code segment goes up to end of the
1852          * page with etext in it, the data segment goes to the end of
1853          * the address space
1854          */
1855         /*
1856          * XXX text protection is temporarily (?) disabled.  The limit was
1857          * i386_btop(round_page(etext)) - 1.
1858          */
1859         gdt_segs[GCODE_SEL].ssd_limit = atop(0 - 1);
1860         gdt_segs[GDATA_SEL].ssd_limit = atop(0 - 1);
1861
1862         gdt_segs[GPRIV_SEL].ssd_limit =
1863                 atop(sizeof(struct privatespace) - 1);
1864         gdt_segs[GPRIV_SEL].ssd_base = (int) &CPU_prvspace[0];
1865         gdt_segs[GPROC0_SEL].ssd_base =
1866                 (int) &CPU_prvspace[0].mdglobaldata.gd_common_tss;
1867
1868         gd->mi.gd_prvspace = &CPU_prvspace[0];
1869
1870         /*
1871          * Note: on both UP and SMP curthread must be set non-NULL
1872          * early in the boot sequence because the system assumes
1873          * that 'curthread' is never NULL.
1874          */
1875
1876         for (x = 0; x < NGDT; x++) {
1877 #ifdef BDE_DEBUGGER
1878                 /* avoid overwriting db entries with APM ones */
1879                 if (x >= GAPMCODE32_SEL && x <= GAPMDATA_SEL)
1880                         continue;
1881 #endif
1882                 ssdtosd(&gdt_segs[x], &gdt[x].sd);
1883         }
1884
1885         r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
1886         r_gdt.rd_base =  (int) gdt;
1887         lgdt(&r_gdt);
1888
1889         mi_gdinit(&gd->mi, 0);
1890         cpu_gdinit(gd, 0);
1891         lwkt_init_thread(&thread0, proc0paddr, 0, &gd->mi);
1892         lwkt_set_comm(&thread0, "thread0");
1893         proc0.p_addr = (void *)thread0.td_kstack;
1894         proc0.p_thread = &thread0;
1895         proc0.p_flag |= P_CURPROC;
1896         gd->mi.gd_uprocscheduled = 1;
1897         thread0.td_proc = &proc0;
1898         thread0.td_switch = cpu_heavy_switch;   /* YYY eventually LWKT */
1899         safepri = thread0.td_cpl = SWI_MASK | HWI_MASK;
1900
1901         /* make ldt memory segments */
1902         /*
1903          * XXX - VM_MAXUSER_ADDRESS is an end address, not a max.  And it
1904          * should be spelled ...MAX_USER...
1905          */
1906         ldt_segs[LUCODE_SEL].ssd_limit = atop(VM_MAXUSER_ADDRESS - 1);
1907         ldt_segs[LUDATA_SEL].ssd_limit = atop(VM_MAXUSER_ADDRESS - 1);
1908         for (x = 0; x < sizeof ldt_segs / sizeof ldt_segs[0]; x++)
1909                 ssdtosd(&ldt_segs[x], &ldt[x].sd);
1910
1911         _default_ldt = GSEL(GLDT_SEL, SEL_KPL);
1912         lldt(_default_ldt);
1913 #ifdef USER_LDT
1914         gd->gd_currentldt = _default_ldt;
1915 #endif
1916
1917         /* exceptions */
1918         for (x = 0; x < NIDT; x++)
1919                 setidt(x, &IDTVEC(rsvd), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1920         setidt(0, &IDTVEC(div),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1921         setidt(1, &IDTVEC(dbg),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1922         setidt(2, &IDTVEC(nmi),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1923         setidt(3, &IDTVEC(bpt),  SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1924         setidt(4, &IDTVEC(ofl),  SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1925         setidt(5, &IDTVEC(bnd),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1926         setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1927         setidt(7, &IDTVEC(dna),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1928         setidt(8, 0,  SDT_SYSTASKGT, SEL_KPL, GSEL(GPANIC_SEL, SEL_KPL));
1929         setidt(9, &IDTVEC(fpusegm),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1930         setidt(10, &IDTVEC(tss),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1931         setidt(11, &IDTVEC(missing),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1932         setidt(12, &IDTVEC(stk),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1933         setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1934         setidt(14, &IDTVEC(page),  SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1935         setidt(15, &IDTVEC(rsvd),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1936         setidt(16, &IDTVEC(fpu),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1937         setidt(17, &IDTVEC(align), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1938         setidt(18, &IDTVEC(mchk),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1939         setidt(19, &IDTVEC(xmm), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1940         setidt(0x80, &IDTVEC(int0x80_syscall),
1941                         SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1942
1943         r_idt.rd_limit = sizeof(idt0) - 1;
1944         r_idt.rd_base = (int) idt;
1945         lidt(&r_idt);
1946
1947         /*
1948          * Initialize the console before we print anything out.
1949          */
1950         cninit();
1951
1952         if (metadata_missing)
1953                 printf("WARNING: loader(8) metadata is missing!\n");
1954
1955 #include        "isa.h"
1956 #if     NISA >0
1957         isa_defaultirq();
1958 #endif
1959         rand_initialize();
1960
1961 #ifdef DDB
1962         kdb_init();
1963         if (boothowto & RB_KDB)
1964                 Debugger("Boot flags requested debugger");
1965 #endif
1966
1967         finishidentcpu();       /* Final stage of CPU initialization */
1968         setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1969         setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1970         initializecpu();        /* Initialize CPU registers */
1971
1972         /*
1973          * make an initial tss so cpu can get interrupt stack on syscall!
1974          * The 16 bytes is to save room for a VM86 context.
1975          */
1976         gd->gd_common_tss.tss_esp0 = (int) thread0.td_pcb - 16;
1977         gd->gd_common_tss.tss_ss0 = GSEL(GDATA_SEL, SEL_KPL) ;
1978         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1979         private_tss = 0;
1980         gd->gd_tss_gdt = &gdt[GPROC0_SEL].sd;
1981         gd->gd_common_tssd = *gd->gd_tss_gdt;
1982         gd->gd_common_tss.tss_ioopt = (sizeof gd->gd_common_tss) << 16;
1983         ltr(gsel_tss);
1984
1985         dblfault_tss.tss_esp = dblfault_tss.tss_esp0 = dblfault_tss.tss_esp1 =
1986             dblfault_tss.tss_esp2 = (int) &dblfault_stack[sizeof(dblfault_stack)];
1987         dblfault_tss.tss_ss = dblfault_tss.tss_ss0 = dblfault_tss.tss_ss1 =
1988             dblfault_tss.tss_ss2 = GSEL(GDATA_SEL, SEL_KPL);
1989         dblfault_tss.tss_cr3 = (int)IdlePTD;
1990         dblfault_tss.tss_eip = (int) dblfault_handler;
1991         dblfault_tss.tss_eflags = PSL_KERNEL;
1992         dblfault_tss.tss_ds = dblfault_tss.tss_es =
1993             dblfault_tss.tss_gs = GSEL(GDATA_SEL, SEL_KPL);
1994         dblfault_tss.tss_fs = GSEL(GPRIV_SEL, SEL_KPL);
1995         dblfault_tss.tss_cs = GSEL(GCODE_SEL, SEL_KPL);
1996         dblfault_tss.tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
1997
1998         vm86_initialize();
1999         getmemsize(first);
2000         init_param2(physmem);
2001
2002         /* now running on new page tables, configured,and u/iom is accessible */
2003
2004         /* Map the message buffer. */
2005         for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
2006                 pmap_kenter((vm_offset_t)msgbufp + off, avail_end + off);
2007
2008         msgbufinit(msgbufp, MSGBUF_SIZE);
2009
2010         /* make a call gate to reenter kernel with */
2011         gdp = &ldt[LSYS5CALLS_SEL].gd;
2012
2013         x = (int) &IDTVEC(syscall);
2014         gdp->gd_looffset = x++;
2015         gdp->gd_selector = GSEL(GCODE_SEL,SEL_KPL);
2016         gdp->gd_stkcpy = 1;
2017         gdp->gd_type = SDT_SYS386CGT;
2018         gdp->gd_dpl = SEL_UPL;
2019         gdp->gd_p = 1;
2020         gdp->gd_hioffset = ((int) &IDTVEC(syscall)) >>16;
2021
2022         /* XXX does this work? */
2023         ldt[LBSDICALLS_SEL] = ldt[LSYS5CALLS_SEL];
2024         ldt[LSOL26CALLS_SEL] = ldt[LSYS5CALLS_SEL];
2025
2026         /* transfer to user mode */
2027
2028         _ucodesel = LSEL(LUCODE_SEL, SEL_UPL);
2029         _udatasel = LSEL(LUDATA_SEL, SEL_UPL);
2030
2031         /* setup proc 0's pcb */
2032         thread0.td_pcb->pcb_flags = 0;
2033         thread0.td_pcb->pcb_cr3 = (int)IdlePTD; /* should already be setup */
2034 #ifdef SMP
2035 #if 0
2036         thread0.td_pcb->pcb_mpnest = 1;
2037 #endif
2038 #endif
2039         thread0.td_pcb->pcb_ext = 0;
2040         proc0.p_md.md_regs = &proc0_tf;
2041 }
2042
2043 /*
2044  * Initialize machine-dependant portions of the global data structure.
2045  * Note that the global data area and cpu0's idlestack in the private
2046  * data space were allocated in locore.
2047  *
2048  * Note: the idlethread's cpl is 0
2049  *
2050  * WARNING!  Called from early boot, 'mycpu' may not work yet.
2051  */
2052 void
2053 cpu_gdinit(struct mdglobaldata *gd, int cpu)
2054 {
2055         char *sp;
2056
2057         if (cpu)
2058                 gd->mi.gd_curthread = &gd->gd_idlethread;
2059
2060         gd->mi.gd_idletd = &gd->gd_idlethread;
2061         sp = gd->mi.gd_prvspace->idlestack;
2062         lwkt_init_thread(&gd->gd_idlethread, sp, 0, &gd->mi);
2063         lwkt_set_comm(&gd->gd_idlethread, "idle_%d", cpu);
2064         gd->gd_idlethread.td_switch = cpu_lwkt_switch;
2065         gd->gd_idlethread.td_sp -= sizeof(void *);
2066         *(void **)gd->gd_idlethread.td_sp = cpu_idle_restore;
2067 }
2068
2069 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
2070 static void f00f_hack(void *unused);
2071 SYSINIT(f00f_hack, SI_SUB_INTRINSIC, SI_ORDER_FIRST, f00f_hack, NULL);
2072
2073 static void
2074 f00f_hack(void *unused) 
2075 {
2076         struct gate_descriptor *new_idt;
2077         vm_offset_t tmp;
2078
2079         if (!has_f00f_bug)
2080                 return;
2081
2082         printf("Intel Pentium detected, installing workaround for F00F bug\n");
2083
2084         r_idt.rd_limit = sizeof(idt0) - 1;
2085
2086         tmp = kmem_alloc(kernel_map, PAGE_SIZE * 2);
2087         if (tmp == 0)
2088                 panic("kmem_alloc returned 0");
2089         if (((unsigned int)tmp & (PAGE_SIZE-1)) != 0)
2090                 panic("kmem_alloc returned non-page-aligned memory");
2091         /* Put the first seven entries in the lower page */
2092         new_idt = (struct gate_descriptor*)(tmp + PAGE_SIZE - (7*8));
2093         bcopy(idt, new_idt, sizeof(idt0));
2094         r_idt.rd_base = (int)new_idt;
2095         lidt(&r_idt);
2096         idt = new_idt;
2097         if (vm_map_protect(kernel_map, tmp, tmp + PAGE_SIZE,
2098                            VM_PROT_READ, FALSE) != KERN_SUCCESS)
2099                 panic("vm_map_protect failed");
2100         return;
2101 }
2102 #endif /* defined(I586_CPU) && !NO_F00F_HACK */
2103
2104 int
2105 ptrace_set_pc(p, addr)
2106         struct proc *p;
2107         unsigned long addr;
2108 {
2109         p->p_md.md_regs->tf_eip = addr;
2110         return (0);
2111 }
2112
2113 int
2114 ptrace_single_step(p)
2115         struct proc *p;
2116 {
2117         p->p_md.md_regs->tf_eflags |= PSL_T;
2118         return (0);
2119 }
2120
2121 int ptrace_read_u_check(p, addr, len)
2122         struct proc *p;
2123         vm_offset_t addr;
2124         size_t len;
2125 {
2126         vm_offset_t gap;
2127
2128         if ((vm_offset_t) (addr + len) < addr)
2129                 return EPERM;
2130         if ((vm_offset_t) (addr + len) <= sizeof(struct user))
2131                 return 0;
2132
2133         gap = (char *) p->p_md.md_regs - (char *) p->p_addr;
2134         
2135         if ((vm_offset_t) addr < gap)
2136                 return EPERM;
2137         if ((vm_offset_t) (addr + len) <= 
2138             (vm_offset_t) (gap + sizeof(struct trapframe)))
2139                 return 0;
2140         return EPERM;
2141 }
2142
2143 int ptrace_write_u(p, off, data)
2144         struct proc *p;
2145         vm_offset_t off;
2146         long data;
2147 {
2148         struct trapframe frame_copy;
2149         vm_offset_t min;
2150         struct trapframe *tp;
2151
2152         /*
2153          * Privileged kernel state is scattered all over the user area.
2154          * Only allow write access to parts of regs and to fpregs.
2155          */
2156         min = (char *)p->p_md.md_regs - (char *)p->p_addr;
2157         if (off >= min && off <= min + sizeof(struct trapframe) - sizeof(int)) {
2158                 tp = p->p_md.md_regs;
2159                 frame_copy = *tp;
2160                 *(int *)((char *)&frame_copy + (off - min)) = data;
2161                 if (!EFL_SECURE(frame_copy.tf_eflags, tp->tf_eflags) ||
2162                     !CS_SECURE(frame_copy.tf_cs))
2163                         return (EINVAL);
2164                 *(int*)((char *)p->p_addr + off) = data;
2165                 return (0);
2166         }
2167
2168         /*
2169          * The PCB is at the end of the user area YYY
2170          */
2171         min = (char *)p->p_thread->td_pcb - (char *)p->p_addr;
2172         min += offsetof(struct pcb, pcb_save);
2173         if (off >= min && off <= min + sizeof(union savefpu) - sizeof(int)) {
2174                 *(int*)((char *)p->p_addr + off) = data;
2175                 return (0);
2176         }
2177         return (EFAULT);
2178 }
2179
2180 int
2181 fill_regs(p, regs)
2182         struct proc *p;
2183         struct reg *regs;
2184 {
2185         struct pcb *pcb;
2186         struct trapframe *tp;
2187
2188         tp = p->p_md.md_regs;
2189         regs->r_fs = tp->tf_fs;
2190         regs->r_es = tp->tf_es;
2191         regs->r_ds = tp->tf_ds;
2192         regs->r_edi = tp->tf_edi;
2193         regs->r_esi = tp->tf_esi;
2194         regs->r_ebp = tp->tf_ebp;
2195         regs->r_ebx = tp->tf_ebx;
2196         regs->r_edx = tp->tf_edx;
2197         regs->r_ecx = tp->tf_ecx;
2198         regs->r_eax = tp->tf_eax;
2199         regs->r_eip = tp->tf_eip;
2200         regs->r_cs = tp->tf_cs;
2201         regs->r_eflags = tp->tf_eflags;
2202         regs->r_esp = tp->tf_esp;
2203         regs->r_ss = tp->tf_ss;
2204         pcb = p->p_thread->td_pcb;
2205         regs->r_gs = pcb->pcb_gs;
2206         return (0);
2207 }
2208
2209 int
2210 set_regs(p, regs)
2211         struct proc *p;
2212         struct reg *regs;
2213 {
2214         struct pcb *pcb;
2215         struct trapframe *tp;
2216
2217         tp = p->p_md.md_regs;
2218         if (!EFL_SECURE(regs->r_eflags, tp->tf_eflags) ||
2219             !CS_SECURE(regs->r_cs))
2220                 return (EINVAL);
2221         tp->tf_fs = regs->r_fs;
2222         tp->tf_es = regs->r_es;
2223         tp->tf_ds = regs->r_ds;
2224         tp->tf_edi = regs->r_edi;
2225         tp->tf_esi = regs->r_esi;
2226         tp->tf_ebp = regs->r_ebp;
2227         tp->tf_ebx = regs->r_ebx;
2228         tp->tf_edx = regs->r_edx;
2229         tp->tf_ecx = regs->r_ecx;
2230         tp->tf_eax = regs->r_eax;
2231         tp->tf_eip = regs->r_eip;
2232         tp->tf_cs = regs->r_cs;
2233         tp->tf_eflags = regs->r_eflags;
2234         tp->tf_esp = regs->r_esp;
2235         tp->tf_ss = regs->r_ss;
2236         pcb = p->p_thread->td_pcb;
2237         pcb->pcb_gs = regs->r_gs;
2238         return (0);
2239 }
2240
2241 #ifdef CPU_ENABLE_SSE
2242 static void
2243 fill_fpregs_xmm(sv_xmm, sv_87)
2244         struct savexmm *sv_xmm;
2245         struct save87 *sv_87;
2246 {
2247         register struct env87 *penv_87 = &sv_87->sv_env;
2248         register struct envxmm *penv_xmm = &sv_xmm->sv_env;
2249         int i;
2250
2251         /* FPU control/status */
2252         penv_87->en_cw = penv_xmm->en_cw;
2253         penv_87->en_sw = penv_xmm->en_sw;
2254         penv_87->en_tw = penv_xmm->en_tw;
2255         penv_87->en_fip = penv_xmm->en_fip;
2256         penv_87->en_fcs = penv_xmm->en_fcs;
2257         penv_87->en_opcode = penv_xmm->en_opcode;
2258         penv_87->en_foo = penv_xmm->en_foo;
2259         penv_87->en_fos = penv_xmm->en_fos;
2260
2261         /* FPU registers */
2262         for (i = 0; i < 8; ++i)
2263                 sv_87->sv_ac[i] = sv_xmm->sv_fp[i].fp_acc;
2264
2265         sv_87->sv_ex_sw = sv_xmm->sv_ex_sw;
2266 }
2267
2268 static void
2269 set_fpregs_xmm(sv_87, sv_xmm)
2270         struct save87 *sv_87;
2271         struct savexmm *sv_xmm;
2272 {
2273         register struct env87 *penv_87 = &sv_87->sv_env;
2274         register struct envxmm *penv_xmm = &sv_xmm->sv_env;
2275         int i;
2276
2277         /* FPU control/status */
2278         penv_xmm->en_cw = penv_87->en_cw;
2279         penv_xmm->en_sw = penv_87->en_sw;
2280         penv_xmm->en_tw = penv_87->en_tw;
2281         penv_xmm->en_fip = penv_87->en_fip;
2282         penv_xmm->en_fcs = penv_87->en_fcs;
2283         penv_xmm->en_opcode = penv_87->en_opcode;
2284         penv_xmm->en_foo = penv_87->en_foo;
2285         penv_xmm->en_fos = penv_87->en_fos;
2286
2287         /* FPU registers */
2288         for (i = 0; i < 8; ++i)
2289                 sv_xmm->sv_fp[i].fp_acc = sv_87->sv_ac[i];
2290
2291         sv_xmm->sv_ex_sw = sv_87->sv_ex_sw;
2292 }
2293 #endif /* CPU_ENABLE_SSE */
2294
2295 int
2296 fill_fpregs(p, fpregs)
2297         struct proc *p;
2298         struct fpreg *fpregs;
2299 {
2300 #ifdef CPU_ENABLE_SSE
2301         if (cpu_fxsr) {
2302                 fill_fpregs_xmm(&p->p_thread->td_pcb->pcb_save.sv_xmm,
2303                                                 (struct save87 *)fpregs);
2304                 return (0);
2305         }
2306 #endif /* CPU_ENABLE_SSE */
2307         bcopy(&p->p_thread->td_pcb->pcb_save.sv_87, fpregs, sizeof *fpregs);
2308         return (0);
2309 }
2310
2311 int
2312 set_fpregs(p, fpregs)
2313         struct proc *p;
2314         struct fpreg *fpregs;
2315 {
2316 #ifdef CPU_ENABLE_SSE
2317         if (cpu_fxsr) {
2318                 set_fpregs_xmm((struct save87 *)fpregs,
2319                                        &p->p_thread->td_pcb->pcb_save.sv_xmm);
2320                 return (0);
2321         }
2322 #endif /* CPU_ENABLE_SSE */
2323         bcopy(fpregs, &p->p_thread->td_pcb->pcb_save.sv_87, sizeof *fpregs);
2324         return (0);
2325 }
2326
2327 int
2328 fill_dbregs(p, dbregs)
2329         struct proc *p;
2330         struct dbreg *dbregs;
2331 {
2332         struct pcb *pcb;
2333
2334         if (p == NULL) {
2335                 dbregs->dr0 = rdr0();
2336                 dbregs->dr1 = rdr1();
2337                 dbregs->dr2 = rdr2();
2338                 dbregs->dr3 = rdr3();
2339                 dbregs->dr4 = rdr4();
2340                 dbregs->dr5 = rdr5();
2341                 dbregs->dr6 = rdr6();
2342                 dbregs->dr7 = rdr7();
2343         }
2344         else {
2345                 pcb = p->p_thread->td_pcb;
2346                 dbregs->dr0 = pcb->pcb_dr0;
2347                 dbregs->dr1 = pcb->pcb_dr1;
2348                 dbregs->dr2 = pcb->pcb_dr2;
2349                 dbregs->dr3 = pcb->pcb_dr3;
2350                 dbregs->dr4 = 0;
2351                 dbregs->dr5 = 0;
2352                 dbregs->dr6 = pcb->pcb_dr6;
2353                 dbregs->dr7 = pcb->pcb_dr7;
2354         }
2355         return (0);
2356 }
2357
2358 int
2359 set_dbregs(p, dbregs)
2360         struct proc *p;
2361         struct dbreg *dbregs;
2362 {
2363         struct pcb *pcb;
2364         int i;
2365         u_int32_t mask1, mask2;
2366
2367         if (p == NULL) {
2368                 load_dr0(dbregs->dr0);
2369                 load_dr1(dbregs->dr1);
2370                 load_dr2(dbregs->dr2);
2371                 load_dr3(dbregs->dr3);
2372                 load_dr4(dbregs->dr4);
2373                 load_dr5(dbregs->dr5);
2374                 load_dr6(dbregs->dr6);
2375                 load_dr7(dbregs->dr7);
2376         }
2377         else {
2378                 /*
2379                  * Don't let an illegal value for dr7 get set.  Specifically,
2380                  * check for undefined settings.  Setting these bit patterns
2381                  * result in undefined behaviour and can lead to an unexpected
2382                  * TRCTRAP.
2383                  */
2384                 for (i = 0, mask1 = 0x3<<16, mask2 = 0x2<<16; i < 8; 
2385                      i++, mask1 <<= 2, mask2 <<= 2)
2386                         if ((dbregs->dr7 & mask1) == mask2)
2387                                 return (EINVAL);
2388                 
2389                 pcb = p->p_thread->td_pcb;
2390                 
2391                 /*
2392                  * Don't let a process set a breakpoint that is not within the
2393                  * process's address space.  If a process could do this, it
2394                  * could halt the system by setting a breakpoint in the kernel
2395                  * (if ddb was enabled).  Thus, we need to check to make sure
2396                  * that no breakpoints are being enabled for addresses outside
2397                  * process's address space, unless, perhaps, we were called by
2398                  * uid 0.
2399                  *
2400                  * XXX - what about when the watched area of the user's
2401                  * address space is written into from within the kernel
2402                  * ... wouldn't that still cause a breakpoint to be generated
2403                  * from within kernel mode?
2404                  */
2405                 
2406                 if (suser_cred(p->p_ucred, 0) != 0) {
2407                         if (dbregs->dr7 & 0x3) {
2408                                 /* dr0 is enabled */
2409                                 if (dbregs->dr0 >= VM_MAXUSER_ADDRESS)
2410                                         return (EINVAL);
2411                         }
2412                         
2413                         if (dbregs->dr7 & (0x3<<2)) {
2414                                 /* dr1 is enabled */
2415                                 if (dbregs->dr1 >= VM_MAXUSER_ADDRESS)
2416                                         return (EINVAL);
2417                         }
2418                         
2419                         if (dbregs->dr7 & (0x3<<4)) {
2420                                 /* dr2 is enabled */
2421                                 if (dbregs->dr2 >= VM_MAXUSER_ADDRESS)
2422                                         return (EINVAL);
2423                         }
2424                         
2425                         if (dbregs->dr7 & (0x3<<6)) {
2426                                 /* dr3 is enabled */
2427                                 if (dbregs->dr3 >= VM_MAXUSER_ADDRESS)
2428                                         return (EINVAL);
2429                         }
2430                 }
2431                 
2432                 pcb->pcb_dr0 = dbregs->dr0;
2433                 pcb->pcb_dr1 = dbregs->dr1;
2434                 pcb->pcb_dr2 = dbregs->dr2;
2435                 pcb->pcb_dr3 = dbregs->dr3;
2436                 pcb->pcb_dr6 = dbregs->dr6;
2437                 pcb->pcb_dr7 = dbregs->dr7;
2438                 
2439                 pcb->pcb_flags |= PCB_DBREGS;
2440         }
2441
2442         return (0);
2443 }
2444
2445 /*
2446  * Return > 0 if a hardware breakpoint has been hit, and the
2447  * breakpoint was in user space.  Return 0, otherwise.
2448  */
2449 int
2450 user_dbreg_trap(void)
2451 {
2452         u_int32_t dr7, dr6; /* debug registers dr6 and dr7 */
2453         u_int32_t bp;       /* breakpoint bits extracted from dr6 */
2454         int nbp;            /* number of breakpoints that triggered */
2455         caddr_t addr[4];    /* breakpoint addresses */
2456         int i;
2457         
2458         dr7 = rdr7();
2459         if ((dr7 & 0x000000ff) == 0) {
2460                 /*
2461                  * all GE and LE bits in the dr7 register are zero,
2462                  * thus the trap couldn't have been caused by the
2463                  * hardware debug registers
2464                  */
2465                 return 0;
2466         }
2467
2468         nbp = 0;
2469         dr6 = rdr6();
2470         bp = dr6 & 0x0000000f;
2471
2472         if (!bp) {
2473                 /*
2474                  * None of the breakpoint bits are set meaning this
2475                  * trap was not caused by any of the debug registers
2476                  */
2477                 return 0;
2478         }
2479
2480         /*
2481          * at least one of the breakpoints were hit, check to see
2482          * which ones and if any of them are user space addresses
2483          */
2484
2485         if (bp & 0x01) {
2486                 addr[nbp++] = (caddr_t)rdr0();
2487         }
2488         if (bp & 0x02) {
2489                 addr[nbp++] = (caddr_t)rdr1();
2490         }
2491         if (bp & 0x04) {
2492                 addr[nbp++] = (caddr_t)rdr2();
2493         }
2494         if (bp & 0x08) {
2495                 addr[nbp++] = (caddr_t)rdr3();
2496         }
2497
2498         for (i=0; i<nbp; i++) {
2499                 if (addr[i] <
2500                     (caddr_t)VM_MAXUSER_ADDRESS) {
2501                         /*
2502                          * addr[i] is in user space
2503                          */
2504                         return nbp;
2505                 }
2506         }
2507
2508         /*
2509          * None of the breakpoints are in user space.
2510          */
2511         return 0;
2512 }
2513
2514
2515 #ifndef DDB
2516 void
2517 Debugger(const char *msg)
2518 {
2519         printf("Debugger(\"%s\") called.\n", msg);
2520 }
2521 #endif /* no DDB */
2522
2523 #include <sys/disklabel.h>
2524
2525 /*
2526  * Determine the size of the transfer, and make sure it is
2527  * within the boundaries of the partition. Adjust transfer
2528  * if needed, and signal errors or early completion.
2529  */
2530 int
2531 bounds_check_with_label(struct buf *bp, struct disklabel *lp, int wlabel)
2532 {
2533         struct partition *p = lp->d_partitions + dkpart(bp->b_dev);
2534         int labelsect = lp->d_partitions[0].p_offset;
2535         int maxsz = p->p_size,
2536                 sz = (bp->b_bcount + DEV_BSIZE - 1) >> DEV_BSHIFT;
2537
2538         /* overwriting disk label ? */
2539         /* XXX should also protect bootstrap in first 8K */
2540         if (bp->b_blkno + p->p_offset <= LABELSECTOR + labelsect &&
2541 #if LABELSECTOR != 0
2542             bp->b_blkno + p->p_offset + sz > LABELSECTOR + labelsect &&
2543 #endif
2544             (bp->b_flags & B_READ) == 0 && wlabel == 0) {
2545                 bp->b_error = EROFS;
2546                 goto bad;
2547         }
2548
2549 #if     defined(DOSBBSECTOR) && defined(notyet)
2550         /* overwriting master boot record? */
2551         if (bp->b_blkno + p->p_offset <= DOSBBSECTOR &&
2552             (bp->b_flags & B_READ) == 0 && wlabel == 0) {
2553                 bp->b_error = EROFS;
2554                 goto bad;
2555         }
2556 #endif
2557
2558         /* beyond partition? */
2559         if (bp->b_blkno < 0 || bp->b_blkno + sz > maxsz) {
2560                 /* if exactly at end of disk, return an EOF */
2561                 if (bp->b_blkno == maxsz) {
2562                         bp->b_resid = bp->b_bcount;
2563                         return(0);
2564                 }
2565                 /* or truncate if part of it fits */
2566                 sz = maxsz - bp->b_blkno;
2567                 if (sz <= 0) {
2568                         bp->b_error = EINVAL;
2569                         goto bad;
2570                 }
2571                 bp->b_bcount = sz << DEV_BSHIFT;
2572         }
2573
2574         bp->b_pblkno = bp->b_blkno + p->p_offset;
2575         return(1);
2576
2577 bad:
2578         bp->b_flags |= B_ERROR;
2579         return(-1);
2580 }
2581
2582 #ifdef DDB
2583
2584 /*
2585  * Provide inb() and outb() as functions.  They are normally only
2586  * available as macros calling inlined functions, thus cannot be
2587  * called inside DDB.
2588  *
2589  * The actual code is stolen from <machine/cpufunc.h>, and de-inlined.
2590  */
2591
2592 #undef inb
2593 #undef outb
2594
2595 /* silence compiler warnings */
2596 u_char inb(u_int);
2597 void outb(u_int, u_char);
2598
2599 u_char
2600 inb(u_int port)
2601 {
2602         u_char  data;
2603         /*
2604          * We use %%dx and not %1 here because i/o is done at %dx and not at
2605          * %edx, while gcc generates inferior code (movw instead of movl)
2606          * if we tell it to load (u_short) port.
2607          */
2608         __asm __volatile("inb %%dx,%0" : "=a" (data) : "d" (port));
2609         return (data);
2610 }
2611
2612 void
2613 outb(u_int port, u_char data)
2614 {
2615         u_char  al;
2616         /*
2617          * Use an unnecessary assignment to help gcc's register allocator.
2618          * This make a large difference for gcc-1.40 and a tiny difference
2619          * for gcc-2.6.0.  For gcc-1.40, al had to be ``asm("ax")'' for
2620          * best results.  gcc-2.6.0 can't handle this.
2621          */
2622         al = data;
2623         __asm __volatile("outb %0,%%dx" : : "a" (al), "d" (port));
2624 }
2625
2626 #endif /* DDB */