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