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