]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/amd64/machdep.c
MFV r331407: 9213 zfs: sytem typo
[FreeBSD/FreeBSD.git] / sys / amd64 / amd64 / machdep.c
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 2003 Peter Wemm.
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  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *      This product includes software developed by the University of
23  *      California, Berkeley and its contributors.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  *
40  *      from: @(#)machdep.c     7.4 (Berkeley) 6/3/91
41  */
42
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
45
46 #include "opt_atpic.h"
47 #include "opt_compat.h"
48 #include "opt_cpu.h"
49 #include "opt_ddb.h"
50 #include "opt_inet.h"
51 #include "opt_isa.h"
52 #include "opt_kstack_pages.h"
53 #include "opt_maxmem.h"
54 #include "opt_mp_watchdog.h"
55 #include "opt_platform.h"
56 #include "opt_sched.h"
57
58 #include <sys/param.h>
59 #include <sys/proc.h>
60 #include <sys/systm.h>
61 #include <sys/bio.h>
62 #include <sys/buf.h>
63 #include <sys/bus.h>
64 #include <sys/callout.h>
65 #include <sys/cons.h>
66 #include <sys/cpu.h>
67 #include <sys/efi.h>
68 #include <sys/eventhandler.h>
69 #include <sys/exec.h>
70 #include <sys/imgact.h>
71 #include <sys/kdb.h>
72 #include <sys/kernel.h>
73 #include <sys/ktr.h>
74 #include <sys/linker.h>
75 #include <sys/lock.h>
76 #include <sys/malloc.h>
77 #include <sys/memrange.h>
78 #include <sys/msgbuf.h>
79 #include <sys/mutex.h>
80 #include <sys/pcpu.h>
81 #include <sys/ptrace.h>
82 #include <sys/reboot.h>
83 #include <sys/rwlock.h>
84 #include <sys/sched.h>
85 #include <sys/signalvar.h>
86 #ifdef SMP
87 #include <sys/smp.h>
88 #endif
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
105 #ifdef DDB
106 #ifndef KDB
107 #error KDB must be enabled in order for DDB to work!
108 #endif
109 #include <ddb/ddb.h>
110 #include <ddb/db_sym.h>
111 #endif
112
113 #include <net/netisr.h>
114
115 #include <machine/clock.h>
116 #include <machine/cpu.h>
117 #include <machine/cputypes.h>
118 #include <machine/frame.h>
119 #include <machine/intr_machdep.h>
120 #include <x86/mca.h>
121 #include <machine/md_var.h>
122 #include <machine/metadata.h>
123 #include <machine/mp_watchdog.h>
124 #include <machine/pc/bios.h>
125 #include <machine/pcb.h>
126 #include <machine/proc.h>
127 #include <machine/reg.h>
128 #include <machine/sigframe.h>
129 #include <machine/specialreg.h>
130 #include <machine/tss.h>
131 #ifdef SMP
132 #include <machine/smp.h>
133 #endif
134 #ifdef FDT
135 #include <x86/fdt.h>
136 #endif
137
138 #ifdef DEV_ATPIC
139 #include <x86/isa/icu.h>
140 #else
141 #include <x86/apicvar.h>
142 #endif
143
144 #include <isa/isareg.h>
145 #include <isa/rtc.h>
146 #include <x86/init.h>
147
148 /* Sanity check for __curthread() */
149 CTASSERT(offsetof(struct pcpu, pc_curthread) == 0);
150
151 /*
152  * The PTI trampoline stack needs enough space for a hardware trapframe and a
153  * couple of scratch registers, as well as the trapframe left behind after an
154  * iret fault.
155  */
156 CTASSERT(PC_PTI_STACK_SZ * sizeof(register_t) >= 2 * sizeof(struct pti_frame) -
157     offsetof(struct pti_frame, pti_rip));
158
159 extern u_int64_t hammer_time(u_int64_t, u_int64_t);
160
161 #define CS_SECURE(cs)           (ISPL(cs) == SEL_UPL)
162 #define EFL_SECURE(ef, oef)     ((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
163
164 static void cpu_startup(void *);
165 static void get_fpcontext(struct thread *td, mcontext_t *mcp,
166     char *xfpusave, size_t xfpusave_len);
167 static int  set_fpcontext(struct thread *td, mcontext_t *mcp,
168     char *xfpustate, size_t xfpustate_len);
169 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
170
171 /* Preload data parse function */
172 static caddr_t native_parse_preload_data(u_int64_t);
173
174 /* Native function to fetch and parse the e820 map */
175 static void native_parse_memmap(caddr_t, vm_paddr_t *, int *);
176
177 /* Default init_ops implementation. */
178 struct init_ops init_ops = {
179         .parse_preload_data =   native_parse_preload_data,
180         .early_clock_source_init =      i8254_init,
181         .early_delay =                  i8254_delay,
182         .parse_memmap =                 native_parse_memmap,
183 #ifdef SMP
184         .mp_bootaddress =               mp_bootaddress,
185         .start_all_aps =                native_start_all_aps,
186 #endif
187         .msi_init =                     msi_init,
188 };
189
190 /*
191  * Physical address of the EFI System Table. Stashed from the metadata hints
192  * passed into the kernel and used by the EFI code to call runtime services.
193  */
194 vm_paddr_t efi_systbl_phys;
195
196 /* Intel ICH registers */
197 #define ICH_PMBASE      0x400
198 #define ICH_SMI_EN      ICH_PMBASE + 0x30
199
200 int     _udatasel, _ucodesel, _ucode32sel, _ufssel, _ugssel;
201
202 int cold = 1;
203
204 long Maxmem = 0;
205 long realmem = 0;
206
207 /*
208  * The number of PHYSMAP entries must be one less than the number of
209  * PHYSSEG entries because the PHYSMAP entry that spans the largest
210  * physical address that is accessible by ISA DMA is split into two
211  * PHYSSEG entries.
212  */
213 #define PHYSMAP_SIZE    (2 * (VM_PHYSSEG_MAX - 1))
214
215 vm_paddr_t phys_avail[PHYSMAP_SIZE + 2];
216 vm_paddr_t dump_avail[PHYSMAP_SIZE + 2];
217
218 /* must be 2 less so 0 0 can signal end of chunks */
219 #define PHYS_AVAIL_ARRAY_END (nitems(phys_avail) - 2)
220 #define DUMP_AVAIL_ARRAY_END (nitems(dump_avail) - 2)
221
222 struct kva_md_info kmi;
223
224 static struct trapframe proc0_tf;
225 struct region_descriptor r_gdt, r_idt;
226
227 struct pcpu __pcpu[MAXCPU];
228
229 struct mtx icu_lock;
230
231 struct mem_range_softc mem_range_softc;
232
233 struct mtx dt_lock;     /* lock for GDT and LDT */
234
235 void (*vmm_resume_p)(void);
236
237 static void
238 cpu_startup(dummy)
239         void *dummy;
240 {
241         uintmax_t memsize;
242         char *sysenv;
243
244         /*
245          * On MacBooks, we need to disallow the legacy USB circuit to
246          * generate an SMI# because this can cause several problems,
247          * namely: incorrect CPU frequency detection and failure to
248          * start the APs.
249          * We do this by disabling a bit in the SMI_EN (SMI Control and
250          * Enable register) of the Intel ICH LPC Interface Bridge. 
251          */
252         sysenv = kern_getenv("smbios.system.product");
253         if (sysenv != NULL) {
254                 if (strncmp(sysenv, "MacBook1,1", 10) == 0 ||
255                     strncmp(sysenv, "MacBook3,1", 10) == 0 ||
256                     strncmp(sysenv, "MacBook4,1", 10) == 0 ||
257                     strncmp(sysenv, "MacBookPro1,1", 13) == 0 ||
258                     strncmp(sysenv, "MacBookPro1,2", 13) == 0 ||
259                     strncmp(sysenv, "MacBookPro3,1", 13) == 0 ||
260                     strncmp(sysenv, "MacBookPro4,1", 13) == 0 ||
261                     strncmp(sysenv, "Macmini1,1", 10) == 0) {
262                         if (bootverbose)
263                                 printf("Disabling LEGACY_USB_EN bit on "
264                                     "Intel ICH.\n");
265                         outl(ICH_SMI_EN, inl(ICH_SMI_EN) & ~0x8);
266                 }
267                 freeenv(sysenv);
268         }
269
270         /*
271          * Good {morning,afternoon,evening,night}.
272          */
273         startrtclock();
274         printcpuinfo();
275
276         /*
277          * Display physical memory if SMBIOS reports reasonable amount.
278          */
279         memsize = 0;
280         sysenv = kern_getenv("smbios.memory.enabled");
281         if (sysenv != NULL) {
282                 memsize = (uintmax_t)strtoul(sysenv, (char **)NULL, 10) << 10;
283                 freeenv(sysenv);
284         }
285         if (memsize < ptoa((uintmax_t)vm_free_count()))
286                 memsize = ptoa((uintmax_t)Maxmem);
287         printf("real memory  = %ju (%ju MB)\n", memsize, memsize >> 20);
288         realmem = atop(memsize);
289
290         /*
291          * Display any holes after the first chunk of extended memory.
292          */
293         if (bootverbose) {
294                 int indx;
295
296                 printf("Physical memory chunk(s):\n");
297                 for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
298                         vm_paddr_t size;
299
300                         size = phys_avail[indx + 1] - phys_avail[indx];
301                         printf(
302                             "0x%016jx - 0x%016jx, %ju bytes (%ju pages)\n",
303                             (uintmax_t)phys_avail[indx],
304                             (uintmax_t)phys_avail[indx + 1] - 1,
305                             (uintmax_t)size, (uintmax_t)size / PAGE_SIZE);
306                 }
307         }
308
309         vm_ksubmap_init(&kmi);
310
311         printf("avail memory = %ju (%ju MB)\n",
312             ptoa((uintmax_t)vm_free_count()),
313             ptoa((uintmax_t)vm_free_count()) / 1048576);
314
315         /*
316          * Set up buffers, so they can be used to read disk labels.
317          */
318         bufinit();
319         vm_pager_bufferinit();
320
321         cpu_setregs();
322 }
323
324 /*
325  * Send an interrupt to process.
326  *
327  * Stack is set up to allow sigcode stored
328  * at top to call routine, followed by call
329  * to sigreturn routine below.  After sigreturn
330  * resets the signal mask, the stack, and the
331  * frame pointer, it returns to the user
332  * specified pc, psl.
333  */
334 void
335 sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
336 {
337         struct sigframe sf, *sfp;
338         struct pcb *pcb;
339         struct proc *p;
340         struct thread *td;
341         struct sigacts *psp;
342         char *sp;
343         struct trapframe *regs;
344         char *xfpusave;
345         size_t xfpusave_len;
346         int sig;
347         int oonstack;
348
349         td = curthread;
350         pcb = td->td_pcb;
351         p = td->td_proc;
352         PROC_LOCK_ASSERT(p, MA_OWNED);
353         sig = ksi->ksi_signo;
354         psp = p->p_sigacts;
355         mtx_assert(&psp->ps_mtx, MA_OWNED);
356         regs = td->td_frame;
357         oonstack = sigonstack(regs->tf_rsp);
358
359         if (cpu_max_ext_state_size > sizeof(struct savefpu) && use_xsave) {
360                 xfpusave_len = cpu_max_ext_state_size - sizeof(struct savefpu);
361                 xfpusave = __builtin_alloca(xfpusave_len);
362         } else {
363                 xfpusave_len = 0;
364                 xfpusave = NULL;
365         }
366
367         /* Save user context. */
368         bzero(&sf, sizeof(sf));
369         sf.sf_uc.uc_sigmask = *mask;
370         sf.sf_uc.uc_stack = td->td_sigstk;
371         sf.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
372             ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
373         sf.sf_uc.uc_mcontext.mc_onstack = (oonstack) ? 1 : 0;
374         bcopy(regs, &sf.sf_uc.uc_mcontext.mc_rdi, sizeof(*regs));
375         sf.sf_uc.uc_mcontext.mc_len = sizeof(sf.sf_uc.uc_mcontext); /* magic */
376         get_fpcontext(td, &sf.sf_uc.uc_mcontext, xfpusave, xfpusave_len);
377         fpstate_drop(td);
378         update_pcb_bases(pcb);
379         sf.sf_uc.uc_mcontext.mc_fsbase = pcb->pcb_fsbase;
380         sf.sf_uc.uc_mcontext.mc_gsbase = pcb->pcb_gsbase;
381         bzero(sf.sf_uc.uc_mcontext.mc_spare,
382             sizeof(sf.sf_uc.uc_mcontext.mc_spare));
383         bzero(sf.sf_uc.__spare__, sizeof(sf.sf_uc.__spare__));
384
385         /* Allocate space for the signal handler context. */
386         if ((td->td_pflags & TDP_ALTSTACK) != 0 && !oonstack &&
387             SIGISMEMBER(psp->ps_sigonstack, sig)) {
388                 sp = (char *)td->td_sigstk.ss_sp + td->td_sigstk.ss_size;
389 #if defined(COMPAT_43)
390                 td->td_sigstk.ss_flags |= SS_ONSTACK;
391 #endif
392         } else
393                 sp = (char *)regs->tf_rsp - 128;
394         if (xfpusave != NULL) {
395                 sp -= xfpusave_len;
396                 sp = (char *)((unsigned long)sp & ~0x3Ful);
397                 sf.sf_uc.uc_mcontext.mc_xfpustate = (register_t)sp;
398         }
399         sp -= sizeof(struct sigframe);
400         /* Align to 16 bytes. */
401         sfp = (struct sigframe *)((unsigned long)sp & ~0xFul);
402
403         /* Build the argument list for the signal handler. */
404         regs->tf_rdi = sig;                     /* arg 1 in %rdi */
405         regs->tf_rdx = (register_t)&sfp->sf_uc; /* arg 3 in %rdx */
406         bzero(&sf.sf_si, sizeof(sf.sf_si));
407         if (SIGISMEMBER(psp->ps_siginfo, sig)) {
408                 /* Signal handler installed with SA_SIGINFO. */
409                 regs->tf_rsi = (register_t)&sfp->sf_si; /* arg 2 in %rsi */
410                 sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
411
412                 /* Fill in POSIX parts */
413                 sf.sf_si = ksi->ksi_info;
414                 sf.sf_si.si_signo = sig; /* maybe a translated signal */
415                 regs->tf_rcx = (register_t)ksi->ksi_addr; /* arg 4 in %rcx */
416         } else {
417                 /* Old FreeBSD-style arguments. */
418                 regs->tf_rsi = ksi->ksi_code;   /* arg 2 in %rsi */
419                 regs->tf_rcx = (register_t)ksi->ksi_addr; /* arg 4 in %rcx */
420                 sf.sf_ahu.sf_handler = catcher;
421         }
422         mtx_unlock(&psp->ps_mtx);
423         PROC_UNLOCK(p);
424
425         /*
426          * Copy the sigframe out to the user's stack.
427          */
428         if (copyout(&sf, sfp, sizeof(*sfp)) != 0 ||
429             (xfpusave != NULL && copyout(xfpusave,
430             (void *)sf.sf_uc.uc_mcontext.mc_xfpustate, xfpusave_len)
431             != 0)) {
432 #ifdef DEBUG
433                 printf("process %ld has trashed its stack\n", (long)p->p_pid);
434 #endif
435                 PROC_LOCK(p);
436                 sigexit(td, SIGILL);
437         }
438
439         regs->tf_rsp = (long)sfp;
440         regs->tf_rip = p->p_sysent->sv_sigcode_base;
441         regs->tf_rflags &= ~(PSL_T | PSL_D);
442         regs->tf_cs = _ucodesel;
443         regs->tf_ds = _udatasel;
444         regs->tf_ss = _udatasel;
445         regs->tf_es = _udatasel;
446         regs->tf_fs = _ufssel;
447         regs->tf_gs = _ugssel;
448         regs->tf_flags = TF_HASSEGS;
449         PROC_LOCK(p);
450         mtx_lock(&psp->ps_mtx);
451 }
452
453 /*
454  * System call to cleanup state after a signal
455  * has been taken.  Reset signal mask and
456  * stack state from context left by sendsig (above).
457  * Return to previous pc and psl as specified by
458  * context left by sendsig. Check carefully to
459  * make sure that the user has not modified the
460  * state to gain improper privileges.
461  *
462  * MPSAFE
463  */
464 int
465 sys_sigreturn(td, uap)
466         struct thread *td;
467         struct sigreturn_args /* {
468                 const struct __ucontext *sigcntxp;
469         } */ *uap;
470 {
471         ucontext_t uc;
472         struct pcb *pcb;
473         struct proc *p;
474         struct trapframe *regs;
475         ucontext_t *ucp;
476         char *xfpustate;
477         size_t xfpustate_len;
478         long rflags;
479         int cs, error, ret;
480         ksiginfo_t ksi;
481
482         pcb = td->td_pcb;
483         p = td->td_proc;
484
485         error = copyin(uap->sigcntxp, &uc, sizeof(uc));
486         if (error != 0) {
487                 uprintf("pid %d (%s): sigreturn copyin failed\n",
488                     p->p_pid, td->td_name);
489                 return (error);
490         }
491         ucp = &uc;
492         if ((ucp->uc_mcontext.mc_flags & ~_MC_FLAG_MASK) != 0) {
493                 uprintf("pid %d (%s): sigreturn mc_flags %x\n", p->p_pid,
494                     td->td_name, ucp->uc_mcontext.mc_flags);
495                 return (EINVAL);
496         }
497         regs = td->td_frame;
498         rflags = ucp->uc_mcontext.mc_rflags;
499         /*
500          * Don't allow users to change privileged or reserved flags.
501          */
502         if (!EFL_SECURE(rflags, regs->tf_rflags)) {
503                 uprintf("pid %d (%s): sigreturn rflags = 0x%lx\n", p->p_pid,
504                     td->td_name, rflags);
505                 return (EINVAL);
506         }
507
508         /*
509          * Don't allow users to load a valid privileged %cs.  Let the
510          * hardware check for invalid selectors, excess privilege in
511          * other selectors, invalid %eip's and invalid %esp's.
512          */
513         cs = ucp->uc_mcontext.mc_cs;
514         if (!CS_SECURE(cs)) {
515                 uprintf("pid %d (%s): sigreturn cs = 0x%x\n", p->p_pid,
516                     td->td_name, cs);
517                 ksiginfo_init_trap(&ksi);
518                 ksi.ksi_signo = SIGBUS;
519                 ksi.ksi_code = BUS_OBJERR;
520                 ksi.ksi_trapno = T_PROTFLT;
521                 ksi.ksi_addr = (void *)regs->tf_rip;
522                 trapsignal(td, &ksi);
523                 return (EINVAL);
524         }
525
526         if ((uc.uc_mcontext.mc_flags & _MC_HASFPXSTATE) != 0) {
527                 xfpustate_len = uc.uc_mcontext.mc_xfpustate_len;
528                 if (xfpustate_len > cpu_max_ext_state_size -
529                     sizeof(struct savefpu)) {
530                         uprintf("pid %d (%s): sigreturn xfpusave_len = 0x%zx\n",
531                             p->p_pid, td->td_name, xfpustate_len);
532                         return (EINVAL);
533                 }
534                 xfpustate = __builtin_alloca(xfpustate_len);
535                 error = copyin((const void *)uc.uc_mcontext.mc_xfpustate,
536                     xfpustate, xfpustate_len);
537                 if (error != 0) {
538                         uprintf(
539         "pid %d (%s): sigreturn copying xfpustate failed\n",
540                             p->p_pid, td->td_name);
541                         return (error);
542                 }
543         } else {
544                 xfpustate = NULL;
545                 xfpustate_len = 0;
546         }
547         ret = set_fpcontext(td, &ucp->uc_mcontext, xfpustate, xfpustate_len);
548         if (ret != 0) {
549                 uprintf("pid %d (%s): sigreturn set_fpcontext err %d\n",
550                     p->p_pid, td->td_name, ret);
551                 return (ret);
552         }
553         bcopy(&ucp->uc_mcontext.mc_rdi, regs, sizeof(*regs));
554         update_pcb_bases(pcb);
555         pcb->pcb_fsbase = ucp->uc_mcontext.mc_fsbase;
556         pcb->pcb_gsbase = ucp->uc_mcontext.mc_gsbase;
557
558 #if defined(COMPAT_43)
559         if (ucp->uc_mcontext.mc_onstack & 1)
560                 td->td_sigstk.ss_flags |= SS_ONSTACK;
561         else
562                 td->td_sigstk.ss_flags &= ~SS_ONSTACK;
563 #endif
564
565         kern_sigprocmask(td, SIG_SETMASK, &ucp->uc_sigmask, NULL, 0);
566         return (EJUSTRETURN);
567 }
568
569 #ifdef COMPAT_FREEBSD4
570 int
571 freebsd4_sigreturn(struct thread *td, struct freebsd4_sigreturn_args *uap)
572 {
573  
574         return sys_sigreturn(td, (struct sigreturn_args *)uap);
575 }
576 #endif
577
578 /*
579  * Reset registers to default values on exec.
580  */
581 void
582 exec_setregs(struct thread *td, struct image_params *imgp, u_long stack)
583 {
584         struct trapframe *regs = td->td_frame;
585         struct pcb *pcb = td->td_pcb;
586
587         if (td->td_proc->p_md.md_ldt != NULL)
588                 user_ldt_free(td);
589
590         update_pcb_bases(pcb);
591         pcb->pcb_fsbase = 0;
592         pcb->pcb_gsbase = 0;
593         clear_pcb_flags(pcb, PCB_32BIT);
594         pcb->pcb_initial_fpucw = __INITIAL_FPUCW__;
595
596         bzero((char *)regs, sizeof(struct trapframe));
597         regs->tf_rip = imgp->entry_addr;
598         regs->tf_rsp = ((stack - 8) & ~0xFul) + 8;
599         regs->tf_rdi = stack;           /* argv */
600         regs->tf_rflags = PSL_USER | (regs->tf_rflags & PSL_T);
601         regs->tf_ss = _udatasel;
602         regs->tf_cs = _ucodesel;
603         regs->tf_ds = _udatasel;
604         regs->tf_es = _udatasel;
605         regs->tf_fs = _ufssel;
606         regs->tf_gs = _ugssel;
607         regs->tf_flags = TF_HASSEGS;
608
609         /*
610          * Reset the hardware debug registers if they were in use.
611          * They won't have any meaning for the newly exec'd process.
612          */
613         if (pcb->pcb_flags & PCB_DBREGS) {
614                 pcb->pcb_dr0 = 0;
615                 pcb->pcb_dr1 = 0;
616                 pcb->pcb_dr2 = 0;
617                 pcb->pcb_dr3 = 0;
618                 pcb->pcb_dr6 = 0;
619                 pcb->pcb_dr7 = 0;
620                 if (pcb == curpcb) {
621                         /*
622                          * Clear the debug registers on the running
623                          * CPU, otherwise they will end up affecting
624                          * the next process we switch to.
625                          */
626                         reset_dbregs();
627                 }
628                 clear_pcb_flags(pcb, PCB_DBREGS);
629         }
630
631         /*
632          * Drop the FP state if we hold it, so that the process gets a
633          * clean FP state if it uses the FPU again.
634          */
635         fpstate_drop(td);
636 }
637
638 void
639 cpu_setregs(void)
640 {
641         register_t cr0;
642
643         cr0 = rcr0();
644         /*
645          * CR0_MP, CR0_NE and CR0_TS are also set by npx_probe() for the
646          * BSP.  See the comments there about why we set them.
647          */
648         cr0 |= CR0_MP | CR0_NE | CR0_TS | CR0_WP | CR0_AM;
649         load_cr0(cr0);
650 }
651
652 /*
653  * Initialize amd64 and configure to run kernel
654  */
655
656 /*
657  * Initialize segments & interrupt table
658  */
659
660 struct user_segment_descriptor gdt[NGDT * MAXCPU];/* global descriptor tables */
661 static struct gate_descriptor idt0[NIDT];
662 struct gate_descriptor *idt = &idt0[0]; /* interrupt descriptor table */
663
664 static char dblfault_stack[PAGE_SIZE] __aligned(16);
665 static char mce0_stack[PAGE_SIZE] __aligned(16);
666 static char nmi0_stack[PAGE_SIZE] __aligned(16);
667 CTASSERT(sizeof(struct nmi_pcpu) == 16);
668
669 struct amd64tss common_tss[MAXCPU];
670
671 /*
672  * Software prototypes -- in more palatable form.
673  *
674  * Keep GUFS32, GUGS32, GUCODE32 and GUDATA at the same
675  * slots as corresponding segments for i386 kernel.
676  */
677 struct soft_segment_descriptor gdt_segs[] = {
678 /* GNULL_SEL    0 Null Descriptor */
679 {       .ssd_base = 0x0,
680         .ssd_limit = 0x0,
681         .ssd_type = 0,
682         .ssd_dpl = 0,
683         .ssd_p = 0,
684         .ssd_long = 0,
685         .ssd_def32 = 0,
686         .ssd_gran = 0           },
687 /* GNULL2_SEL   1 Null Descriptor */
688 {       .ssd_base = 0x0,
689         .ssd_limit = 0x0,
690         .ssd_type = 0,
691         .ssd_dpl = 0,
692         .ssd_p = 0,
693         .ssd_long = 0,
694         .ssd_def32 = 0,
695         .ssd_gran = 0           },
696 /* GUFS32_SEL   2 32 bit %gs Descriptor for user */
697 {       .ssd_base = 0x0,
698         .ssd_limit = 0xfffff,
699         .ssd_type = SDT_MEMRWA,
700         .ssd_dpl = SEL_UPL,
701         .ssd_p = 1,
702         .ssd_long = 0,
703         .ssd_def32 = 1,
704         .ssd_gran = 1           },
705 /* GUGS32_SEL   3 32 bit %fs Descriptor for user */
706 {       .ssd_base = 0x0,
707         .ssd_limit = 0xfffff,
708         .ssd_type = SDT_MEMRWA,
709         .ssd_dpl = SEL_UPL,
710         .ssd_p = 1,
711         .ssd_long = 0,
712         .ssd_def32 = 1,
713         .ssd_gran = 1           },
714 /* GCODE_SEL    4 Code Descriptor for kernel */
715 {       .ssd_base = 0x0,
716         .ssd_limit = 0xfffff,
717         .ssd_type = SDT_MEMERA,
718         .ssd_dpl = SEL_KPL,
719         .ssd_p = 1,
720         .ssd_long = 1,
721         .ssd_def32 = 0,
722         .ssd_gran = 1           },
723 /* GDATA_SEL    5 Data Descriptor for kernel */
724 {       .ssd_base = 0x0,
725         .ssd_limit = 0xfffff,
726         .ssd_type = SDT_MEMRWA,
727         .ssd_dpl = SEL_KPL,
728         .ssd_p = 1,
729         .ssd_long = 1,
730         .ssd_def32 = 0,
731         .ssd_gran = 1           },
732 /* GUCODE32_SEL 6 32 bit Code Descriptor for user */
733 {       .ssd_base = 0x0,
734         .ssd_limit = 0xfffff,
735         .ssd_type = SDT_MEMERA,
736         .ssd_dpl = SEL_UPL,
737         .ssd_p = 1,
738         .ssd_long = 0,
739         .ssd_def32 = 1,
740         .ssd_gran = 1           },
741 /* GUDATA_SEL   7 32/64 bit Data Descriptor for user */
742 {       .ssd_base = 0x0,
743         .ssd_limit = 0xfffff,
744         .ssd_type = SDT_MEMRWA,
745         .ssd_dpl = SEL_UPL,
746         .ssd_p = 1,
747         .ssd_long = 0,
748         .ssd_def32 = 1,
749         .ssd_gran = 1           },
750 /* GUCODE_SEL   8 64 bit Code Descriptor for user */
751 {       .ssd_base = 0x0,
752         .ssd_limit = 0xfffff,
753         .ssd_type = SDT_MEMERA,
754         .ssd_dpl = SEL_UPL,
755         .ssd_p = 1,
756         .ssd_long = 1,
757         .ssd_def32 = 0,
758         .ssd_gran = 1           },
759 /* GPROC0_SEL   9 Proc 0 Tss Descriptor */
760 {       .ssd_base = 0x0,
761         .ssd_limit = sizeof(struct amd64tss) + IOPERM_BITMAP_SIZE - 1,
762         .ssd_type = SDT_SYSTSS,
763         .ssd_dpl = SEL_KPL,
764         .ssd_p = 1,
765         .ssd_long = 0,
766         .ssd_def32 = 0,
767         .ssd_gran = 0           },
768 /* Actually, the TSS is a system descriptor which is double size */
769 {       .ssd_base = 0x0,
770         .ssd_limit = 0x0,
771         .ssd_type = 0,
772         .ssd_dpl = 0,
773         .ssd_p = 0,
774         .ssd_long = 0,
775         .ssd_def32 = 0,
776         .ssd_gran = 0           },
777 /* GUSERLDT_SEL 11 LDT Descriptor */
778 {       .ssd_base = 0x0,
779         .ssd_limit = 0x0,
780         .ssd_type = 0,
781         .ssd_dpl = 0,
782         .ssd_p = 0,
783         .ssd_long = 0,
784         .ssd_def32 = 0,
785         .ssd_gran = 0           },
786 /* GUSERLDT_SEL 12 LDT Descriptor, double size */
787 {       .ssd_base = 0x0,
788         .ssd_limit = 0x0,
789         .ssd_type = 0,
790         .ssd_dpl = 0,
791         .ssd_p = 0,
792         .ssd_long = 0,
793         .ssd_def32 = 0,
794         .ssd_gran = 0           },
795 };
796
797 void
798 setidt(int idx, inthand_t *func, int typ, int dpl, int ist)
799 {
800         struct gate_descriptor *ip;
801
802         ip = idt + idx;
803         ip->gd_looffset = (uintptr_t)func;
804         ip->gd_selector = GSEL(GCODE_SEL, SEL_KPL);
805         ip->gd_ist = ist;
806         ip->gd_xx = 0;
807         ip->gd_type = typ;
808         ip->gd_dpl = dpl;
809         ip->gd_p = 1;
810         ip->gd_hioffset = ((uintptr_t)func)>>16 ;
811 }
812
813 extern inthand_t
814         IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
815         IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
816         IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
817         IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
818         IDTVEC(xmm), IDTVEC(dblfault),
819         IDTVEC(div_pti), IDTVEC(dbg_pti), IDTVEC(bpt_pti),
820         IDTVEC(ofl_pti), IDTVEC(bnd_pti), IDTVEC(ill_pti), IDTVEC(dna_pti),
821         IDTVEC(fpusegm_pti), IDTVEC(tss_pti), IDTVEC(missing_pti),
822         IDTVEC(stk_pti), IDTVEC(prot_pti), IDTVEC(page_pti),
823         IDTVEC(rsvd_pti), IDTVEC(fpu_pti), IDTVEC(align_pti),
824         IDTVEC(xmm_pti),
825 #ifdef KDTRACE_HOOKS
826         IDTVEC(dtrace_ret), IDTVEC(dtrace_ret_pti),
827 #endif
828 #ifdef XENHVM
829         IDTVEC(xen_intr_upcall), IDTVEC(xen_intr_upcall_pti),
830 #endif
831         IDTVEC(fast_syscall), IDTVEC(fast_syscall32),
832         IDTVEC(fast_syscall_pti);
833
834 #ifdef DDB
835 /*
836  * Display the index and function name of any IDT entries that don't use
837  * the default 'rsvd' entry point.
838  */
839 DB_SHOW_COMMAND(idt, db_show_idt)
840 {
841         struct gate_descriptor *ip;
842         int idx;
843         uintptr_t func;
844
845         ip = idt;
846         for (idx = 0; idx < NIDT && !db_pager_quit; idx++) {
847                 func = ((long)ip->gd_hioffset << 16 | ip->gd_looffset);
848                 if (func != (uintptr_t)&IDTVEC(rsvd)) {
849                         db_printf("%3d\t", idx);
850                         db_printsym(func, DB_STGY_PROC);
851                         db_printf("\n");
852                 }
853                 ip++;
854         }
855 }
856
857 /* Show privileged registers. */
858 DB_SHOW_COMMAND(sysregs, db_show_sysregs)
859 {
860         struct {
861                 uint16_t limit;
862                 uint64_t base;
863         } __packed idtr, gdtr;
864         uint16_t ldt, tr;
865
866         __asm __volatile("sidt %0" : "=m" (idtr));
867         db_printf("idtr\t0x%016lx/%04x\n",
868             (u_long)idtr.base, (u_int)idtr.limit);
869         __asm __volatile("sgdt %0" : "=m" (gdtr));
870         db_printf("gdtr\t0x%016lx/%04x\n",
871             (u_long)gdtr.base, (u_int)gdtr.limit);
872         __asm __volatile("sldt %0" : "=r" (ldt));
873         db_printf("ldtr\t0x%04x\n", ldt);
874         __asm __volatile("str %0" : "=r" (tr));
875         db_printf("tr\t0x%04x\n", tr);
876         db_printf("cr0\t0x%016lx\n", rcr0());
877         db_printf("cr2\t0x%016lx\n", rcr2());
878         db_printf("cr3\t0x%016lx\n", rcr3());
879         db_printf("cr4\t0x%016lx\n", rcr4());
880         if (rcr4() & CR4_XSAVE)
881                 db_printf("xcr0\t0x%016lx\n", rxcr(0));
882         db_printf("EFER\t0x%016lx\n", rdmsr(MSR_EFER));
883         if (cpu_feature2 & (CPUID2_VMX | CPUID2_SMX))
884                 db_printf("FEATURES_CTL\t%016lx\n",
885                     rdmsr(MSR_IA32_FEATURE_CONTROL));
886         db_printf("DEBUG_CTL\t0x%016lx\n", rdmsr(MSR_DEBUGCTLMSR));
887         db_printf("PAT\t0x%016lx\n", rdmsr(MSR_PAT));
888         db_printf("GSBASE\t0x%016lx\n", rdmsr(MSR_GSBASE));
889 }
890
891 DB_SHOW_COMMAND(dbregs, db_show_dbregs)
892 {
893
894         db_printf("dr0\t0x%016lx\n", rdr0());
895         db_printf("dr1\t0x%016lx\n", rdr1());
896         db_printf("dr2\t0x%016lx\n", rdr2());
897         db_printf("dr3\t0x%016lx\n", rdr3());
898         db_printf("dr6\t0x%016lx\n", rdr6());
899         db_printf("dr7\t0x%016lx\n", rdr7());   
900 }
901 #endif
902
903 void
904 sdtossd(sd, ssd)
905         struct user_segment_descriptor *sd;
906         struct soft_segment_descriptor *ssd;
907 {
908
909         ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
910         ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
911         ssd->ssd_type  = sd->sd_type;
912         ssd->ssd_dpl   = sd->sd_dpl;
913         ssd->ssd_p     = sd->sd_p;
914         ssd->ssd_long  = sd->sd_long;
915         ssd->ssd_def32 = sd->sd_def32;
916         ssd->ssd_gran  = sd->sd_gran;
917 }
918
919 void
920 ssdtosd(ssd, sd)
921         struct soft_segment_descriptor *ssd;
922         struct user_segment_descriptor *sd;
923 {
924
925         sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
926         sd->sd_hibase = (ssd->ssd_base >> 24) & 0xff;
927         sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
928         sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
929         sd->sd_type  = ssd->ssd_type;
930         sd->sd_dpl   = ssd->ssd_dpl;
931         sd->sd_p     = ssd->ssd_p;
932         sd->sd_long  = ssd->ssd_long;
933         sd->sd_def32 = ssd->ssd_def32;
934         sd->sd_gran  = ssd->ssd_gran;
935 }
936
937 void
938 ssdtosyssd(ssd, sd)
939         struct soft_segment_descriptor *ssd;
940         struct system_segment_descriptor *sd;
941 {
942
943         sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
944         sd->sd_hibase = (ssd->ssd_base >> 24) & 0xfffffffffful;
945         sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
946         sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
947         sd->sd_type  = ssd->ssd_type;
948         sd->sd_dpl   = ssd->ssd_dpl;
949         sd->sd_p     = ssd->ssd_p;
950         sd->sd_gran  = ssd->ssd_gran;
951 }
952
953 #if !defined(DEV_ATPIC) && defined(DEV_ISA)
954 #include <isa/isavar.h>
955 #include <isa/isareg.h>
956 /*
957  * Return a bitmap of the current interrupt requests.  This is 8259-specific
958  * and is only suitable for use at probe time.
959  * This is only here to pacify sio.  It is NOT FATAL if this doesn't work.
960  * It shouldn't be here.  There should probably be an APIC centric
961  * implementation in the apic driver code, if at all.
962  */
963 intrmask_t
964 isa_irq_pending(void)
965 {
966         u_char irr1;
967         u_char irr2;
968
969         irr1 = inb(IO_ICU1);
970         irr2 = inb(IO_ICU2);
971         return ((irr2 << 8) | irr1);
972 }
973 #endif
974
975 u_int basemem;
976
977 static int
978 add_physmap_entry(uint64_t base, uint64_t length, vm_paddr_t *physmap,
979     int *physmap_idxp)
980 {
981         int i, insert_idx, physmap_idx;
982
983         physmap_idx = *physmap_idxp;
984
985         if (length == 0)
986                 return (1);
987
988         /*
989          * Find insertion point while checking for overlap.  Start off by
990          * assuming the new entry will be added to the end.
991          *
992          * NB: physmap_idx points to the next free slot.
993          */
994         insert_idx = physmap_idx;
995         for (i = 0; i <= physmap_idx; i += 2) {
996                 if (base < physmap[i + 1]) {
997                         if (base + length <= physmap[i]) {
998                                 insert_idx = i;
999                                 break;
1000                         }
1001                         if (boothowto & RB_VERBOSE)
1002                                 printf(
1003                     "Overlapping memory regions, ignoring second region\n");
1004                         return (1);
1005                 }
1006         }
1007
1008         /* See if we can prepend to the next entry. */
1009         if (insert_idx <= physmap_idx && base + length == physmap[insert_idx]) {
1010                 physmap[insert_idx] = base;
1011                 return (1);
1012         }
1013
1014         /* See if we can append to the previous entry. */
1015         if (insert_idx > 0 && base == physmap[insert_idx - 1]) {
1016                 physmap[insert_idx - 1] += length;
1017                 return (1);
1018         }
1019
1020         physmap_idx += 2;
1021         *physmap_idxp = physmap_idx;
1022         if (physmap_idx == PHYSMAP_SIZE) {
1023                 printf(
1024                 "Too many segments in the physical address map, giving up\n");
1025                 return (0);
1026         }
1027
1028         /*
1029          * Move the last 'N' entries down to make room for the new
1030          * entry if needed.
1031          */
1032         for (i = (physmap_idx - 2); i > insert_idx; i -= 2) {
1033                 physmap[i] = physmap[i - 2];
1034                 physmap[i + 1] = physmap[i - 1];
1035         }
1036
1037         /* Insert the new entry. */
1038         physmap[insert_idx] = base;
1039         physmap[insert_idx + 1] = base + length;
1040         return (1);
1041 }
1042
1043 void
1044 bios_add_smap_entries(struct bios_smap *smapbase, u_int32_t smapsize,
1045                       vm_paddr_t *physmap, int *physmap_idx)
1046 {
1047         struct bios_smap *smap, *smapend;
1048
1049         smapend = (struct bios_smap *)((uintptr_t)smapbase + smapsize);
1050
1051         for (smap = smapbase; smap < smapend; smap++) {
1052                 if (boothowto & RB_VERBOSE)
1053                         printf("SMAP type=%02x base=%016lx len=%016lx\n",
1054                             smap->type, smap->base, smap->length);
1055
1056                 if (smap->type != SMAP_TYPE_MEMORY)
1057                         continue;
1058
1059                 if (!add_physmap_entry(smap->base, smap->length, physmap,
1060                     physmap_idx))
1061                         break;
1062         }
1063 }
1064
1065 static void
1066 add_efi_map_entries(struct efi_map_header *efihdr, vm_paddr_t *physmap,
1067     int *physmap_idx)
1068 {
1069         struct efi_md *map, *p;
1070         const char *type;
1071         size_t efisz;
1072         int ndesc, i;
1073
1074         static const char *types[] = {
1075                 "Reserved",
1076                 "LoaderCode",
1077                 "LoaderData",
1078                 "BootServicesCode",
1079                 "BootServicesData",
1080                 "RuntimeServicesCode",
1081                 "RuntimeServicesData",
1082                 "ConventionalMemory",
1083                 "UnusableMemory",
1084                 "ACPIReclaimMemory",
1085                 "ACPIMemoryNVS",
1086                 "MemoryMappedIO",
1087                 "MemoryMappedIOPortSpace",
1088                 "PalCode",
1089                 "PersistentMemory"
1090         };
1091
1092         /*
1093          * Memory map data provided by UEFI via the GetMemoryMap
1094          * Boot Services API.
1095          */
1096         efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
1097         map = (struct efi_md *)((uint8_t *)efihdr + efisz);
1098
1099         if (efihdr->descriptor_size == 0)
1100                 return;
1101         ndesc = efihdr->memory_size / efihdr->descriptor_size;
1102
1103         if (boothowto & RB_VERBOSE)
1104                 printf("%23s %12s %12s %8s %4s\n",
1105                     "Type", "Physical", "Virtual", "#Pages", "Attr");
1106
1107         for (i = 0, p = map; i < ndesc; i++,
1108             p = efi_next_descriptor(p, efihdr->descriptor_size)) {
1109                 if (boothowto & RB_VERBOSE) {
1110                         if (p->md_type < nitems(types))
1111                                 type = types[p->md_type];
1112                         else
1113                                 type = "<INVALID>";
1114                         printf("%23s %012lx %12p %08lx ", type, p->md_phys,
1115                             p->md_virt, p->md_pages);
1116                         if (p->md_attr & EFI_MD_ATTR_UC)
1117                                 printf("UC ");
1118                         if (p->md_attr & EFI_MD_ATTR_WC)
1119                                 printf("WC ");
1120                         if (p->md_attr & EFI_MD_ATTR_WT)
1121                                 printf("WT ");
1122                         if (p->md_attr & EFI_MD_ATTR_WB)
1123                                 printf("WB ");
1124                         if (p->md_attr & EFI_MD_ATTR_UCE)
1125                                 printf("UCE ");
1126                         if (p->md_attr & EFI_MD_ATTR_WP)
1127                                 printf("WP ");
1128                         if (p->md_attr & EFI_MD_ATTR_RP)
1129                                 printf("RP ");
1130                         if (p->md_attr & EFI_MD_ATTR_XP)
1131                                 printf("XP ");
1132                         if (p->md_attr & EFI_MD_ATTR_NV)
1133                                 printf("NV ");
1134                         if (p->md_attr & EFI_MD_ATTR_MORE_RELIABLE)
1135                                 printf("MORE_RELIABLE ");
1136                         if (p->md_attr & EFI_MD_ATTR_RO)
1137                                 printf("RO ");
1138                         if (p->md_attr & EFI_MD_ATTR_RT)
1139                                 printf("RUNTIME");
1140                         printf("\n");
1141                 }
1142
1143                 switch (p->md_type) {
1144                 case EFI_MD_TYPE_CODE:
1145                 case EFI_MD_TYPE_DATA:
1146                 case EFI_MD_TYPE_BS_CODE:
1147                 case EFI_MD_TYPE_BS_DATA:
1148                 case EFI_MD_TYPE_FREE:
1149                         /*
1150                          * We're allowed to use any entry with these types.
1151                          */
1152                         break;
1153                 default:
1154                         continue;
1155                 }
1156
1157                 if (!add_physmap_entry(p->md_phys, (p->md_pages * PAGE_SIZE),
1158                     physmap, physmap_idx))
1159                         break;
1160         }
1161 }
1162
1163 static char bootmethod[16] = "";
1164 SYSCTL_STRING(_machdep, OID_AUTO, bootmethod, CTLFLAG_RD, bootmethod, 0,
1165     "System firmware boot method");
1166
1167 static void
1168 native_parse_memmap(caddr_t kmdp, vm_paddr_t *physmap, int *physmap_idx)
1169 {
1170         struct bios_smap *smap;
1171         struct efi_map_header *efihdr;
1172         u_int32_t size;
1173
1174         /*
1175          * Memory map from INT 15:E820.
1176          *
1177          * subr_module.c says:
1178          * "Consumer may safely assume that size value precedes data."
1179          * ie: an int32_t immediately precedes smap.
1180          */
1181
1182         efihdr = (struct efi_map_header *)preload_search_info(kmdp,
1183             MODINFO_METADATA | MODINFOMD_EFI_MAP);
1184         smap = (struct bios_smap *)preload_search_info(kmdp,
1185             MODINFO_METADATA | MODINFOMD_SMAP);
1186         if (efihdr == NULL && smap == NULL)
1187                 panic("No BIOS smap or EFI map info from loader!");
1188
1189         if (efihdr != NULL) {
1190                 add_efi_map_entries(efihdr, physmap, physmap_idx);
1191                 strlcpy(bootmethod, "UEFI", sizeof(bootmethod));
1192         } else {
1193                 size = *((u_int32_t *)smap - 1);
1194                 bios_add_smap_entries(smap, size, physmap, physmap_idx);
1195                 strlcpy(bootmethod, "BIOS", sizeof(bootmethod));
1196         }
1197 }
1198
1199 #define PAGES_PER_GB    (1024 * 1024 * 1024 / PAGE_SIZE)
1200
1201 /*
1202  * Populate the (physmap) array with base/bound pairs describing the
1203  * available physical memory in the system, then test this memory and
1204  * build the phys_avail array describing the actually-available memory.
1205  *
1206  * Total memory size may be set by the kernel environment variable
1207  * hw.physmem or the compile-time define MAXMEM.
1208  *
1209  * XXX first should be vm_paddr_t.
1210  */
1211 static void
1212 getmemsize(caddr_t kmdp, u_int64_t first)
1213 {
1214         int i, physmap_idx, pa_indx, da_indx;
1215         vm_paddr_t pa, physmap[PHYSMAP_SIZE];
1216         u_long physmem_start, physmem_tunable, memtest;
1217         pt_entry_t *pte;
1218         quad_t dcons_addr, dcons_size;
1219         int page_counter;
1220
1221         bzero(physmap, sizeof(physmap));
1222         physmap_idx = 0;
1223
1224         init_ops.parse_memmap(kmdp, physmap, &physmap_idx);
1225         physmap_idx -= 2;
1226
1227         /*
1228          * Find the 'base memory' segment for SMP
1229          */
1230         basemem = 0;
1231         for (i = 0; i <= physmap_idx; i += 2) {
1232                 if (physmap[i] <= 0xA0000) {
1233                         basemem = physmap[i + 1] / 1024;
1234                         break;
1235                 }
1236         }
1237         if (basemem == 0 || basemem > 640) {
1238                 if (bootverbose)
1239                         printf(
1240                 "Memory map doesn't contain a basemem segment, faking it");
1241                 basemem = 640;
1242         }
1243
1244         /*
1245          * Make hole for "AP -> long mode" bootstrap code.  The
1246          * mp_bootaddress vector is only available when the kernel
1247          * is configured to support APs and APs for the system start
1248          * in 32bit mode (e.g. SMP bare metal).
1249          */
1250         if (init_ops.mp_bootaddress) {
1251                 if (physmap[1] >= 0x100000000)
1252                         panic(
1253         "Basemem segment is not suitable for AP bootstrap code!");
1254                 physmap[1] = init_ops.mp_bootaddress(physmap[1] / 1024);
1255         }
1256
1257         /*
1258          * Maxmem isn't the "maximum memory", it's one larger than the
1259          * highest page of the physical address space.  It should be
1260          * called something like "Maxphyspage".  We may adjust this
1261          * based on ``hw.physmem'' and the results of the memory test.
1262          */
1263         Maxmem = atop(physmap[physmap_idx + 1]);
1264
1265 #ifdef MAXMEM
1266         Maxmem = MAXMEM / 4;
1267 #endif
1268
1269         if (TUNABLE_ULONG_FETCH("hw.physmem", &physmem_tunable))
1270                 Maxmem = atop(physmem_tunable);
1271
1272         /*
1273          * The boot memory test is disabled by default, as it takes a
1274          * significant amount of time on large-memory systems, and is
1275          * unfriendly to virtual machines as it unnecessarily touches all
1276          * pages.
1277          *
1278          * A general name is used as the code may be extended to support
1279          * additional tests beyond the current "page present" test.
1280          */
1281         memtest = 0;
1282         TUNABLE_ULONG_FETCH("hw.memtest.tests", &memtest);
1283
1284         /*
1285          * Don't allow MAXMEM or hw.physmem to extend the amount of memory
1286          * in the system.
1287          */
1288         if (Maxmem > atop(physmap[physmap_idx + 1]))
1289                 Maxmem = atop(physmap[physmap_idx + 1]);
1290
1291         if (atop(physmap[physmap_idx + 1]) != Maxmem &&
1292             (boothowto & RB_VERBOSE))
1293                 printf("Physical memory use set to %ldK\n", Maxmem * 4);
1294
1295         /* call pmap initialization to make new kernel address space */
1296         pmap_bootstrap(&first);
1297
1298         /*
1299          * Size up each available chunk of physical memory.
1300          *
1301          * XXX Some BIOSes corrupt low 64KB between suspend and resume.
1302          * By default, mask off the first 16 pages unless we appear to be
1303          * running in a VM.
1304          */
1305         physmem_start = (vm_guest > VM_GUEST_NO ? 1 : 16) << PAGE_SHIFT;
1306         TUNABLE_ULONG_FETCH("hw.physmem.start", &physmem_start);
1307         if (physmap[0] < physmem_start) {
1308                 if (physmem_start < PAGE_SIZE)
1309                         physmap[0] = PAGE_SIZE;
1310                 else if (physmem_start >= physmap[1])
1311                         physmap[0] = round_page(physmap[1] - PAGE_SIZE);
1312                 else
1313                         physmap[0] = round_page(physmem_start);
1314         }
1315         pa_indx = 0;
1316         da_indx = 1;
1317         phys_avail[pa_indx++] = physmap[0];
1318         phys_avail[pa_indx] = physmap[0];
1319         dump_avail[da_indx] = physmap[0];
1320         pte = CMAP1;
1321
1322         /*
1323          * Get dcons buffer address
1324          */
1325         if (getenv_quad("dcons.addr", &dcons_addr) == 0 ||
1326             getenv_quad("dcons.size", &dcons_size) == 0)
1327                 dcons_addr = 0;
1328
1329         /*
1330          * physmap is in bytes, so when converting to page boundaries,
1331          * round up the start address and round down the end address.
1332          */
1333         page_counter = 0;
1334         if (memtest != 0)
1335                 printf("Testing system memory");
1336         for (i = 0; i <= physmap_idx; i += 2) {
1337                 vm_paddr_t end;
1338
1339                 end = ptoa((vm_paddr_t)Maxmem);
1340                 if (physmap[i + 1] < end)
1341                         end = trunc_page(physmap[i + 1]);
1342                 for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
1343                         int tmp, page_bad, full;
1344                         int *ptr = (int *)CADDR1;
1345
1346                         full = FALSE;
1347                         /*
1348                          * block out kernel memory as not available.
1349                          */
1350                         if (pa >= (vm_paddr_t)kernphys && pa < first)
1351                                 goto do_dump_avail;
1352
1353                         /*
1354                          * block out dcons buffer
1355                          */
1356                         if (dcons_addr > 0
1357                             && pa >= trunc_page(dcons_addr)
1358                             && pa < dcons_addr + dcons_size)
1359                                 goto do_dump_avail;
1360
1361                         page_bad = FALSE;
1362                         if (memtest == 0)
1363                                 goto skip_memtest;
1364
1365                         /*
1366                          * Print a "." every GB to show we're making
1367                          * progress.
1368                          */
1369                         page_counter++;
1370                         if ((page_counter % PAGES_PER_GB) == 0)
1371                                 printf(".");
1372
1373                         /*
1374                          * map page into kernel: valid, read/write,non-cacheable
1375                          */
1376                         *pte = pa | PG_V | PG_RW | PG_NC_PWT | PG_NC_PCD;
1377                         invltlb();
1378
1379                         tmp = *(int *)ptr;
1380                         /*
1381                          * Test for alternating 1's and 0's
1382                          */
1383                         *(volatile int *)ptr = 0xaaaaaaaa;
1384                         if (*(volatile int *)ptr != 0xaaaaaaaa)
1385                                 page_bad = TRUE;
1386                         /*
1387                          * Test for alternating 0's and 1's
1388                          */
1389                         *(volatile int *)ptr = 0x55555555;
1390                         if (*(volatile int *)ptr != 0x55555555)
1391                                 page_bad = TRUE;
1392                         /*
1393                          * Test for all 1's
1394                          */
1395                         *(volatile int *)ptr = 0xffffffff;
1396                         if (*(volatile int *)ptr != 0xffffffff)
1397                                 page_bad = TRUE;
1398                         /*
1399                          * Test for all 0's
1400                          */
1401                         *(volatile int *)ptr = 0x0;
1402                         if (*(volatile int *)ptr != 0x0)
1403                                 page_bad = TRUE;
1404                         /*
1405                          * Restore original value.
1406                          */
1407                         *(int *)ptr = tmp;
1408
1409 skip_memtest:
1410                         /*
1411                          * Adjust array of valid/good pages.
1412                          */
1413                         if (page_bad == TRUE)
1414                                 continue;
1415                         /*
1416                          * If this good page is a continuation of the
1417                          * previous set of good pages, then just increase
1418                          * the end pointer. Otherwise start a new chunk.
1419                          * Note that "end" points one higher than end,
1420                          * making the range >= start and < end.
1421                          * If we're also doing a speculative memory
1422                          * test and we at or past the end, bump up Maxmem
1423                          * so that we keep going. The first bad page
1424                          * will terminate the loop.
1425                          */
1426                         if (phys_avail[pa_indx] == pa) {
1427                                 phys_avail[pa_indx] += PAGE_SIZE;
1428                         } else {
1429                                 pa_indx++;
1430                                 if (pa_indx == PHYS_AVAIL_ARRAY_END) {
1431                                         printf(
1432                 "Too many holes in the physical address space, giving up\n");
1433                                         pa_indx--;
1434                                         full = TRUE;
1435                                         goto do_dump_avail;
1436                                 }
1437                                 phys_avail[pa_indx++] = pa;     /* start */
1438                                 phys_avail[pa_indx] = pa + PAGE_SIZE; /* end */
1439                         }
1440                         physmem++;
1441 do_dump_avail:
1442                         if (dump_avail[da_indx] == pa) {
1443                                 dump_avail[da_indx] += PAGE_SIZE;
1444                         } else {
1445                                 da_indx++;
1446                                 if (da_indx == DUMP_AVAIL_ARRAY_END) {
1447                                         da_indx--;
1448                                         goto do_next;
1449                                 }
1450                                 dump_avail[da_indx++] = pa; /* start */
1451                                 dump_avail[da_indx] = pa + PAGE_SIZE; /* end */
1452                         }
1453 do_next:
1454                         if (full)
1455                                 break;
1456                 }
1457         }
1458         *pte = 0;
1459         invltlb();
1460         if (memtest != 0)
1461                 printf("\n");
1462
1463         /*
1464          * XXX
1465          * The last chunk must contain at least one page plus the message
1466          * buffer to avoid complicating other code (message buffer address
1467          * calculation, etc.).
1468          */
1469         while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1470             round_page(msgbufsize) >= phys_avail[pa_indx]) {
1471                 physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1472                 phys_avail[pa_indx--] = 0;
1473                 phys_avail[pa_indx--] = 0;
1474         }
1475
1476         Maxmem = atop(phys_avail[pa_indx]);
1477
1478         /* Trim off space for the message buffer. */
1479         phys_avail[pa_indx] -= round_page(msgbufsize);
1480
1481         /* Map the message buffer. */
1482         msgbufp = (struct msgbuf *)PHYS_TO_DMAP(phys_avail[pa_indx]);
1483 }
1484
1485 static caddr_t
1486 native_parse_preload_data(u_int64_t modulep)
1487 {
1488         caddr_t kmdp;
1489         char *envp;
1490 #ifdef DDB
1491         vm_offset_t ksym_start;
1492         vm_offset_t ksym_end;
1493 #endif
1494
1495         preload_metadata = (caddr_t)(uintptr_t)(modulep + KERNBASE);
1496         preload_bootstrap_relocate(KERNBASE);
1497         kmdp = preload_search_by_type("elf kernel");
1498         if (kmdp == NULL)
1499                 kmdp = preload_search_by_type("elf64 kernel");
1500         boothowto = MD_FETCH(kmdp, MODINFOMD_HOWTO, int);
1501         envp = MD_FETCH(kmdp, MODINFOMD_ENVP, char *);
1502         if (envp != NULL)
1503                 envp += KERNBASE;
1504         init_static_kenv(envp, 0);
1505 #ifdef DDB
1506         ksym_start = MD_FETCH(kmdp, MODINFOMD_SSYM, uintptr_t);
1507         ksym_end = MD_FETCH(kmdp, MODINFOMD_ESYM, uintptr_t);
1508         db_fetch_ksymtab(ksym_start, ksym_end);
1509 #endif
1510         efi_systbl_phys = MD_FETCH(kmdp, MODINFOMD_FW_HANDLE, vm_paddr_t);
1511
1512         return (kmdp);
1513 }
1514
1515 static void
1516 amd64_kdb_init(void)
1517 {
1518         kdb_init();
1519 #ifdef KDB
1520         if (boothowto & RB_KDB)
1521                 kdb_enter(KDB_WHY_BOOTFLAGS, "Boot flags requested debugger");
1522 #endif
1523 }
1524
1525 /* Set up the fast syscall stuff */
1526 void
1527 amd64_conf_fast_syscall(void)
1528 {
1529         uint64_t msr;
1530
1531         msr = rdmsr(MSR_EFER) | EFER_SCE;
1532         wrmsr(MSR_EFER, msr);
1533         wrmsr(MSR_LSTAR, pti ? (u_int64_t)IDTVEC(fast_syscall_pti) :
1534             (u_int64_t)IDTVEC(fast_syscall));
1535         wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
1536         msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
1537             ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
1538         wrmsr(MSR_STAR, msr);
1539         wrmsr(MSR_SF_MASK, PSL_NT | PSL_T | PSL_I | PSL_C | PSL_D);
1540 }
1541
1542 u_int64_t
1543 hammer_time(u_int64_t modulep, u_int64_t physfree)
1544 {
1545         caddr_t kmdp;
1546         int gsel_tss, x;
1547         struct pcpu *pc;
1548         struct nmi_pcpu *np;
1549         struct xstate_hdr *xhdr;
1550         u_int64_t rsp0;
1551         char *env;
1552         size_t kstack0_sz;
1553         int late_console;
1554
1555         TSRAW(&thread0, TS_ENTER, __func__, NULL);
1556
1557         /*
1558          * This may be done better later if it gets more high level
1559          * components in it. If so just link td->td_proc here.
1560          */
1561         proc_linkup0(&proc0, &thread0);
1562
1563         kmdp = init_ops.parse_preload_data(modulep);
1564
1565         identify_cpu1();
1566         identify_hypervisor();
1567
1568         /* Init basic tunables, hz etc */
1569         init_param1();
1570
1571         thread0.td_kstack = physfree + KERNBASE;
1572         thread0.td_kstack_pages = kstack_pages;
1573         kstack0_sz = thread0.td_kstack_pages * PAGE_SIZE;
1574         bzero((void *)thread0.td_kstack, kstack0_sz);
1575         physfree += kstack0_sz;
1576
1577         /*
1578          * make gdt memory segments
1579          */
1580         for (x = 0; x < NGDT; x++) {
1581                 if (x != GPROC0_SEL && x != (GPROC0_SEL + 1) &&
1582                     x != GUSERLDT_SEL && x != (GUSERLDT_SEL) + 1)
1583                         ssdtosd(&gdt_segs[x], &gdt[x]);
1584         }
1585         gdt_segs[GPROC0_SEL].ssd_base = (uintptr_t)&common_tss[0];
1586         ssdtosyssd(&gdt_segs[GPROC0_SEL],
1587             (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
1588
1589         r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
1590         r_gdt.rd_base =  (long) gdt;
1591         lgdt(&r_gdt);
1592         pc = &__pcpu[0];
1593
1594         wrmsr(MSR_FSBASE, 0);           /* User value */
1595         wrmsr(MSR_GSBASE, (u_int64_t)pc);
1596         wrmsr(MSR_KGSBASE, 0);          /* User value while in the kernel */
1597
1598         pcpu_init(pc, 0, sizeof(struct pcpu));
1599         dpcpu_init((void *)(physfree + KERNBASE), 0);
1600         physfree += DPCPU_SIZE;
1601         PCPU_SET(prvspace, pc);
1602         PCPU_SET(curthread, &thread0);
1603         /* Non-late cninit() and printf() can be moved up to here. */
1604         PCPU_SET(tssp, &common_tss[0]);
1605         PCPU_SET(commontssp, &common_tss[0]);
1606         PCPU_SET(tss, (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
1607         PCPU_SET(ldt, (struct system_segment_descriptor *)&gdt[GUSERLDT_SEL]);
1608         PCPU_SET(fs32p, &gdt[GUFS32_SEL]);
1609         PCPU_SET(gs32p, &gdt[GUGS32_SEL]);
1610
1611         /*
1612          * Initialize mutexes.
1613          *
1614          * icu_lock: in order to allow an interrupt to occur in a critical
1615          *           section, to set pcpu->ipending (etc...) properly, we
1616          *           must be able to get the icu lock, so it can't be
1617          *           under witness.
1618          */
1619         mutex_init();
1620         mtx_init(&icu_lock, "icu", NULL, MTX_SPIN | MTX_NOWITNESS);
1621         mtx_init(&dt_lock, "descriptor tables", NULL, MTX_DEF);
1622
1623         /* exceptions */
1624         pti = pti_get_default();
1625         TUNABLE_INT_FETCH("vm.pmap.pti", &pti);
1626
1627         for (x = 0; x < NIDT; x++)
1628                 setidt(x, pti ? &IDTVEC(rsvd_pti) : &IDTVEC(rsvd), SDT_SYSIGT,
1629                     SEL_KPL, 0);
1630         setidt(IDT_DE, pti ? &IDTVEC(div_pti) : &IDTVEC(div), SDT_SYSIGT,
1631             SEL_KPL, 0);
1632         setidt(IDT_DB, pti ? &IDTVEC(dbg_pti) : &IDTVEC(dbg), SDT_SYSIGT,
1633             SEL_KPL, 0);
1634         setidt(IDT_NMI, &IDTVEC(nmi),  SDT_SYSIGT, SEL_KPL, 2);
1635         setidt(IDT_BP, pti ? &IDTVEC(bpt_pti) : &IDTVEC(bpt), SDT_SYSIGT,
1636             SEL_UPL, 0);
1637         setidt(IDT_OF, pti ? &IDTVEC(ofl_pti) : &IDTVEC(ofl), SDT_SYSIGT,
1638             SEL_KPL, 0);
1639         setidt(IDT_BR, pti ? &IDTVEC(bnd_pti) : &IDTVEC(bnd), SDT_SYSIGT,
1640             SEL_KPL, 0);
1641         setidt(IDT_UD, pti ? &IDTVEC(ill_pti) : &IDTVEC(ill), SDT_SYSIGT,
1642             SEL_KPL, 0);
1643         setidt(IDT_NM, pti ? &IDTVEC(dna_pti) : &IDTVEC(dna), SDT_SYSIGT,
1644             SEL_KPL, 0);
1645         setidt(IDT_DF, &IDTVEC(dblfault), SDT_SYSIGT, SEL_KPL, 1);
1646         setidt(IDT_FPUGP, pti ? &IDTVEC(fpusegm_pti) : &IDTVEC(fpusegm),
1647             SDT_SYSIGT, SEL_KPL, 0);
1648         setidt(IDT_TS, pti ? &IDTVEC(tss_pti) : &IDTVEC(tss), SDT_SYSIGT,
1649             SEL_KPL, 0);
1650         setidt(IDT_NP, pti ? &IDTVEC(missing_pti) : &IDTVEC(missing),
1651             SDT_SYSIGT, SEL_KPL, 0);
1652         setidt(IDT_SS, pti ? &IDTVEC(stk_pti) : &IDTVEC(stk), SDT_SYSIGT,
1653             SEL_KPL, 0);
1654         setidt(IDT_GP, pti ? &IDTVEC(prot_pti) : &IDTVEC(prot), SDT_SYSIGT,
1655             SEL_KPL, 0);
1656         setidt(IDT_PF, pti ? &IDTVEC(page_pti) : &IDTVEC(page), SDT_SYSIGT,
1657             SEL_KPL, 0);
1658         setidt(IDT_MF, pti ? &IDTVEC(fpu_pti) : &IDTVEC(fpu), SDT_SYSIGT,
1659             SEL_KPL, 0);
1660         setidt(IDT_AC, pti ? &IDTVEC(align_pti) : &IDTVEC(align), SDT_SYSIGT,
1661             SEL_KPL, 0);
1662         setidt(IDT_MC, &IDTVEC(mchk), SDT_SYSIGT, SEL_KPL, 3);
1663         setidt(IDT_XF, pti ? &IDTVEC(xmm_pti) : &IDTVEC(xmm), SDT_SYSIGT,
1664             SEL_KPL, 0);
1665 #ifdef KDTRACE_HOOKS
1666         setidt(IDT_DTRACE_RET, pti ? &IDTVEC(dtrace_ret_pti) :
1667             &IDTVEC(dtrace_ret), SDT_SYSIGT, SEL_UPL, 0);
1668 #endif
1669 #ifdef XENHVM
1670         setidt(IDT_EVTCHN, pti ? &IDTVEC(xen_intr_upcall_pti) :
1671             &IDTVEC(xen_intr_upcall), SDT_SYSIGT, SEL_KPL, 0);
1672 #endif
1673         r_idt.rd_limit = sizeof(idt0) - 1;
1674         r_idt.rd_base = (long) idt;
1675         lidt(&r_idt);
1676
1677         /*
1678          * Initialize the clock before the console so that console
1679          * initialization can use DELAY().
1680          */
1681         clock_init();
1682
1683         /*
1684          * Use vt(4) by default for UEFI boot (during the sc(4)/vt(4)
1685          * transition).
1686          * Once bootblocks have updated, we can test directly for
1687          * efi_systbl != NULL here...
1688          */
1689         if (preload_search_info(kmdp, MODINFO_METADATA | MODINFOMD_EFI_MAP)
1690             != NULL)
1691                 vty_set_preferred(VTY_VT);
1692
1693         finishidentcpu();       /* Final stage of CPU initialization */
1694         initializecpu();        /* Initialize CPU registers */
1695         initializecpucache();
1696
1697         /* doublefault stack space, runs on ist1 */
1698         common_tss[0].tss_ist1 = (long)&dblfault_stack[sizeof(dblfault_stack)];
1699
1700         /*
1701          * NMI stack, runs on ist2.  The pcpu pointer is stored just
1702          * above the start of the ist2 stack.
1703          */
1704         np = ((struct nmi_pcpu *) &nmi0_stack[sizeof(nmi0_stack)]) - 1;
1705         np->np_pcpu = (register_t) pc;
1706         common_tss[0].tss_ist2 = (long) np;
1707
1708         /*
1709          * MC# stack, runs on ist3.  The pcpu pointer is stored just
1710          * above the start of the ist3 stack.
1711          */
1712         np = ((struct nmi_pcpu *) &mce0_stack[sizeof(mce0_stack)]) - 1;
1713         np->np_pcpu = (register_t) pc;
1714         common_tss[0].tss_ist3 = (long) np;
1715         
1716         /* Set the IO permission bitmap (empty due to tss seg limit) */
1717         common_tss[0].tss_iobase = sizeof(struct amd64tss) + IOPERM_BITMAP_SIZE;
1718
1719         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1720         ltr(gsel_tss);
1721
1722         amd64_conf_fast_syscall();
1723
1724         /*
1725          * Temporary forge some valid pointer to PCB, for exception
1726          * handlers.  It is reinitialized properly below after FPU is
1727          * set up.  Also set up td_critnest to short-cut the page
1728          * fault handler.
1729          */
1730         cpu_max_ext_state_size = sizeof(struct savefpu);
1731         thread0.td_pcb = get_pcb_td(&thread0);
1732         thread0.td_critnest = 1;
1733
1734         /*
1735          * The console and kdb should be initialized even earlier than here,
1736          * but some console drivers don't work until after getmemsize().
1737          * Default to late console initialization to support these drivers.
1738          * This loses mainly printf()s in getmemsize() and early debugging.
1739          */
1740         late_console = 1;
1741         TUNABLE_INT_FETCH("debug.late_console", &late_console);
1742         if (!late_console) {
1743                 cninit();
1744                 amd64_kdb_init();
1745         }
1746
1747         getmemsize(kmdp, physfree);
1748         init_param2(physmem);
1749
1750         /* now running on new page tables, configured,and u/iom is accessible */
1751
1752         if (late_console)
1753                 cninit();
1754
1755 #ifdef DEV_ISA
1756 #ifdef DEV_ATPIC
1757         elcr_probe();
1758         atpic_startup();
1759 #else
1760         /* Reset and mask the atpics and leave them shut down. */
1761         atpic_reset();
1762
1763         /*
1764          * Point the ICU spurious interrupt vectors at the APIC spurious
1765          * interrupt handler.
1766          */
1767         setidt(IDT_IO_INTS + 7, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
1768         setidt(IDT_IO_INTS + 15, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
1769 #endif
1770 #else
1771 #error "have you forgotten the isa device?";
1772 #endif
1773
1774         if (late_console)
1775                 amd64_kdb_init();
1776
1777         msgbufinit(msgbufp, msgbufsize);
1778         fpuinit();
1779
1780         /*
1781          * Set up thread0 pcb after fpuinit calculated pcb + fpu save
1782          * area size.  Zero out the extended state header in fpu save
1783          * area.
1784          */
1785         thread0.td_pcb = get_pcb_td(&thread0);
1786         thread0.td_pcb->pcb_save = get_pcb_user_save_td(&thread0);
1787         bzero(get_pcb_user_save_td(&thread0), cpu_max_ext_state_size);
1788         if (use_xsave) {
1789                 xhdr = (struct xstate_hdr *)(get_pcb_user_save_td(&thread0) +
1790                     1);
1791                 xhdr->xstate_bv = xsave_mask;
1792         }
1793         /* make an initial tss so cpu can get interrupt stack on syscall! */
1794         rsp0 = (vm_offset_t)thread0.td_pcb;
1795         /* Ensure the stack is aligned to 16 bytes */
1796         rsp0 &= ~0xFul;
1797         common_tss[0].tss_rsp0 = pti ? ((vm_offset_t)PCPU_PTR(pti_stack) +
1798             PC_PTI_STACK_SZ * sizeof(uint64_t)) & ~0xful : rsp0;
1799         PCPU_SET(rsp0, rsp0);
1800         PCPU_SET(curpcb, thread0.td_pcb);
1801
1802         /* transfer to user mode */
1803
1804         _ucodesel = GSEL(GUCODE_SEL, SEL_UPL);
1805         _udatasel = GSEL(GUDATA_SEL, SEL_UPL);
1806         _ucode32sel = GSEL(GUCODE32_SEL, SEL_UPL);
1807         _ufssel = GSEL(GUFS32_SEL, SEL_UPL);
1808         _ugssel = GSEL(GUGS32_SEL, SEL_UPL);
1809
1810         load_ds(_udatasel);
1811         load_es(_udatasel);
1812         load_fs(_ufssel);
1813
1814         /* setup proc 0's pcb */
1815         thread0.td_pcb->pcb_flags = 0;
1816         thread0.td_frame = &proc0_tf;
1817
1818         env = kern_getenv("kernelname");
1819         if (env != NULL)
1820                 strlcpy(kernelname, env, sizeof(kernelname));
1821
1822         cpu_probe_amdc1e();
1823
1824 #ifdef FDT
1825         x86_init_fdt();
1826 #endif
1827         thread0.td_critnest = 0;
1828
1829         TUNABLE_INT_FETCH("hw.ibrs_disable", &hw_ibrs_disable);
1830
1831         TSEXIT();
1832
1833         /* Location of kernel stack for locore */
1834         return ((u_int64_t)thread0.td_pcb);
1835 }
1836
1837 void
1838 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
1839 {
1840
1841         pcpu->pc_acpi_id = 0xffffffff;
1842 }
1843
1844 static int
1845 smap_sysctl_handler(SYSCTL_HANDLER_ARGS)
1846 {
1847         struct bios_smap *smapbase;
1848         struct bios_smap_xattr smap;
1849         caddr_t kmdp;
1850         uint32_t *smapattr;
1851         int count, error, i;
1852
1853         /* Retrieve the system memory map from the loader. */
1854         kmdp = preload_search_by_type("elf kernel");
1855         if (kmdp == NULL)
1856                 kmdp = preload_search_by_type("elf64 kernel");
1857         smapbase = (struct bios_smap *)preload_search_info(kmdp,
1858             MODINFO_METADATA | MODINFOMD_SMAP);
1859         if (smapbase == NULL)
1860                 return (0);
1861         smapattr = (uint32_t *)preload_search_info(kmdp,
1862             MODINFO_METADATA | MODINFOMD_SMAP_XATTR);
1863         count = *((uint32_t *)smapbase - 1) / sizeof(*smapbase);
1864         error = 0;
1865         for (i = 0; i < count; i++) {
1866                 smap.base = smapbase[i].base;
1867                 smap.length = smapbase[i].length;
1868                 smap.type = smapbase[i].type;
1869                 if (smapattr != NULL)
1870                         smap.xattr = smapattr[i];
1871                 else
1872                         smap.xattr = 0;
1873                 error = SYSCTL_OUT(req, &smap, sizeof(smap));
1874         }
1875         return (error);
1876 }
1877 SYSCTL_PROC(_machdep, OID_AUTO, smap, CTLTYPE_OPAQUE|CTLFLAG_RD, NULL, 0,
1878     smap_sysctl_handler, "S,bios_smap_xattr", "Raw BIOS SMAP data");
1879
1880 static int
1881 efi_map_sysctl_handler(SYSCTL_HANDLER_ARGS)
1882 {
1883         struct efi_map_header *efihdr;
1884         caddr_t kmdp;
1885         uint32_t efisize;
1886
1887         kmdp = preload_search_by_type("elf kernel");
1888         if (kmdp == NULL)
1889                 kmdp = preload_search_by_type("elf64 kernel");
1890         efihdr = (struct efi_map_header *)preload_search_info(kmdp,
1891             MODINFO_METADATA | MODINFOMD_EFI_MAP);
1892         if (efihdr == NULL)
1893                 return (0);
1894         efisize = *((uint32_t *)efihdr - 1);
1895         return (SYSCTL_OUT(req, efihdr, efisize));
1896 }
1897 SYSCTL_PROC(_machdep, OID_AUTO, efi_map, CTLTYPE_OPAQUE|CTLFLAG_RD, NULL, 0,
1898     efi_map_sysctl_handler, "S,efi_map_header", "Raw EFI Memory Map");
1899
1900 void
1901 spinlock_enter(void)
1902 {
1903         struct thread *td;
1904         register_t flags;
1905
1906         td = curthread;
1907         if (td->td_md.md_spinlock_count == 0) {
1908                 flags = intr_disable();
1909                 td->td_md.md_spinlock_count = 1;
1910                 td->td_md.md_saved_flags = flags;
1911                 critical_enter();
1912         } else
1913                 td->td_md.md_spinlock_count++;
1914 }
1915
1916 void
1917 spinlock_exit(void)
1918 {
1919         struct thread *td;
1920         register_t flags;
1921
1922         td = curthread;
1923         flags = td->td_md.md_saved_flags;
1924         td->td_md.md_spinlock_count--;
1925         if (td->td_md.md_spinlock_count == 0) {
1926                 critical_exit();
1927                 intr_restore(flags);
1928         }
1929 }
1930
1931 /*
1932  * Construct a PCB from a trapframe. This is called from kdb_trap() where
1933  * we want to start a backtrace from the function that caused us to enter
1934  * the debugger. We have the context in the trapframe, but base the trace
1935  * on the PCB. The PCB doesn't have to be perfect, as long as it contains
1936  * enough for a backtrace.
1937  */
1938 void
1939 makectx(struct trapframe *tf, struct pcb *pcb)
1940 {
1941
1942         pcb->pcb_r12 = tf->tf_r12;
1943         pcb->pcb_r13 = tf->tf_r13;
1944         pcb->pcb_r14 = tf->tf_r14;
1945         pcb->pcb_r15 = tf->tf_r15;
1946         pcb->pcb_rbp = tf->tf_rbp;
1947         pcb->pcb_rbx = tf->tf_rbx;
1948         pcb->pcb_rip = tf->tf_rip;
1949         pcb->pcb_rsp = tf->tf_rsp;
1950 }
1951
1952 int
1953 ptrace_set_pc(struct thread *td, unsigned long addr)
1954 {
1955
1956         td->td_frame->tf_rip = addr;
1957         set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
1958         return (0);
1959 }
1960
1961 int
1962 ptrace_single_step(struct thread *td)
1963 {
1964         td->td_frame->tf_rflags |= PSL_T;
1965         return (0);
1966 }
1967
1968 int
1969 ptrace_clear_single_step(struct thread *td)
1970 {
1971         td->td_frame->tf_rflags &= ~PSL_T;
1972         return (0);
1973 }
1974
1975 int
1976 fill_regs(struct thread *td, struct reg *regs)
1977 {
1978         struct trapframe *tp;
1979
1980         tp = td->td_frame;
1981         return (fill_frame_regs(tp, regs));
1982 }
1983
1984 int
1985 fill_frame_regs(struct trapframe *tp, struct reg *regs)
1986 {
1987         regs->r_r15 = tp->tf_r15;
1988         regs->r_r14 = tp->tf_r14;
1989         regs->r_r13 = tp->tf_r13;
1990         regs->r_r12 = tp->tf_r12;
1991         regs->r_r11 = tp->tf_r11;
1992         regs->r_r10 = tp->tf_r10;
1993         regs->r_r9  = tp->tf_r9;
1994         regs->r_r8  = tp->tf_r8;
1995         regs->r_rdi = tp->tf_rdi;
1996         regs->r_rsi = tp->tf_rsi;
1997         regs->r_rbp = tp->tf_rbp;
1998         regs->r_rbx = tp->tf_rbx;
1999         regs->r_rdx = tp->tf_rdx;
2000         regs->r_rcx = tp->tf_rcx;
2001         regs->r_rax = tp->tf_rax;
2002         regs->r_rip = tp->tf_rip;
2003         regs->r_cs = tp->tf_cs;
2004         regs->r_rflags = tp->tf_rflags;
2005         regs->r_rsp = tp->tf_rsp;
2006         regs->r_ss = tp->tf_ss;
2007         if (tp->tf_flags & TF_HASSEGS) {
2008                 regs->r_ds = tp->tf_ds;
2009                 regs->r_es = tp->tf_es;
2010                 regs->r_fs = tp->tf_fs;
2011                 regs->r_gs = tp->tf_gs;
2012         } else {
2013                 regs->r_ds = 0;
2014                 regs->r_es = 0;
2015                 regs->r_fs = 0;
2016                 regs->r_gs = 0;
2017         }
2018         return (0);
2019 }
2020
2021 int
2022 set_regs(struct thread *td, struct reg *regs)
2023 {
2024         struct trapframe *tp;
2025         register_t rflags;
2026
2027         tp = td->td_frame;
2028         rflags = regs->r_rflags & 0xffffffff;
2029         if (!EFL_SECURE(rflags, tp->tf_rflags) || !CS_SECURE(regs->r_cs))
2030                 return (EINVAL);
2031         tp->tf_r15 = regs->r_r15;
2032         tp->tf_r14 = regs->r_r14;
2033         tp->tf_r13 = regs->r_r13;
2034         tp->tf_r12 = regs->r_r12;
2035         tp->tf_r11 = regs->r_r11;
2036         tp->tf_r10 = regs->r_r10;
2037         tp->tf_r9  = regs->r_r9;
2038         tp->tf_r8  = regs->r_r8;
2039         tp->tf_rdi = regs->r_rdi;
2040         tp->tf_rsi = regs->r_rsi;
2041         tp->tf_rbp = regs->r_rbp;
2042         tp->tf_rbx = regs->r_rbx;
2043         tp->tf_rdx = regs->r_rdx;
2044         tp->tf_rcx = regs->r_rcx;
2045         tp->tf_rax = regs->r_rax;
2046         tp->tf_rip = regs->r_rip;
2047         tp->tf_cs = regs->r_cs;
2048         tp->tf_rflags = rflags;
2049         tp->tf_rsp = regs->r_rsp;
2050         tp->tf_ss = regs->r_ss;
2051         if (0) {        /* XXXKIB */
2052                 tp->tf_ds = regs->r_ds;
2053                 tp->tf_es = regs->r_es;
2054                 tp->tf_fs = regs->r_fs;
2055                 tp->tf_gs = regs->r_gs;
2056                 tp->tf_flags = TF_HASSEGS;
2057         }
2058         set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
2059         return (0);
2060 }
2061
2062 /* XXX check all this stuff! */
2063 /* externalize from sv_xmm */
2064 static void
2065 fill_fpregs_xmm(struct savefpu *sv_xmm, struct fpreg *fpregs)
2066 {
2067         struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env;
2068         struct envxmm *penv_xmm = &sv_xmm->sv_env;
2069         int i;
2070
2071         /* pcb -> fpregs */
2072         bzero(fpregs, sizeof(*fpregs));
2073
2074         /* FPU control/status */
2075         penv_fpreg->en_cw = penv_xmm->en_cw;
2076         penv_fpreg->en_sw = penv_xmm->en_sw;
2077         penv_fpreg->en_tw = penv_xmm->en_tw;
2078         penv_fpreg->en_opcode = penv_xmm->en_opcode;
2079         penv_fpreg->en_rip = penv_xmm->en_rip;
2080         penv_fpreg->en_rdp = penv_xmm->en_rdp;
2081         penv_fpreg->en_mxcsr = penv_xmm->en_mxcsr;
2082         penv_fpreg->en_mxcsr_mask = penv_xmm->en_mxcsr_mask;
2083
2084         /* FPU registers */
2085         for (i = 0; i < 8; ++i)
2086                 bcopy(sv_xmm->sv_fp[i].fp_acc.fp_bytes, fpregs->fpr_acc[i], 10);
2087
2088         /* SSE registers */
2089         for (i = 0; i < 16; ++i)
2090                 bcopy(sv_xmm->sv_xmm[i].xmm_bytes, fpregs->fpr_xacc[i], 16);
2091 }
2092
2093 /* internalize from fpregs into sv_xmm */
2094 static void
2095 set_fpregs_xmm(struct fpreg *fpregs, struct savefpu *sv_xmm)
2096 {
2097         struct envxmm *penv_xmm = &sv_xmm->sv_env;
2098         struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env;
2099         int i;
2100
2101         /* fpregs -> pcb */
2102         /* FPU control/status */
2103         penv_xmm->en_cw = penv_fpreg->en_cw;
2104         penv_xmm->en_sw = penv_fpreg->en_sw;
2105         penv_xmm->en_tw = penv_fpreg->en_tw;
2106         penv_xmm->en_opcode = penv_fpreg->en_opcode;
2107         penv_xmm->en_rip = penv_fpreg->en_rip;
2108         penv_xmm->en_rdp = penv_fpreg->en_rdp;
2109         penv_xmm->en_mxcsr = penv_fpreg->en_mxcsr;
2110         penv_xmm->en_mxcsr_mask = penv_fpreg->en_mxcsr_mask & cpu_mxcsr_mask;
2111
2112         /* FPU registers */
2113         for (i = 0; i < 8; ++i)
2114                 bcopy(fpregs->fpr_acc[i], sv_xmm->sv_fp[i].fp_acc.fp_bytes, 10);
2115
2116         /* SSE registers */
2117         for (i = 0; i < 16; ++i)
2118                 bcopy(fpregs->fpr_xacc[i], sv_xmm->sv_xmm[i].xmm_bytes, 16);
2119 }
2120
2121 /* externalize from td->pcb */
2122 int
2123 fill_fpregs(struct thread *td, struct fpreg *fpregs)
2124 {
2125
2126         KASSERT(td == curthread || TD_IS_SUSPENDED(td) ||
2127             P_SHOULDSTOP(td->td_proc),
2128             ("not suspended thread %p", td));
2129         fpugetregs(td);
2130         fill_fpregs_xmm(get_pcb_user_save_td(td), fpregs);
2131         return (0);
2132 }
2133
2134 /* internalize to td->pcb */
2135 int
2136 set_fpregs(struct thread *td, struct fpreg *fpregs)
2137 {
2138
2139         set_fpregs_xmm(fpregs, get_pcb_user_save_td(td));
2140         fpuuserinited(td);
2141         return (0);
2142 }
2143
2144 /*
2145  * Get machine context.
2146  */
2147 int
2148 get_mcontext(struct thread *td, mcontext_t *mcp, int flags)
2149 {
2150         struct pcb *pcb;
2151         struct trapframe *tp;
2152
2153         pcb = td->td_pcb;
2154         tp = td->td_frame;
2155         PROC_LOCK(curthread->td_proc);
2156         mcp->mc_onstack = sigonstack(tp->tf_rsp);
2157         PROC_UNLOCK(curthread->td_proc);
2158         mcp->mc_r15 = tp->tf_r15;
2159         mcp->mc_r14 = tp->tf_r14;
2160         mcp->mc_r13 = tp->tf_r13;
2161         mcp->mc_r12 = tp->tf_r12;
2162         mcp->mc_r11 = tp->tf_r11;
2163         mcp->mc_r10 = tp->tf_r10;
2164         mcp->mc_r9  = tp->tf_r9;
2165         mcp->mc_r8  = tp->tf_r8;
2166         mcp->mc_rdi = tp->tf_rdi;
2167         mcp->mc_rsi = tp->tf_rsi;
2168         mcp->mc_rbp = tp->tf_rbp;
2169         mcp->mc_rbx = tp->tf_rbx;
2170         mcp->mc_rcx = tp->tf_rcx;
2171         mcp->mc_rflags = tp->tf_rflags;
2172         if (flags & GET_MC_CLEAR_RET) {
2173                 mcp->mc_rax = 0;
2174                 mcp->mc_rdx = 0;
2175                 mcp->mc_rflags &= ~PSL_C;
2176         } else {
2177                 mcp->mc_rax = tp->tf_rax;
2178                 mcp->mc_rdx = tp->tf_rdx;
2179         }
2180         mcp->mc_rip = tp->tf_rip;
2181         mcp->mc_cs = tp->tf_cs;
2182         mcp->mc_rsp = tp->tf_rsp;
2183         mcp->mc_ss = tp->tf_ss;
2184         mcp->mc_ds = tp->tf_ds;
2185         mcp->mc_es = tp->tf_es;
2186         mcp->mc_fs = tp->tf_fs;
2187         mcp->mc_gs = tp->tf_gs;
2188         mcp->mc_flags = tp->tf_flags;
2189         mcp->mc_len = sizeof(*mcp);
2190         get_fpcontext(td, mcp, NULL, 0);
2191         update_pcb_bases(pcb);
2192         mcp->mc_fsbase = pcb->pcb_fsbase;
2193         mcp->mc_gsbase = pcb->pcb_gsbase;
2194         mcp->mc_xfpustate = 0;
2195         mcp->mc_xfpustate_len = 0;
2196         bzero(mcp->mc_spare, sizeof(mcp->mc_spare));
2197         return (0);
2198 }
2199
2200 /*
2201  * Set machine context.
2202  *
2203  * However, we don't set any but the user modifiable flags, and we won't
2204  * touch the cs selector.
2205  */
2206 int
2207 set_mcontext(struct thread *td, mcontext_t *mcp)
2208 {
2209         struct pcb *pcb;
2210         struct trapframe *tp;
2211         char *xfpustate;
2212         long rflags;
2213         int ret;
2214
2215         pcb = td->td_pcb;
2216         tp = td->td_frame;
2217         if (mcp->mc_len != sizeof(*mcp) ||
2218             (mcp->mc_flags & ~_MC_FLAG_MASK) != 0)
2219                 return (EINVAL);
2220         rflags = (mcp->mc_rflags & PSL_USERCHANGE) |
2221             (tp->tf_rflags & ~PSL_USERCHANGE);
2222         if (mcp->mc_flags & _MC_HASFPXSTATE) {
2223                 if (mcp->mc_xfpustate_len > cpu_max_ext_state_size -
2224                     sizeof(struct savefpu))
2225                         return (EINVAL);
2226                 xfpustate = __builtin_alloca(mcp->mc_xfpustate_len);
2227                 ret = copyin((void *)mcp->mc_xfpustate, xfpustate,
2228                     mcp->mc_xfpustate_len);
2229                 if (ret != 0)
2230                         return (ret);
2231         } else
2232                 xfpustate = NULL;
2233         ret = set_fpcontext(td, mcp, xfpustate, mcp->mc_xfpustate_len);
2234         if (ret != 0)
2235                 return (ret);
2236         tp->tf_r15 = mcp->mc_r15;
2237         tp->tf_r14 = mcp->mc_r14;
2238         tp->tf_r13 = mcp->mc_r13;
2239         tp->tf_r12 = mcp->mc_r12;
2240         tp->tf_r11 = mcp->mc_r11;
2241         tp->tf_r10 = mcp->mc_r10;
2242         tp->tf_r9  = mcp->mc_r9;
2243         tp->tf_r8  = mcp->mc_r8;
2244         tp->tf_rdi = mcp->mc_rdi;
2245         tp->tf_rsi = mcp->mc_rsi;
2246         tp->tf_rbp = mcp->mc_rbp;
2247         tp->tf_rbx = mcp->mc_rbx;
2248         tp->tf_rdx = mcp->mc_rdx;
2249         tp->tf_rcx = mcp->mc_rcx;
2250         tp->tf_rax = mcp->mc_rax;
2251         tp->tf_rip = mcp->mc_rip;
2252         tp->tf_rflags = rflags;
2253         tp->tf_rsp = mcp->mc_rsp;
2254         tp->tf_ss = mcp->mc_ss;
2255         tp->tf_flags = mcp->mc_flags;
2256         if (tp->tf_flags & TF_HASSEGS) {
2257                 tp->tf_ds = mcp->mc_ds;
2258                 tp->tf_es = mcp->mc_es;
2259                 tp->tf_fs = mcp->mc_fs;
2260                 tp->tf_gs = mcp->mc_gs;
2261         }
2262         set_pcb_flags(pcb, PCB_FULL_IRET);
2263         if (mcp->mc_flags & _MC_HASBASES) {
2264                 pcb->pcb_fsbase = mcp->mc_fsbase;
2265                 pcb->pcb_gsbase = mcp->mc_gsbase;
2266         }
2267         return (0);
2268 }
2269
2270 static void
2271 get_fpcontext(struct thread *td, mcontext_t *mcp, char *xfpusave,
2272     size_t xfpusave_len)
2273 {
2274         size_t max_len, len;
2275
2276         mcp->mc_ownedfp = fpugetregs(td);
2277         bcopy(get_pcb_user_save_td(td), &mcp->mc_fpstate[0],
2278             sizeof(mcp->mc_fpstate));
2279         mcp->mc_fpformat = fpuformat();
2280         if (!use_xsave || xfpusave_len == 0)
2281                 return;
2282         max_len = cpu_max_ext_state_size - sizeof(struct savefpu);
2283         len = xfpusave_len;
2284         if (len > max_len) {
2285                 len = max_len;
2286                 bzero(xfpusave + max_len, len - max_len);
2287         }
2288         mcp->mc_flags |= _MC_HASFPXSTATE;
2289         mcp->mc_xfpustate_len = len;
2290         bcopy(get_pcb_user_save_td(td) + 1, xfpusave, len);
2291 }
2292
2293 static int
2294 set_fpcontext(struct thread *td, mcontext_t *mcp, char *xfpustate,
2295     size_t xfpustate_len)
2296 {
2297         int error;
2298
2299         if (mcp->mc_fpformat == _MC_FPFMT_NODEV)
2300                 return (0);
2301         else if (mcp->mc_fpformat != _MC_FPFMT_XMM)
2302                 return (EINVAL);
2303         else if (mcp->mc_ownedfp == _MC_FPOWNED_NONE) {
2304                 /* We don't care what state is left in the FPU or PCB. */
2305                 fpstate_drop(td);
2306                 error = 0;
2307         } else if (mcp->mc_ownedfp == _MC_FPOWNED_FPU ||
2308             mcp->mc_ownedfp == _MC_FPOWNED_PCB) {
2309                 error = fpusetregs(td, (struct savefpu *)&mcp->mc_fpstate,
2310                     xfpustate, xfpustate_len);
2311         } else
2312                 return (EINVAL);
2313         return (error);
2314 }
2315
2316 void
2317 fpstate_drop(struct thread *td)
2318 {
2319
2320         KASSERT(PCB_USER_FPU(td->td_pcb), ("fpstate_drop: kernel-owned fpu"));
2321         critical_enter();
2322         if (PCPU_GET(fpcurthread) == td)
2323                 fpudrop();
2324         /*
2325          * XXX force a full drop of the fpu.  The above only drops it if we
2326          * owned it.
2327          *
2328          * XXX I don't much like fpugetuserregs()'s semantics of doing a full
2329          * drop.  Dropping only to the pcb matches fnsave's behaviour.
2330          * We only need to drop to !PCB_INITDONE in sendsig().  But
2331          * sendsig() is the only caller of fpugetuserregs()... perhaps we just
2332          * have too many layers.
2333          */
2334         clear_pcb_flags(curthread->td_pcb,
2335             PCB_FPUINITDONE | PCB_USERFPUINITDONE);
2336         critical_exit();
2337 }
2338
2339 int
2340 fill_dbregs(struct thread *td, struct dbreg *dbregs)
2341 {
2342         struct pcb *pcb;
2343
2344         if (td == NULL) {
2345                 dbregs->dr[0] = rdr0();
2346                 dbregs->dr[1] = rdr1();
2347                 dbregs->dr[2] = rdr2();
2348                 dbregs->dr[3] = rdr3();
2349                 dbregs->dr[6] = rdr6();
2350                 dbregs->dr[7] = rdr7();
2351         } else {
2352                 pcb = td->td_pcb;
2353                 dbregs->dr[0] = pcb->pcb_dr0;
2354                 dbregs->dr[1] = pcb->pcb_dr1;
2355                 dbregs->dr[2] = pcb->pcb_dr2;
2356                 dbregs->dr[3] = pcb->pcb_dr3;
2357                 dbregs->dr[6] = pcb->pcb_dr6;
2358                 dbregs->dr[7] = pcb->pcb_dr7;
2359         }
2360         dbregs->dr[4] = 0;
2361         dbregs->dr[5] = 0;
2362         dbregs->dr[8] = 0;
2363         dbregs->dr[9] = 0;
2364         dbregs->dr[10] = 0;
2365         dbregs->dr[11] = 0;
2366         dbregs->dr[12] = 0;
2367         dbregs->dr[13] = 0;
2368         dbregs->dr[14] = 0;
2369         dbregs->dr[15] = 0;
2370         return (0);
2371 }
2372
2373 int
2374 set_dbregs(struct thread *td, struct dbreg *dbregs)
2375 {
2376         struct pcb *pcb;
2377         int i;
2378
2379         if (td == NULL) {
2380                 load_dr0(dbregs->dr[0]);
2381                 load_dr1(dbregs->dr[1]);
2382                 load_dr2(dbregs->dr[2]);
2383                 load_dr3(dbregs->dr[3]);
2384                 load_dr6(dbregs->dr[6]);
2385                 load_dr7(dbregs->dr[7]);
2386         } else {
2387                 /*
2388                  * Don't let an illegal value for dr7 get set.  Specifically,
2389                  * check for undefined settings.  Setting these bit patterns
2390                  * result in undefined behaviour and can lead to an unexpected
2391                  * TRCTRAP or a general protection fault right here.
2392                  * Upper bits of dr6 and dr7 must not be set
2393                  */
2394                 for (i = 0; i < 4; i++) {
2395                         if (DBREG_DR7_ACCESS(dbregs->dr[7], i) == 0x02)
2396                                 return (EINVAL);
2397                         if (td->td_frame->tf_cs == _ucode32sel &&
2398                             DBREG_DR7_LEN(dbregs->dr[7], i) == DBREG_DR7_LEN_8)
2399                                 return (EINVAL);
2400                 }
2401                 if ((dbregs->dr[6] & 0xffffffff00000000ul) != 0 ||
2402                     (dbregs->dr[7] & 0xffffffff00000000ul) != 0)
2403                         return (EINVAL);
2404
2405                 pcb = td->td_pcb;
2406
2407                 /*
2408                  * Don't let a process set a breakpoint that is not within the
2409                  * process's address space.  If a process could do this, it
2410                  * could halt the system by setting a breakpoint in the kernel
2411                  * (if ddb was enabled).  Thus, we need to check to make sure
2412                  * that no breakpoints are being enabled for addresses outside
2413                  * process's address space.
2414                  *
2415                  * XXX - what about when the watched area of the user's
2416                  * address space is written into from within the kernel
2417                  * ... wouldn't that still cause a breakpoint to be generated
2418                  * from within kernel mode?
2419                  */
2420
2421                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 0)) {
2422                         /* dr0 is enabled */
2423                         if (dbregs->dr[0] >= VM_MAXUSER_ADDRESS)
2424                                 return (EINVAL);
2425                 }
2426                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 1)) {
2427                         /* dr1 is enabled */
2428                         if (dbregs->dr[1] >= VM_MAXUSER_ADDRESS)
2429                                 return (EINVAL);
2430                 }
2431                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 2)) {
2432                         /* dr2 is enabled */
2433                         if (dbregs->dr[2] >= VM_MAXUSER_ADDRESS)
2434                                 return (EINVAL);
2435                 }
2436                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 3)) {
2437                         /* dr3 is enabled */
2438                         if (dbregs->dr[3] >= VM_MAXUSER_ADDRESS)
2439                                 return (EINVAL);
2440                 }
2441
2442                 pcb->pcb_dr0 = dbregs->dr[0];
2443                 pcb->pcb_dr1 = dbregs->dr[1];
2444                 pcb->pcb_dr2 = dbregs->dr[2];
2445                 pcb->pcb_dr3 = dbregs->dr[3];
2446                 pcb->pcb_dr6 = dbregs->dr[6];
2447                 pcb->pcb_dr7 = dbregs->dr[7];
2448
2449                 set_pcb_flags(pcb, PCB_DBREGS);
2450         }
2451
2452         return (0);
2453 }
2454
2455 void
2456 reset_dbregs(void)
2457 {
2458
2459         load_dr7(0);    /* Turn off the control bits first */
2460         load_dr0(0);
2461         load_dr1(0);
2462         load_dr2(0);
2463         load_dr3(0);
2464         load_dr6(0);
2465 }
2466
2467 /*
2468  * Return > 0 if a hardware breakpoint has been hit, and the
2469  * breakpoint was in user space.  Return 0, otherwise.
2470  */
2471 int
2472 user_dbreg_trap(void)
2473 {
2474         u_int64_t dr7, dr6; /* debug registers dr6 and dr7 */
2475         u_int64_t bp;       /* breakpoint bits extracted from dr6 */
2476         int nbp;            /* number of breakpoints that triggered */
2477         caddr_t addr[4];    /* breakpoint addresses */
2478         int i;
2479         
2480         dr7 = rdr7();
2481         if ((dr7 & 0x000000ff) == 0) {
2482                 /*
2483                  * all GE and LE bits in the dr7 register are zero,
2484                  * thus the trap couldn't have been caused by the
2485                  * hardware debug registers
2486                  */
2487                 return 0;
2488         }
2489
2490         nbp = 0;
2491         dr6 = rdr6();
2492         bp = dr6 & 0x0000000f;
2493
2494         if (!bp) {
2495                 /*
2496                  * None of the breakpoint bits are set meaning this
2497                  * trap was not caused by any of the debug registers
2498                  */
2499                 return 0;
2500         }
2501
2502         /*
2503          * at least one of the breakpoints were hit, check to see
2504          * which ones and if any of them are user space addresses
2505          */
2506
2507         if (bp & 0x01) {
2508                 addr[nbp++] = (caddr_t)rdr0();
2509         }
2510         if (bp & 0x02) {
2511                 addr[nbp++] = (caddr_t)rdr1();
2512         }
2513         if (bp & 0x04) {
2514                 addr[nbp++] = (caddr_t)rdr2();
2515         }
2516         if (bp & 0x08) {
2517                 addr[nbp++] = (caddr_t)rdr3();
2518         }
2519
2520         for (i = 0; i < nbp; i++) {
2521                 if (addr[i] < (caddr_t)VM_MAXUSER_ADDRESS) {
2522                         /*
2523                          * addr[i] is in user space
2524                          */
2525                         return nbp;
2526                 }
2527         }
2528
2529         /*
2530          * None of the breakpoints are in user space.
2531          */
2532         return 0;
2533 }
2534
2535 /*
2536  * The pcb_flags is only modified by current thread, or by other threads
2537  * when current thread is stopped.  However, current thread may change it
2538  * from the interrupt context in cpu_switch(), or in the trap handler.
2539  * When we read-modify-write pcb_flags from C sources, compiler may generate
2540  * code that is not atomic regarding the interrupt handler.  If a trap or
2541  * interrupt happens and any flag is modified from the handler, it can be
2542  * clobbered with the cached value later.  Therefore, we implement setting
2543  * and clearing flags with single-instruction functions, which do not race
2544  * with possible modification of the flags from the trap or interrupt context,
2545  * because traps and interrupts are executed only on instruction boundary.
2546  */
2547 void
2548 set_pcb_flags_raw(struct pcb *pcb, const u_int flags)
2549 {
2550
2551         __asm __volatile("orl %1,%0"
2552             : "=m" (pcb->pcb_flags) : "ir" (flags), "m" (pcb->pcb_flags)
2553             : "cc", "memory");
2554
2555 }
2556
2557 /*
2558  * The support for RDFSBASE, WRFSBASE and similar instructions for %gs
2559  * base requires that kernel saves MSR_FSBASE and MSR_{K,}GSBASE into
2560  * pcb if user space modified the bases.  We must save on the context
2561  * switch or if the return to usermode happens through the doreti.
2562  *
2563  * Tracking of both events is performed by the pcb flag PCB_FULL_IRET,
2564  * which have a consequence that the base MSRs must be saved each time
2565  * the PCB_FULL_IRET flag is set.  We disable interrupts to sync with
2566  * context switches.
2567  */
2568 void
2569 set_pcb_flags(struct pcb *pcb, const u_int flags)
2570 {
2571         register_t r;
2572
2573         if (curpcb == pcb &&
2574             (flags & PCB_FULL_IRET) != 0 &&
2575             (pcb->pcb_flags & PCB_FULL_IRET) == 0 &&
2576             (cpu_stdext_feature & CPUID_STDEXT_FSGSBASE) != 0) {
2577                 r = intr_disable();
2578                 if ((pcb->pcb_flags & PCB_FULL_IRET) == 0) {
2579                         if (rfs() == _ufssel)
2580                                 pcb->pcb_fsbase = rdfsbase();
2581                         if (rgs() == _ugssel)
2582                                 pcb->pcb_gsbase = rdmsr(MSR_KGSBASE);
2583                 }
2584                 set_pcb_flags_raw(pcb, flags);
2585                 intr_restore(r);
2586         } else {
2587                 set_pcb_flags_raw(pcb, flags);
2588         }
2589 }
2590
2591 void
2592 clear_pcb_flags(struct pcb *pcb, const u_int flags)
2593 {
2594
2595         __asm __volatile("andl %1,%0"
2596             : "=m" (pcb->pcb_flags) : "ir" (~flags), "m" (pcb->pcb_flags)
2597             : "cc", "memory");
2598 }
2599
2600 #ifdef KDB
2601
2602 /*
2603  * Provide inb() and outb() as functions.  They are normally only available as
2604  * inline functions, thus cannot be called from the debugger.
2605  */
2606
2607 /* silence compiler warnings */
2608 u_char inb_(u_short);
2609 void outb_(u_short, u_char);
2610
2611 u_char
2612 inb_(u_short port)
2613 {
2614         return inb(port);
2615 }
2616
2617 void
2618 outb_(u_short port, u_char data)
2619 {
2620         outb(port, data);
2621 }
2622
2623 #endif /* KDB */