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