]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/i386/i386/machdep.c
Integrate tools/regression/kqueue into the FreeBSD test suite as
[FreeBSD/FreeBSD.git] / sys / i386 / i386 / machdep.c
1 /*-
2  * Copyright (c) 1992 Terrence R. Lambert.
3  * Copyright (c) 1982, 1987, 1990 The Regents of the University of California.
4  * All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * William Jolitz.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *      This product includes software developed by the University of
20  *      California, Berkeley and its contributors.
21  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *      from: @(#)machdep.c     7.4 (Berkeley) 6/3/91
38  */
39
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42
43 #include "opt_apic.h"
44 #include "opt_atpic.h"
45 #include "opt_compat.h"
46 #include "opt_cpu.h"
47 #include "opt_ddb.h"
48 #include "opt_inet.h"
49 #include "opt_isa.h"
50 #include "opt_kstack_pages.h"
51 #include "opt_maxmem.h"
52 #include "opt_mp_watchdog.h"
53 #include "opt_npx.h"
54 #include "opt_perfmon.h"
55 #include "opt_platform.h"
56 #include "opt_xbox.h"
57
58 #include <sys/param.h>
59 #include <sys/proc.h>
60 #include <sys/systm.h>
61 #include <sys/bio.h>
62 #include <sys/buf.h>
63 #include <sys/bus.h>
64 #include <sys/callout.h>
65 #include <sys/cons.h>
66 #include <sys/cpu.h>
67 #include <sys/eventhandler.h>
68 #include <sys/exec.h>
69 #include <sys/imgact.h>
70 #include <sys/kdb.h>
71 #include <sys/kernel.h>
72 #include <sys/ktr.h>
73 #include <sys/linker.h>
74 #include <sys/lock.h>
75 #include <sys/malloc.h>
76 #include <sys/memrange.h>
77 #include <sys/msgbuf.h>
78 #include <sys/mutex.h>
79 #include <sys/pcpu.h>
80 #include <sys/ptrace.h>
81 #include <sys/reboot.h>
82 #include <sys/rwlock.h>
83 #include <sys/sched.h>
84 #include <sys/signalvar.h>
85 #ifdef SMP
86 #include <sys/smp.h>
87 #endif
88 #include <sys/syscallsubr.h>
89 #include <sys/sysctl.h>
90 #include <sys/sysent.h>
91 #include <sys/sysproto.h>
92 #include <sys/ucontext.h>
93 #include <sys/vmmeter.h>
94
95 #include <vm/vm.h>
96 #include <vm/vm_extern.h>
97 #include <vm/vm_kern.h>
98 #include <vm/vm_page.h>
99 #include <vm/vm_map.h>
100 #include <vm/vm_object.h>
101 #include <vm/vm_pager.h>
102 #include <vm/vm_param.h>
103
104 #ifdef DDB
105 #ifndef KDB
106 #error KDB must be enabled in order for DDB to work!
107 #endif
108 #include <ddb/ddb.h>
109 #include <ddb/db_sym.h>
110 #endif
111
112 #ifdef PC98
113 #include <pc98/pc98/pc98_machdep.h>
114 #else
115 #include <isa/rtc.h>
116 #endif
117
118 #include <net/netisr.h>
119
120 #include <machine/bootinfo.h>
121 #include <machine/clock.h>
122 #include <machine/cpu.h>
123 #include <machine/cputypes.h>
124 #include <machine/intr_machdep.h>
125 #include <x86/mca.h>
126 #include <machine/md_var.h>
127 #include <machine/metadata.h>
128 #include <machine/mp_watchdog.h>
129 #include <machine/pc/bios.h>
130 #include <machine/pcb.h>
131 #include <machine/pcb_ext.h>
132 #include <machine/proc.h>
133 #include <machine/reg.h>
134 #include <machine/sigframe.h>
135 #include <machine/specialreg.h>
136 #include <machine/vm86.h>
137 #include <x86/init.h>
138 #ifdef PERFMON
139 #include <machine/perfmon.h>
140 #endif
141 #ifdef SMP
142 #include <machine/smp.h>
143 #endif
144 #ifdef FDT
145 #include <x86/fdt.h>
146 #endif
147
148 #ifdef DEV_APIC
149 #include <x86/apicvar.h>
150 #endif
151
152 #ifdef DEV_ISA
153 #include <x86/isa/icu.h>
154 #endif
155
156 #ifdef XBOX
157 #include <machine/xbox.h>
158
159 int arch_i386_is_xbox = 0;
160 uint32_t arch_i386_xbox_memsize = 0;
161 #endif
162
163 #ifdef XEN
164 /* XEN includes */
165 #include <xen/xen-os.h>
166 #include <xen/hypervisor.h>
167 #include <machine/xen/xenvar.h>
168 #include <machine/xen/xenfunc.h>
169 #include <xen/xen_intr.h>
170
171 void Xhypervisor_callback(void);
172 void failsafe_callback(void);
173
174 extern trap_info_t trap_table[];
175 struct proc_ldt default_proc_ldt;
176 extern int init_first;
177 int running_xen = 1;
178 extern unsigned long physfree;
179 #endif /* XEN */
180
181 /* Sanity check for __curthread() */
182 CTASSERT(offsetof(struct pcpu, pc_curthread) == 0);
183
184 extern register_t init386(int first);
185 extern void dblfault_handler(void);
186
187 #define CS_SECURE(cs)           (ISPL(cs) == SEL_UPL)
188 #define EFL_SECURE(ef, oef)     ((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
189
190 #if !defined(CPU_DISABLE_SSE) && defined(I686_CPU)
191 #define CPU_ENABLE_SSE
192 #endif
193
194 static void cpu_startup(void *);
195 static void fpstate_drop(struct thread *td);
196 static void get_fpcontext(struct thread *td, mcontext_t *mcp,
197     char *xfpusave, size_t xfpusave_len);
198 static int  set_fpcontext(struct thread *td, mcontext_t *mcp,
199     char *xfpustate, size_t xfpustate_len);
200 #ifdef CPU_ENABLE_SSE
201 static void set_fpregs_xmm(struct save87 *, struct savexmm *);
202 static void fill_fpregs_xmm(struct savexmm *, struct save87 *);
203 #endif /* CPU_ENABLE_SSE */
204 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
205
206 /* Intel ICH registers */
207 #define ICH_PMBASE      0x400
208 #define ICH_SMI_EN      ICH_PMBASE + 0x30
209
210 int     _udatasel, _ucodesel;
211 u_int   basemem;
212
213 #ifdef PC98
214 int     need_pre_dma_flush;     /* If 1, use wbinvd befor DMA transfer. */
215 int     need_post_dma_flush;    /* If 1, use invd after DMA transfer. */
216
217 static int      ispc98 = 1;
218 SYSCTL_INT(_machdep, OID_AUTO, ispc98, CTLFLAG_RD, &ispc98, 0, "");
219 #endif
220
221 int cold = 1;
222
223 #ifdef COMPAT_43
224 static void osendsig(sig_t catcher, ksiginfo_t *, sigset_t *mask);
225 #endif
226 #ifdef COMPAT_FREEBSD4
227 static void freebsd4_sendsig(sig_t catcher, ksiginfo_t *, sigset_t *mask);
228 #endif
229
230 long Maxmem = 0;
231 long realmem = 0;
232
233 #ifdef PAE
234 FEATURE(pae, "Physical Address Extensions");
235 #endif
236
237 /*
238  * The number of PHYSMAP entries must be one less than the number of
239  * PHYSSEG entries because the PHYSMAP entry that spans the largest
240  * physical address that is accessible by ISA DMA is split into two
241  * PHYSSEG entries.
242  */
243 #define PHYSMAP_SIZE    (2 * (VM_PHYSSEG_MAX - 1))
244
245 vm_paddr_t phys_avail[PHYSMAP_SIZE + 2];
246 vm_paddr_t dump_avail[PHYSMAP_SIZE + 2];
247
248 /* must be 2 less so 0 0 can signal end of chunks */
249 #define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(phys_avail[0])) - 2)
250 #define DUMP_AVAIL_ARRAY_END ((sizeof(dump_avail) / sizeof(dump_avail[0])) - 2)
251
252 struct kva_md_info kmi;
253
254 static struct trapframe proc0_tf;
255 struct pcpu __pcpu[MAXCPU];
256
257 struct mtx icu_lock;
258
259 struct mem_range_softc mem_range_softc;
260
261  /* Default init_ops implementation. */
262  struct init_ops init_ops = {
263         .early_clock_source_init =      i8254_init,
264         .early_delay =                  i8254_delay,
265 #ifdef DEV_APIC
266         .msi_init =                     msi_init,
267 #endif
268  };
269
270 static void
271 cpu_startup(dummy)
272         void *dummy;
273 {
274         uintmax_t memsize;
275         char *sysenv;
276
277 #ifndef PC98
278         /*
279          * On MacBooks, we need to disallow the legacy USB circuit to
280          * generate an SMI# because this can cause several problems,
281          * namely: incorrect CPU frequency detection and failure to
282          * start the APs.
283          * We do this by disabling a bit in the SMI_EN (SMI Control and
284          * Enable register) of the Intel ICH LPC Interface Bridge.
285          */
286         sysenv = kern_getenv("smbios.system.product");
287         if (sysenv != NULL) {
288                 if (strncmp(sysenv, "MacBook1,1", 10) == 0 ||
289                     strncmp(sysenv, "MacBook3,1", 10) == 0 ||
290                     strncmp(sysenv, "MacBook4,1", 10) == 0 ||
291                     strncmp(sysenv, "MacBookPro1,1", 13) == 0 ||
292                     strncmp(sysenv, "MacBookPro1,2", 13) == 0 ||
293                     strncmp(sysenv, "MacBookPro3,1", 13) == 0 ||
294                     strncmp(sysenv, "MacBookPro4,1", 13) == 0 ||
295                     strncmp(sysenv, "Macmini1,1", 10) == 0) {
296                         if (bootverbose)
297                                 printf("Disabling LEGACY_USB_EN bit on "
298                                     "Intel ICH.\n");
299                         outl(ICH_SMI_EN, inl(ICH_SMI_EN) & ~0x8);
300                 }
301                 freeenv(sysenv);
302         }
303 #endif /* !PC98 */
304
305         /*
306          * Good {morning,afternoon,evening,night}.
307          */
308         startrtclock();
309         printcpuinfo();
310         panicifcpuunsupported();
311 #ifdef PERFMON
312         perfmon_init();
313 #endif
314
315         /*
316          * Display physical memory if SMBIOS reports reasonable amount.
317          */
318         memsize = 0;
319         sysenv = kern_getenv("smbios.memory.enabled");
320         if (sysenv != NULL) {
321                 memsize = (uintmax_t)strtoul(sysenv, (char **)NULL, 10) << 10;
322                 freeenv(sysenv);
323         }
324         if (memsize < ptoa((uintmax_t)vm_cnt.v_free_count))
325                 memsize = ptoa((uintmax_t)Maxmem);
326         printf("real memory  = %ju (%ju MB)\n", memsize, memsize >> 20);
327         realmem = atop(memsize);
328
329         /*
330          * Display any holes after the first chunk of extended memory.
331          */
332         if (bootverbose) {
333                 int indx;
334
335                 printf("Physical memory chunk(s):\n");
336                 for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
337                         vm_paddr_t size;
338
339                         size = phys_avail[indx + 1] - phys_avail[indx];
340                         printf(
341                             "0x%016jx - 0x%016jx, %ju bytes (%ju pages)\n",
342                             (uintmax_t)phys_avail[indx],
343                             (uintmax_t)phys_avail[indx + 1] - 1,
344                             (uintmax_t)size, (uintmax_t)size / PAGE_SIZE);
345                 }
346         }
347
348         vm_ksubmap_init(&kmi);
349
350         printf("avail memory = %ju (%ju MB)\n",
351             ptoa((uintmax_t)vm_cnt.v_free_count),
352             ptoa((uintmax_t)vm_cnt.v_free_count) / 1048576);
353
354         /*
355          * Set up buffers, so they can be used to read disk labels.
356          */
357         bufinit();
358         vm_pager_bufferinit();
359 #ifndef XEN
360         cpu_setregs();
361 #endif
362 }
363
364 /*
365  * Send an interrupt to process.
366  *
367  * Stack is set up to allow sigcode stored
368  * at top to call routine, followed by call
369  * to sigreturn routine below.  After sigreturn
370  * resets the signal mask, the stack, and the
371  * frame pointer, it returns to the user
372  * specified pc, psl.
373  */
374 #ifdef COMPAT_43
375 static void
376 osendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
377 {
378         struct osigframe sf, *fp;
379         struct proc *p;
380         struct thread *td;
381         struct sigacts *psp;
382         struct trapframe *regs;
383         int sig;
384         int oonstack;
385
386         td = curthread;
387         p = td->td_proc;
388         PROC_LOCK_ASSERT(p, MA_OWNED);
389         sig = ksi->ksi_signo;
390         psp = p->p_sigacts;
391         mtx_assert(&psp->ps_mtx, MA_OWNED);
392         regs = td->td_frame;
393         oonstack = sigonstack(regs->tf_esp);
394
395         /* Allocate space for the signal handler context. */
396         if ((td->td_pflags & TDP_ALTSTACK) && !oonstack &&
397             SIGISMEMBER(psp->ps_sigonstack, sig)) {
398                 fp = (struct osigframe *)(td->td_sigstk.ss_sp +
399                     td->td_sigstk.ss_size - sizeof(struct osigframe));
400 #if defined(COMPAT_43)
401                 td->td_sigstk.ss_flags |= SS_ONSTACK;
402 #endif
403         } else
404                 fp = (struct osigframe *)regs->tf_esp - 1;
405
406         /* Translate the signal if appropriate. */
407         if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
408                 sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
409
410         /* Build the argument list for the signal handler. */
411         sf.sf_signum = sig;
412         sf.sf_scp = (register_t)&fp->sf_siginfo.si_sc;
413         bzero(&sf.sf_siginfo, sizeof(sf.sf_siginfo));
414         if (SIGISMEMBER(psp->ps_siginfo, sig)) {
415                 /* Signal handler installed with SA_SIGINFO. */
416                 sf.sf_arg2 = (register_t)&fp->sf_siginfo;
417                 sf.sf_siginfo.si_signo = sig;
418                 sf.sf_siginfo.si_code = ksi->ksi_code;
419                 sf.sf_ahu.sf_action = (__osiginfohandler_t *)catcher;
420                 sf.sf_addr = 0;
421         } else {
422                 /* Old FreeBSD-style arguments. */
423                 sf.sf_arg2 = ksi->ksi_code;
424                 sf.sf_addr = (register_t)ksi->ksi_addr;
425                 sf.sf_ahu.sf_handler = catcher;
426         }
427         mtx_unlock(&psp->ps_mtx);
428         PROC_UNLOCK(p);
429
430         /* Save most if not all of trap frame. */
431         sf.sf_siginfo.si_sc.sc_eax = regs->tf_eax;
432         sf.sf_siginfo.si_sc.sc_ebx = regs->tf_ebx;
433         sf.sf_siginfo.si_sc.sc_ecx = regs->tf_ecx;
434         sf.sf_siginfo.si_sc.sc_edx = regs->tf_edx;
435         sf.sf_siginfo.si_sc.sc_esi = regs->tf_esi;
436         sf.sf_siginfo.si_sc.sc_edi = regs->tf_edi;
437         sf.sf_siginfo.si_sc.sc_cs = regs->tf_cs;
438         sf.sf_siginfo.si_sc.sc_ds = regs->tf_ds;
439         sf.sf_siginfo.si_sc.sc_ss = regs->tf_ss;
440         sf.sf_siginfo.si_sc.sc_es = regs->tf_es;
441         sf.sf_siginfo.si_sc.sc_fs = regs->tf_fs;
442         sf.sf_siginfo.si_sc.sc_gs = rgs();
443         sf.sf_siginfo.si_sc.sc_isp = regs->tf_isp;
444
445         /* Build the signal context to be used by osigreturn(). */
446         sf.sf_siginfo.si_sc.sc_onstack = (oonstack) ? 1 : 0;
447         SIG2OSIG(*mask, sf.sf_siginfo.si_sc.sc_mask);
448         sf.sf_siginfo.si_sc.sc_sp = regs->tf_esp;
449         sf.sf_siginfo.si_sc.sc_fp = regs->tf_ebp;
450         sf.sf_siginfo.si_sc.sc_pc = regs->tf_eip;
451         sf.sf_siginfo.si_sc.sc_ps = regs->tf_eflags;
452         sf.sf_siginfo.si_sc.sc_trapno = regs->tf_trapno;
453         sf.sf_siginfo.si_sc.sc_err = regs->tf_err;
454
455         /*
456          * If we're a vm86 process, we want to save the segment registers.
457          * We also change eflags to be our emulated eflags, not the actual
458          * eflags.
459          */
460         if (regs->tf_eflags & PSL_VM) {
461                 /* XXX confusing names: `tf' isn't a trapframe; `regs' is. */
462                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
463                 struct vm86_kernel *vm86 = &td->td_pcb->pcb_ext->ext_vm86;
464
465                 sf.sf_siginfo.si_sc.sc_gs = tf->tf_vm86_gs;
466                 sf.sf_siginfo.si_sc.sc_fs = tf->tf_vm86_fs;
467                 sf.sf_siginfo.si_sc.sc_es = tf->tf_vm86_es;
468                 sf.sf_siginfo.si_sc.sc_ds = tf->tf_vm86_ds;
469
470                 if (vm86->vm86_has_vme == 0)
471                         sf.sf_siginfo.si_sc.sc_ps =
472                             (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
473                             (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
474
475                 /* See sendsig() for comments. */
476                 tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_VIF | PSL_VIP);
477         }
478
479         /*
480          * Copy the sigframe out to the user's stack.
481          */
482         if (copyout(&sf, fp, sizeof(*fp)) != 0) {
483 #ifdef DEBUG
484                 printf("process %ld has trashed its stack\n", (long)p->p_pid);
485 #endif
486                 PROC_LOCK(p);
487                 sigexit(td, SIGILL);
488         }
489
490         regs->tf_esp = (int)fp;
491         if (p->p_sysent->sv_sigcode_base != 0) {
492                 regs->tf_eip = p->p_sysent->sv_sigcode_base + szsigcode -
493                     szosigcode;
494         } else {
495                 /* a.out sysentvec does not use shared page */
496                 regs->tf_eip = p->p_sysent->sv_psstrings - szosigcode;
497         }
498         regs->tf_eflags &= ~(PSL_T | PSL_D);
499         regs->tf_cs = _ucodesel;
500         regs->tf_ds = _udatasel;
501         regs->tf_es = _udatasel;
502         regs->tf_fs = _udatasel;
503         load_gs(_udatasel);
504         regs->tf_ss = _udatasel;
505         PROC_LOCK(p);
506         mtx_lock(&psp->ps_mtx);
507 }
508 #endif /* COMPAT_43 */
509
510 #ifdef COMPAT_FREEBSD4
511 static void
512 freebsd4_sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
513 {
514         struct sigframe4 sf, *sfp;
515         struct proc *p;
516         struct thread *td;
517         struct sigacts *psp;
518         struct trapframe *regs;
519         int sig;
520         int oonstack;
521
522         td = curthread;
523         p = td->td_proc;
524         PROC_LOCK_ASSERT(p, MA_OWNED);
525         sig = ksi->ksi_signo;
526         psp = p->p_sigacts;
527         mtx_assert(&psp->ps_mtx, MA_OWNED);
528         regs = td->td_frame;
529         oonstack = sigonstack(regs->tf_esp);
530
531         /* Save user context. */
532         bzero(&sf, sizeof(sf));
533         sf.sf_uc.uc_sigmask = *mask;
534         sf.sf_uc.uc_stack = td->td_sigstk;
535         sf.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
536             ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
537         sf.sf_uc.uc_mcontext.mc_onstack = (oonstack) ? 1 : 0;
538         sf.sf_uc.uc_mcontext.mc_gs = rgs();
539         bcopy(regs, &sf.sf_uc.uc_mcontext.mc_fs, sizeof(*regs));
540         bzero(sf.sf_uc.uc_mcontext.mc_fpregs,
541             sizeof(sf.sf_uc.uc_mcontext.mc_fpregs));
542         bzero(sf.sf_uc.uc_mcontext.__spare__,
543             sizeof(sf.sf_uc.uc_mcontext.__spare__));
544         bzero(sf.sf_uc.__spare__, sizeof(sf.sf_uc.__spare__));
545
546         /* Allocate space for the signal handler context. */
547         if ((td->td_pflags & TDP_ALTSTACK) != 0 && !oonstack &&
548             SIGISMEMBER(psp->ps_sigonstack, sig)) {
549                 sfp = (struct sigframe4 *)(td->td_sigstk.ss_sp +
550                     td->td_sigstk.ss_size - sizeof(struct sigframe4));
551 #if defined(COMPAT_43)
552                 td->td_sigstk.ss_flags |= SS_ONSTACK;
553 #endif
554         } else
555                 sfp = (struct sigframe4 *)regs->tf_esp - 1;
556
557         /* Translate the signal if appropriate. */
558         if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
559                 sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
560
561         /* Build the argument list for the signal handler. */
562         sf.sf_signum = sig;
563         sf.sf_ucontext = (register_t)&sfp->sf_uc;
564         bzero(&sf.sf_si, sizeof(sf.sf_si));
565         if (SIGISMEMBER(psp->ps_siginfo, sig)) {
566                 /* Signal handler installed with SA_SIGINFO. */
567                 sf.sf_siginfo = (register_t)&sfp->sf_si;
568                 sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
569
570                 /* Fill in POSIX parts */
571                 sf.sf_si.si_signo = sig;
572                 sf.sf_si.si_code = ksi->ksi_code;
573                 sf.sf_si.si_addr = ksi->ksi_addr;
574         } else {
575                 /* Old FreeBSD-style arguments. */
576                 sf.sf_siginfo = ksi->ksi_code;
577                 sf.sf_addr = (register_t)ksi->ksi_addr;
578                 sf.sf_ahu.sf_handler = catcher;
579         }
580         mtx_unlock(&psp->ps_mtx);
581         PROC_UNLOCK(p);
582
583         /*
584          * If we're a vm86 process, we want to save the segment registers.
585          * We also change eflags to be our emulated eflags, not the actual
586          * eflags.
587          */
588         if (regs->tf_eflags & PSL_VM) {
589                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
590                 struct vm86_kernel *vm86 = &td->td_pcb->pcb_ext->ext_vm86;
591
592                 sf.sf_uc.uc_mcontext.mc_gs = tf->tf_vm86_gs;
593                 sf.sf_uc.uc_mcontext.mc_fs = tf->tf_vm86_fs;
594                 sf.sf_uc.uc_mcontext.mc_es = tf->tf_vm86_es;
595                 sf.sf_uc.uc_mcontext.mc_ds = tf->tf_vm86_ds;
596
597                 if (vm86->vm86_has_vme == 0)
598                         sf.sf_uc.uc_mcontext.mc_eflags =
599                             (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
600                             (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
601
602                 /*
603                  * Clear PSL_NT to inhibit T_TSSFLT faults on return from
604                  * syscalls made by the signal handler.  This just avoids
605                  * wasting time for our lazy fixup of such faults.  PSL_NT
606                  * does nothing in vm86 mode, but vm86 programs can set it
607                  * almost legitimately in probes for old cpu types.
608                  */
609                 tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_VIF | PSL_VIP);
610         }
611
612         /*
613          * Copy the sigframe out to the user's stack.
614          */
615         if (copyout(&sf, sfp, sizeof(*sfp)) != 0) {
616 #ifdef DEBUG
617                 printf("process %ld has trashed its stack\n", (long)p->p_pid);
618 #endif
619                 PROC_LOCK(p);
620                 sigexit(td, SIGILL);
621         }
622
623         regs->tf_esp = (int)sfp;
624         regs->tf_eip = p->p_sysent->sv_sigcode_base + szsigcode -
625             szfreebsd4_sigcode;
626         regs->tf_eflags &= ~(PSL_T | PSL_D);
627         regs->tf_cs = _ucodesel;
628         regs->tf_ds = _udatasel;
629         regs->tf_es = _udatasel;
630         regs->tf_fs = _udatasel;
631         regs->tf_ss = _udatasel;
632         PROC_LOCK(p);
633         mtx_lock(&psp->ps_mtx);
634 }
635 #endif  /* COMPAT_FREEBSD4 */
636
637 void
638 sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
639 {
640         struct sigframe sf, *sfp;
641         struct proc *p;
642         struct thread *td;
643         struct sigacts *psp;
644         char *sp;
645         struct trapframe *regs;
646         struct segment_descriptor *sdp;
647         char *xfpusave;
648         size_t xfpusave_len;
649         int sig;
650         int oonstack;
651
652         td = curthread;
653         p = td->td_proc;
654         PROC_LOCK_ASSERT(p, MA_OWNED);
655         sig = ksi->ksi_signo;
656         psp = p->p_sigacts;
657         mtx_assert(&psp->ps_mtx, MA_OWNED);
658 #ifdef COMPAT_FREEBSD4
659         if (SIGISMEMBER(psp->ps_freebsd4, sig)) {
660                 freebsd4_sendsig(catcher, ksi, mask);
661                 return;
662         }
663 #endif
664 #ifdef COMPAT_43
665         if (SIGISMEMBER(psp->ps_osigset, sig)) {
666                 osendsig(catcher, ksi, mask);
667                 return;
668         }
669 #endif
670         regs = td->td_frame;
671         oonstack = sigonstack(regs->tf_esp);
672
673 #ifdef CPU_ENABLE_SSE
674         if (cpu_max_ext_state_size > sizeof(union savefpu) && use_xsave) {
675                 xfpusave_len = cpu_max_ext_state_size - sizeof(union savefpu);
676                 xfpusave = __builtin_alloca(xfpusave_len);
677         } else {
678 #else
679         {
680 #endif
681                 xfpusave_len = 0;
682                 xfpusave = NULL;
683         }
684
685         /* Save user context. */
686         bzero(&sf, sizeof(sf));
687         sf.sf_uc.uc_sigmask = *mask;
688         sf.sf_uc.uc_stack = td->td_sigstk;
689         sf.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
690             ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
691         sf.sf_uc.uc_mcontext.mc_onstack = (oonstack) ? 1 : 0;
692         sf.sf_uc.uc_mcontext.mc_gs = rgs();
693         bcopy(regs, &sf.sf_uc.uc_mcontext.mc_fs, sizeof(*regs));
694         sf.sf_uc.uc_mcontext.mc_len = sizeof(sf.sf_uc.uc_mcontext); /* magic */
695         get_fpcontext(td, &sf.sf_uc.uc_mcontext, xfpusave, xfpusave_len);
696         fpstate_drop(td);
697         /*
698          * Unconditionally fill the fsbase and gsbase into the mcontext.
699          */
700         sdp = &td->td_pcb->pcb_fsd;
701         sf.sf_uc.uc_mcontext.mc_fsbase = sdp->sd_hibase << 24 |
702             sdp->sd_lobase;
703         sdp = &td->td_pcb->pcb_gsd;
704         sf.sf_uc.uc_mcontext.mc_gsbase = sdp->sd_hibase << 24 |
705             sdp->sd_lobase;
706         bzero(sf.sf_uc.uc_mcontext.mc_spare2,
707             sizeof(sf.sf_uc.uc_mcontext.mc_spare2));
708         bzero(sf.sf_uc.__spare__, sizeof(sf.sf_uc.__spare__));
709
710         /* Allocate space for the signal handler context. */
711         if ((td->td_pflags & TDP_ALTSTACK) != 0 && !oonstack &&
712             SIGISMEMBER(psp->ps_sigonstack, sig)) {
713                 sp = td->td_sigstk.ss_sp + td->td_sigstk.ss_size;
714 #if defined(COMPAT_43)
715                 td->td_sigstk.ss_flags |= SS_ONSTACK;
716 #endif
717         } else
718                 sp = (char *)regs->tf_esp - 128;
719         if (xfpusave != NULL) {
720                 sp -= xfpusave_len;
721                 sp = (char *)((unsigned int)sp & ~0x3F);
722                 sf.sf_uc.uc_mcontext.mc_xfpustate = (register_t)sp;
723         }
724         sp -= sizeof(struct sigframe);
725
726         /* Align to 16 bytes. */
727         sfp = (struct sigframe *)((unsigned int)sp & ~0xF);
728
729         /* Translate the signal if appropriate. */
730         if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
731                 sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
732
733         /* Build the argument list for the signal handler. */
734         sf.sf_signum = sig;
735         sf.sf_ucontext = (register_t)&sfp->sf_uc;
736         bzero(&sf.sf_si, sizeof(sf.sf_si));
737         if (SIGISMEMBER(psp->ps_siginfo, sig)) {
738                 /* Signal handler installed with SA_SIGINFO. */
739                 sf.sf_siginfo = (register_t)&sfp->sf_si;
740                 sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
741
742                 /* Fill in POSIX parts */
743                 sf.sf_si = ksi->ksi_info;
744                 sf.sf_si.si_signo = sig; /* maybe a translated signal */
745         } else {
746                 /* Old FreeBSD-style arguments. */
747                 sf.sf_siginfo = ksi->ksi_code;
748                 sf.sf_addr = (register_t)ksi->ksi_addr;
749                 sf.sf_ahu.sf_handler = catcher;
750         }
751         mtx_unlock(&psp->ps_mtx);
752         PROC_UNLOCK(p);
753
754         /*
755          * If we're a vm86 process, we want to save the segment registers.
756          * We also change eflags to be our emulated eflags, not the actual
757          * eflags.
758          */
759         if (regs->tf_eflags & PSL_VM) {
760                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
761                 struct vm86_kernel *vm86 = &td->td_pcb->pcb_ext->ext_vm86;
762
763                 sf.sf_uc.uc_mcontext.mc_gs = tf->tf_vm86_gs;
764                 sf.sf_uc.uc_mcontext.mc_fs = tf->tf_vm86_fs;
765                 sf.sf_uc.uc_mcontext.mc_es = tf->tf_vm86_es;
766                 sf.sf_uc.uc_mcontext.mc_ds = tf->tf_vm86_ds;
767
768                 if (vm86->vm86_has_vme == 0)
769                         sf.sf_uc.uc_mcontext.mc_eflags =
770                             (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
771                             (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
772
773                 /*
774                  * Clear PSL_NT to inhibit T_TSSFLT faults on return from
775                  * syscalls made by the signal handler.  This just avoids
776                  * wasting time for our lazy fixup of such faults.  PSL_NT
777                  * does nothing in vm86 mode, but vm86 programs can set it
778                  * almost legitimately in probes for old cpu types.
779                  */
780                 tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_VIF | PSL_VIP);
781         }
782
783         /*
784          * Copy the sigframe out to the user's stack.
785          */
786         if (copyout(&sf, sfp, sizeof(*sfp)) != 0 ||
787             (xfpusave != NULL && copyout(xfpusave,
788             (void *)sf.sf_uc.uc_mcontext.mc_xfpustate, xfpusave_len)
789             != 0)) {
790 #ifdef DEBUG
791                 printf("process %ld has trashed its stack\n", (long)p->p_pid);
792 #endif
793                 PROC_LOCK(p);
794                 sigexit(td, SIGILL);
795         }
796
797         regs->tf_esp = (int)sfp;
798         regs->tf_eip = p->p_sysent->sv_sigcode_base;
799         if (regs->tf_eip == 0)
800                 regs->tf_eip = p->p_sysent->sv_psstrings - szsigcode;
801         regs->tf_eflags &= ~(PSL_T | PSL_D);
802         regs->tf_cs = _ucodesel;
803         regs->tf_ds = _udatasel;
804         regs->tf_es = _udatasel;
805         regs->tf_fs = _udatasel;
806         regs->tf_ss = _udatasel;
807         PROC_LOCK(p);
808         mtx_lock(&psp->ps_mtx);
809 }
810
811 /*
812  * System call to cleanup state after a signal
813  * has been taken.  Reset signal mask and
814  * stack state from context left by sendsig (above).
815  * Return to previous pc and psl as specified by
816  * context left by sendsig. Check carefully to
817  * make sure that the user has not modified the
818  * state to gain improper privileges.
819  *
820  * MPSAFE
821  */
822 #ifdef COMPAT_43
823 int
824 osigreturn(td, uap)
825         struct thread *td;
826         struct osigreturn_args /* {
827                 struct osigcontext *sigcntxp;
828         } */ *uap;
829 {
830         struct osigcontext sc;
831         struct trapframe *regs;
832         struct osigcontext *scp;
833         int eflags, error;
834         ksiginfo_t ksi;
835
836         regs = td->td_frame;
837         error = copyin(uap->sigcntxp, &sc, sizeof(sc));
838         if (error != 0)
839                 return (error);
840         scp = &sc;
841         eflags = scp->sc_ps;
842         if (eflags & PSL_VM) {
843                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
844                 struct vm86_kernel *vm86;
845
846                 /*
847                  * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
848                  * set up the vm86 area, and we can't enter vm86 mode.
849                  */
850                 if (td->td_pcb->pcb_ext == 0)
851                         return (EINVAL);
852                 vm86 = &td->td_pcb->pcb_ext->ext_vm86;
853                 if (vm86->vm86_inited == 0)
854                         return (EINVAL);
855
856                 /* Go back to user mode if both flags are set. */
857                 if ((eflags & PSL_VIP) && (eflags & PSL_VIF)) {
858                         ksiginfo_init_trap(&ksi);
859                         ksi.ksi_signo = SIGBUS;
860                         ksi.ksi_code = BUS_OBJERR;
861                         ksi.ksi_addr = (void *)regs->tf_eip;
862                         trapsignal(td, &ksi);
863                 }
864
865                 if (vm86->vm86_has_vme) {
866                         eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
867                             (eflags & VME_USERCHANGE) | PSL_VM;
868                 } else {
869                         vm86->vm86_eflags = eflags;     /* save VIF, VIP */
870                         eflags = (tf->tf_eflags & ~VM_USERCHANGE) |
871                             (eflags & VM_USERCHANGE) | PSL_VM;
872                 }
873                 tf->tf_vm86_ds = scp->sc_ds;
874                 tf->tf_vm86_es = scp->sc_es;
875                 tf->tf_vm86_fs = scp->sc_fs;
876                 tf->tf_vm86_gs = scp->sc_gs;
877                 tf->tf_ds = _udatasel;
878                 tf->tf_es = _udatasel;
879                 tf->tf_fs = _udatasel;
880         } else {
881                 /*
882                  * Don't allow users to change privileged or reserved flags.
883                  */
884                 if (!EFL_SECURE(eflags, regs->tf_eflags)) {
885                         return (EINVAL);
886                 }
887
888                 /*
889                  * Don't allow users to load a valid privileged %cs.  Let the
890                  * hardware check for invalid selectors, excess privilege in
891                  * other selectors, invalid %eip's and invalid %esp's.
892                  */
893                 if (!CS_SECURE(scp->sc_cs)) {
894                         ksiginfo_init_trap(&ksi);
895                         ksi.ksi_signo = SIGBUS;
896                         ksi.ksi_code = BUS_OBJERR;
897                         ksi.ksi_trapno = T_PROTFLT;
898                         ksi.ksi_addr = (void *)regs->tf_eip;
899                         trapsignal(td, &ksi);
900                         return (EINVAL);
901                 }
902                 regs->tf_ds = scp->sc_ds;
903                 regs->tf_es = scp->sc_es;
904                 regs->tf_fs = scp->sc_fs;
905         }
906
907         /* Restore remaining registers. */
908         regs->tf_eax = scp->sc_eax;
909         regs->tf_ebx = scp->sc_ebx;
910         regs->tf_ecx = scp->sc_ecx;
911         regs->tf_edx = scp->sc_edx;
912         regs->tf_esi = scp->sc_esi;
913         regs->tf_edi = scp->sc_edi;
914         regs->tf_cs = scp->sc_cs;
915         regs->tf_ss = scp->sc_ss;
916         regs->tf_isp = scp->sc_isp;
917         regs->tf_ebp = scp->sc_fp;
918         regs->tf_esp = scp->sc_sp;
919         regs->tf_eip = scp->sc_pc;
920         regs->tf_eflags = eflags;
921
922 #if defined(COMPAT_43)
923         if (scp->sc_onstack & 1)
924                 td->td_sigstk.ss_flags |= SS_ONSTACK;
925         else
926                 td->td_sigstk.ss_flags &= ~SS_ONSTACK;
927 #endif
928         kern_sigprocmask(td, SIG_SETMASK, (sigset_t *)&scp->sc_mask, NULL,
929             SIGPROCMASK_OLD);
930         return (EJUSTRETURN);
931 }
932 #endif /* COMPAT_43 */
933
934 #ifdef COMPAT_FREEBSD4
935 /*
936  * MPSAFE
937  */
938 int
939 freebsd4_sigreturn(td, uap)
940         struct thread *td;
941         struct freebsd4_sigreturn_args /* {
942                 const ucontext4 *sigcntxp;
943         } */ *uap;
944 {
945         struct ucontext4 uc;
946         struct trapframe *regs;
947         struct ucontext4 *ucp;
948         int cs, eflags, error;
949         ksiginfo_t ksi;
950
951         error = copyin(uap->sigcntxp, &uc, sizeof(uc));
952         if (error != 0)
953                 return (error);
954         ucp = &uc;
955         regs = td->td_frame;
956         eflags = ucp->uc_mcontext.mc_eflags;
957         if (eflags & PSL_VM) {
958                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
959                 struct vm86_kernel *vm86;
960
961                 /*
962                  * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
963                  * set up the vm86 area, and we can't enter vm86 mode.
964                  */
965                 if (td->td_pcb->pcb_ext == 0)
966                         return (EINVAL);
967                 vm86 = &td->td_pcb->pcb_ext->ext_vm86;
968                 if (vm86->vm86_inited == 0)
969                         return (EINVAL);
970
971                 /* Go back to user mode if both flags are set. */
972                 if ((eflags & PSL_VIP) && (eflags & PSL_VIF)) {
973                         ksiginfo_init_trap(&ksi);
974                         ksi.ksi_signo = SIGBUS;
975                         ksi.ksi_code = BUS_OBJERR;
976                         ksi.ksi_addr = (void *)regs->tf_eip;
977                         trapsignal(td, &ksi);
978                 }
979                 if (vm86->vm86_has_vme) {
980                         eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
981                             (eflags & VME_USERCHANGE) | PSL_VM;
982                 } else {
983                         vm86->vm86_eflags = eflags;     /* save VIF, VIP */
984                         eflags = (tf->tf_eflags & ~VM_USERCHANGE) |
985                             (eflags & VM_USERCHANGE) | PSL_VM;
986                 }
987                 bcopy(&ucp->uc_mcontext.mc_fs, tf, sizeof(struct trapframe));
988                 tf->tf_eflags = eflags;
989                 tf->tf_vm86_ds = tf->tf_ds;
990                 tf->tf_vm86_es = tf->tf_es;
991                 tf->tf_vm86_fs = tf->tf_fs;
992                 tf->tf_vm86_gs = ucp->uc_mcontext.mc_gs;
993                 tf->tf_ds = _udatasel;
994                 tf->tf_es = _udatasel;
995                 tf->tf_fs = _udatasel;
996         } else {
997                 /*
998                  * Don't allow users to change privileged or reserved flags.
999                  */
1000                 if (!EFL_SECURE(eflags, regs->tf_eflags)) {
1001                         uprintf("pid %d (%s): freebsd4_sigreturn eflags = 0x%x\n",
1002                             td->td_proc->p_pid, td->td_name, eflags);
1003                         return (EINVAL);
1004                 }
1005
1006                 /*
1007                  * Don't allow users to load a valid privileged %cs.  Let the
1008                  * hardware check for invalid selectors, excess privilege in
1009                  * other selectors, invalid %eip's and invalid %esp's.
1010                  */
1011                 cs = ucp->uc_mcontext.mc_cs;
1012                 if (!CS_SECURE(cs)) {
1013                         uprintf("pid %d (%s): freebsd4_sigreturn cs = 0x%x\n",
1014                             td->td_proc->p_pid, td->td_name, cs);
1015                         ksiginfo_init_trap(&ksi);
1016                         ksi.ksi_signo = SIGBUS;
1017                         ksi.ksi_code = BUS_OBJERR;
1018                         ksi.ksi_trapno = T_PROTFLT;
1019                         ksi.ksi_addr = (void *)regs->tf_eip;
1020                         trapsignal(td, &ksi);
1021                         return (EINVAL);
1022                 }
1023
1024                 bcopy(&ucp->uc_mcontext.mc_fs, regs, sizeof(*regs));
1025         }
1026
1027 #if defined(COMPAT_43)
1028         if (ucp->uc_mcontext.mc_onstack & 1)
1029                 td->td_sigstk.ss_flags |= SS_ONSTACK;
1030         else
1031                 td->td_sigstk.ss_flags &= ~SS_ONSTACK;
1032 #endif
1033         kern_sigprocmask(td, SIG_SETMASK, &ucp->uc_sigmask, NULL, 0);
1034         return (EJUSTRETURN);
1035 }
1036 #endif  /* COMPAT_FREEBSD4 */
1037
1038 /*
1039  * MPSAFE
1040  */
1041 int
1042 sys_sigreturn(td, uap)
1043         struct thread *td;
1044         struct sigreturn_args /* {
1045                 const struct __ucontext *sigcntxp;
1046         } */ *uap;
1047 {
1048         ucontext_t uc;
1049         struct proc *p;
1050         struct trapframe *regs;
1051         ucontext_t *ucp;
1052         char *xfpustate;
1053         size_t xfpustate_len;
1054         int cs, eflags, error, ret;
1055         ksiginfo_t ksi;
1056
1057         p = td->td_proc;
1058
1059         error = copyin(uap->sigcntxp, &uc, sizeof(uc));
1060         if (error != 0)
1061                 return (error);
1062         ucp = &uc;
1063         if ((ucp->uc_mcontext.mc_flags & ~_MC_FLAG_MASK) != 0) {
1064                 uprintf("pid %d (%s): sigreturn mc_flags %x\n", p->p_pid,
1065                     td->td_name, ucp->uc_mcontext.mc_flags);
1066                 return (EINVAL);
1067         }
1068         regs = td->td_frame;
1069         eflags = ucp->uc_mcontext.mc_eflags;
1070         if (eflags & PSL_VM) {
1071                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
1072                 struct vm86_kernel *vm86;
1073
1074                 /*
1075                  * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
1076                  * set up the vm86 area, and we can't enter vm86 mode.
1077                  */
1078                 if (td->td_pcb->pcb_ext == 0)
1079                         return (EINVAL);
1080                 vm86 = &td->td_pcb->pcb_ext->ext_vm86;
1081                 if (vm86->vm86_inited == 0)
1082                         return (EINVAL);
1083
1084                 /* Go back to user mode if both flags are set. */
1085                 if ((eflags & PSL_VIP) && (eflags & PSL_VIF)) {
1086                         ksiginfo_init_trap(&ksi);
1087                         ksi.ksi_signo = SIGBUS;
1088                         ksi.ksi_code = BUS_OBJERR;
1089                         ksi.ksi_addr = (void *)regs->tf_eip;
1090                         trapsignal(td, &ksi);
1091                 }
1092
1093                 if (vm86->vm86_has_vme) {
1094                         eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
1095                             (eflags & VME_USERCHANGE) | PSL_VM;
1096                 } else {
1097                         vm86->vm86_eflags = eflags;     /* save VIF, VIP */
1098                         eflags = (tf->tf_eflags & ~VM_USERCHANGE) |
1099                             (eflags & VM_USERCHANGE) | PSL_VM;
1100                 }
1101                 bcopy(&ucp->uc_mcontext.mc_fs, tf, sizeof(struct trapframe));
1102                 tf->tf_eflags = eflags;
1103                 tf->tf_vm86_ds = tf->tf_ds;
1104                 tf->tf_vm86_es = tf->tf_es;
1105                 tf->tf_vm86_fs = tf->tf_fs;
1106                 tf->tf_vm86_gs = ucp->uc_mcontext.mc_gs;
1107                 tf->tf_ds = _udatasel;
1108                 tf->tf_es = _udatasel;
1109                 tf->tf_fs = _udatasel;
1110         } else {
1111                 /*
1112                  * Don't allow users to change privileged or reserved flags.
1113                  */
1114                 if (!EFL_SECURE(eflags, regs->tf_eflags)) {
1115                         uprintf("pid %d (%s): sigreturn eflags = 0x%x\n",
1116                             td->td_proc->p_pid, td->td_name, eflags);
1117                         return (EINVAL);
1118                 }
1119
1120                 /*
1121                  * Don't allow users to load a valid privileged %cs.  Let the
1122                  * hardware check for invalid selectors, excess privilege in
1123                  * other selectors, invalid %eip's and invalid %esp's.
1124                  */
1125                 cs = ucp->uc_mcontext.mc_cs;
1126                 if (!CS_SECURE(cs)) {
1127                         uprintf("pid %d (%s): sigreturn cs = 0x%x\n",
1128                             td->td_proc->p_pid, td->td_name, cs);
1129                         ksiginfo_init_trap(&ksi);
1130                         ksi.ksi_signo = SIGBUS;
1131                         ksi.ksi_code = BUS_OBJERR;
1132                         ksi.ksi_trapno = T_PROTFLT;
1133                         ksi.ksi_addr = (void *)regs->tf_eip;
1134                         trapsignal(td, &ksi);
1135                         return (EINVAL);
1136                 }
1137
1138                 if ((uc.uc_mcontext.mc_flags & _MC_HASFPXSTATE) != 0) {
1139                         xfpustate_len = uc.uc_mcontext.mc_xfpustate_len;
1140                         if (xfpustate_len > cpu_max_ext_state_size -
1141                             sizeof(union savefpu)) {
1142                                 uprintf(
1143                             "pid %d (%s): sigreturn xfpusave_len = 0x%zx\n",
1144                                     p->p_pid, td->td_name, xfpustate_len);
1145                                 return (EINVAL);
1146                         }
1147                         xfpustate = __builtin_alloca(xfpustate_len);
1148                         error = copyin((const void *)uc.uc_mcontext.mc_xfpustate,
1149                             xfpustate, xfpustate_len);
1150                         if (error != 0) {
1151                                 uprintf(
1152         "pid %d (%s): sigreturn copying xfpustate failed\n",
1153                                     p->p_pid, td->td_name);
1154                                 return (error);
1155                         }
1156                 } else {
1157                         xfpustate = NULL;
1158                         xfpustate_len = 0;
1159                 }
1160                 ret = set_fpcontext(td, &ucp->uc_mcontext, xfpustate,
1161                     xfpustate_len);
1162                 if (ret != 0)
1163                         return (ret);
1164                 bcopy(&ucp->uc_mcontext.mc_fs, regs, sizeof(*regs));
1165         }
1166
1167 #if defined(COMPAT_43)
1168         if (ucp->uc_mcontext.mc_onstack & 1)
1169                 td->td_sigstk.ss_flags |= SS_ONSTACK;
1170         else
1171                 td->td_sigstk.ss_flags &= ~SS_ONSTACK;
1172 #endif
1173
1174         kern_sigprocmask(td, SIG_SETMASK, &ucp->uc_sigmask, NULL, 0);
1175         return (EJUSTRETURN);
1176 }
1177
1178 /*
1179  * Reset registers to default values on exec.
1180  */
1181 void
1182 exec_setregs(struct thread *td, struct image_params *imgp, u_long stack)
1183 {
1184         struct trapframe *regs = td->td_frame;
1185         struct pcb *pcb = td->td_pcb;
1186
1187         /* Reset pc->pcb_gs and %gs before possibly invalidating it. */
1188         pcb->pcb_gs = _udatasel;
1189         load_gs(_udatasel);
1190
1191         mtx_lock_spin(&dt_lock);
1192         if (td->td_proc->p_md.md_ldt)
1193                 user_ldt_free(td);
1194         else
1195                 mtx_unlock_spin(&dt_lock);
1196   
1197         bzero((char *)regs, sizeof(struct trapframe));
1198         regs->tf_eip = imgp->entry_addr;
1199         regs->tf_esp = stack;
1200         regs->tf_eflags = PSL_USER | (regs->tf_eflags & PSL_T);
1201         regs->tf_ss = _udatasel;
1202         regs->tf_ds = _udatasel;
1203         regs->tf_es = _udatasel;
1204         regs->tf_fs = _udatasel;
1205         regs->tf_cs = _ucodesel;
1206
1207         /* PS_STRINGS value for BSD/OS binaries.  It is 0 for non-BSD/OS. */
1208         regs->tf_ebx = imgp->ps_strings;
1209
1210         /*
1211          * Reset the hardware debug registers if they were in use.
1212          * They won't have any meaning for the newly exec'd process.  
1213          */
1214         if (pcb->pcb_flags & PCB_DBREGS) {
1215                 pcb->pcb_dr0 = 0;
1216                 pcb->pcb_dr1 = 0;
1217                 pcb->pcb_dr2 = 0;
1218                 pcb->pcb_dr3 = 0;
1219                 pcb->pcb_dr6 = 0;
1220                 pcb->pcb_dr7 = 0;
1221                 if (pcb == curpcb) {
1222                         /*
1223                          * Clear the debug registers on the running
1224                          * CPU, otherwise they will end up affecting
1225                          * the next process we switch to.
1226                          */
1227                         reset_dbregs();
1228                 }
1229                 pcb->pcb_flags &= ~PCB_DBREGS;
1230         }
1231
1232         pcb->pcb_initial_npxcw = __INITIAL_NPXCW__;
1233
1234         /*
1235          * Drop the FP state if we hold it, so that the process gets a
1236          * clean FP state if it uses the FPU again.
1237          */
1238         fpstate_drop(td);
1239
1240         /*
1241          * XXX - Linux emulator
1242          * Make sure sure edx is 0x0 on entry. Linux binaries depend
1243          * on it.
1244          */
1245         td->td_retval[1] = 0;
1246 }
1247
1248 void
1249 cpu_setregs(void)
1250 {
1251         unsigned int cr0;
1252
1253         cr0 = rcr0();
1254
1255         /*
1256          * CR0_MP, CR0_NE and CR0_TS are set for NPX (FPU) support:
1257          *
1258          * Prepare to trap all ESC (i.e., NPX) instructions and all WAIT
1259          * instructions.  We must set the CR0_MP bit and use the CR0_TS
1260          * bit to control the trap, because setting the CR0_EM bit does
1261          * not cause WAIT instructions to trap.  It's important to trap
1262          * WAIT instructions - otherwise the "wait" variants of no-wait
1263          * control instructions would degenerate to the "no-wait" variants
1264          * after FP context switches but work correctly otherwise.  It's
1265          * particularly important to trap WAITs when there is no NPX -
1266          * otherwise the "wait" variants would always degenerate.
1267          *
1268          * Try setting CR0_NE to get correct error reporting on 486DX's.
1269          * Setting it should fail or do nothing on lesser processors.
1270          */
1271         cr0 |= CR0_MP | CR0_NE | CR0_TS | CR0_WP | CR0_AM;
1272         load_cr0(cr0);
1273         load_gs(_udatasel);
1274 }
1275
1276 u_long bootdev;         /* not a struct cdev *- encoding is different */
1277 SYSCTL_ULONG(_machdep, OID_AUTO, guessed_bootdev,
1278         CTLFLAG_RD, &bootdev, 0, "Maybe the Boot device (not in struct cdev *format)");
1279
1280 static char bootmethod[16] = "BIOS";
1281 SYSCTL_STRING(_machdep, OID_AUTO, bootmethod, CTLFLAG_RD, bootmethod, 0,
1282     "System firmware boot method");
1283
1284 /*
1285  * Initialize 386 and configure to run kernel
1286  */
1287
1288 /*
1289  * Initialize segments & interrupt table
1290  */
1291
1292 int _default_ldt;
1293
1294 #ifdef XEN
1295 union descriptor *gdt;
1296 union descriptor *ldt;
1297 #else
1298 union descriptor gdt[NGDT * MAXCPU];    /* global descriptor table */
1299 union descriptor ldt[NLDT];             /* local descriptor table */
1300 #endif
1301 static struct gate_descriptor idt0[NIDT];
1302 struct gate_descriptor *idt = &idt0[0]; /* interrupt descriptor table */
1303 struct region_descriptor r_gdt, r_idt;  /* table descriptors */
1304 struct mtx dt_lock;                     /* lock for GDT and LDT */
1305
1306 static struct i386tss dblfault_tss;
1307 static char dblfault_stack[PAGE_SIZE];
1308
1309 extern  vm_offset_t     proc0kstack;
1310
1311
1312 /*
1313  * software prototypes -- in more palatable form.
1314  *
1315  * GCODE_SEL through GUDATA_SEL must be in this order for syscall/sysret
1316  * GUFS_SEL and GUGS_SEL must be in this order (swtch.s knows it)
1317  */
1318 struct soft_segment_descriptor gdt_segs[] = {
1319 /* GNULL_SEL    0 Null Descriptor */
1320 {       .ssd_base = 0x0,
1321         .ssd_limit = 0x0,
1322         .ssd_type = 0,
1323         .ssd_dpl = SEL_KPL,
1324         .ssd_p = 0,
1325         .ssd_xx = 0, .ssd_xx1 = 0,
1326         .ssd_def32 = 0,
1327         .ssd_gran = 0           },
1328 /* GPRIV_SEL    1 SMP Per-Processor Private Data Descriptor */
1329 {       .ssd_base = 0x0,
1330         .ssd_limit = 0xfffff,
1331         .ssd_type = SDT_MEMRWA,
1332         .ssd_dpl = SEL_KPL,
1333         .ssd_p = 1,
1334         .ssd_xx = 0, .ssd_xx1 = 0,
1335         .ssd_def32 = 1,
1336         .ssd_gran = 1           },
1337 /* GUFS_SEL     2 %fs Descriptor for user */
1338 {       .ssd_base = 0x0,
1339         .ssd_limit = 0xfffff,
1340         .ssd_type = SDT_MEMRWA,
1341         .ssd_dpl = SEL_UPL,
1342         .ssd_p = 1,
1343         .ssd_xx = 0, .ssd_xx1 = 0,
1344         .ssd_def32 = 1,
1345         .ssd_gran = 1           },
1346 /* GUGS_SEL     3 %gs Descriptor for user */
1347 {       .ssd_base = 0x0,
1348         .ssd_limit = 0xfffff,
1349         .ssd_type = SDT_MEMRWA,
1350         .ssd_dpl = SEL_UPL,
1351         .ssd_p = 1,
1352         .ssd_xx = 0, .ssd_xx1 = 0,
1353         .ssd_def32 = 1,
1354         .ssd_gran = 1           },
1355 /* GCODE_SEL    4 Code Descriptor for kernel */
1356 {       .ssd_base = 0x0,
1357         .ssd_limit = 0xfffff,
1358         .ssd_type = SDT_MEMERA,
1359         .ssd_dpl = SEL_KPL,
1360         .ssd_p = 1,
1361         .ssd_xx = 0, .ssd_xx1 = 0,
1362         .ssd_def32 = 1,
1363         .ssd_gran = 1           },
1364 /* GDATA_SEL    5 Data Descriptor for kernel */
1365 {       .ssd_base = 0x0,
1366         .ssd_limit = 0xfffff,
1367         .ssd_type = SDT_MEMRWA,
1368         .ssd_dpl = SEL_KPL,
1369         .ssd_p = 1,
1370         .ssd_xx = 0, .ssd_xx1 = 0,
1371         .ssd_def32 = 1,
1372         .ssd_gran = 1           },
1373 /* GUCODE_SEL   6 Code Descriptor for user */
1374 {       .ssd_base = 0x0,
1375         .ssd_limit = 0xfffff,
1376         .ssd_type = SDT_MEMERA,
1377         .ssd_dpl = SEL_UPL,
1378         .ssd_p = 1,
1379         .ssd_xx = 0, .ssd_xx1 = 0,
1380         .ssd_def32 = 1,
1381         .ssd_gran = 1           },
1382 /* GUDATA_SEL   7 Data Descriptor for user */
1383 {       .ssd_base = 0x0,
1384         .ssd_limit = 0xfffff,
1385         .ssd_type = SDT_MEMRWA,
1386         .ssd_dpl = SEL_UPL,
1387         .ssd_p = 1,
1388         .ssd_xx = 0, .ssd_xx1 = 0,
1389         .ssd_def32 = 1,
1390         .ssd_gran = 1           },
1391 /* GBIOSLOWMEM_SEL 8 BIOS access to realmode segment 0x40, must be #8 in GDT */
1392 {       .ssd_base = 0x400,
1393         .ssd_limit = 0xfffff,
1394         .ssd_type = SDT_MEMRWA,
1395         .ssd_dpl = SEL_KPL,
1396         .ssd_p = 1,
1397         .ssd_xx = 0, .ssd_xx1 = 0,
1398         .ssd_def32 = 1,
1399         .ssd_gran = 1           },
1400 #ifndef XEN
1401 /* GPROC0_SEL   9 Proc 0 Tss Descriptor */
1402 {
1403         .ssd_base = 0x0,
1404         .ssd_limit = sizeof(struct i386tss)-1,
1405         .ssd_type = SDT_SYS386TSS,
1406         .ssd_dpl = 0,
1407         .ssd_p = 1,
1408         .ssd_xx = 0, .ssd_xx1 = 0,
1409         .ssd_def32 = 0,
1410         .ssd_gran = 0           },
1411 /* GLDT_SEL     10 LDT Descriptor */
1412 {       .ssd_base = (int) ldt,
1413         .ssd_limit = sizeof(ldt)-1,
1414         .ssd_type = SDT_SYSLDT,
1415         .ssd_dpl = SEL_UPL,
1416         .ssd_p = 1,
1417         .ssd_xx = 0, .ssd_xx1 = 0,
1418         .ssd_def32 = 0,
1419         .ssd_gran = 0           },
1420 /* GUSERLDT_SEL 11 User LDT Descriptor per process */
1421 {       .ssd_base = (int) ldt,
1422         .ssd_limit = (512 * sizeof(union descriptor)-1),
1423         .ssd_type = SDT_SYSLDT,
1424         .ssd_dpl = 0,
1425         .ssd_p = 1,
1426         .ssd_xx = 0, .ssd_xx1 = 0,
1427         .ssd_def32 = 0,
1428         .ssd_gran = 0           },
1429 /* GPANIC_SEL   12 Panic Tss Descriptor */
1430 {       .ssd_base = (int) &dblfault_tss,
1431         .ssd_limit = sizeof(struct i386tss)-1,
1432         .ssd_type = SDT_SYS386TSS,
1433         .ssd_dpl = 0,
1434         .ssd_p = 1,
1435         .ssd_xx = 0, .ssd_xx1 = 0,
1436         .ssd_def32 = 0,
1437         .ssd_gran = 0           },
1438 /* GBIOSCODE32_SEL 13 BIOS 32-bit interface (32bit Code) */
1439 {       .ssd_base = 0,
1440         .ssd_limit = 0xfffff,
1441         .ssd_type = SDT_MEMERA,
1442         .ssd_dpl = 0,
1443         .ssd_p = 1,
1444         .ssd_xx = 0, .ssd_xx1 = 0,
1445         .ssd_def32 = 0,
1446         .ssd_gran = 1           },
1447 /* GBIOSCODE16_SEL 14 BIOS 32-bit interface (16bit Code) */
1448 {       .ssd_base = 0,
1449         .ssd_limit = 0xfffff,
1450         .ssd_type = SDT_MEMERA,
1451         .ssd_dpl = 0,
1452         .ssd_p = 1,
1453         .ssd_xx = 0, .ssd_xx1 = 0,
1454         .ssd_def32 = 0,
1455         .ssd_gran = 1           },
1456 /* GBIOSDATA_SEL 15 BIOS 32-bit interface (Data) */
1457 {       .ssd_base = 0,
1458         .ssd_limit = 0xfffff,
1459         .ssd_type = SDT_MEMRWA,
1460         .ssd_dpl = 0,
1461         .ssd_p = 1,
1462         .ssd_xx = 0, .ssd_xx1 = 0,
1463         .ssd_def32 = 1,
1464         .ssd_gran = 1           },
1465 /* GBIOSUTIL_SEL 16 BIOS 16-bit interface (Utility) */
1466 {       .ssd_base = 0,
1467         .ssd_limit = 0xfffff,
1468         .ssd_type = SDT_MEMRWA,
1469         .ssd_dpl = 0,
1470         .ssd_p = 1,
1471         .ssd_xx = 0, .ssd_xx1 = 0,
1472         .ssd_def32 = 0,
1473         .ssd_gran = 1           },
1474 /* GBIOSARGS_SEL 17 BIOS 16-bit interface (Arguments) */
1475 {       .ssd_base = 0,
1476         .ssd_limit = 0xfffff,
1477         .ssd_type = SDT_MEMRWA,
1478         .ssd_dpl = 0,
1479         .ssd_p = 1,
1480         .ssd_xx = 0, .ssd_xx1 = 0,
1481         .ssd_def32 = 0,
1482         .ssd_gran = 1           },
1483 /* GNDIS_SEL    18 NDIS Descriptor */
1484 {       .ssd_base = 0x0,
1485         .ssd_limit = 0x0,
1486         .ssd_type = 0,
1487         .ssd_dpl = 0,
1488         .ssd_p = 0,
1489         .ssd_xx = 0, .ssd_xx1 = 0,
1490         .ssd_def32 = 0,
1491         .ssd_gran = 0           },
1492 #endif /* !XEN */
1493 };
1494
1495 static struct soft_segment_descriptor ldt_segs[] = {
1496         /* Null Descriptor - overwritten by call gate */
1497 {       .ssd_base = 0x0,
1498         .ssd_limit = 0x0,
1499         .ssd_type = 0,
1500         .ssd_dpl = 0,
1501         .ssd_p = 0,
1502         .ssd_xx = 0, .ssd_xx1 = 0,
1503         .ssd_def32 = 0,
1504         .ssd_gran = 0           },
1505         /* Null Descriptor - overwritten by call gate */
1506 {       .ssd_base = 0x0,
1507         .ssd_limit = 0x0,
1508         .ssd_type = 0,
1509         .ssd_dpl = 0,
1510         .ssd_p = 0,
1511         .ssd_xx = 0, .ssd_xx1 = 0,
1512         .ssd_def32 = 0,
1513         .ssd_gran = 0           },
1514         /* Null Descriptor - overwritten by call gate */
1515 {       .ssd_base = 0x0,
1516         .ssd_limit = 0x0,
1517         .ssd_type = 0,
1518         .ssd_dpl = 0,
1519         .ssd_p = 0,
1520         .ssd_xx = 0, .ssd_xx1 = 0,
1521         .ssd_def32 = 0,
1522         .ssd_gran = 0           },
1523         /* Code Descriptor for user */
1524 {       .ssd_base = 0x0,
1525         .ssd_limit = 0xfffff,
1526         .ssd_type = SDT_MEMERA,
1527         .ssd_dpl = SEL_UPL,
1528         .ssd_p = 1,
1529         .ssd_xx = 0, .ssd_xx1 = 0,
1530         .ssd_def32 = 1,
1531         .ssd_gran = 1           },
1532         /* Null Descriptor - overwritten by call gate */
1533 {       .ssd_base = 0x0,
1534         .ssd_limit = 0x0,
1535         .ssd_type = 0,
1536         .ssd_dpl = 0,
1537         .ssd_p = 0,
1538         .ssd_xx = 0, .ssd_xx1 = 0,
1539         .ssd_def32 = 0,
1540         .ssd_gran = 0           },
1541         /* Data Descriptor for user */
1542 {       .ssd_base = 0x0,
1543         .ssd_limit = 0xfffff,
1544         .ssd_type = SDT_MEMRWA,
1545         .ssd_dpl = SEL_UPL,
1546         .ssd_p = 1,
1547         .ssd_xx = 0, .ssd_xx1 = 0,
1548         .ssd_def32 = 1,
1549         .ssd_gran = 1           },
1550 };
1551
1552 void
1553 setidt(idx, func, typ, dpl, selec)
1554         int idx;
1555         inthand_t *func;
1556         int typ;
1557         int dpl;
1558         int selec;
1559 {
1560         struct gate_descriptor *ip;
1561
1562         ip = idt + idx;
1563         ip->gd_looffset = (int)func;
1564         ip->gd_selector = selec;
1565         ip->gd_stkcpy = 0;
1566         ip->gd_xx = 0;
1567         ip->gd_type = typ;
1568         ip->gd_dpl = dpl;
1569         ip->gd_p = 1;
1570         ip->gd_hioffset = ((int)func)>>16 ;
1571 }
1572
1573 extern inthand_t
1574         IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
1575         IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
1576         IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
1577         IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
1578         IDTVEC(xmm),
1579 #ifdef KDTRACE_HOOKS
1580         IDTVEC(dtrace_ret),
1581 #endif
1582 #ifdef XENHVM
1583         IDTVEC(xen_intr_upcall),
1584 #endif
1585         IDTVEC(lcall_syscall), IDTVEC(int0x80_syscall);
1586
1587 #ifdef DDB
1588 /*
1589  * Display the index and function name of any IDT entries that don't use
1590  * the default 'rsvd' entry point.
1591  */
1592 DB_SHOW_COMMAND(idt, db_show_idt)
1593 {
1594         struct gate_descriptor *ip;
1595         int idx;
1596         uintptr_t func;
1597
1598         ip = idt;
1599         for (idx = 0; idx < NIDT && !db_pager_quit; idx++) {
1600                 func = (ip->gd_hioffset << 16 | ip->gd_looffset);
1601                 if (func != (uintptr_t)&IDTVEC(rsvd)) {
1602                         db_printf("%3d\t", idx);
1603                         db_printsym(func, DB_STGY_PROC);
1604                         db_printf("\n");
1605                 }
1606                 ip++;
1607         }
1608 }
1609
1610 /* Show privileged registers. */
1611 DB_SHOW_COMMAND(sysregs, db_show_sysregs)
1612 {
1613         uint64_t idtr, gdtr;
1614
1615         idtr = ridt();
1616         db_printf("idtr\t0x%08x/%04x\n",
1617             (u_int)(idtr >> 16), (u_int)idtr & 0xffff);
1618         gdtr = rgdt();
1619         db_printf("gdtr\t0x%08x/%04x\n",
1620             (u_int)(gdtr >> 16), (u_int)gdtr & 0xffff);
1621         db_printf("ldtr\t0x%04x\n", rldt());
1622         db_printf("tr\t0x%04x\n", rtr());
1623         db_printf("cr0\t0x%08x\n", rcr0());
1624         db_printf("cr2\t0x%08x\n", rcr2());
1625         db_printf("cr3\t0x%08x\n", rcr3());
1626         db_printf("cr4\t0x%08x\n", rcr4());
1627 }
1628 #endif
1629
1630 void
1631 sdtossd(sd, ssd)
1632         struct segment_descriptor *sd;
1633         struct soft_segment_descriptor *ssd;
1634 {
1635         ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
1636         ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
1637         ssd->ssd_type  = sd->sd_type;
1638         ssd->ssd_dpl   = sd->sd_dpl;
1639         ssd->ssd_p     = sd->sd_p;
1640         ssd->ssd_def32 = sd->sd_def32;
1641         ssd->ssd_gran  = sd->sd_gran;
1642 }
1643
1644 #if !defined(PC98) && !defined(XEN)
1645 static int
1646 add_physmap_entry(uint64_t base, uint64_t length, vm_paddr_t *physmap,
1647     int *physmap_idxp)
1648 {
1649         int i, insert_idx, physmap_idx;
1650
1651         physmap_idx = *physmap_idxp;
1652         
1653         if (length == 0)
1654                 return (1);
1655
1656 #ifndef PAE
1657         if (base > 0xffffffff) {
1658                 printf("%uK of memory above 4GB ignored\n",
1659                     (u_int)(length / 1024));
1660                 return (1);
1661         }
1662 #endif
1663
1664         /*
1665          * Find insertion point while checking for overlap.  Start off by
1666          * assuming the new entry will be added to the end.
1667          */
1668         insert_idx = physmap_idx + 2;
1669         for (i = 0; i <= physmap_idx; i += 2) {
1670                 if (base < physmap[i + 1]) {
1671                         if (base + length <= physmap[i]) {
1672                                 insert_idx = i;
1673                                 break;
1674                         }
1675                         if (boothowto & RB_VERBOSE)
1676                                 printf(
1677                     "Overlapping memory regions, ignoring second region\n");
1678                         return (1);
1679                 }
1680         }
1681
1682         /* See if we can prepend to the next entry. */
1683         if (insert_idx <= physmap_idx && base + length == physmap[insert_idx]) {
1684                 physmap[insert_idx] = base;
1685                 return (1);
1686         }
1687
1688         /* See if we can append to the previous entry. */
1689         if (insert_idx > 0 && base == physmap[insert_idx - 1]) {
1690                 physmap[insert_idx - 1] += length;
1691                 return (1);
1692         }
1693
1694         physmap_idx += 2;
1695         *physmap_idxp = physmap_idx;
1696         if (physmap_idx == PHYSMAP_SIZE) {
1697                 printf(
1698                 "Too many segments in the physical address map, giving up\n");
1699                 return (0);
1700         }
1701
1702         /*
1703          * Move the last 'N' entries down to make room for the new
1704          * entry if needed.
1705          */
1706         for (i = physmap_idx; i > insert_idx; i -= 2) {
1707                 physmap[i] = physmap[i - 2];
1708                 physmap[i + 1] = physmap[i - 1];
1709         }
1710
1711         /* Insert the new entry. */
1712         physmap[insert_idx] = base;
1713         physmap[insert_idx + 1] = base + length;
1714         return (1);
1715 }
1716
1717 static int
1718 add_smap_entry(struct bios_smap *smap, vm_paddr_t *physmap, int *physmap_idxp)
1719 {
1720         if (boothowto & RB_VERBOSE)
1721                 printf("SMAP type=%02x base=%016llx len=%016llx\n",
1722                     smap->type, smap->base, smap->length);
1723
1724         if (smap->type != SMAP_TYPE_MEMORY)
1725                 return (1);
1726
1727         return (add_physmap_entry(smap->base, smap->length, physmap,
1728             physmap_idxp));
1729 }
1730
1731 static void
1732 add_smap_entries(struct bios_smap *smapbase, vm_paddr_t *physmap,
1733     int *physmap_idxp)
1734 {
1735         struct bios_smap *smap, *smapend;
1736         u_int32_t smapsize;
1737         /*
1738          * Memory map from INT 15:E820.
1739          *
1740          * subr_module.c says:
1741          * "Consumer may safely assume that size value precedes data."
1742          * ie: an int32_t immediately precedes SMAP.
1743          */
1744         smapsize = *((u_int32_t *)smapbase - 1);
1745         smapend = (struct bios_smap *)((uintptr_t)smapbase + smapsize);
1746
1747         for (smap = smapbase; smap < smapend; smap++)
1748                 if (!add_smap_entry(smap, physmap, physmap_idxp))
1749                         break;
1750 }
1751 #endif /* !PC98 && !XEN */
1752
1753 #ifndef XEN
1754 static void
1755 basemem_setup(void)
1756 {
1757         vm_paddr_t pa;
1758         pt_entry_t *pte;
1759         int i;
1760
1761         if (basemem > 640) {
1762                 printf("Preposterous BIOS basemem of %uK, truncating to 640K\n",
1763                         basemem);
1764                 basemem = 640;
1765         }
1766
1767         /*
1768          * XXX if biosbasemem is now < 640, there is a `hole'
1769          * between the end of base memory and the start of
1770          * ISA memory.  The hole may be empty or it may
1771          * contain BIOS code or data.  Map it read/write so
1772          * that the BIOS can write to it.  (Memory from 0 to
1773          * the physical end of the kernel is mapped read-only
1774          * to begin with and then parts of it are remapped.
1775          * The parts that aren't remapped form holes that
1776          * remain read-only and are unused by the kernel.
1777          * The base memory area is below the physical end of
1778          * the kernel and right now forms a read-only hole.
1779          * The part of it from PAGE_SIZE to
1780          * (trunc_page(biosbasemem * 1024) - 1) will be
1781          * remapped and used by the kernel later.)
1782          *
1783          * This code is similar to the code used in
1784          * pmap_mapdev, but since no memory needs to be
1785          * allocated we simply change the mapping.
1786          */
1787         for (pa = trunc_page(basemem * 1024);
1788              pa < ISA_HOLE_START; pa += PAGE_SIZE)
1789                 pmap_kenter(KERNBASE + pa, pa);
1790
1791         /*
1792          * Map pages between basemem and ISA_HOLE_START, if any, r/w into
1793          * the vm86 page table so that vm86 can scribble on them using
1794          * the vm86 map too.  XXX: why 2 ways for this and only 1 way for
1795          * page 0, at least as initialized here?
1796          */
1797         pte = (pt_entry_t *)vm86paddr;
1798         for (i = basemem / 4; i < 160; i++)
1799                 pte[i] = (i << PAGE_SHIFT) | PG_V | PG_RW | PG_U;
1800 }
1801 #endif /* !XEN */
1802
1803 /*
1804  * Populate the (physmap) array with base/bound pairs describing the
1805  * available physical memory in the system, then test this memory and
1806  * build the phys_avail array describing the actually-available memory.
1807  *
1808  * If we cannot accurately determine the physical memory map, then use
1809  * value from the 0xE801 call, and failing that, the RTC.
1810  *
1811  * Total memory size may be set by the kernel environment variable
1812  * hw.physmem or the compile-time define MAXMEM.
1813  *
1814  * XXX first should be vm_paddr_t.
1815  */
1816 #ifdef PC98
1817 static void
1818 getmemsize(int first)
1819 {
1820         int off, physmap_idx, pa_indx, da_indx;
1821         u_long physmem_tunable, memtest;
1822         vm_paddr_t physmap[PHYSMAP_SIZE];
1823         pt_entry_t *pte;
1824         quad_t dcons_addr, dcons_size;
1825         int i;
1826         int pg_n;
1827         u_int extmem;
1828         u_int under16;
1829         vm_paddr_t pa;
1830
1831         bzero(physmap, sizeof(physmap));
1832
1833         /* XXX - some of EPSON machines can't use PG_N */
1834         pg_n = PG_N;
1835         if (pc98_machine_type & M_EPSON_PC98) {
1836                 switch (epson_machine_id) {
1837 #ifdef WB_CACHE
1838                 default:
1839 #endif
1840                 case EPSON_PC486_HX:
1841                 case EPSON_PC486_HG:
1842                 case EPSON_PC486_HA:
1843                         pg_n = 0;
1844                         break;
1845                 }
1846         }
1847
1848         under16 = pc98_getmemsize(&basemem, &extmem);
1849         basemem_setup();
1850
1851         physmap[0] = 0;
1852         physmap[1] = basemem * 1024;
1853         physmap_idx = 2;
1854         physmap[physmap_idx] = 0x100000;
1855         physmap[physmap_idx + 1] = physmap[physmap_idx] + extmem * 1024;
1856
1857         /*
1858          * Now, physmap contains a map of physical memory.
1859          */
1860
1861 #ifdef SMP
1862         /* make hole for AP bootstrap code */
1863         physmap[1] = mp_bootaddress(physmap[1]);
1864 #endif
1865
1866         /*
1867          * Maxmem isn't the "maximum memory", it's one larger than the
1868          * highest page of the physical address space.  It should be
1869          * called something like "Maxphyspage".  We may adjust this 
1870          * based on ``hw.physmem'' and the results of the memory test.
1871          */
1872         Maxmem = atop(physmap[physmap_idx + 1]);
1873
1874 #ifdef MAXMEM
1875         Maxmem = MAXMEM / 4;
1876 #endif
1877
1878         if (TUNABLE_ULONG_FETCH("hw.physmem", &physmem_tunable))
1879                 Maxmem = atop(physmem_tunable);
1880
1881         /*
1882          * By default keep the memtest enabled.  Use a general name so that
1883          * one could eventually do more with the code than just disable it.
1884          */
1885         memtest = 1;
1886         TUNABLE_ULONG_FETCH("hw.memtest.tests", &memtest);
1887
1888         if (atop(physmap[physmap_idx + 1]) != Maxmem &&
1889             (boothowto & RB_VERBOSE))
1890                 printf("Physical memory use set to %ldK\n", Maxmem * 4);
1891
1892         /*
1893          * If Maxmem has been increased beyond what the system has detected,
1894          * extend the last memory segment to the new limit.
1895          */ 
1896         if (atop(physmap[physmap_idx + 1]) < Maxmem)
1897                 physmap[physmap_idx + 1] = ptoa((vm_paddr_t)Maxmem);
1898
1899         /*
1900          * We need to divide chunk if Maxmem is larger than 16MB and
1901          * under 16MB area is not full of memory.
1902          * (1) system area (15-16MB region) is cut off
1903          * (2) extended memory is only over 16MB area (ex. Melco "HYPERMEMORY")
1904          */
1905         if ((under16 != 16 * 1024) && (extmem > 15 * 1024)) {
1906                 /* 15M - 16M region is cut off, so need to divide chunk */
1907                 physmap[physmap_idx + 1] = under16 * 1024;
1908                 physmap_idx += 2;
1909                 physmap[physmap_idx] = 0x1000000;
1910                 physmap[physmap_idx + 1] = physmap[2] + extmem * 1024;
1911         }
1912
1913         /* call pmap initialization to make new kernel address space */
1914         pmap_bootstrap(first);
1915
1916         /*
1917          * Size up each available chunk of physical memory.
1918          */
1919         physmap[0] = PAGE_SIZE;         /* mask off page 0 */
1920         pa_indx = 0;
1921         da_indx = 1;
1922         phys_avail[pa_indx++] = physmap[0];
1923         phys_avail[pa_indx] = physmap[0];
1924         dump_avail[da_indx] = physmap[0];
1925         pte = CMAP3;
1926
1927         /*
1928          * Get dcons buffer address
1929          */
1930         if (getenv_quad("dcons.addr", &dcons_addr) == 0 ||
1931             getenv_quad("dcons.size", &dcons_size) == 0)
1932                 dcons_addr = 0;
1933
1934         /*
1935          * physmap is in bytes, so when converting to page boundaries,
1936          * round up the start address and round down the end address.
1937          */
1938         for (i = 0; i <= physmap_idx; i += 2) {
1939                 vm_paddr_t end;
1940
1941                 end = ptoa((vm_paddr_t)Maxmem);
1942                 if (physmap[i + 1] < end)
1943                         end = trunc_page(physmap[i + 1]);
1944                 for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
1945                         int tmp, page_bad, full;
1946                         int *ptr = (int *)CADDR3;
1947
1948                         full = FALSE;
1949                         /*
1950                          * block out kernel memory as not available.
1951                          */
1952                         if (pa >= KERNLOAD && pa < first)
1953                                 goto do_dump_avail;
1954
1955                         /*
1956                          * block out dcons buffer
1957                          */
1958                         if (dcons_addr > 0
1959                             && pa >= trunc_page(dcons_addr)
1960                             && pa < dcons_addr + dcons_size)
1961                                 goto do_dump_avail;
1962
1963                         page_bad = FALSE;
1964                         if (memtest == 0)
1965                                 goto skip_memtest;
1966
1967                         /*
1968                          * map page into kernel: valid, read/write,non-cacheable
1969                          */
1970                         *pte = pa | PG_V | PG_RW | pg_n;
1971                         invltlb();
1972
1973                         tmp = *(int *)ptr;
1974                         /*
1975                          * Test for alternating 1's and 0's
1976                          */
1977                         *(volatile int *)ptr = 0xaaaaaaaa;
1978                         if (*(volatile int *)ptr != 0xaaaaaaaa)
1979                                 page_bad = TRUE;
1980                         /*
1981                          * Test for alternating 0's and 1's
1982                          */
1983                         *(volatile int *)ptr = 0x55555555;
1984                         if (*(volatile int *)ptr != 0x55555555)
1985                                 page_bad = TRUE;
1986                         /*
1987                          * Test for all 1's
1988                          */
1989                         *(volatile int *)ptr = 0xffffffff;
1990                         if (*(volatile int *)ptr != 0xffffffff)
1991                                 page_bad = TRUE;
1992                         /*
1993                          * Test for all 0's
1994                          */
1995                         *(volatile int *)ptr = 0x0;
1996                         if (*(volatile int *)ptr != 0x0)
1997                                 page_bad = TRUE;
1998                         /*
1999                          * Restore original value.
2000                          */
2001                         *(int *)ptr = tmp;
2002
2003 skip_memtest:
2004                         /*
2005                          * Adjust array of valid/good pages.
2006                          */
2007                         if (page_bad == TRUE)
2008                                 continue;
2009                         /*
2010                          * If this good page is a continuation of the
2011                          * previous set of good pages, then just increase
2012                          * the end pointer. Otherwise start a new chunk.
2013                          * Note that "end" points one higher than end,
2014                          * making the range >= start and < end.
2015                          * If we're also doing a speculative memory
2016                          * test and we at or past the end, bump up Maxmem
2017                          * so that we keep going. The first bad page
2018                          * will terminate the loop.
2019                          */
2020                         if (phys_avail[pa_indx] == pa) {
2021                                 phys_avail[pa_indx] += PAGE_SIZE;
2022                         } else {
2023                                 pa_indx++;
2024                                 if (pa_indx == PHYS_AVAIL_ARRAY_END) {
2025                                         printf(
2026                 "Too many holes in the physical address space, giving up\n");
2027                                         pa_indx--;
2028                                         full = TRUE;
2029                                         goto do_dump_avail;
2030                                 }
2031                                 phys_avail[pa_indx++] = pa;     /* start */
2032                                 phys_avail[pa_indx] = pa + PAGE_SIZE; /* end */
2033                         }
2034                         physmem++;
2035 do_dump_avail:
2036                         if (dump_avail[da_indx] == pa) {
2037                                 dump_avail[da_indx] += PAGE_SIZE;
2038                         } else {
2039                                 da_indx++;
2040                                 if (da_indx == DUMP_AVAIL_ARRAY_END) {
2041                                         da_indx--;
2042                                         goto do_next;
2043                                 }
2044                                 dump_avail[da_indx++] = pa;     /* start */
2045                                 dump_avail[da_indx] = pa + PAGE_SIZE; /* end */
2046                         }
2047 do_next:
2048                         if (full)
2049                                 break;
2050                 }
2051         }
2052         *pte = 0;
2053         invltlb();
2054         
2055         /*
2056          * XXX
2057          * The last chunk must contain at least one page plus the message
2058          * buffer to avoid complicating other code (message buffer address
2059          * calculation, etc.).
2060          */
2061         while (phys_avail[pa_indx - 1] + PAGE_SIZE +
2062             round_page(msgbufsize) >= phys_avail[pa_indx]) {
2063                 physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
2064                 phys_avail[pa_indx--] = 0;
2065                 phys_avail[pa_indx--] = 0;
2066         }
2067
2068         Maxmem = atop(phys_avail[pa_indx]);
2069
2070         /* Trim off space for the message buffer. */
2071         phys_avail[pa_indx] -= round_page(msgbufsize);
2072
2073         /* Map the message buffer. */
2074         for (off = 0; off < round_page(msgbufsize); off += PAGE_SIZE)
2075                 pmap_kenter((vm_offset_t)msgbufp + off, phys_avail[pa_indx] +
2076                     off);
2077
2078         PT_UPDATES_FLUSH();
2079 }
2080 #else /* PC98 */
2081 static void
2082 getmemsize(int first)
2083 {
2084         int has_smap, off, physmap_idx, pa_indx, da_indx;
2085         u_long memtest;
2086         vm_paddr_t physmap[PHYSMAP_SIZE];
2087         pt_entry_t *pte;
2088         quad_t dcons_addr, dcons_size, physmem_tunable;
2089 #ifndef XEN
2090         int hasbrokenint12, i, res;
2091         u_int extmem;
2092         struct vm86frame vmf;
2093         struct vm86context vmc;
2094         vm_paddr_t pa;
2095         struct bios_smap *smap, *smapbase;
2096         caddr_t kmdp;
2097 #endif
2098
2099         has_smap = 0;
2100 #if defined(XEN)
2101         Maxmem = xen_start_info->nr_pages - init_first;
2102         physmem = Maxmem;
2103         basemem = 0;
2104         physmap[0] = init_first << PAGE_SHIFT;
2105         physmap[1] = ptoa(Maxmem) - round_page(msgbufsize);
2106         physmap_idx = 0;
2107 #else
2108 #ifdef XBOX
2109         if (arch_i386_is_xbox) {
2110                 /*
2111                  * We queried the memory size before, so chop off 4MB for
2112                  * the framebuffer and inform the OS of this.
2113                  */
2114                 physmap[0] = 0;
2115                 physmap[1] = (arch_i386_xbox_memsize * 1024 * 1024) - XBOX_FB_SIZE;
2116                 physmap_idx = 0;
2117                 goto physmap_done;
2118         }
2119 #endif
2120         bzero(&vmf, sizeof(vmf));
2121         bzero(physmap, sizeof(physmap));
2122         basemem = 0;
2123
2124         /*
2125          * Check if the loader supplied an SMAP memory map.  If so,
2126          * use that and do not make any VM86 calls.
2127          */
2128         physmap_idx = 0;
2129         smapbase = NULL;
2130         kmdp = preload_search_by_type("elf kernel");
2131         if (kmdp == NULL)
2132                 kmdp = preload_search_by_type("elf32 kernel");
2133         if (kmdp != NULL)
2134                 smapbase = (struct bios_smap *)preload_search_info(kmdp,
2135                     MODINFO_METADATA | MODINFOMD_SMAP);
2136         if (smapbase != NULL) {
2137                 add_smap_entries(smapbase, physmap, &physmap_idx);
2138                 has_smap = 1;
2139                 goto have_smap;
2140         }
2141
2142         /*
2143          * Some newer BIOSes have a broken INT 12H implementation
2144          * which causes a kernel panic immediately.  In this case, we
2145          * need use the SMAP to determine the base memory size.
2146          */
2147         hasbrokenint12 = 0;
2148         TUNABLE_INT_FETCH("hw.hasbrokenint12", &hasbrokenint12);
2149         if (hasbrokenint12 == 0) {
2150                 /* Use INT12 to determine base memory size. */
2151                 vm86_intcall(0x12, &vmf);
2152                 basemem = vmf.vmf_ax;
2153                 basemem_setup();
2154         }
2155
2156         /*
2157          * Fetch the memory map with INT 15:E820.  Map page 1 R/W into
2158          * the kernel page table so we can use it as a buffer.  The
2159          * kernel will unmap this page later.
2160          */
2161         pmap_kenter(KERNBASE + (1 << PAGE_SHIFT), 1 << PAGE_SHIFT);
2162         vmc.npages = 0;
2163         smap = (void *)vm86_addpage(&vmc, 1, KERNBASE + (1 << PAGE_SHIFT));
2164         res = vm86_getptr(&vmc, (vm_offset_t)smap, &vmf.vmf_es, &vmf.vmf_di);
2165         KASSERT(res != 0, ("vm86_getptr() failed: address not found"));
2166
2167         vmf.vmf_ebx = 0;
2168         do {
2169                 vmf.vmf_eax = 0xE820;
2170                 vmf.vmf_edx = SMAP_SIG;
2171                 vmf.vmf_ecx = sizeof(struct bios_smap);
2172                 i = vm86_datacall(0x15, &vmf, &vmc);
2173                 if (i || vmf.vmf_eax != SMAP_SIG)
2174                         break;
2175                 has_smap = 1;
2176                 if (!add_smap_entry(smap, physmap, &physmap_idx))
2177                         break;
2178         } while (vmf.vmf_ebx != 0);
2179
2180 have_smap:
2181         /*
2182          * If we didn't fetch the "base memory" size from INT12,
2183          * figure it out from the SMAP (or just guess).
2184          */
2185         if (basemem == 0) {
2186                 for (i = 0; i <= physmap_idx; i += 2) {
2187                         if (physmap[i] == 0x00000000) {
2188                                 basemem = physmap[i + 1] / 1024;
2189                                 break;
2190                         }
2191                 }
2192
2193                 /* XXX: If we couldn't find basemem from SMAP, just guess. */
2194                 if (basemem == 0)
2195                         basemem = 640;
2196                 basemem_setup();
2197         }
2198
2199         if (physmap[1] != 0)
2200                 goto physmap_done;
2201
2202         /*
2203          * If we failed to find an SMAP, figure out the extended
2204          * memory size.  We will then build a simple memory map with
2205          * two segments, one for "base memory" and the second for
2206          * "extended memory".  Note that "extended memory" starts at a
2207          * physical address of 1MB and that both basemem and extmem
2208          * are in units of 1KB.
2209          *
2210          * First, try to fetch the extended memory size via INT 15:E801.
2211          */
2212         vmf.vmf_ax = 0xE801;
2213         if (vm86_intcall(0x15, &vmf) == 0) {
2214                 extmem = vmf.vmf_cx + vmf.vmf_dx * 64;
2215         } else {
2216                 /*
2217                  * If INT15:E801 fails, this is our last ditch effort
2218                  * to determine the extended memory size.  Currently
2219                  * we prefer the RTC value over INT15:88.
2220                  */
2221 #if 0
2222                 vmf.vmf_ah = 0x88;
2223                 vm86_intcall(0x15, &vmf);
2224                 extmem = vmf.vmf_ax;
2225 #else
2226                 extmem = rtcin(RTC_EXTLO) + (rtcin(RTC_EXTHI) << 8);
2227 #endif
2228         }
2229
2230         /*
2231          * Special hack for chipsets that still remap the 384k hole when
2232          * there's 16MB of memory - this really confuses people that
2233          * are trying to use bus mastering ISA controllers with the
2234          * "16MB limit"; they only have 16MB, but the remapping puts
2235          * them beyond the limit.
2236          *
2237          * If extended memory is between 15-16MB (16-17MB phys address range),
2238          *      chop it to 15MB.
2239          */
2240         if ((extmem > 15 * 1024) && (extmem < 16 * 1024))
2241                 extmem = 15 * 1024;
2242
2243         physmap[0] = 0;
2244         physmap[1] = basemem * 1024;
2245         physmap_idx = 2;
2246         physmap[physmap_idx] = 0x100000;
2247         physmap[physmap_idx + 1] = physmap[physmap_idx] + extmem * 1024;
2248
2249 physmap_done:
2250 #endif  
2251         /*
2252          * Now, physmap contains a map of physical memory.
2253          */
2254
2255 #ifdef SMP
2256         /* make hole for AP bootstrap code */
2257         physmap[1] = mp_bootaddress(physmap[1]);
2258 #endif
2259
2260         /*
2261          * Maxmem isn't the "maximum memory", it's one larger than the
2262          * highest page of the physical address space.  It should be
2263          * called something like "Maxphyspage".  We may adjust this 
2264          * based on ``hw.physmem'' and the results of the memory test.
2265          */
2266         Maxmem = atop(physmap[physmap_idx + 1]);
2267
2268 #ifdef MAXMEM
2269         Maxmem = MAXMEM / 4;
2270 #endif
2271
2272         if (TUNABLE_QUAD_FETCH("hw.physmem", &physmem_tunable))
2273                 Maxmem = atop(physmem_tunable);
2274
2275         /*
2276          * If we have an SMAP, don't allow MAXMEM or hw.physmem to extend
2277          * the amount of memory in the system.
2278          */
2279         if (has_smap && Maxmem > atop(physmap[physmap_idx + 1]))
2280                 Maxmem = atop(physmap[physmap_idx + 1]);
2281
2282         /*
2283          * By default enable the memory test on real hardware, and disable
2284          * it if we appear to be running in a VM.  This avoids touching all
2285          * pages unnecessarily, which doesn't matter on real hardware but is
2286          * bad for shared VM hosts.  Use a general name so that
2287          * one could eventually do more with the code than just disable it.
2288          */
2289         memtest = (vm_guest > VM_GUEST_NO) ? 0 : 1;
2290         TUNABLE_ULONG_FETCH("hw.memtest.tests", &memtest);
2291
2292         if (atop(physmap[physmap_idx + 1]) != Maxmem &&
2293             (boothowto & RB_VERBOSE))
2294                 printf("Physical memory use set to %ldK\n", Maxmem * 4);
2295
2296         /*
2297          * If Maxmem has been increased beyond what the system has detected,
2298          * extend the last memory segment to the new limit.
2299          */ 
2300         if (atop(physmap[physmap_idx + 1]) < Maxmem)
2301                 physmap[physmap_idx + 1] = ptoa((vm_paddr_t)Maxmem);
2302
2303         /* call pmap initialization to make new kernel address space */
2304         pmap_bootstrap(first);
2305
2306         /*
2307          * Size up each available chunk of physical memory.
2308          */
2309         physmap[0] = PAGE_SIZE;         /* mask off page 0 */
2310         pa_indx = 0;
2311         da_indx = 1;
2312         phys_avail[pa_indx++] = physmap[0];
2313         phys_avail[pa_indx] = physmap[0];
2314         dump_avail[da_indx] = physmap[0];
2315         pte = CMAP3;
2316
2317         /*
2318          * Get dcons buffer address
2319          */
2320         if (getenv_quad("dcons.addr", &dcons_addr) == 0 ||
2321             getenv_quad("dcons.size", &dcons_size) == 0)
2322                 dcons_addr = 0;
2323
2324 #ifndef XEN
2325         /*
2326          * physmap is in bytes, so when converting to page boundaries,
2327          * round up the start address and round down the end address.
2328          */
2329         for (i = 0; i <= physmap_idx; i += 2) {
2330                 vm_paddr_t end;
2331
2332                 end = ptoa((vm_paddr_t)Maxmem);
2333                 if (physmap[i + 1] < end)
2334                         end = trunc_page(physmap[i + 1]);
2335                 for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
2336                         int tmp, page_bad, full;
2337                         int *ptr = (int *)CADDR3;
2338
2339                         full = FALSE;
2340                         /*
2341                          * block out kernel memory as not available.
2342                          */
2343                         if (pa >= KERNLOAD && pa < first)
2344                                 goto do_dump_avail;
2345
2346                         /*
2347                          * block out dcons buffer
2348                          */
2349                         if (dcons_addr > 0
2350                             && pa >= trunc_page(dcons_addr)
2351                             && pa < dcons_addr + dcons_size)
2352                                 goto do_dump_avail;
2353
2354                         page_bad = FALSE;
2355                         if (memtest == 0)
2356                                 goto skip_memtest;
2357
2358                         /*
2359                          * map page into kernel: valid, read/write,non-cacheable
2360                          */
2361                         *pte = pa | PG_V | PG_RW | PG_N;
2362                         invltlb();
2363
2364                         tmp = *(int *)ptr;
2365                         /*
2366                          * Test for alternating 1's and 0's
2367                          */
2368                         *(volatile int *)ptr = 0xaaaaaaaa;
2369                         if (*(volatile int *)ptr != 0xaaaaaaaa)
2370                                 page_bad = TRUE;
2371                         /*
2372                          * Test for alternating 0's and 1's
2373                          */
2374                         *(volatile int *)ptr = 0x55555555;
2375                         if (*(volatile int *)ptr != 0x55555555)
2376                                 page_bad = TRUE;
2377                         /*
2378                          * Test for all 1's
2379                          */
2380                         *(volatile int *)ptr = 0xffffffff;
2381                         if (*(volatile int *)ptr != 0xffffffff)
2382                                 page_bad = TRUE;
2383                         /*
2384                          * Test for all 0's
2385                          */
2386                         *(volatile int *)ptr = 0x0;
2387                         if (*(volatile int *)ptr != 0x0)
2388                                 page_bad = TRUE;
2389                         /*
2390                          * Restore original value.
2391                          */
2392                         *(int *)ptr = tmp;
2393
2394 skip_memtest:
2395                         /*
2396                          * Adjust array of valid/good pages.
2397                          */
2398                         if (page_bad == TRUE)
2399                                 continue;
2400                         /*
2401                          * If this good page is a continuation of the
2402                          * previous set of good pages, then just increase
2403                          * the end pointer. Otherwise start a new chunk.
2404                          * Note that "end" points one higher than end,
2405                          * making the range >= start and < end.
2406                          * If we're also doing a speculative memory
2407                          * test and we at or past the end, bump up Maxmem
2408                          * so that we keep going. The first bad page
2409                          * will terminate the loop.
2410                          */
2411                         if (phys_avail[pa_indx] == pa) {
2412                                 phys_avail[pa_indx] += PAGE_SIZE;
2413                         } else {
2414                                 pa_indx++;
2415                                 if (pa_indx == PHYS_AVAIL_ARRAY_END) {
2416                                         printf(
2417                 "Too many holes in the physical address space, giving up\n");
2418                                         pa_indx--;
2419                                         full = TRUE;
2420                                         goto do_dump_avail;
2421                                 }
2422                                 phys_avail[pa_indx++] = pa;     /* start */
2423                                 phys_avail[pa_indx] = pa + PAGE_SIZE; /* end */
2424                         }
2425                         physmem++;
2426 do_dump_avail:
2427                         if (dump_avail[da_indx] == pa) {
2428                                 dump_avail[da_indx] += PAGE_SIZE;
2429                         } else {
2430                                 da_indx++;
2431                                 if (da_indx == DUMP_AVAIL_ARRAY_END) {
2432                                         da_indx--;
2433                                         goto do_next;
2434                                 }
2435                                 dump_avail[da_indx++] = pa;     /* start */
2436                                 dump_avail[da_indx] = pa + PAGE_SIZE; /* end */
2437                         }
2438 do_next:
2439                         if (full)
2440                                 break;
2441                 }
2442         }
2443         *pte = 0;
2444         invltlb();
2445 #else
2446         phys_avail[0] = physfree;
2447         phys_avail[1] = xen_start_info->nr_pages*PAGE_SIZE;
2448         dump_avail[0] = 0;      
2449         dump_avail[1] = xen_start_info->nr_pages*PAGE_SIZE;
2450         
2451 #endif
2452         
2453         /*
2454          * XXX
2455          * The last chunk must contain at least one page plus the message
2456          * buffer to avoid complicating other code (message buffer address
2457          * calculation, etc.).
2458          */
2459         while (phys_avail[pa_indx - 1] + PAGE_SIZE +
2460             round_page(msgbufsize) >= phys_avail[pa_indx]) {
2461                 physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
2462                 phys_avail[pa_indx--] = 0;
2463                 phys_avail[pa_indx--] = 0;
2464         }
2465
2466         Maxmem = atop(phys_avail[pa_indx]);
2467
2468         /* Trim off space for the message buffer. */
2469         phys_avail[pa_indx] -= round_page(msgbufsize);
2470
2471         /* Map the message buffer. */
2472         for (off = 0; off < round_page(msgbufsize); off += PAGE_SIZE)
2473                 pmap_kenter((vm_offset_t)msgbufp + off, phys_avail[pa_indx] +
2474                     off);
2475
2476         PT_UPDATES_FLUSH();
2477 }
2478 #endif /* PC98 */
2479
2480 #ifdef XEN
2481 #define MTOPSIZE (1<<(14 + PAGE_SHIFT))
2482
2483 register_t
2484 init386(first)
2485         int first;
2486 {
2487         unsigned long gdtmachpfn;
2488         int error, gsel_tss, metadata_missing, x, pa;
2489         struct pcpu *pc;
2490 #ifdef CPU_ENABLE_SSE
2491         struct xstate_hdr *xhdr;
2492 #endif
2493         struct callback_register event = {
2494                 .type = CALLBACKTYPE_event,
2495                 .address = {GSEL(GCODE_SEL, SEL_KPL), (unsigned long)Xhypervisor_callback },
2496         };
2497         struct callback_register failsafe = {
2498                 .type = CALLBACKTYPE_failsafe,
2499                 .address = {GSEL(GCODE_SEL, SEL_KPL), (unsigned long)failsafe_callback },
2500         };
2501
2502         thread0.td_kstack = proc0kstack;
2503         thread0.td_kstack_pages = KSTACK_PAGES;
2504
2505         /*
2506          * This may be done better later if it gets more high level
2507          * components in it. If so just link td->td_proc here.
2508          */
2509         proc_linkup0(&proc0, &thread0);
2510
2511         metadata_missing = 0;
2512         if (xen_start_info->mod_start) {
2513                 preload_metadata = (caddr_t)xen_start_info->mod_start;
2514                 preload_bootstrap_relocate(KERNBASE);
2515         } else {
2516                 metadata_missing = 1;
2517         }
2518         if (envmode == 1)
2519                 kern_envp = static_env;
2520         else if ((caddr_t)xen_start_info->cmd_line)
2521                 kern_envp = xen_setbootenv((caddr_t)xen_start_info->cmd_line);
2522
2523         boothowto |= xen_boothowto(kern_envp);
2524         
2525         /* Init basic tunables, hz etc */
2526         init_param1();
2527
2528         /*
2529          * XEN occupies a portion of the upper virtual address space 
2530          * At its base it manages an array mapping machine page frames 
2531          * to physical page frames - hence we need to be able to 
2532          * access 4GB - (64MB  - 4MB + 64k) 
2533          */
2534         gdt_segs[GPRIV_SEL].ssd_limit = atop(HYPERVISOR_VIRT_START + MTOPSIZE);
2535         gdt_segs[GUFS_SEL].ssd_limit = atop(HYPERVISOR_VIRT_START + MTOPSIZE);
2536         gdt_segs[GUGS_SEL].ssd_limit = atop(HYPERVISOR_VIRT_START + MTOPSIZE);
2537         gdt_segs[GCODE_SEL].ssd_limit = atop(HYPERVISOR_VIRT_START + MTOPSIZE);
2538         gdt_segs[GDATA_SEL].ssd_limit = atop(HYPERVISOR_VIRT_START + MTOPSIZE);
2539         gdt_segs[GUCODE_SEL].ssd_limit = atop(HYPERVISOR_VIRT_START + MTOPSIZE);
2540         gdt_segs[GUDATA_SEL].ssd_limit = atop(HYPERVISOR_VIRT_START + MTOPSIZE);
2541         gdt_segs[GBIOSLOWMEM_SEL].ssd_limit = atop(HYPERVISOR_VIRT_START + MTOPSIZE);
2542
2543         pc = &__pcpu[0];
2544         gdt_segs[GPRIV_SEL].ssd_base = (int) pc;
2545         gdt_segs[GPROC0_SEL].ssd_base = (int) &pc->pc_common_tss;
2546
2547         PT_SET_MA(gdt, xpmap_ptom(VTOP(gdt)) | PG_V | PG_RW);
2548         bzero(gdt, PAGE_SIZE);
2549         for (x = 0; x < NGDT; x++)
2550                 ssdtosd(&gdt_segs[x], &gdt[x].sd);
2551
2552         mtx_init(&dt_lock, "descriptor tables", NULL, MTX_SPIN);
2553
2554         gdtmachpfn = vtomach(gdt) >> PAGE_SHIFT;
2555         PT_SET_MA(gdt, xpmap_ptom(VTOP(gdt)) | PG_V);
2556         PANIC_IF(HYPERVISOR_set_gdt(&gdtmachpfn, 512) != 0);    
2557         lgdt(&r_gdt);
2558         gdtset = 1;
2559
2560         if ((error = HYPERVISOR_set_trap_table(trap_table)) != 0) {
2561                 panic("set_trap_table failed - error %d\n", error);
2562         }
2563         
2564         error = HYPERVISOR_callback_op(CALLBACKOP_register, &event);
2565         if (error == 0)
2566                 error = HYPERVISOR_callback_op(CALLBACKOP_register, &failsafe);
2567 #if     CONFIG_XEN_COMPAT <= 0x030002
2568         if (error == -ENOXENSYS)
2569                 HYPERVISOR_set_callbacks(GSEL(GCODE_SEL, SEL_KPL),
2570                     (unsigned long)Xhypervisor_callback,
2571                     GSEL(GCODE_SEL, SEL_KPL), (unsigned long)failsafe_callback);
2572 #endif
2573         pcpu_init(pc, 0, sizeof(struct pcpu));
2574         for (pa = first; pa < first + DPCPU_SIZE; pa += PAGE_SIZE)
2575                 pmap_kenter(pa + KERNBASE, pa);
2576         dpcpu_init((void *)(first + KERNBASE), 0);
2577         first += DPCPU_SIZE;
2578         physfree += DPCPU_SIZE;
2579         init_first += DPCPU_SIZE / PAGE_SIZE;
2580
2581         PCPU_SET(prvspace, pc);
2582         PCPU_SET(curthread, &thread0);
2583
2584         /*
2585          * Initialize mutexes.
2586          *
2587          * icu_lock: in order to allow an interrupt to occur in a critical
2588          *           section, to set pcpu->ipending (etc...) properly, we
2589          *           must be able to get the icu lock, so it can't be
2590          *           under witness.
2591          */
2592         mutex_init();
2593         mtx_init(&icu_lock, "icu", NULL, MTX_SPIN | MTX_NOWITNESS | MTX_NOPROFILE);
2594
2595         /* make ldt memory segments */
2596         PT_SET_MA(ldt, xpmap_ptom(VTOP(ldt)) | PG_V | PG_RW);
2597         bzero(ldt, PAGE_SIZE);
2598         ldt_segs[LUCODE_SEL].ssd_limit = atop(0 - 1);
2599         ldt_segs[LUDATA_SEL].ssd_limit = atop(0 - 1);
2600         for (x = 0; x < sizeof ldt_segs / sizeof ldt_segs[0]; x++)
2601                 ssdtosd(&ldt_segs[x], &ldt[x].sd);
2602
2603         default_proc_ldt.ldt_base = (caddr_t)ldt;
2604         default_proc_ldt.ldt_len = 6;
2605         _default_ldt = (int)&default_proc_ldt;
2606         PCPU_SET(currentldt, _default_ldt);
2607         PT_SET_MA(ldt, *vtopte((unsigned long)ldt) & ~PG_RW);
2608         xen_set_ldt((unsigned long) ldt, (sizeof ldt_segs / sizeof ldt_segs[0]));
2609         
2610 #if defined(XEN_PRIVILEGED)
2611         /*
2612          * Initialize the i8254 before the console so that console
2613          * initialization can use DELAY().
2614          */
2615         i8254_init();
2616 #endif
2617         
2618         /*
2619          * Initialize the console before we print anything out.
2620          */
2621         cninit();
2622
2623         if (metadata_missing)
2624                 printf("WARNING: loader(8) metadata is missing!\n");
2625
2626 #ifdef DEV_ISA
2627 #ifdef DEV_ATPIC
2628         elcr_probe();
2629         atpic_startup();
2630 #else
2631         /* Reset and mask the atpics and leave them shut down. */
2632         atpic_reset();
2633
2634         /*
2635          * Point the ICU spurious interrupt vectors at the APIC spurious
2636          * interrupt handler.
2637          */
2638         setidt(IDT_IO_INTS + 7, IDTVEC(spuriousint), SDT_SYS386IGT, SEL_KPL,
2639             GSEL(GCODE_SEL, SEL_KPL));
2640         setidt(IDT_IO_INTS + 15, IDTVEC(spuriousint), SDT_SYS386IGT, SEL_KPL,
2641             GSEL(GCODE_SEL, SEL_KPL));
2642 #endif
2643 #endif
2644
2645 #ifdef DDB
2646         db_fetch_ksymtab(bootinfo.bi_symtab, bootinfo.bi_esymtab);
2647 #endif
2648
2649         kdb_init();
2650
2651 #ifdef KDB
2652         if (boothowto & RB_KDB)
2653                 kdb_enter(KDB_WHY_BOOTFLAGS, "Boot flags requested debugger");
2654 #endif
2655
2656         finishidentcpu();       /* Final stage of CPU initialization */
2657         setidt(IDT_UD, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL,
2658             GSEL(GCODE_SEL, SEL_KPL));
2659         setidt(IDT_GP, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL,
2660             GSEL(GCODE_SEL, SEL_KPL));
2661         initializecpu();        /* Initialize CPU registers */
2662         initializecpucache();
2663
2664         /* pointer to selector slot for %fs/%gs */
2665         PCPU_SET(fsgs_gdt, &gdt[GUFS_SEL].sd);
2666
2667         dblfault_tss.tss_esp = dblfault_tss.tss_esp0 = dblfault_tss.tss_esp1 =
2668             dblfault_tss.tss_esp2 = (int)&dblfault_stack[sizeof(dblfault_stack)];
2669         dblfault_tss.tss_ss = dblfault_tss.tss_ss0 = dblfault_tss.tss_ss1 =
2670             dblfault_tss.tss_ss2 = GSEL(GDATA_SEL, SEL_KPL);
2671 #if defined(PAE) || defined(PAE_TABLES)
2672         dblfault_tss.tss_cr3 = (int)IdlePDPT;
2673 #else
2674         dblfault_tss.tss_cr3 = (int)IdlePTD;
2675 #endif
2676         dblfault_tss.tss_eip = (int)dblfault_handler;
2677         dblfault_tss.tss_eflags = PSL_KERNEL;
2678         dblfault_tss.tss_ds = dblfault_tss.tss_es =
2679             dblfault_tss.tss_gs = GSEL(GDATA_SEL, SEL_KPL);
2680         dblfault_tss.tss_fs = GSEL(GPRIV_SEL, SEL_KPL);
2681         dblfault_tss.tss_cs = GSEL(GCODE_SEL, SEL_KPL);
2682         dblfault_tss.tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
2683
2684         vm86_initialize();
2685         getmemsize(first);
2686         init_param2(physmem);
2687
2688         /* now running on new page tables, configured,and u/iom is accessible */
2689
2690         msgbufinit(msgbufp, msgbufsize);
2691 #ifdef DEV_NPX
2692         npxinit(true);
2693 #endif
2694         /*
2695          * Set up thread0 pcb after npxinit calculated pcb + fpu save
2696          * area size.  Zero out the extended state header in fpu save
2697          * area.
2698          */
2699         thread0.td_pcb = get_pcb_td(&thread0);
2700         bzero(get_pcb_user_save_td(&thread0), cpu_max_ext_state_size);
2701 #ifdef CPU_ENABLE_SSE
2702         if (use_xsave) {
2703                 xhdr = (struct xstate_hdr *)(get_pcb_user_save_td(&thread0) +
2704                     1);
2705                 xhdr->xstate_bv = xsave_mask;
2706         }
2707 #endif
2708         PCPU_SET(curpcb, thread0.td_pcb);
2709         /* make an initial tss so cpu can get interrupt stack on syscall! */
2710         /* Note: -16 is so we can grow the trapframe if we came from vm86 */
2711         PCPU_SET(common_tss.tss_esp0, (vm_offset_t)thread0.td_pcb - 16);
2712         PCPU_SET(common_tss.tss_ss0, GSEL(GDATA_SEL, SEL_KPL));
2713         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
2714         HYPERVISOR_stack_switch(GSEL(GDATA_SEL, SEL_KPL),
2715             PCPU_GET(common_tss.tss_esp0));
2716         
2717         /* transfer to user mode */
2718
2719         _ucodesel = GSEL(GUCODE_SEL, SEL_UPL);
2720         _udatasel = GSEL(GUDATA_SEL, SEL_UPL);
2721
2722         /* setup proc 0's pcb */
2723         thread0.td_pcb->pcb_flags = 0;
2724 #if defined(PAE) || defined(PAE_TABLES)
2725         thread0.td_pcb->pcb_cr3 = (int)IdlePDPT;
2726 #else
2727         thread0.td_pcb->pcb_cr3 = (int)IdlePTD;
2728 #endif
2729         thread0.td_pcb->pcb_ext = 0;
2730         thread0.td_frame = &proc0_tf;
2731         thread0.td_pcb->pcb_fsd = PCPU_GET(fsgs_gdt)[0];
2732         thread0.td_pcb->pcb_gsd = PCPU_GET(fsgs_gdt)[1];
2733
2734         cpu_probe_amdc1e();
2735
2736         /* Location of kernel stack for locore */
2737         return ((register_t)thread0.td_pcb);
2738 }
2739
2740 #else
2741 register_t
2742 init386(first)
2743         int first;
2744 {
2745         struct gate_descriptor *gdp;
2746         int gsel_tss, metadata_missing, x, pa;
2747         struct pcpu *pc;
2748 #ifdef CPU_ENABLE_SSE
2749         struct xstate_hdr *xhdr;
2750 #endif
2751
2752         thread0.td_kstack = proc0kstack;
2753         thread0.td_kstack_pages = KSTACK_PAGES;
2754
2755         /*
2756          * This may be done better later if it gets more high level
2757          * components in it. If so just link td->td_proc here.
2758          */
2759         proc_linkup0(&proc0, &thread0);
2760
2761 #ifdef PC98
2762         /*
2763          * Initialize DMAC
2764          */
2765         pc98_init_dmac();
2766 #endif
2767
2768         metadata_missing = 0;
2769         if (bootinfo.bi_modulep) {
2770                 preload_metadata = (caddr_t)bootinfo.bi_modulep + KERNBASE;
2771                 preload_bootstrap_relocate(KERNBASE);
2772         } else {
2773                 metadata_missing = 1;
2774         }
2775         if (envmode == 1)
2776                 kern_envp = static_env;
2777         else if (bootinfo.bi_envp)
2778                 kern_envp = (caddr_t)bootinfo.bi_envp + KERNBASE;
2779
2780         /* Init basic tunables, hz etc */
2781         init_param1();
2782
2783         /*
2784          * Make gdt memory segments.  All segments cover the full 4GB
2785          * of address space and permissions are enforced at page level.
2786          */
2787         gdt_segs[GCODE_SEL].ssd_limit = atop(0 - 1);
2788         gdt_segs[GDATA_SEL].ssd_limit = atop(0 - 1);
2789         gdt_segs[GUCODE_SEL].ssd_limit = atop(0 - 1);
2790         gdt_segs[GUDATA_SEL].ssd_limit = atop(0 - 1);
2791         gdt_segs[GUFS_SEL].ssd_limit = atop(0 - 1);
2792         gdt_segs[GUGS_SEL].ssd_limit = atop(0 - 1);
2793
2794         pc = &__pcpu[0];
2795         gdt_segs[GPRIV_SEL].ssd_limit = atop(0 - 1);
2796         gdt_segs[GPRIV_SEL].ssd_base = (int) pc;
2797         gdt_segs[GPROC0_SEL].ssd_base = (int) &pc->pc_common_tss;
2798
2799         for (x = 0; x < NGDT; x++)
2800                 ssdtosd(&gdt_segs[x], &gdt[x].sd);
2801
2802         r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
2803         r_gdt.rd_base =  (int) gdt;
2804         mtx_init(&dt_lock, "descriptor tables", NULL, MTX_SPIN);
2805         lgdt(&r_gdt);
2806
2807         pcpu_init(pc, 0, sizeof(struct pcpu));
2808         for (pa = first; pa < first + DPCPU_SIZE; pa += PAGE_SIZE)
2809                 pmap_kenter(pa + KERNBASE, pa);
2810         dpcpu_init((void *)(first + KERNBASE), 0);
2811         first += DPCPU_SIZE;
2812         PCPU_SET(prvspace, pc);
2813         PCPU_SET(curthread, &thread0);
2814
2815         /*
2816          * Initialize mutexes.
2817          *
2818          * icu_lock: in order to allow an interrupt to occur in a critical
2819          *           section, to set pcpu->ipending (etc...) properly, we
2820          *           must be able to get the icu lock, so it can't be
2821          *           under witness.
2822          */
2823         mutex_init();
2824         mtx_init(&icu_lock, "icu", NULL, MTX_SPIN | MTX_NOWITNESS | MTX_NOPROFILE);
2825
2826         /* make ldt memory segments */
2827         ldt_segs[LUCODE_SEL].ssd_limit = atop(0 - 1);
2828         ldt_segs[LUDATA_SEL].ssd_limit = atop(0 - 1);
2829         for (x = 0; x < sizeof ldt_segs / sizeof ldt_segs[0]; x++)
2830                 ssdtosd(&ldt_segs[x], &ldt[x].sd);
2831
2832         _default_ldt = GSEL(GLDT_SEL, SEL_KPL);
2833         lldt(_default_ldt);
2834         PCPU_SET(currentldt, _default_ldt);
2835
2836         /* exceptions */
2837         for (x = 0; x < NIDT; x++)
2838                 setidt(x, &IDTVEC(rsvd), SDT_SYS386TGT, SEL_KPL,
2839                     GSEL(GCODE_SEL, SEL_KPL));
2840         setidt(IDT_DE, &IDTVEC(div),  SDT_SYS386TGT, SEL_KPL,
2841             GSEL(GCODE_SEL, SEL_KPL));
2842         setidt(IDT_DB, &IDTVEC(dbg),  SDT_SYS386IGT, SEL_KPL,
2843             GSEL(GCODE_SEL, SEL_KPL));
2844         setidt(IDT_NMI, &IDTVEC(nmi),  SDT_SYS386IGT, SEL_KPL,
2845             GSEL(GCODE_SEL, SEL_KPL));
2846         setidt(IDT_BP, &IDTVEC(bpt),  SDT_SYS386IGT, SEL_UPL,
2847             GSEL(GCODE_SEL, SEL_KPL));
2848         setidt(IDT_OF, &IDTVEC(ofl),  SDT_SYS386TGT, SEL_UPL,
2849             GSEL(GCODE_SEL, SEL_KPL));
2850         setidt(IDT_BR, &IDTVEC(bnd),  SDT_SYS386TGT, SEL_KPL,
2851             GSEL(GCODE_SEL, SEL_KPL));
2852         setidt(IDT_UD, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL,
2853             GSEL(GCODE_SEL, SEL_KPL));
2854         setidt(IDT_NM, &IDTVEC(dna),  SDT_SYS386TGT, SEL_KPL
2855             , GSEL(GCODE_SEL, SEL_KPL));
2856         setidt(IDT_DF, 0,  SDT_SYSTASKGT, SEL_KPL, GSEL(GPANIC_SEL, SEL_KPL));
2857         setidt(IDT_FPUGP, &IDTVEC(fpusegm),  SDT_SYS386TGT, SEL_KPL,
2858             GSEL(GCODE_SEL, SEL_KPL));
2859         setidt(IDT_TS, &IDTVEC(tss),  SDT_SYS386TGT, SEL_KPL,
2860             GSEL(GCODE_SEL, SEL_KPL));
2861         setidt(IDT_NP, &IDTVEC(missing),  SDT_SYS386TGT, SEL_KPL,
2862             GSEL(GCODE_SEL, SEL_KPL));
2863         setidt(IDT_SS, &IDTVEC(stk),  SDT_SYS386TGT, SEL_KPL,
2864             GSEL(GCODE_SEL, SEL_KPL));
2865         setidt(IDT_GP, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL,
2866             GSEL(GCODE_SEL, SEL_KPL));
2867         setidt(IDT_PF, &IDTVEC(page),  SDT_SYS386IGT, SEL_KPL,
2868             GSEL(GCODE_SEL, SEL_KPL));
2869         setidt(IDT_MF, &IDTVEC(fpu),  SDT_SYS386TGT, SEL_KPL,
2870             GSEL(GCODE_SEL, SEL_KPL));
2871         setidt(IDT_AC, &IDTVEC(align), SDT_SYS386TGT, SEL_KPL,
2872             GSEL(GCODE_SEL, SEL_KPL));
2873         setidt(IDT_MC, &IDTVEC(mchk),  SDT_SYS386TGT, SEL_KPL,
2874             GSEL(GCODE_SEL, SEL_KPL));
2875         setidt(IDT_XF, &IDTVEC(xmm), SDT_SYS386TGT, SEL_KPL,
2876             GSEL(GCODE_SEL, SEL_KPL));
2877         setidt(IDT_SYSCALL, &IDTVEC(int0x80_syscall), SDT_SYS386TGT, SEL_UPL,
2878             GSEL(GCODE_SEL, SEL_KPL));
2879 #ifdef KDTRACE_HOOKS
2880         setidt(IDT_DTRACE_RET, &IDTVEC(dtrace_ret), SDT_SYS386TGT, SEL_UPL,
2881             GSEL(GCODE_SEL, SEL_KPL));
2882 #endif
2883 #ifdef XENHVM
2884         setidt(IDT_EVTCHN, &IDTVEC(xen_intr_upcall), SDT_SYS386IGT, SEL_UPL,
2885             GSEL(GCODE_SEL, SEL_KPL));
2886 #endif
2887
2888         r_idt.rd_limit = sizeof(idt0) - 1;
2889         r_idt.rd_base = (int) idt;
2890         lidt(&r_idt);
2891
2892 #ifdef XBOX
2893         /*
2894          * The following code queries the PCI ID of 0:0:0. For the XBOX,
2895          * This should be 0x10de / 0x02a5.
2896          *
2897          * This is exactly what Linux does.
2898          */
2899         outl(0xcf8, 0x80000000);
2900         if (inl(0xcfc) == 0x02a510de) {
2901                 arch_i386_is_xbox = 1;
2902                 pic16l_setled(XBOX_LED_GREEN);
2903
2904                 /*
2905                  * We are an XBOX, but we may have either 64MB or 128MB of
2906                  * memory. The PCI host bridge should be programmed for this,
2907                  * so we just query it. 
2908                  */
2909                 outl(0xcf8, 0x80000084);
2910                 arch_i386_xbox_memsize = (inl(0xcfc) == 0x7FFFFFF) ? 128 : 64;
2911         }
2912 #endif /* XBOX */
2913
2914         /*
2915          * Initialize the clock before the console so that console
2916          * initialization can use DELAY().
2917          */
2918         clock_init();
2919
2920         /*
2921          * Initialize the console before we print anything out.
2922          */
2923         cninit();
2924
2925         if (metadata_missing)
2926                 printf("WARNING: loader(8) metadata is missing!\n");
2927
2928 #ifdef DEV_ISA
2929 #ifdef DEV_ATPIC
2930 #ifndef PC98
2931         elcr_probe();
2932 #endif
2933         atpic_startup();
2934 #else
2935         /* Reset and mask the atpics and leave them shut down. */
2936         atpic_reset();
2937
2938         /*
2939          * Point the ICU spurious interrupt vectors at the APIC spurious
2940          * interrupt handler.
2941          */
2942         setidt(IDT_IO_INTS + 7, IDTVEC(spuriousint), SDT_SYS386IGT, SEL_KPL,
2943             GSEL(GCODE_SEL, SEL_KPL));
2944         setidt(IDT_IO_INTS + 15, IDTVEC(spuriousint), SDT_SYS386IGT, SEL_KPL,
2945             GSEL(GCODE_SEL, SEL_KPL));
2946 #endif
2947 #endif
2948
2949 #ifdef DDB
2950         db_fetch_ksymtab(bootinfo.bi_symtab, bootinfo.bi_esymtab);
2951 #endif
2952
2953         kdb_init();
2954
2955 #ifdef KDB
2956         if (boothowto & RB_KDB)
2957                 kdb_enter(KDB_WHY_BOOTFLAGS, "Boot flags requested debugger");
2958 #endif
2959
2960         finishidentcpu();       /* Final stage of CPU initialization */
2961         setidt(IDT_UD, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL,
2962             GSEL(GCODE_SEL, SEL_KPL));
2963         setidt(IDT_GP, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL,
2964             GSEL(GCODE_SEL, SEL_KPL));
2965         initializecpu();        /* Initialize CPU registers */
2966         initializecpucache();
2967
2968         /* pointer to selector slot for %fs/%gs */
2969         PCPU_SET(fsgs_gdt, &gdt[GUFS_SEL].sd);
2970
2971         dblfault_tss.tss_esp = dblfault_tss.tss_esp0 = dblfault_tss.tss_esp1 =
2972             dblfault_tss.tss_esp2 = (int)&dblfault_stack[sizeof(dblfault_stack)];
2973         dblfault_tss.tss_ss = dblfault_tss.tss_ss0 = dblfault_tss.tss_ss1 =
2974             dblfault_tss.tss_ss2 = GSEL(GDATA_SEL, SEL_KPL);
2975 #if defined(PAE) || defined(PAE_TABLES)
2976         dblfault_tss.tss_cr3 = (int)IdlePDPT;
2977 #else
2978         dblfault_tss.tss_cr3 = (int)IdlePTD;
2979 #endif
2980         dblfault_tss.tss_eip = (int)dblfault_handler;
2981         dblfault_tss.tss_eflags = PSL_KERNEL;
2982         dblfault_tss.tss_ds = dblfault_tss.tss_es =
2983             dblfault_tss.tss_gs = GSEL(GDATA_SEL, SEL_KPL);
2984         dblfault_tss.tss_fs = GSEL(GPRIV_SEL, SEL_KPL);
2985         dblfault_tss.tss_cs = GSEL(GCODE_SEL, SEL_KPL);
2986         dblfault_tss.tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
2987
2988         vm86_initialize();
2989         getmemsize(first);
2990         init_param2(physmem);
2991
2992         /* now running on new page tables, configured,and u/iom is accessible */
2993
2994         msgbufinit(msgbufp, msgbufsize);
2995 #ifdef DEV_NPX
2996         npxinit(true);
2997 #endif
2998         /*
2999          * Set up thread0 pcb after npxinit calculated pcb + fpu save
3000          * area size.  Zero out the extended state header in fpu save
3001          * area.
3002          */
3003         thread0.td_pcb = get_pcb_td(&thread0);
3004         bzero(get_pcb_user_save_td(&thread0), cpu_max_ext_state_size);
3005 #ifdef CPU_ENABLE_SSE
3006         if (use_xsave) {
3007                 xhdr = (struct xstate_hdr *)(get_pcb_user_save_td(&thread0) +
3008                     1);
3009                 xhdr->xstate_bv = xsave_mask;
3010         }
3011 #endif
3012         PCPU_SET(curpcb, thread0.td_pcb);
3013         /* make an initial tss so cpu can get interrupt stack on syscall! */
3014         /* Note: -16 is so we can grow the trapframe if we came from vm86 */
3015         PCPU_SET(common_tss.tss_esp0, (vm_offset_t)thread0.td_pcb - 16);
3016         PCPU_SET(common_tss.tss_ss0, GSEL(GDATA_SEL, SEL_KPL));
3017         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
3018         PCPU_SET(tss_gdt, &gdt[GPROC0_SEL].sd);
3019         PCPU_SET(common_tssd, *PCPU_GET(tss_gdt));
3020         PCPU_SET(common_tss.tss_ioopt, (sizeof (struct i386tss)) << 16);
3021         ltr(gsel_tss);
3022
3023         /* make a call gate to reenter kernel with */
3024         gdp = &ldt[LSYS5CALLS_SEL].gd;
3025
3026         x = (int) &IDTVEC(lcall_syscall);
3027         gdp->gd_looffset = x;
3028         gdp->gd_selector = GSEL(GCODE_SEL,SEL_KPL);
3029         gdp->gd_stkcpy = 1;
3030         gdp->gd_type = SDT_SYS386CGT;
3031         gdp->gd_dpl = SEL_UPL;
3032         gdp->gd_p = 1;
3033         gdp->gd_hioffset = x >> 16;
3034
3035         /* XXX does this work? */
3036         /* XXX yes! */
3037         ldt[LBSDICALLS_SEL] = ldt[LSYS5CALLS_SEL];
3038         ldt[LSOL26CALLS_SEL] = ldt[LSYS5CALLS_SEL];
3039
3040         /* transfer to user mode */
3041
3042         _ucodesel = GSEL(GUCODE_SEL, SEL_UPL);
3043         _udatasel = GSEL(GUDATA_SEL, SEL_UPL);
3044
3045         /* setup proc 0's pcb */
3046         thread0.td_pcb->pcb_flags = 0;
3047 #if defined(PAE) || defined(PAE_TABLES)
3048         thread0.td_pcb->pcb_cr3 = (int)IdlePDPT;
3049 #else
3050         thread0.td_pcb->pcb_cr3 = (int)IdlePTD;
3051 #endif
3052         thread0.td_pcb->pcb_ext = 0;
3053         thread0.td_frame = &proc0_tf;
3054
3055         cpu_probe_amdc1e();
3056
3057 #ifdef FDT
3058         x86_init_fdt();
3059 #endif
3060
3061         /* Location of kernel stack for locore */
3062         return ((register_t)thread0.td_pcb);
3063 }
3064 #endif
3065
3066 void
3067 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
3068 {
3069
3070         pcpu->pc_acpi_id = 0xffffffff;
3071 }
3072
3073 #ifndef PC98
3074 static int
3075 smap_sysctl_handler(SYSCTL_HANDLER_ARGS)
3076 {
3077         struct bios_smap *smapbase;
3078         struct bios_smap_xattr smap;
3079         caddr_t kmdp;
3080         uint32_t *smapattr;
3081         int count, error, i;
3082
3083         /* Retrieve the system memory map from the loader. */
3084         kmdp = preload_search_by_type("elf kernel");
3085         if (kmdp == NULL)
3086                 kmdp = preload_search_by_type("elf32 kernel");
3087         if (kmdp == NULL)
3088                 return (0);
3089         smapbase = (struct bios_smap *)preload_search_info(kmdp,
3090             MODINFO_METADATA | MODINFOMD_SMAP);
3091         if (smapbase == NULL)
3092                 return (0);
3093         smapattr = (uint32_t *)preload_search_info(kmdp,
3094             MODINFO_METADATA | MODINFOMD_SMAP_XATTR);
3095         count = *((u_int32_t *)smapbase - 1) / sizeof(*smapbase);
3096         error = 0;
3097         for (i = 0; i < count; i++) {
3098                 smap.base = smapbase[i].base;
3099                 smap.length = smapbase[i].length;
3100                 smap.type = smapbase[i].type;
3101                 if (smapattr != NULL)
3102                         smap.xattr = smapattr[i];
3103                 else
3104                         smap.xattr = 0;
3105                 error = SYSCTL_OUT(req, &smap, sizeof(smap));
3106         }
3107         return (error);
3108 }
3109 SYSCTL_PROC(_machdep, OID_AUTO, smap, CTLTYPE_OPAQUE|CTLFLAG_RD, NULL, 0,
3110     smap_sysctl_handler, "S,bios_smap_xattr", "Raw BIOS SMAP data");
3111 #endif /* !PC98 */
3112
3113 void
3114 spinlock_enter(void)
3115 {
3116         struct thread *td;
3117         register_t flags;
3118
3119         td = curthread;
3120         if (td->td_md.md_spinlock_count == 0) {
3121                 flags = intr_disable();
3122                 td->td_md.md_spinlock_count = 1;
3123                 td->td_md.md_saved_flags = flags;
3124         } else
3125                 td->td_md.md_spinlock_count++;
3126         critical_enter();
3127 }
3128
3129 void
3130 spinlock_exit(void)
3131 {
3132         struct thread *td;
3133         register_t flags;
3134
3135         td = curthread;
3136         critical_exit();
3137         flags = td->td_md.md_saved_flags;
3138         td->td_md.md_spinlock_count--;
3139         if (td->td_md.md_spinlock_count == 0)
3140                 intr_restore(flags);
3141 }
3142
3143 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
3144 static void f00f_hack(void *unused);
3145 SYSINIT(f00f_hack, SI_SUB_INTRINSIC, SI_ORDER_FIRST, f00f_hack, NULL);
3146
3147 static void
3148 f00f_hack(void *unused)
3149 {
3150         struct gate_descriptor *new_idt;
3151         vm_offset_t tmp;
3152
3153         if (!has_f00f_bug)
3154                 return;
3155
3156         GIANT_REQUIRED;
3157
3158         printf("Intel Pentium detected, installing workaround for F00F bug\n");
3159
3160         tmp = kmem_malloc(kernel_arena, PAGE_SIZE * 2, M_WAITOK | M_ZERO);
3161         if (tmp == 0)
3162                 panic("kmem_malloc returned 0");
3163
3164         /* Put the problematic entry (#6) at the end of the lower page. */
3165         new_idt = (struct gate_descriptor*)
3166             (tmp + PAGE_SIZE - 7 * sizeof(struct gate_descriptor));
3167         bcopy(idt, new_idt, sizeof(idt0));
3168         r_idt.rd_base = (u_int)new_idt;
3169         lidt(&r_idt);
3170         idt = new_idt;
3171         pmap_protect(kernel_pmap, tmp, tmp + PAGE_SIZE, VM_PROT_READ);
3172 }
3173 #endif /* defined(I586_CPU) && !NO_F00F_HACK */
3174
3175 /*
3176  * Construct a PCB from a trapframe. This is called from kdb_trap() where
3177  * we want to start a backtrace from the function that caused us to enter
3178  * the debugger. We have the context in the trapframe, but base the trace
3179  * on the PCB. The PCB doesn't have to be perfect, as long as it contains
3180  * enough for a backtrace.
3181  */
3182 void
3183 makectx(struct trapframe *tf, struct pcb *pcb)
3184 {
3185
3186         pcb->pcb_edi = tf->tf_edi;
3187         pcb->pcb_esi = tf->tf_esi;
3188         pcb->pcb_ebp = tf->tf_ebp;
3189         pcb->pcb_ebx = tf->tf_ebx;
3190         pcb->pcb_eip = tf->tf_eip;
3191         pcb->pcb_esp = (ISPL(tf->tf_cs)) ? tf->tf_esp : (int)(tf + 1) - 8;
3192 }
3193
3194 int
3195 ptrace_set_pc(struct thread *td, u_long addr)
3196 {
3197
3198         td->td_frame->tf_eip = addr;
3199         return (0);
3200 }
3201
3202 int
3203 ptrace_single_step(struct thread *td)
3204 {
3205         td->td_frame->tf_eflags |= PSL_T;
3206         return (0);
3207 }
3208
3209 int
3210 ptrace_clear_single_step(struct thread *td)
3211 {
3212         td->td_frame->tf_eflags &= ~PSL_T;
3213         return (0);
3214 }
3215
3216 int
3217 fill_regs(struct thread *td, struct reg *regs)
3218 {
3219         struct pcb *pcb;
3220         struct trapframe *tp;
3221
3222         tp = td->td_frame;
3223         pcb = td->td_pcb;
3224         regs->r_gs = pcb->pcb_gs;
3225         return (fill_frame_regs(tp, regs));
3226 }
3227
3228 int
3229 fill_frame_regs(struct trapframe *tp, struct reg *regs)
3230 {
3231         regs->r_fs = tp->tf_fs;
3232         regs->r_es = tp->tf_es;
3233         regs->r_ds = tp->tf_ds;
3234         regs->r_edi = tp->tf_edi;
3235         regs->r_esi = tp->tf_esi;
3236         regs->r_ebp = tp->tf_ebp;
3237         regs->r_ebx = tp->tf_ebx;
3238         regs->r_edx = tp->tf_edx;
3239         regs->r_ecx = tp->tf_ecx;
3240         regs->r_eax = tp->tf_eax;
3241         regs->r_eip = tp->tf_eip;
3242         regs->r_cs = tp->tf_cs;
3243         regs->r_eflags = tp->tf_eflags;
3244         regs->r_esp = tp->tf_esp;
3245         regs->r_ss = tp->tf_ss;
3246         return (0);
3247 }
3248
3249 int
3250 set_regs(struct thread *td, struct reg *regs)
3251 {
3252         struct pcb *pcb;
3253         struct trapframe *tp;
3254
3255         tp = td->td_frame;
3256         if (!EFL_SECURE(regs->r_eflags, tp->tf_eflags) ||
3257             !CS_SECURE(regs->r_cs))
3258                 return (EINVAL);
3259         pcb = td->td_pcb;
3260         tp->tf_fs = regs->r_fs;
3261         tp->tf_es = regs->r_es;
3262         tp->tf_ds = regs->r_ds;
3263         tp->tf_edi = regs->r_edi;
3264         tp->tf_esi = regs->r_esi;
3265         tp->tf_ebp = regs->r_ebp;
3266         tp->tf_ebx = regs->r_ebx;
3267         tp->tf_edx = regs->r_edx;
3268         tp->tf_ecx = regs->r_ecx;
3269         tp->tf_eax = regs->r_eax;
3270         tp->tf_eip = regs->r_eip;
3271         tp->tf_cs = regs->r_cs;
3272         tp->tf_eflags = regs->r_eflags;
3273         tp->tf_esp = regs->r_esp;
3274         tp->tf_ss = regs->r_ss;
3275         pcb->pcb_gs = regs->r_gs;
3276         return (0);
3277 }
3278
3279 #ifdef CPU_ENABLE_SSE
3280 static void
3281 fill_fpregs_xmm(sv_xmm, sv_87)
3282         struct savexmm *sv_xmm;
3283         struct save87 *sv_87;
3284 {
3285         register struct env87 *penv_87 = &sv_87->sv_env;
3286         register struct envxmm *penv_xmm = &sv_xmm->sv_env;
3287         int i;
3288
3289         bzero(sv_87, sizeof(*sv_87));
3290
3291         /* FPU control/status */
3292         penv_87->en_cw = penv_xmm->en_cw;
3293         penv_87->en_sw = penv_xmm->en_sw;
3294         penv_87->en_tw = penv_xmm->en_tw;
3295         penv_87->en_fip = penv_xmm->en_fip;
3296         penv_87->en_fcs = penv_xmm->en_fcs;
3297         penv_87->en_opcode = penv_xmm->en_opcode;
3298         penv_87->en_foo = penv_xmm->en_foo;
3299         penv_87->en_fos = penv_xmm->en_fos;
3300
3301         /* FPU registers */
3302         for (i = 0; i < 8; ++i)
3303                 sv_87->sv_ac[i] = sv_xmm->sv_fp[i].fp_acc;
3304 }
3305
3306 static void
3307 set_fpregs_xmm(sv_87, sv_xmm)
3308         struct save87 *sv_87;
3309         struct savexmm *sv_xmm;
3310 {
3311         register struct env87 *penv_87 = &sv_87->sv_env;
3312         register struct envxmm *penv_xmm = &sv_xmm->sv_env;
3313         int i;
3314
3315         /* FPU control/status */
3316         penv_xmm->en_cw = penv_87->en_cw;
3317         penv_xmm->en_sw = penv_87->en_sw;
3318         penv_xmm->en_tw = penv_87->en_tw;
3319         penv_xmm->en_fip = penv_87->en_fip;
3320         penv_xmm->en_fcs = penv_87->en_fcs;
3321         penv_xmm->en_opcode = penv_87->en_opcode;
3322         penv_xmm->en_foo = penv_87->en_foo;
3323         penv_xmm->en_fos = penv_87->en_fos;
3324
3325         /* FPU registers */
3326         for (i = 0; i < 8; ++i)
3327                 sv_xmm->sv_fp[i].fp_acc = sv_87->sv_ac[i];
3328 }
3329 #endif /* CPU_ENABLE_SSE */
3330
3331 int
3332 fill_fpregs(struct thread *td, struct fpreg *fpregs)
3333 {
3334
3335         KASSERT(td == curthread || TD_IS_SUSPENDED(td) ||
3336             P_SHOULDSTOP(td->td_proc),
3337             ("not suspended thread %p", td));
3338 #ifdef DEV_NPX
3339         npxgetregs(td);
3340 #else
3341         bzero(fpregs, sizeof(*fpregs));
3342 #endif
3343 #ifdef CPU_ENABLE_SSE
3344         if (cpu_fxsr)
3345                 fill_fpregs_xmm(&get_pcb_user_save_td(td)->sv_xmm,
3346                     (struct save87 *)fpregs);
3347         else
3348 #endif /* CPU_ENABLE_SSE */
3349                 bcopy(&get_pcb_user_save_td(td)->sv_87, fpregs,
3350                     sizeof(*fpregs));
3351         return (0);
3352 }
3353
3354 int
3355 set_fpregs(struct thread *td, struct fpreg *fpregs)
3356 {
3357
3358 #ifdef CPU_ENABLE_SSE
3359         if (cpu_fxsr)
3360                 set_fpregs_xmm((struct save87 *)fpregs,
3361                     &get_pcb_user_save_td(td)->sv_xmm);
3362         else
3363 #endif /* CPU_ENABLE_SSE */
3364                 bcopy(fpregs, &get_pcb_user_save_td(td)->sv_87,
3365                     sizeof(*fpregs));
3366 #ifdef DEV_NPX
3367         npxuserinited(td);
3368 #endif
3369         return (0);
3370 }
3371
3372 /*
3373  * Get machine context.
3374  */
3375 int
3376 get_mcontext(struct thread *td, mcontext_t *mcp, int flags)
3377 {
3378         struct trapframe *tp;
3379         struct segment_descriptor *sdp;
3380
3381         tp = td->td_frame;
3382
3383         PROC_LOCK(curthread->td_proc);
3384         mcp->mc_onstack = sigonstack(tp->tf_esp);
3385         PROC_UNLOCK(curthread->td_proc);
3386         mcp->mc_gs = td->td_pcb->pcb_gs;
3387         mcp->mc_fs = tp->tf_fs;
3388         mcp->mc_es = tp->tf_es;
3389         mcp->mc_ds = tp->tf_ds;
3390         mcp->mc_edi = tp->tf_edi;
3391         mcp->mc_esi = tp->tf_esi;
3392         mcp->mc_ebp = tp->tf_ebp;
3393         mcp->mc_isp = tp->tf_isp;
3394         mcp->mc_eflags = tp->tf_eflags;
3395         if (flags & GET_MC_CLEAR_RET) {
3396                 mcp->mc_eax = 0;
3397                 mcp->mc_edx = 0;
3398                 mcp->mc_eflags &= ~PSL_C;
3399         } else {
3400                 mcp->mc_eax = tp->tf_eax;
3401                 mcp->mc_edx = tp->tf_edx;
3402         }
3403         mcp->mc_ebx = tp->tf_ebx;
3404         mcp->mc_ecx = tp->tf_ecx;
3405         mcp->mc_eip = tp->tf_eip;
3406         mcp->mc_cs = tp->tf_cs;
3407         mcp->mc_esp = tp->tf_esp;
3408         mcp->mc_ss = tp->tf_ss;
3409         mcp->mc_len = sizeof(*mcp);
3410         get_fpcontext(td, mcp, NULL, 0);
3411         sdp = &td->td_pcb->pcb_fsd;
3412         mcp->mc_fsbase = sdp->sd_hibase << 24 | sdp->sd_lobase;
3413         sdp = &td->td_pcb->pcb_gsd;
3414         mcp->mc_gsbase = sdp->sd_hibase << 24 | sdp->sd_lobase;
3415         mcp->mc_flags = 0;
3416         mcp->mc_xfpustate = 0;
3417         mcp->mc_xfpustate_len = 0;
3418         bzero(mcp->mc_spare2, sizeof(mcp->mc_spare2));
3419         return (0);
3420 }
3421
3422 /*
3423  * Set machine context.
3424  *
3425  * However, we don't set any but the user modifiable flags, and we won't
3426  * touch the cs selector.
3427  */
3428 int
3429 set_mcontext(struct thread *td, mcontext_t *mcp)
3430 {
3431         struct trapframe *tp;
3432         char *xfpustate;
3433         int eflags, ret;
3434
3435         tp = td->td_frame;
3436         if (mcp->mc_len != sizeof(*mcp) ||
3437             (mcp->mc_flags & ~_MC_FLAG_MASK) != 0)
3438                 return (EINVAL);
3439         eflags = (mcp->mc_eflags & PSL_USERCHANGE) |
3440             (tp->tf_eflags & ~PSL_USERCHANGE);
3441         if (mcp->mc_flags & _MC_HASFPXSTATE) {
3442                 if (mcp->mc_xfpustate_len > cpu_max_ext_state_size -
3443                     sizeof(union savefpu))
3444                         return (EINVAL);
3445                 xfpustate = __builtin_alloca(mcp->mc_xfpustate_len);
3446                 ret = copyin((void *)mcp->mc_xfpustate, xfpustate,
3447                     mcp->mc_xfpustate_len);
3448                 if (ret != 0)
3449                         return (ret);
3450         } else
3451                 xfpustate = NULL;
3452         ret = set_fpcontext(td, mcp, xfpustate, mcp->mc_xfpustate_len);
3453         if (ret != 0)
3454                 return (ret);
3455         tp->tf_fs = mcp->mc_fs;
3456         tp->tf_es = mcp->mc_es;
3457         tp->tf_ds = mcp->mc_ds;
3458         tp->tf_edi = mcp->mc_edi;
3459         tp->tf_esi = mcp->mc_esi;
3460         tp->tf_ebp = mcp->mc_ebp;
3461         tp->tf_ebx = mcp->mc_ebx;
3462         tp->tf_edx = mcp->mc_edx;
3463         tp->tf_ecx = mcp->mc_ecx;
3464         tp->tf_eax = mcp->mc_eax;
3465         tp->tf_eip = mcp->mc_eip;
3466         tp->tf_eflags = eflags;
3467         tp->tf_esp = mcp->mc_esp;
3468         tp->tf_ss = mcp->mc_ss;
3469         td->td_pcb->pcb_gs = mcp->mc_gs;
3470         return (0);
3471 }
3472
3473 static void
3474 get_fpcontext(struct thread *td, mcontext_t *mcp, char *xfpusave,
3475     size_t xfpusave_len)
3476 {
3477 #ifdef CPU_ENABLE_SSE
3478         size_t max_len, len;
3479 #endif
3480
3481 #ifndef DEV_NPX
3482         mcp->mc_fpformat = _MC_FPFMT_NODEV;
3483         mcp->mc_ownedfp = _MC_FPOWNED_NONE;
3484         bzero(mcp->mc_fpstate, sizeof(mcp->mc_fpstate));
3485 #else
3486         mcp->mc_ownedfp = npxgetregs(td);
3487         bcopy(get_pcb_user_save_td(td), &mcp->mc_fpstate[0],
3488             sizeof(mcp->mc_fpstate));
3489         mcp->mc_fpformat = npxformat();
3490 #ifdef CPU_ENABLE_SSE
3491         if (!use_xsave || xfpusave_len == 0)
3492                 return;
3493         max_len = cpu_max_ext_state_size - sizeof(union savefpu);
3494         len = xfpusave_len;
3495         if (len > max_len) {
3496                 len = max_len;
3497                 bzero(xfpusave + max_len, len - max_len);
3498         }
3499         mcp->mc_flags |= _MC_HASFPXSTATE;
3500         mcp->mc_xfpustate_len = len;
3501         bcopy(get_pcb_user_save_td(td) + 1, xfpusave, len);
3502 #endif
3503 #endif
3504 }
3505
3506 static int
3507 set_fpcontext(struct thread *td, mcontext_t *mcp, char *xfpustate,
3508     size_t xfpustate_len)
3509 {
3510         union savefpu *fpstate;
3511         int error;
3512
3513         if (mcp->mc_fpformat == _MC_FPFMT_NODEV)
3514                 return (0);
3515         else if (mcp->mc_fpformat != _MC_FPFMT_387 &&
3516             mcp->mc_fpformat != _MC_FPFMT_XMM)
3517                 return (EINVAL);
3518         else if (mcp->mc_ownedfp == _MC_FPOWNED_NONE) {
3519                 /* We don't care what state is left in the FPU or PCB. */
3520                 fpstate_drop(td);
3521                 error = 0;
3522         } else if (mcp->mc_ownedfp == _MC_FPOWNED_FPU ||
3523             mcp->mc_ownedfp == _MC_FPOWNED_PCB) {
3524 #ifdef DEV_NPX
3525                 fpstate = (union savefpu *)&mcp->mc_fpstate;
3526 #ifdef CPU_ENABLE_SSE
3527                 if (cpu_fxsr)
3528                         fpstate->sv_xmm.sv_env.en_mxcsr &= cpu_mxcsr_mask;
3529 #endif
3530                 error = npxsetregs(td, fpstate, xfpustate, xfpustate_len);
3531 #else
3532                 error = EINVAL;
3533 #endif
3534         } else
3535                 return (EINVAL);
3536         return (error);
3537 }
3538
3539 static void
3540 fpstate_drop(struct thread *td)
3541 {
3542
3543         KASSERT(PCB_USER_FPU(td->td_pcb), ("fpstate_drop: kernel-owned fpu"));
3544         critical_enter();
3545 #ifdef DEV_NPX
3546         if (PCPU_GET(fpcurthread) == td)
3547                 npxdrop();
3548 #endif
3549         /*
3550          * XXX force a full drop of the npx.  The above only drops it if we
3551          * owned it.  npxgetregs() has the same bug in the !cpu_fxsr case.
3552          *
3553          * XXX I don't much like npxgetregs()'s semantics of doing a full
3554          * drop.  Dropping only to the pcb matches fnsave's behaviour.
3555          * We only need to drop to !PCB_INITDONE in sendsig().  But
3556          * sendsig() is the only caller of npxgetregs()... perhaps we just
3557          * have too many layers.
3558          */
3559         curthread->td_pcb->pcb_flags &= ~(PCB_NPXINITDONE |
3560             PCB_NPXUSERINITDONE);
3561         critical_exit();
3562 }
3563
3564 int
3565 fill_dbregs(struct thread *td, struct dbreg *dbregs)
3566 {
3567         struct pcb *pcb;
3568
3569         if (td == NULL) {
3570                 dbregs->dr[0] = rdr0();
3571                 dbregs->dr[1] = rdr1();
3572                 dbregs->dr[2] = rdr2();
3573                 dbregs->dr[3] = rdr3();
3574                 dbregs->dr[4] = rdr4();
3575                 dbregs->dr[5] = rdr5();
3576                 dbregs->dr[6] = rdr6();
3577                 dbregs->dr[7] = rdr7();
3578         } else {
3579                 pcb = td->td_pcb;
3580                 dbregs->dr[0] = pcb->pcb_dr0;
3581                 dbregs->dr[1] = pcb->pcb_dr1;
3582                 dbregs->dr[2] = pcb->pcb_dr2;
3583                 dbregs->dr[3] = pcb->pcb_dr3;
3584                 dbregs->dr[4] = 0;
3585                 dbregs->dr[5] = 0;
3586                 dbregs->dr[6] = pcb->pcb_dr6;
3587                 dbregs->dr[7] = pcb->pcb_dr7;
3588         }
3589         return (0);
3590 }
3591
3592 int
3593 set_dbregs(struct thread *td, struct dbreg *dbregs)
3594 {
3595         struct pcb *pcb;
3596         int i;
3597
3598         if (td == NULL) {
3599                 load_dr0(dbregs->dr[0]);
3600                 load_dr1(dbregs->dr[1]);
3601                 load_dr2(dbregs->dr[2]);
3602                 load_dr3(dbregs->dr[3]);
3603                 load_dr4(dbregs->dr[4]);
3604                 load_dr5(dbregs->dr[5]);
3605                 load_dr6(dbregs->dr[6]);
3606                 load_dr7(dbregs->dr[7]);
3607         } else {
3608                 /*
3609                  * Don't let an illegal value for dr7 get set.  Specifically,
3610                  * check for undefined settings.  Setting these bit patterns
3611                  * result in undefined behaviour and can lead to an unexpected
3612                  * TRCTRAP.
3613                  */
3614                 for (i = 0; i < 4; i++) {
3615                         if (DBREG_DR7_ACCESS(dbregs->dr[7], i) == 0x02)
3616                                 return (EINVAL);
3617                         if (DBREG_DR7_LEN(dbregs->dr[7], i) == 0x02)
3618                                 return (EINVAL);
3619                 }
3620                 
3621                 pcb = td->td_pcb;
3622                 
3623                 /*
3624                  * Don't let a process set a breakpoint that is not within the
3625                  * process's address space.  If a process could do this, it
3626                  * could halt the system by setting a breakpoint in the kernel
3627                  * (if ddb was enabled).  Thus, we need to check to make sure
3628                  * that no breakpoints are being enabled for addresses outside
3629                  * process's address space.
3630                  *
3631                  * XXX - what about when the watched area of the user's
3632                  * address space is written into from within the kernel
3633                  * ... wouldn't that still cause a breakpoint to be generated
3634                  * from within kernel mode?
3635                  */
3636
3637                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 0)) {
3638                         /* dr0 is enabled */
3639                         if (dbregs->dr[0] >= VM_MAXUSER_ADDRESS)
3640                                 return (EINVAL);
3641                 }
3642                         
3643                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 1)) {
3644                         /* dr1 is enabled */
3645                         if (dbregs->dr[1] >= VM_MAXUSER_ADDRESS)
3646                                 return (EINVAL);
3647                 }
3648                         
3649                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 2)) {
3650                         /* dr2 is enabled */
3651                         if (dbregs->dr[2] >= VM_MAXUSER_ADDRESS)
3652                                 return (EINVAL);
3653                 }
3654                         
3655                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 3)) {
3656                         /* dr3 is enabled */
3657                         if (dbregs->dr[3] >= VM_MAXUSER_ADDRESS)
3658                                 return (EINVAL);
3659                 }
3660
3661                 pcb->pcb_dr0 = dbregs->dr[0];
3662                 pcb->pcb_dr1 = dbregs->dr[1];
3663                 pcb->pcb_dr2 = dbregs->dr[2];
3664                 pcb->pcb_dr3 = dbregs->dr[3];
3665                 pcb->pcb_dr6 = dbregs->dr[6];
3666                 pcb->pcb_dr7 = dbregs->dr[7];
3667
3668                 pcb->pcb_flags |= PCB_DBREGS;
3669         }
3670
3671         return (0);
3672 }
3673
3674 /*
3675  * Return > 0 if a hardware breakpoint has been hit, and the
3676  * breakpoint was in user space.  Return 0, otherwise.
3677  */
3678 int
3679 user_dbreg_trap(void)
3680 {
3681         u_int32_t dr7, dr6; /* debug registers dr6 and dr7 */
3682         u_int32_t bp;       /* breakpoint bits extracted from dr6 */
3683         int nbp;            /* number of breakpoints that triggered */
3684         caddr_t addr[4];    /* breakpoint addresses */
3685         int i;
3686         
3687         dr7 = rdr7();
3688         if ((dr7 & 0x000000ff) == 0) {
3689                 /*
3690                  * all GE and LE bits in the dr7 register are zero,
3691                  * thus the trap couldn't have been caused by the
3692                  * hardware debug registers
3693                  */
3694                 return 0;
3695         }
3696
3697         nbp = 0;
3698         dr6 = rdr6();
3699         bp = dr6 & 0x0000000f;
3700
3701         if (!bp) {
3702                 /*
3703                  * None of the breakpoint bits are set meaning this
3704                  * trap was not caused by any of the debug registers
3705                  */
3706                 return 0;
3707         }
3708
3709         /*
3710          * at least one of the breakpoints were hit, check to see
3711          * which ones and if any of them are user space addresses
3712          */
3713
3714         if (bp & 0x01) {
3715                 addr[nbp++] = (caddr_t)rdr0();
3716         }
3717         if (bp & 0x02) {
3718                 addr[nbp++] = (caddr_t)rdr1();
3719         }
3720         if (bp & 0x04) {
3721                 addr[nbp++] = (caddr_t)rdr2();
3722         }
3723         if (bp & 0x08) {
3724                 addr[nbp++] = (caddr_t)rdr3();
3725         }
3726
3727         for (i = 0; i < nbp; i++) {
3728                 if (addr[i] < (caddr_t)VM_MAXUSER_ADDRESS) {
3729                         /*
3730                          * addr[i] is in user space
3731                          */
3732                         return nbp;
3733                 }
3734         }
3735
3736         /*
3737          * None of the breakpoints are in user space.
3738          */
3739         return 0;
3740 }
3741
3742 #ifdef KDB
3743
3744 /*
3745  * Provide inb() and outb() as functions.  They are normally only available as
3746  * inline functions, thus cannot be called from the debugger.
3747  */
3748
3749 /* silence compiler warnings */
3750 u_char inb_(u_short);
3751 void outb_(u_short, u_char);
3752
3753 u_char
3754 inb_(u_short port)
3755 {
3756         return inb(port);
3757 }
3758
3759 void
3760 outb_(u_short port, u_char data)
3761 {
3762         outb(port, data);
3763 }
3764
3765 #endif /* KDB */