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