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