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