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