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