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