]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/amd64/machdep.c
amd64: stop using top of the thread' kernel stack for FPU user save area
[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_cpu.h"
48 #include "opt_ddb.h"
49 #include "opt_inet.h"
50 #include "opt_isa.h"
51 #include "opt_kstack_pages.h"
52 #include "opt_maxmem.h"
53 #include "opt_mp_watchdog.h"
54 #include "opt_pci.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/asan.h>
62 #include <sys/bio.h>
63 #include <sys/buf.h>
64 #include <sys/bus.h>
65 #include <sys/callout.h>
66 #include <sys/cons.h>
67 #include <sys/cpu.h>
68 #include <sys/csan.h>
69 #include <sys/efi.h>
70 #include <sys/eventhandler.h>
71 #include <sys/exec.h>
72 #include <sys/imgact.h>
73 #include <sys/kdb.h>
74 #include <sys/kernel.h>
75 #include <sys/ktr.h>
76 #include <sys/linker.h>
77 #include <sys/lock.h>
78 #include <sys/malloc.h>
79 #include <sys/memrange.h>
80 #include <sys/msan.h>
81 #include <sys/msgbuf.h>
82 #include <sys/mutex.h>
83 #include <sys/pcpu.h>
84 #include <sys/ptrace.h>
85 #include <sys/reboot.h>
86 #include <sys/reg.h>
87 #include <sys/rwlock.h>
88 #include <sys/sched.h>
89 #include <sys/signalvar.h>
90 #ifdef SMP
91 #include <sys/smp.h>
92 #endif
93 #include <sys/syscallsubr.h>
94 #include <sys/sysctl.h>
95 #include <sys/sysent.h>
96 #include <sys/sysproto.h>
97 #include <sys/ucontext.h>
98 #include <sys/vmmeter.h>
99
100 #include <vm/vm.h>
101 #include <vm/vm_param.h>
102 #include <vm/vm_extern.h>
103 #include <vm/vm_kern.h>
104 #include <vm/vm_page.h>
105 #include <vm/vm_map.h>
106 #include <vm/vm_object.h>
107 #include <vm/vm_pager.h>
108 #include <vm/vm_phys.h>
109 #include <vm/vm_dumpset.h>
110
111 #ifdef DDB
112 #ifndef KDB
113 #error KDB must be enabled in order for DDB to work!
114 #endif
115 #include <ddb/ddb.h>
116 #include <ddb/db_sym.h>
117 #endif
118
119 #include <net/netisr.h>
120
121 #include <machine/clock.h>
122 #include <machine/cpu.h>
123 #include <machine/cputypes.h>
124 #include <machine/frame.h>
125 #include <machine/intr_machdep.h>
126 #include <x86/mca.h>
127 #include <machine/md_var.h>
128 #include <machine/metadata.h>
129 #include <machine/mp_watchdog.h>
130 #include <machine/pc/bios.h>
131 #include <machine/pcb.h>
132 #include <machine/proc.h>
133 #include <machine/sigframe.h>
134 #include <machine/specialreg.h>
135 #include <machine/trap.h>
136 #include <machine/tss.h>
137 #include <x86/ucode.h>
138 #include <x86/ifunc.h>
139 #ifdef SMP
140 #include <machine/smp.h>
141 #endif
142 #ifdef FDT
143 #include <x86/fdt.h>
144 #endif
145
146 #ifdef DEV_ATPIC
147 #include <x86/isa/icu.h>
148 #else
149 #include <x86/apicvar.h>
150 #endif
151
152 #include <isa/isareg.h>
153 #include <isa/rtc.h>
154 #include <x86/init.h>
155
156 /* Sanity check for __curthread() */
157 CTASSERT(offsetof(struct pcpu, pc_curthread) == 0);
158
159 /*
160  * The PTI trampoline stack needs enough space for a hardware trapframe and a
161  * couple of scratch registers, as well as the trapframe left behind after an
162  * iret fault.
163  */
164 CTASSERT(PC_PTI_STACK_SZ * sizeof(register_t) >= 2 * sizeof(struct pti_frame) -
165     offsetof(struct pti_frame, pti_rip));
166
167 extern u_int64_t hammer_time(u_int64_t, u_int64_t);
168
169 static void cpu_startup(void *);
170 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
171
172 /* Preload data parse function */
173 static caddr_t native_parse_preload_data(u_int64_t);
174
175 /* Native function to fetch and parse the e820 map */
176 static void native_parse_memmap(caddr_t, vm_paddr_t *, int *);
177
178 /* Default init_ops implementation. */
179 struct init_ops init_ops = {
180         .parse_preload_data =   native_parse_preload_data,
181         .early_clock_source_init =      i8254_init,
182         .early_delay =                  i8254_delay,
183         .parse_memmap =                 native_parse_memmap,
184 };
185
186 /*
187  * Physical address of the EFI System Table. Stashed from the metadata hints
188  * passed into the kernel and used by the EFI code to call runtime services.
189  */
190 vm_paddr_t efi_systbl_phys;
191
192 /* Intel ICH registers */
193 #define ICH_PMBASE      0x400
194 #define ICH_SMI_EN      ICH_PMBASE + 0x30
195
196 int     _udatasel, _ucodesel, _ucode32sel, _ufssel, _ugssel;
197
198 int cold = 1;
199
200 long Maxmem = 0;
201 long realmem = 0;
202
203 struct kva_md_info kmi;
204
205 static struct trapframe proc0_tf;
206 struct region_descriptor r_idt;
207
208 struct pcpu *__pcpu;
209 struct pcpu temp_bsp_pcpu;
210
211 struct mtx icu_lock;
212
213 struct mem_range_softc mem_range_softc;
214
215 struct mtx dt_lock;     /* lock for GDT and LDT */
216
217 void (*vmm_resume_p)(void);
218
219 bool efi_boot;
220
221 static void
222 cpu_startup(dummy)
223         void *dummy;
224 {
225         uintmax_t memsize;
226         char *sysenv;
227
228         /*
229          * On MacBooks, we need to disallow the legacy USB circuit to
230          * generate an SMI# because this can cause several problems,
231          * namely: incorrect CPU frequency detection and failure to
232          * start the APs.
233          * We do this by disabling a bit in the SMI_EN (SMI Control and
234          * Enable register) of the Intel ICH LPC Interface Bridge. 
235          */
236         sysenv = kern_getenv("smbios.system.product");
237         if (sysenv != NULL) {
238                 if (strncmp(sysenv, "MacBook1,1", 10) == 0 ||
239                     strncmp(sysenv, "MacBook3,1", 10) == 0 ||
240                     strncmp(sysenv, "MacBook4,1", 10) == 0 ||
241                     strncmp(sysenv, "MacBookPro1,1", 13) == 0 ||
242                     strncmp(sysenv, "MacBookPro1,2", 13) == 0 ||
243                     strncmp(sysenv, "MacBookPro3,1", 13) == 0 ||
244                     strncmp(sysenv, "MacBookPro4,1", 13) == 0 ||
245                     strncmp(sysenv, "Macmini1,1", 10) == 0) {
246                         if (bootverbose)
247                                 printf("Disabling LEGACY_USB_EN bit on "
248                                     "Intel ICH.\n");
249                         outl(ICH_SMI_EN, inl(ICH_SMI_EN) & ~0x8);
250                 }
251                 freeenv(sysenv);
252         }
253
254         /*
255          * Good {morning,afternoon,evening,night}.
256          */
257         startrtclock();
258         printcpuinfo();
259
260         /*
261          * Display physical memory if SMBIOS reports reasonable amount.
262          */
263         memsize = 0;
264         sysenv = kern_getenv("smbios.memory.enabled");
265         if (sysenv != NULL) {
266                 memsize = (uintmax_t)strtoul(sysenv, (char **)NULL, 10) << 10;
267                 freeenv(sysenv);
268         }
269         if (memsize < ptoa((uintmax_t)vm_free_count()))
270                 memsize = ptoa((uintmax_t)Maxmem);
271         printf("real memory  = %ju (%ju MB)\n", memsize, memsize >> 20);
272         realmem = atop(memsize);
273
274         /*
275          * Display any holes after the first chunk of extended memory.
276          */
277         if (bootverbose) {
278                 int indx;
279
280                 printf("Physical memory chunk(s):\n");
281                 for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
282                         vm_paddr_t size;
283
284                         size = phys_avail[indx + 1] - phys_avail[indx];
285                         printf(
286                             "0x%016jx - 0x%016jx, %ju bytes (%ju pages)\n",
287                             (uintmax_t)phys_avail[indx],
288                             (uintmax_t)phys_avail[indx + 1] - 1,
289                             (uintmax_t)size, (uintmax_t)size / PAGE_SIZE);
290                 }
291         }
292
293         vm_ksubmap_init(&kmi);
294
295         printf("avail memory = %ju (%ju MB)\n",
296             ptoa((uintmax_t)vm_free_count()),
297             ptoa((uintmax_t)vm_free_count()) / 1048576);
298 #ifdef DEV_PCI
299         if (bootverbose && intel_graphics_stolen_base != 0)
300                 printf("intel stolen mem: base %#jx size %ju MB\n",
301                     (uintmax_t)intel_graphics_stolen_base,
302                     (uintmax_t)intel_graphics_stolen_size / 1024 / 1024);
303 #endif
304
305         /*
306          * Set up buffers, so they can be used to read disk labels.
307          */
308         bufinit();
309         vm_pager_bufferinit();
310
311         cpu_setregs();
312 }
313
314 static void
315 late_ifunc_resolve(void *dummy __unused)
316 {
317         link_elf_late_ireloc();
318 }
319 SYSINIT(late_ifunc_resolve, SI_SUB_CPU, SI_ORDER_ANY, late_ifunc_resolve, NULL);
320
321
322 void
323 cpu_setregs(void)
324 {
325         register_t cr0;
326
327         cr0 = rcr0();
328         /*
329          * CR0_MP, CR0_NE and CR0_TS are also set by npx_probe() for the
330          * BSP.  See the comments there about why we set them.
331          */
332         cr0 |= CR0_MP | CR0_NE | CR0_TS | CR0_WP | CR0_AM;
333         load_cr0(cr0);
334 }
335
336 /*
337  * Initialize amd64 and configure to run kernel
338  */
339
340 /*
341  * Initialize segments & interrupt table
342  */
343 static struct gate_descriptor idt0[NIDT];
344 struct gate_descriptor *idt = &idt0[0]; /* interrupt descriptor table */
345
346 static char dblfault_stack[DBLFAULT_STACK_SIZE] __aligned(16);
347 static char mce0_stack[MCE_STACK_SIZE] __aligned(16);
348 static char nmi0_stack[NMI_STACK_SIZE] __aligned(16);
349 static char dbg0_stack[DBG_STACK_SIZE] __aligned(16);
350 CTASSERT(sizeof(struct nmi_pcpu) == 16);
351
352 /*
353  * Software prototypes -- in more palatable form.
354  *
355  * Keep GUFS32, GUGS32, GUCODE32 and GUDATA at the same
356  * slots as corresponding segments for i386 kernel.
357  */
358 struct soft_segment_descriptor gdt_segs[] = {
359 /* GNULL_SEL    0 Null Descriptor */
360 {       .ssd_base = 0x0,
361         .ssd_limit = 0x0,
362         .ssd_type = 0,
363         .ssd_dpl = 0,
364         .ssd_p = 0,
365         .ssd_long = 0,
366         .ssd_def32 = 0,
367         .ssd_gran = 0           },
368 /* GNULL2_SEL   1 Null Descriptor */
369 {       .ssd_base = 0x0,
370         .ssd_limit = 0x0,
371         .ssd_type = 0,
372         .ssd_dpl = 0,
373         .ssd_p = 0,
374         .ssd_long = 0,
375         .ssd_def32 = 0,
376         .ssd_gran = 0           },
377 /* GUFS32_SEL   2 32 bit %gs Descriptor for user */
378 {       .ssd_base = 0x0,
379         .ssd_limit = 0xfffff,
380         .ssd_type = SDT_MEMRWA,
381         .ssd_dpl = SEL_UPL,
382         .ssd_p = 1,
383         .ssd_long = 0,
384         .ssd_def32 = 1,
385         .ssd_gran = 1           },
386 /* GUGS32_SEL   3 32 bit %fs Descriptor for user */
387 {       .ssd_base = 0x0,
388         .ssd_limit = 0xfffff,
389         .ssd_type = SDT_MEMRWA,
390         .ssd_dpl = SEL_UPL,
391         .ssd_p = 1,
392         .ssd_long = 0,
393         .ssd_def32 = 1,
394         .ssd_gran = 1           },
395 /* GCODE_SEL    4 Code Descriptor for kernel */
396 {       .ssd_base = 0x0,
397         .ssd_limit = 0xfffff,
398         .ssd_type = SDT_MEMERA,
399         .ssd_dpl = SEL_KPL,
400         .ssd_p = 1,
401         .ssd_long = 1,
402         .ssd_def32 = 0,
403         .ssd_gran = 1           },
404 /* GDATA_SEL    5 Data Descriptor for kernel */
405 {       .ssd_base = 0x0,
406         .ssd_limit = 0xfffff,
407         .ssd_type = SDT_MEMRWA,
408         .ssd_dpl = SEL_KPL,
409         .ssd_p = 1,
410         .ssd_long = 1,
411         .ssd_def32 = 0,
412         .ssd_gran = 1           },
413 /* GUCODE32_SEL 6 32 bit Code Descriptor for user */
414 {       .ssd_base = 0x0,
415         .ssd_limit = 0xfffff,
416         .ssd_type = SDT_MEMERA,
417         .ssd_dpl = SEL_UPL,
418         .ssd_p = 1,
419         .ssd_long = 0,
420         .ssd_def32 = 1,
421         .ssd_gran = 1           },
422 /* GUDATA_SEL   7 32/64 bit Data Descriptor for user */
423 {       .ssd_base = 0x0,
424         .ssd_limit = 0xfffff,
425         .ssd_type = SDT_MEMRWA,
426         .ssd_dpl = SEL_UPL,
427         .ssd_p = 1,
428         .ssd_long = 0,
429         .ssd_def32 = 1,
430         .ssd_gran = 1           },
431 /* GUCODE_SEL   8 64 bit Code Descriptor for user */
432 {       .ssd_base = 0x0,
433         .ssd_limit = 0xfffff,
434         .ssd_type = SDT_MEMERA,
435         .ssd_dpl = SEL_UPL,
436         .ssd_p = 1,
437         .ssd_long = 1,
438         .ssd_def32 = 0,
439         .ssd_gran = 1           },
440 /* GPROC0_SEL   9 Proc 0 Tss Descriptor */
441 {       .ssd_base = 0x0,
442         .ssd_limit = sizeof(struct amd64tss) + IOPERM_BITMAP_SIZE - 1,
443         .ssd_type = SDT_SYSTSS,
444         .ssd_dpl = SEL_KPL,
445         .ssd_p = 1,
446         .ssd_long = 0,
447         .ssd_def32 = 0,
448         .ssd_gran = 0           },
449 /* Actually, the TSS is a system descriptor which is double size */
450 {       .ssd_base = 0x0,
451         .ssd_limit = 0x0,
452         .ssd_type = 0,
453         .ssd_dpl = 0,
454         .ssd_p = 0,
455         .ssd_long = 0,
456         .ssd_def32 = 0,
457         .ssd_gran = 0           },
458 /* GUSERLDT_SEL 11 LDT Descriptor */
459 {       .ssd_base = 0x0,
460         .ssd_limit = 0x0,
461         .ssd_type = 0,
462         .ssd_dpl = 0,
463         .ssd_p = 0,
464         .ssd_long = 0,
465         .ssd_def32 = 0,
466         .ssd_gran = 0           },
467 /* GUSERLDT_SEL 12 LDT Descriptor, double size */
468 {       .ssd_base = 0x0,
469         .ssd_limit = 0x0,
470         .ssd_type = 0,
471         .ssd_dpl = 0,
472         .ssd_p = 0,
473         .ssd_long = 0,
474         .ssd_def32 = 0,
475         .ssd_gran = 0           },
476 };
477 _Static_assert(nitems(gdt_segs) == NGDT, "Stale NGDT");
478
479 void
480 setidt(int idx, inthand_t *func, int typ, int dpl, int ist)
481 {
482         struct gate_descriptor *ip;
483
484         ip = idt + idx;
485         ip->gd_looffset = (uintptr_t)func;
486         ip->gd_selector = GSEL(GCODE_SEL, SEL_KPL);
487         ip->gd_ist = ist;
488         ip->gd_xx = 0;
489         ip->gd_type = typ;
490         ip->gd_dpl = dpl;
491         ip->gd_p = 1;
492         ip->gd_hioffset = ((uintptr_t)func)>>16 ;
493 }
494
495 extern inthand_t
496         IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
497         IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
498         IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
499         IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
500         IDTVEC(xmm), IDTVEC(dblfault),
501         IDTVEC(div_pti), IDTVEC(bpt_pti),
502         IDTVEC(ofl_pti), IDTVEC(bnd_pti), IDTVEC(ill_pti), IDTVEC(dna_pti),
503         IDTVEC(fpusegm_pti), IDTVEC(tss_pti), IDTVEC(missing_pti),
504         IDTVEC(stk_pti), IDTVEC(prot_pti), IDTVEC(page_pti),
505         IDTVEC(rsvd_pti), IDTVEC(fpu_pti), IDTVEC(align_pti),
506         IDTVEC(xmm_pti),
507 #ifdef KDTRACE_HOOKS
508         IDTVEC(dtrace_ret), IDTVEC(dtrace_ret_pti),
509 #endif
510 #ifdef XENHVM
511         IDTVEC(xen_intr_upcall), IDTVEC(xen_intr_upcall_pti),
512 #endif
513         IDTVEC(fast_syscall), IDTVEC(fast_syscall32),
514         IDTVEC(fast_syscall_pti);
515
516 #ifdef DDB
517 /*
518  * Display the index and function name of any IDT entries that don't use
519  * the default 'rsvd' entry point.
520  */
521 DB_SHOW_COMMAND(idt, db_show_idt)
522 {
523         struct gate_descriptor *ip;
524         int idx;
525         uintptr_t func;
526
527         ip = idt;
528         for (idx = 0; idx < NIDT && !db_pager_quit; idx++) {
529                 func = ((long)ip->gd_hioffset << 16 | ip->gd_looffset);
530                 if (func != (uintptr_t)&IDTVEC(rsvd)) {
531                         db_printf("%3d\t", idx);
532                         db_printsym(func, DB_STGY_PROC);
533                         db_printf("\n");
534                 }
535                 ip++;
536         }
537 }
538
539 /* Show privileged registers. */
540 DB_SHOW_COMMAND(sysregs, db_show_sysregs)
541 {
542         struct {
543                 uint16_t limit;
544                 uint64_t base;
545         } __packed idtr, gdtr;
546         uint16_t ldt, tr;
547
548         __asm __volatile("sidt %0" : "=m" (idtr));
549         db_printf("idtr\t0x%016lx/%04x\n",
550             (u_long)idtr.base, (u_int)idtr.limit);
551         __asm __volatile("sgdt %0" : "=m" (gdtr));
552         db_printf("gdtr\t0x%016lx/%04x\n",
553             (u_long)gdtr.base, (u_int)gdtr.limit);
554         __asm __volatile("sldt %0" : "=r" (ldt));
555         db_printf("ldtr\t0x%04x\n", ldt);
556         __asm __volatile("str %0" : "=r" (tr));
557         db_printf("tr\t0x%04x\n", tr);
558         db_printf("cr0\t0x%016lx\n", rcr0());
559         db_printf("cr2\t0x%016lx\n", rcr2());
560         db_printf("cr3\t0x%016lx\n", rcr3());
561         db_printf("cr4\t0x%016lx\n", rcr4());
562         if (rcr4() & CR4_XSAVE)
563                 db_printf("xcr0\t0x%016lx\n", rxcr(0));
564         db_printf("EFER\t0x%016lx\n", rdmsr(MSR_EFER));
565         if (cpu_feature2 & (CPUID2_VMX | CPUID2_SMX))
566                 db_printf("FEATURES_CTL\t%016lx\n",
567                     rdmsr(MSR_IA32_FEATURE_CONTROL));
568         db_printf("DEBUG_CTL\t0x%016lx\n", rdmsr(MSR_DEBUGCTLMSR));
569         db_printf("PAT\t0x%016lx\n", rdmsr(MSR_PAT));
570         db_printf("GSBASE\t0x%016lx\n", rdmsr(MSR_GSBASE));
571 }
572
573 DB_SHOW_COMMAND(dbregs, db_show_dbregs)
574 {
575
576         db_printf("dr0\t0x%016lx\n", rdr0());
577         db_printf("dr1\t0x%016lx\n", rdr1());
578         db_printf("dr2\t0x%016lx\n", rdr2());
579         db_printf("dr3\t0x%016lx\n", rdr3());
580         db_printf("dr6\t0x%016lx\n", rdr6());
581         db_printf("dr7\t0x%016lx\n", rdr7());   
582 }
583 #endif
584
585 void
586 sdtossd(sd, ssd)
587         struct user_segment_descriptor *sd;
588         struct soft_segment_descriptor *ssd;
589 {
590
591         ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
592         ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
593         ssd->ssd_type  = sd->sd_type;
594         ssd->ssd_dpl   = sd->sd_dpl;
595         ssd->ssd_p     = sd->sd_p;
596         ssd->ssd_long  = sd->sd_long;
597         ssd->ssd_def32 = sd->sd_def32;
598         ssd->ssd_gran  = sd->sd_gran;
599 }
600
601 void
602 ssdtosd(ssd, sd)
603         struct soft_segment_descriptor *ssd;
604         struct user_segment_descriptor *sd;
605 {
606
607         sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
608         sd->sd_hibase = (ssd->ssd_base >> 24) & 0xff;
609         sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
610         sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
611         sd->sd_type  = ssd->ssd_type;
612         sd->sd_dpl   = ssd->ssd_dpl;
613         sd->sd_p     = ssd->ssd_p;
614         sd->sd_long  = ssd->ssd_long;
615         sd->sd_def32 = ssd->ssd_def32;
616         sd->sd_gran  = ssd->ssd_gran;
617 }
618
619 void
620 ssdtosyssd(ssd, sd)
621         struct soft_segment_descriptor *ssd;
622         struct system_segment_descriptor *sd;
623 {
624
625         sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
626         sd->sd_hibase = (ssd->ssd_base >> 24) & 0xfffffffffful;
627         sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
628         sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
629         sd->sd_type  = ssd->ssd_type;
630         sd->sd_dpl   = ssd->ssd_dpl;
631         sd->sd_p     = ssd->ssd_p;
632         sd->sd_gran  = ssd->ssd_gran;
633 }
634
635 u_int basemem;
636
637 static int
638 add_physmap_entry(uint64_t base, uint64_t length, vm_paddr_t *physmap,
639     int *physmap_idxp)
640 {
641         int i, insert_idx, physmap_idx;
642
643         physmap_idx = *physmap_idxp;
644
645         if (length == 0)
646                 return (1);
647
648         /*
649          * Find insertion point while checking for overlap.  Start off by
650          * assuming the new entry will be added to the end.
651          *
652          * NB: physmap_idx points to the next free slot.
653          */
654         insert_idx = physmap_idx;
655         for (i = 0; i <= physmap_idx; i += 2) {
656                 if (base < physmap[i + 1]) {
657                         if (base + length <= physmap[i]) {
658                                 insert_idx = i;
659                                 break;
660                         }
661                         if (boothowto & RB_VERBOSE)
662                                 printf(
663                     "Overlapping memory regions, ignoring second region\n");
664                         return (1);
665                 }
666         }
667
668         /* See if we can prepend to the next entry. */
669         if (insert_idx <= physmap_idx && base + length == physmap[insert_idx]) {
670                 physmap[insert_idx] = base;
671                 return (1);
672         }
673
674         /* See if we can append to the previous entry. */
675         if (insert_idx > 0 && base == physmap[insert_idx - 1]) {
676                 physmap[insert_idx - 1] += length;
677                 return (1);
678         }
679
680         physmap_idx += 2;
681         *physmap_idxp = physmap_idx;
682         if (physmap_idx == PHYS_AVAIL_ENTRIES) {
683                 printf(
684                 "Too many segments in the physical address map, giving up\n");
685                 return (0);
686         }
687
688         /*
689          * Move the last 'N' entries down to make room for the new
690          * entry if needed.
691          */
692         for (i = (physmap_idx - 2); i > insert_idx; i -= 2) {
693                 physmap[i] = physmap[i - 2];
694                 physmap[i + 1] = physmap[i - 1];
695         }
696
697         /* Insert the new entry. */
698         physmap[insert_idx] = base;
699         physmap[insert_idx + 1] = base + length;
700         return (1);
701 }
702
703 void
704 bios_add_smap_entries(struct bios_smap *smapbase, u_int32_t smapsize,
705                       vm_paddr_t *physmap, int *physmap_idx)
706 {
707         struct bios_smap *smap, *smapend;
708
709         smapend = (struct bios_smap *)((uintptr_t)smapbase + smapsize);
710
711         for (smap = smapbase; smap < smapend; smap++) {
712                 if (boothowto & RB_VERBOSE)
713                         printf("SMAP type=%02x base=%016lx len=%016lx\n",
714                             smap->type, smap->base, smap->length);
715
716                 if (smap->type != SMAP_TYPE_MEMORY)
717                         continue;
718
719                 if (!add_physmap_entry(smap->base, smap->length, physmap,
720                     physmap_idx))
721                         break;
722         }
723 }
724
725 static void
726 add_efi_map_entries(struct efi_map_header *efihdr, vm_paddr_t *physmap,
727     int *physmap_idx)
728 {
729         struct efi_md *map, *p;
730         const char *type;
731         size_t efisz;
732         int ndesc, i;
733
734         static const char *types[] = {
735                 "Reserved",
736                 "LoaderCode",
737                 "LoaderData",
738                 "BootServicesCode",
739                 "BootServicesData",
740                 "RuntimeServicesCode",
741                 "RuntimeServicesData",
742                 "ConventionalMemory",
743                 "UnusableMemory",
744                 "ACPIReclaimMemory",
745                 "ACPIMemoryNVS",
746                 "MemoryMappedIO",
747                 "MemoryMappedIOPortSpace",
748                 "PalCode",
749                 "PersistentMemory"
750         };
751
752         /*
753          * Memory map data provided by UEFI via the GetMemoryMap
754          * Boot Services API.
755          */
756         efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
757         map = (struct efi_md *)((uint8_t *)efihdr + efisz);
758
759         if (efihdr->descriptor_size == 0)
760                 return;
761         ndesc = efihdr->memory_size / efihdr->descriptor_size;
762
763         if (boothowto & RB_VERBOSE)
764                 printf("%23s %12s %12s %8s %4s\n",
765                     "Type", "Physical", "Virtual", "#Pages", "Attr");
766
767         for (i = 0, p = map; i < ndesc; i++,
768             p = efi_next_descriptor(p, efihdr->descriptor_size)) {
769                 if (boothowto & RB_VERBOSE) {
770                         if (p->md_type < nitems(types))
771                                 type = types[p->md_type];
772                         else
773                                 type = "<INVALID>";
774                         printf("%23s %012lx %012lx %08lx ", type, p->md_phys,
775                             p->md_virt, p->md_pages);
776                         if (p->md_attr & EFI_MD_ATTR_UC)
777                                 printf("UC ");
778                         if (p->md_attr & EFI_MD_ATTR_WC)
779                                 printf("WC ");
780                         if (p->md_attr & EFI_MD_ATTR_WT)
781                                 printf("WT ");
782                         if (p->md_attr & EFI_MD_ATTR_WB)
783                                 printf("WB ");
784                         if (p->md_attr & EFI_MD_ATTR_UCE)
785                                 printf("UCE ");
786                         if (p->md_attr & EFI_MD_ATTR_WP)
787                                 printf("WP ");
788                         if (p->md_attr & EFI_MD_ATTR_RP)
789                                 printf("RP ");
790                         if (p->md_attr & EFI_MD_ATTR_XP)
791                                 printf("XP ");
792                         if (p->md_attr & EFI_MD_ATTR_NV)
793                                 printf("NV ");
794                         if (p->md_attr & EFI_MD_ATTR_MORE_RELIABLE)
795                                 printf("MORE_RELIABLE ");
796                         if (p->md_attr & EFI_MD_ATTR_RO)
797                                 printf("RO ");
798                         if (p->md_attr & EFI_MD_ATTR_RT)
799                                 printf("RUNTIME");
800                         printf("\n");
801                 }
802
803                 switch (p->md_type) {
804                 case EFI_MD_TYPE_CODE:
805                 case EFI_MD_TYPE_DATA:
806                 case EFI_MD_TYPE_BS_CODE:
807                 case EFI_MD_TYPE_BS_DATA:
808                 case EFI_MD_TYPE_FREE:
809                         /*
810                          * We're allowed to use any entry with these types.
811                          */
812                         break;
813                 default:
814                         continue;
815                 }
816
817                 if (!add_physmap_entry(p->md_phys, (p->md_pages * PAGE_SIZE),
818                     physmap, physmap_idx))
819                         break;
820         }
821 }
822
823 static void
824 native_parse_memmap(caddr_t kmdp, vm_paddr_t *physmap, int *physmap_idx)
825 {
826         struct bios_smap *smap;
827         struct efi_map_header *efihdr;
828         u_int32_t size;
829
830         /*
831          * Memory map from INT 15:E820.
832          *
833          * subr_module.c says:
834          * "Consumer may safely assume that size value precedes data."
835          * ie: an int32_t immediately precedes smap.
836          */
837
838         efihdr = (struct efi_map_header *)preload_search_info(kmdp,
839             MODINFO_METADATA | MODINFOMD_EFI_MAP);
840         smap = (struct bios_smap *)preload_search_info(kmdp,
841             MODINFO_METADATA | MODINFOMD_SMAP);
842         if (efihdr == NULL && smap == NULL)
843                 panic("No BIOS smap or EFI map info from loader!");
844
845         if (efihdr != NULL) {
846                 add_efi_map_entries(efihdr, physmap, physmap_idx);
847                 strlcpy(bootmethod, "UEFI", sizeof(bootmethod));
848         } else {
849                 size = *((u_int32_t *)smap - 1);
850                 bios_add_smap_entries(smap, size, physmap, physmap_idx);
851                 strlcpy(bootmethod, "BIOS", sizeof(bootmethod));
852         }
853 }
854
855 #define PAGES_PER_GB    (1024 * 1024 * 1024 / PAGE_SIZE)
856
857 /*
858  * Populate the (physmap) array with base/bound pairs describing the
859  * available physical memory in the system, then test this memory and
860  * build the phys_avail array describing the actually-available memory.
861  *
862  * Total memory size may be set by the kernel environment variable
863  * hw.physmem or the compile-time define MAXMEM.
864  *
865  * XXX first should be vm_paddr_t.
866  */
867 static void
868 getmemsize(caddr_t kmdp, u_int64_t first)
869 {
870         int i, physmap_idx, pa_indx, da_indx;
871         vm_paddr_t pa, physmap[PHYS_AVAIL_ENTRIES];
872         u_long physmem_start, physmem_tunable, memtest;
873         pt_entry_t *pte;
874         quad_t dcons_addr, dcons_size;
875         int page_counter;
876
877         /*
878          * Tell the physical memory allocator about pages used to store
879          * the kernel and preloaded data.  See kmem_bootstrap_free().
880          */
881         vm_phys_early_add_seg((vm_paddr_t)kernphys, trunc_page(first));
882
883         bzero(physmap, sizeof(physmap));
884         physmap_idx = 0;
885
886         init_ops.parse_memmap(kmdp, physmap, &physmap_idx);
887         physmap_idx -= 2;
888
889         /*
890          * Find the 'base memory' segment for SMP
891          */
892         basemem = 0;
893         for (i = 0; i <= physmap_idx; i += 2) {
894                 if (physmap[i] <= 0xA0000) {
895                         basemem = physmap[i + 1] / 1024;
896                         break;
897                 }
898         }
899         if (basemem == 0 || basemem > 640) {
900                 if (bootverbose)
901                         printf(
902                 "Memory map doesn't contain a basemem segment, faking it");
903                 basemem = 640;
904         }
905
906         /*
907          * Maxmem isn't the "maximum memory", it's one larger than the
908          * highest page of the physical address space.  It should be
909          * called something like "Maxphyspage".  We may adjust this
910          * based on ``hw.physmem'' and the results of the memory test.
911          */
912         Maxmem = atop(physmap[physmap_idx + 1]);
913
914 #ifdef MAXMEM
915         Maxmem = MAXMEM / 4;
916 #endif
917
918         if (TUNABLE_ULONG_FETCH("hw.physmem", &physmem_tunable))
919                 Maxmem = atop(physmem_tunable);
920
921         /*
922          * The boot memory test is disabled by default, as it takes a
923          * significant amount of time on large-memory systems, and is
924          * unfriendly to virtual machines as it unnecessarily touches all
925          * pages.
926          *
927          * A general name is used as the code may be extended to support
928          * additional tests beyond the current "page present" test.
929          */
930         memtest = 0;
931         TUNABLE_ULONG_FETCH("hw.memtest.tests", &memtest);
932
933         /*
934          * Don't allow MAXMEM or hw.physmem to extend the amount of memory
935          * in the system.
936          */
937         if (Maxmem > atop(physmap[physmap_idx + 1]))
938                 Maxmem = atop(physmap[physmap_idx + 1]);
939
940         if (atop(physmap[physmap_idx + 1]) != Maxmem &&
941             (boothowto & RB_VERBOSE))
942                 printf("Physical memory use set to %ldK\n", Maxmem * 4);
943
944         /* call pmap initialization to make new kernel address space */
945         pmap_bootstrap(&first);
946
947         /*
948          * Size up each available chunk of physical memory.
949          *
950          * XXX Some BIOSes corrupt low 64KB between suspend and resume.
951          * By default, mask off the first 16 pages unless we appear to be
952          * running in a VM.
953          */
954         physmem_start = (vm_guest > VM_GUEST_NO ? 1 : 16) << PAGE_SHIFT;
955         TUNABLE_ULONG_FETCH("hw.physmem.start", &physmem_start);
956         if (physmap[0] < physmem_start) {
957                 if (physmem_start < PAGE_SIZE)
958                         physmap[0] = PAGE_SIZE;
959                 else if (physmem_start >= physmap[1])
960                         physmap[0] = round_page(physmap[1] - PAGE_SIZE);
961                 else
962                         physmap[0] = round_page(physmem_start);
963         }
964         pa_indx = 0;
965         da_indx = 1;
966         phys_avail[pa_indx++] = physmap[0];
967         phys_avail[pa_indx] = physmap[0];
968         dump_avail[da_indx] = physmap[0];
969         pte = CMAP1;
970
971         /*
972          * Get dcons buffer address
973          */
974         if (getenv_quad("dcons.addr", &dcons_addr) == 0 ||
975             getenv_quad("dcons.size", &dcons_size) == 0)
976                 dcons_addr = 0;
977
978         /*
979          * physmap is in bytes, so when converting to page boundaries,
980          * round up the start address and round down the end address.
981          */
982         page_counter = 0;
983         if (memtest != 0)
984                 printf("Testing system memory");
985         for (i = 0; i <= physmap_idx; i += 2) {
986                 vm_paddr_t end;
987
988                 end = ptoa((vm_paddr_t)Maxmem);
989                 if (physmap[i + 1] < end)
990                         end = trunc_page(physmap[i + 1]);
991                 for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
992                         int tmp, page_bad, full;
993                         int *ptr = (int *)CADDR1;
994
995                         full = FALSE;
996                         /*
997                          * block out kernel memory as not available.
998                          */
999                         if (pa >= (vm_paddr_t)kernphys && pa < first)
1000                                 goto do_dump_avail;
1001
1002                         /*
1003                          * block out dcons buffer
1004                          */
1005                         if (dcons_addr > 0
1006                             && pa >= trunc_page(dcons_addr)
1007                             && pa < dcons_addr + dcons_size)
1008                                 goto do_dump_avail;
1009
1010                         page_bad = FALSE;
1011                         if (memtest == 0)
1012                                 goto skip_memtest;
1013
1014                         /*
1015                          * Print a "." every GB to show we're making
1016                          * progress.
1017                          */
1018                         page_counter++;
1019                         if ((page_counter % PAGES_PER_GB) == 0)
1020                                 printf(".");
1021
1022                         /*
1023                          * map page into kernel: valid, read/write,non-cacheable
1024                          */
1025                         *pte = pa | PG_V | PG_RW | PG_NC_PWT | PG_NC_PCD;
1026                         invltlb();
1027
1028                         tmp = *(int *)ptr;
1029                         /*
1030                          * Test for alternating 1's and 0's
1031                          */
1032                         *(volatile int *)ptr = 0xaaaaaaaa;
1033                         if (*(volatile int *)ptr != 0xaaaaaaaa)
1034                                 page_bad = TRUE;
1035                         /*
1036                          * Test for alternating 0's and 1's
1037                          */
1038                         *(volatile int *)ptr = 0x55555555;
1039                         if (*(volatile int *)ptr != 0x55555555)
1040                                 page_bad = TRUE;
1041                         /*
1042                          * Test for all 1's
1043                          */
1044                         *(volatile int *)ptr = 0xffffffff;
1045                         if (*(volatile int *)ptr != 0xffffffff)
1046                                 page_bad = TRUE;
1047                         /*
1048                          * Test for all 0's
1049                          */
1050                         *(volatile int *)ptr = 0x0;
1051                         if (*(volatile int *)ptr != 0x0)
1052                                 page_bad = TRUE;
1053                         /*
1054                          * Restore original value.
1055                          */
1056                         *(int *)ptr = tmp;
1057
1058 skip_memtest:
1059                         /*
1060                          * Adjust array of valid/good pages.
1061                          */
1062                         if (page_bad == TRUE)
1063                                 continue;
1064                         /*
1065                          * If this good page is a continuation of the
1066                          * previous set of good pages, then just increase
1067                          * the end pointer. Otherwise start a new chunk.
1068                          * Note that "end" points one higher than end,
1069                          * making the range >= start and < end.
1070                          * If we're also doing a speculative memory
1071                          * test and we at or past the end, bump up Maxmem
1072                          * so that we keep going. The first bad page
1073                          * will terminate the loop.
1074                          */
1075                         if (phys_avail[pa_indx] == pa) {
1076                                 phys_avail[pa_indx] += PAGE_SIZE;
1077                         } else {
1078                                 pa_indx++;
1079                                 if (pa_indx == PHYS_AVAIL_ENTRIES) {
1080                                         printf(
1081                 "Too many holes in the physical address space, giving up\n");
1082                                         pa_indx--;
1083                                         full = TRUE;
1084                                         goto do_dump_avail;
1085                                 }
1086                                 phys_avail[pa_indx++] = pa;     /* start */
1087                                 phys_avail[pa_indx] = pa + PAGE_SIZE; /* end */
1088                         }
1089                         physmem++;
1090 do_dump_avail:
1091                         if (dump_avail[da_indx] == pa) {
1092                                 dump_avail[da_indx] += PAGE_SIZE;
1093                         } else {
1094                                 da_indx++;
1095                                 if (da_indx == PHYS_AVAIL_ENTRIES) {
1096                                         da_indx--;
1097                                         goto do_next;
1098                                 }
1099                                 dump_avail[da_indx++] = pa; /* start */
1100                                 dump_avail[da_indx] = pa + PAGE_SIZE; /* end */
1101                         }
1102 do_next:
1103                         if (full)
1104                                 break;
1105                 }
1106         }
1107         *pte = 0;
1108         invltlb();
1109         if (memtest != 0)
1110                 printf("\n");
1111
1112         /*
1113          * XXX
1114          * The last chunk must contain at least one page plus the message
1115          * buffer to avoid complicating other code (message buffer address
1116          * calculation, etc.).
1117          */
1118         while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1119             round_page(msgbufsize) >= phys_avail[pa_indx]) {
1120                 physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1121                 phys_avail[pa_indx--] = 0;
1122                 phys_avail[pa_indx--] = 0;
1123         }
1124
1125         Maxmem = atop(phys_avail[pa_indx]);
1126
1127         /* Trim off space for the message buffer. */
1128         phys_avail[pa_indx] -= round_page(msgbufsize);
1129
1130         /* Map the message buffer. */
1131         msgbufp = (struct msgbuf *)PHYS_TO_DMAP(phys_avail[pa_indx]);
1132 }
1133
1134 static caddr_t
1135 native_parse_preload_data(u_int64_t modulep)
1136 {
1137         caddr_t kmdp;
1138         char *envp;
1139 #ifdef DDB
1140         vm_offset_t ksym_start;
1141         vm_offset_t ksym_end;
1142 #endif
1143
1144         preload_metadata = (caddr_t)(uintptr_t)(modulep + KERNBASE);
1145         preload_bootstrap_relocate(KERNBASE);
1146         kmdp = preload_search_by_type("elf kernel");
1147         if (kmdp == NULL)
1148                 kmdp = preload_search_by_type("elf64 kernel");
1149         boothowto = MD_FETCH(kmdp, MODINFOMD_HOWTO, int);
1150         envp = MD_FETCH(kmdp, MODINFOMD_ENVP, char *);
1151         if (envp != NULL)
1152                 envp += KERNBASE;
1153         init_static_kenv(envp, 0);
1154 #ifdef DDB
1155         ksym_start = MD_FETCH(kmdp, MODINFOMD_SSYM, uintptr_t);
1156         ksym_end = MD_FETCH(kmdp, MODINFOMD_ESYM, uintptr_t);
1157         db_fetch_ksymtab(ksym_start, ksym_end, 0);
1158 #endif
1159         efi_systbl_phys = MD_FETCH(kmdp, MODINFOMD_FW_HANDLE, vm_paddr_t);
1160
1161         return (kmdp);
1162 }
1163
1164 static void
1165 amd64_kdb_init(void)
1166 {
1167         kdb_init();
1168 #ifdef KDB
1169         if (boothowto & RB_KDB)
1170                 kdb_enter(KDB_WHY_BOOTFLAGS, "Boot flags requested debugger");
1171 #endif
1172 }
1173
1174 /* Set up the fast syscall stuff */
1175 void
1176 amd64_conf_fast_syscall(void)
1177 {
1178         uint64_t msr;
1179
1180         msr = rdmsr(MSR_EFER) | EFER_SCE;
1181         wrmsr(MSR_EFER, msr);
1182         wrmsr(MSR_LSTAR, pti ? (u_int64_t)IDTVEC(fast_syscall_pti) :
1183             (u_int64_t)IDTVEC(fast_syscall));
1184         wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
1185         msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
1186             ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
1187         wrmsr(MSR_STAR, msr);
1188         wrmsr(MSR_SF_MASK, PSL_NT | PSL_T | PSL_I | PSL_C | PSL_D | PSL_AC);
1189 }
1190
1191 void
1192 amd64_bsp_pcpu_init1(struct pcpu *pc)
1193 {
1194         struct user_segment_descriptor *gdt;
1195
1196         PCPU_SET(prvspace, pc);
1197         gdt = *PCPU_PTR(gdt);
1198         PCPU_SET(curthread, &thread0);
1199         PCPU_SET(tssp, PCPU_PTR(common_tss));
1200         PCPU_SET(tss, (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
1201         PCPU_SET(ldt, (struct system_segment_descriptor *)&gdt[GUSERLDT_SEL]);
1202         PCPU_SET(fs32p, &gdt[GUFS32_SEL]);
1203         PCPU_SET(gs32p, &gdt[GUGS32_SEL]);
1204         PCPU_SET(ucr3_load_mask, PMAP_UCR3_NOMASK);
1205         PCPU_SET(smp_tlb_gen, 1);
1206 }
1207
1208 void
1209 amd64_bsp_pcpu_init2(uint64_t rsp0)
1210 {
1211
1212         PCPU_SET(rsp0, rsp0);
1213         PCPU_SET(pti_rsp0, ((vm_offset_t)PCPU_PTR(pti_stack) +
1214             PC_PTI_STACK_SZ * sizeof(uint64_t)) & ~0xful);
1215         PCPU_SET(curpcb, thread0.td_pcb);
1216 }
1217
1218 void
1219 amd64_bsp_ist_init(struct pcpu *pc)
1220 {
1221         struct nmi_pcpu *np;
1222         struct amd64tss *tssp;
1223
1224         tssp = &pc->pc_common_tss;
1225
1226         /* doublefault stack space, runs on ist1 */
1227         np = ((struct nmi_pcpu *)&dblfault_stack[sizeof(dblfault_stack)]) - 1;
1228         np->np_pcpu = (register_t)pc;
1229         tssp->tss_ist1 = (long)np;
1230
1231         /*
1232          * NMI stack, runs on ist2.  The pcpu pointer is stored just
1233          * above the start of the ist2 stack.
1234          */
1235         np = ((struct nmi_pcpu *)&nmi0_stack[sizeof(nmi0_stack)]) - 1;
1236         np->np_pcpu = (register_t)pc;
1237         tssp->tss_ist2 = (long)np;
1238
1239         /*
1240          * MC# stack, runs on ist3.  The pcpu pointer is stored just
1241          * above the start of the ist3 stack.
1242          */
1243         np = ((struct nmi_pcpu *)&mce0_stack[sizeof(mce0_stack)]) - 1;
1244         np->np_pcpu = (register_t)pc;
1245         tssp->tss_ist3 = (long)np;
1246
1247         /*
1248          * DB# stack, runs on ist4.
1249          */
1250         np = ((struct nmi_pcpu *)&dbg0_stack[sizeof(dbg0_stack)]) - 1;
1251         np->np_pcpu = (register_t)pc;
1252         tssp->tss_ist4 = (long)np;
1253 }
1254
1255 u_int64_t
1256 hammer_time(u_int64_t modulep, u_int64_t physfree)
1257 {
1258         caddr_t kmdp;
1259         int gsel_tss, x;
1260         struct pcpu *pc;
1261         uint64_t cr3, rsp0;
1262         pml4_entry_t *pml4e;
1263         pdp_entry_t *pdpe;
1264         pd_entry_t *pde;
1265         char *env;
1266         struct user_segment_descriptor *gdt;
1267         struct region_descriptor r_gdt;
1268         size_t kstack0_sz;
1269         int late_console;
1270
1271         TSRAW(&thread0, TS_ENTER, __func__, NULL);
1272
1273         /*
1274          * Calculate kernphys by inspecting page table created by loader.
1275          * The assumptions:
1276          * - kernel is mapped at KERNBASE, backed by contiguous phys memory
1277          *   aligned at 2M, below 4G (the latter is important for AP startup)
1278          * - there is a 2M hole at KERNBASE
1279          * - kernel is mapped with 2M superpages
1280          * - all participating memory, i.e. kernel, modules, metadata,
1281          *   page table is accessible by pre-created 1:1 mapping
1282          *   (right now loader creates 1:1 mapping for lower 4G, and all
1283          *   memory is from there)
1284          * - there is a usable memory block right after the end of the
1285          *   mapped kernel and all modules/metadata, pointed to by
1286          *   physfree, for early allocations
1287          */
1288         cr3 = rcr3();
1289         pml4e = (pml4_entry_t *)(cr3 & ~PAGE_MASK) + pmap_pml4e_index(
1290             (vm_offset_t)hammer_time);
1291         pdpe = (pdp_entry_t *)(*pml4e & ~PAGE_MASK) + pmap_pdpe_index(
1292             (vm_offset_t)hammer_time);
1293         pde = (pd_entry_t *)(*pdpe & ~PAGE_MASK) + pmap_pde_index(
1294             (vm_offset_t)hammer_time);
1295         kernphys = (vm_paddr_t)(*pde & ~PDRMASK) -
1296             (vm_paddr_t)(((vm_offset_t)hammer_time - KERNBASE) & ~PDRMASK);
1297
1298         /* Fix-up for 2M hole */
1299         physfree += kernphys;
1300         kernphys += NBPDR;
1301
1302         kmdp = init_ops.parse_preload_data(modulep);
1303
1304         efi_boot = preload_search_info(kmdp, MODINFO_METADATA |
1305             MODINFOMD_EFI_MAP) != NULL;
1306
1307         if (!efi_boot) {
1308                 /* Tell the bios to warmboot next time */
1309                 atomic_store_short((u_short *)0x472, 0x1234);
1310         }
1311
1312         physfree += ucode_load_bsp(physfree - kernphys + KERNSTART);
1313         physfree = roundup2(physfree, PAGE_SIZE);
1314
1315         identify_cpu1();
1316         identify_hypervisor();
1317         identify_cpu_fixup_bsp();
1318         identify_cpu2();
1319         initializecpucache();
1320
1321         /*
1322          * Check for pti, pcid, and invpcid before ifuncs are
1323          * resolved, to correctly select the implementation for
1324          * pmap_activate_sw_mode().
1325          */
1326         pti = pti_get_default();
1327         TUNABLE_INT_FETCH("vm.pmap.pti", &pti);
1328         TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1329         if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1330                 invpcid_works = (cpu_stdext_feature &
1331                     CPUID_STDEXT_INVPCID) != 0;
1332         } else {
1333                 pmap_pcid_enabled = 0;
1334         }
1335
1336         link_elf_ireloc(kmdp);
1337
1338         /*
1339          * This may be done better later if it gets more high level
1340          * components in it. If so just link td->td_proc here.
1341          */
1342         proc_linkup0(&proc0, &thread0);
1343
1344         /* Init basic tunables, hz etc */
1345         init_param1();
1346
1347         thread0.td_kstack = physfree - kernphys + KERNSTART;
1348         thread0.td_kstack_pages = kstack_pages;
1349         kstack0_sz = thread0.td_kstack_pages * PAGE_SIZE;
1350         bzero((void *)thread0.td_kstack, kstack0_sz);
1351         physfree += kstack0_sz;
1352
1353         /*
1354          * Initialize enough of thread0 for delayed invalidation to
1355          * work very early.  Rely on thread0.td_base_pri
1356          * zero-initialization, it is reset to PVM at proc0_init().
1357          */
1358         pmap_thread_init_invl_gen(&thread0);
1359
1360         pc = &temp_bsp_pcpu;
1361         pcpu_init(pc, 0, sizeof(struct pcpu));
1362         gdt = &temp_bsp_pcpu.pc_gdt[0];
1363
1364         /*
1365          * make gdt memory segments
1366          */
1367         for (x = 0; x < NGDT; x++) {
1368                 if (x != GPROC0_SEL && x != (GPROC0_SEL + 1) &&
1369                     x != GUSERLDT_SEL && x != (GUSERLDT_SEL) + 1)
1370                         ssdtosd(&gdt_segs[x], &gdt[x]);
1371         }
1372         gdt_segs[GPROC0_SEL].ssd_base = (uintptr_t)&pc->pc_common_tss;
1373         ssdtosyssd(&gdt_segs[GPROC0_SEL],
1374             (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
1375
1376         r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
1377         r_gdt.rd_base = (long)gdt;
1378         lgdt(&r_gdt);
1379
1380         wrmsr(MSR_FSBASE, 0);           /* User value */
1381         wrmsr(MSR_GSBASE, (u_int64_t)pc);
1382         wrmsr(MSR_KGSBASE, 0);          /* User value while in the kernel */
1383
1384         dpcpu_init((void *)(physfree - kernphys + KERNSTART), 0);
1385         physfree += DPCPU_SIZE;
1386         amd64_bsp_pcpu_init1(pc);
1387         /* Non-late cninit() and printf() can be moved up to here. */
1388
1389         /*
1390          * Initialize mutexes.
1391          *
1392          * icu_lock: in order to allow an interrupt to occur in a critical
1393          *           section, to set pcpu->ipending (etc...) properly, we
1394          *           must be able to get the icu lock, so it can't be
1395          *           under witness.
1396          */
1397         mutex_init();
1398         mtx_init(&icu_lock, "icu", NULL, MTX_SPIN | MTX_NOWITNESS);
1399         mtx_init(&dt_lock, "descriptor tables", NULL, MTX_DEF);
1400
1401         /* exceptions */
1402         for (x = 0; x < NIDT; x++)
1403                 setidt(x, pti ? &IDTVEC(rsvd_pti) : &IDTVEC(rsvd), SDT_SYSIGT,
1404                     SEL_KPL, 0);
1405         setidt(IDT_DE, pti ? &IDTVEC(div_pti) : &IDTVEC(div), SDT_SYSIGT,
1406             SEL_KPL, 0);
1407         setidt(IDT_DB, &IDTVEC(dbg), SDT_SYSIGT, SEL_KPL, 4);
1408         setidt(IDT_NMI, &IDTVEC(nmi),  SDT_SYSIGT, SEL_KPL, 2);
1409         setidt(IDT_BP, pti ? &IDTVEC(bpt_pti) : &IDTVEC(bpt), SDT_SYSIGT,
1410             SEL_UPL, 0);
1411         setidt(IDT_OF, pti ? &IDTVEC(ofl_pti) : &IDTVEC(ofl), SDT_SYSIGT,
1412             SEL_UPL, 0);
1413         setidt(IDT_BR, pti ? &IDTVEC(bnd_pti) : &IDTVEC(bnd), SDT_SYSIGT,
1414             SEL_KPL, 0);
1415         setidt(IDT_UD, pti ? &IDTVEC(ill_pti) : &IDTVEC(ill), SDT_SYSIGT,
1416             SEL_KPL, 0);
1417         setidt(IDT_NM, pti ? &IDTVEC(dna_pti) : &IDTVEC(dna), SDT_SYSIGT,
1418             SEL_KPL, 0);
1419         setidt(IDT_DF, &IDTVEC(dblfault), SDT_SYSIGT, SEL_KPL, 1);
1420         setidt(IDT_FPUGP, pti ? &IDTVEC(fpusegm_pti) : &IDTVEC(fpusegm),
1421             SDT_SYSIGT, SEL_KPL, 0);
1422         setidt(IDT_TS, pti ? &IDTVEC(tss_pti) : &IDTVEC(tss), SDT_SYSIGT,
1423             SEL_KPL, 0);
1424         setidt(IDT_NP, pti ? &IDTVEC(missing_pti) : &IDTVEC(missing),
1425             SDT_SYSIGT, SEL_KPL, 0);
1426         setidt(IDT_SS, pti ? &IDTVEC(stk_pti) : &IDTVEC(stk), SDT_SYSIGT,
1427             SEL_KPL, 0);
1428         setidt(IDT_GP, pti ? &IDTVEC(prot_pti) : &IDTVEC(prot), SDT_SYSIGT,
1429             SEL_KPL, 0);
1430         setidt(IDT_PF, pti ? &IDTVEC(page_pti) : &IDTVEC(page), SDT_SYSIGT,
1431             SEL_KPL, 0);
1432         setidt(IDT_MF, pti ? &IDTVEC(fpu_pti) : &IDTVEC(fpu), SDT_SYSIGT,
1433             SEL_KPL, 0);
1434         setidt(IDT_AC, pti ? &IDTVEC(align_pti) : &IDTVEC(align), SDT_SYSIGT,
1435             SEL_KPL, 0);
1436         setidt(IDT_MC, &IDTVEC(mchk), SDT_SYSIGT, SEL_KPL, 3);
1437         setidt(IDT_XF, pti ? &IDTVEC(xmm_pti) : &IDTVEC(xmm), SDT_SYSIGT,
1438             SEL_KPL, 0);
1439 #ifdef KDTRACE_HOOKS
1440         setidt(IDT_DTRACE_RET, pti ? &IDTVEC(dtrace_ret_pti) :
1441             &IDTVEC(dtrace_ret), SDT_SYSIGT, SEL_UPL, 0);
1442 #endif
1443 #ifdef XENHVM
1444         setidt(IDT_EVTCHN, pti ? &IDTVEC(xen_intr_upcall_pti) :
1445             &IDTVEC(xen_intr_upcall), SDT_SYSIGT, SEL_KPL, 0);
1446 #endif
1447         r_idt.rd_limit = sizeof(idt0) - 1;
1448         r_idt.rd_base = (long) idt;
1449         lidt(&r_idt);
1450
1451         /*
1452          * Initialize the clock before the console so that console
1453          * initialization can use DELAY().
1454          */
1455         clock_init();
1456
1457         /*
1458          * Use vt(4) by default for UEFI boot (during the sc(4)/vt(4)
1459          * transition).
1460          * Once bootblocks have updated, we can test directly for
1461          * efi_systbl != NULL here...
1462          */
1463         if (efi_boot)
1464                 vty_set_preferred(VTY_VT);
1465
1466         TUNABLE_INT_FETCH("hw.ibrs_disable", &hw_ibrs_disable);
1467         TUNABLE_INT_FETCH("machdep.mitigations.ibrs.disable", &hw_ibrs_disable);
1468
1469         TUNABLE_INT_FETCH("hw.spec_store_bypass_disable", &hw_ssb_disable);
1470         TUNABLE_INT_FETCH("machdep.mitigations.ssb.disable", &hw_ssb_disable);
1471
1472         TUNABLE_INT_FETCH("machdep.syscall_ret_l1d_flush",
1473             &syscall_ret_l1d_flush_mode);
1474
1475         TUNABLE_INT_FETCH("hw.mds_disable", &hw_mds_disable);
1476         TUNABLE_INT_FETCH("machdep.mitigations.mds.disable", &hw_mds_disable);
1477
1478         TUNABLE_INT_FETCH("machdep.mitigations.taa.enable", &x86_taa_enable);
1479
1480         TUNABLE_INT_FETCH("machdep.mitigations.rndgs.enable",
1481             &x86_rngds_mitg_enable);
1482
1483         finishidentcpu();       /* Final stage of CPU initialization */
1484         initializecpu();        /* Initialize CPU registers */
1485
1486         amd64_bsp_ist_init(pc);
1487
1488         /* Set the IO permission bitmap (empty due to tss seg limit) */
1489         pc->pc_common_tss.tss_iobase = sizeof(struct amd64tss) +
1490             IOPERM_BITMAP_SIZE;
1491
1492         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1493         ltr(gsel_tss);
1494
1495         amd64_conf_fast_syscall();
1496
1497         /*
1498          * We initialize the PCB pointer early so that exception
1499          * handlers will work.  Also set up td_critnest to short-cut
1500          * the page fault handler.
1501          */
1502         cpu_max_ext_state_size = sizeof(struct savefpu);
1503         set_top_of_stack_td(&thread0);
1504         thread0.td_pcb = get_pcb_td(&thread0);
1505         thread0.td_critnest = 1;
1506
1507         /*
1508          * The console and kdb should be initialized even earlier than here,
1509          * but some console drivers don't work until after getmemsize().
1510          * Default to late console initialization to support these drivers.
1511          * This loses mainly printf()s in getmemsize() and early debugging.
1512          */
1513         late_console = 1;
1514         TUNABLE_INT_FETCH("debug.late_console", &late_console);
1515         if (!late_console) {
1516                 cninit();
1517                 amd64_kdb_init();
1518         }
1519
1520         getmemsize(kmdp, physfree);
1521         init_param2(physmem);
1522
1523         /* now running on new page tables, configured,and u/iom is accessible */
1524
1525 #ifdef DEV_PCI
1526         /* This call might adjust phys_avail[]. */
1527         pci_early_quirks();
1528 #endif
1529
1530         if (late_console)
1531                 cninit();
1532
1533         /*
1534          * Dump the boot metadata. We have to wait for cninit() since console
1535          * output is required. If it's grossly incorrect the kernel will never
1536          * make it this far.
1537          */
1538         if (getenv_is_true("debug.dump_modinfo_at_boot"))
1539                 preload_dump();
1540
1541 #ifdef DEV_ISA
1542 #ifdef DEV_ATPIC
1543         elcr_probe();
1544         atpic_startup();
1545 #else
1546         /* Reset and mask the atpics and leave them shut down. */
1547         atpic_reset();
1548
1549         /*
1550          * Point the ICU spurious interrupt vectors at the APIC spurious
1551          * interrupt handler.
1552          */
1553         setidt(IDT_IO_INTS + 7, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
1554         setidt(IDT_IO_INTS + 15, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
1555 #endif
1556 #else
1557 #error "have you forgotten the isa device?"
1558 #endif
1559
1560         if (late_console)
1561                 amd64_kdb_init();
1562
1563         msgbufinit(msgbufp, msgbufsize);
1564         fpuinit();
1565
1566         /* make an initial tss so cpu can get interrupt stack on syscall! */
1567         rsp0 = thread0.td_md.md_stack_base;
1568         /* Ensure the stack is aligned to 16 bytes */
1569         rsp0 &= ~0xFul;
1570         PCPU_PTR(common_tss)->tss_rsp0 = rsp0;
1571         amd64_bsp_pcpu_init2(rsp0);
1572
1573         /* transfer to user mode */
1574
1575         _ucodesel = GSEL(GUCODE_SEL, SEL_UPL);
1576         _udatasel = GSEL(GUDATA_SEL, SEL_UPL);
1577         _ucode32sel = GSEL(GUCODE32_SEL, SEL_UPL);
1578         _ufssel = GSEL(GUFS32_SEL, SEL_UPL);
1579         _ugssel = GSEL(GUGS32_SEL, SEL_UPL);
1580
1581         load_ds(_udatasel);
1582         load_es(_udatasel);
1583         load_fs(_ufssel);
1584
1585         /* setup proc 0's pcb */
1586         thread0.td_pcb->pcb_flags = 0;
1587         thread0.td_frame = &proc0_tf;
1588
1589         env = kern_getenv("kernelname");
1590         if (env != NULL)
1591                 strlcpy(kernelname, env, sizeof(kernelname));
1592
1593         kcsan_cpu_init(0);
1594
1595 #ifdef FDT
1596         x86_init_fdt();
1597 #endif
1598         thread0.td_critnest = 0;
1599
1600         kasan_init();
1601         kmsan_init();
1602
1603         TSEXIT();
1604
1605         /* Location of kernel stack for locore */
1606         return (thread0.td_md.md_stack_base);
1607 }
1608
1609 void
1610 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
1611 {
1612
1613         pcpu->pc_acpi_id = 0xffffffff;
1614 }
1615
1616 static int
1617 smap_sysctl_handler(SYSCTL_HANDLER_ARGS)
1618 {
1619         struct bios_smap *smapbase;
1620         struct bios_smap_xattr smap;
1621         caddr_t kmdp;
1622         uint32_t *smapattr;
1623         int count, error, i;
1624
1625         /* Retrieve the system memory map from the loader. */
1626         kmdp = preload_search_by_type("elf kernel");
1627         if (kmdp == NULL)
1628                 kmdp = preload_search_by_type("elf64 kernel");
1629         smapbase = (struct bios_smap *)preload_search_info(kmdp,
1630             MODINFO_METADATA | MODINFOMD_SMAP);
1631         if (smapbase == NULL)
1632                 return (0);
1633         smapattr = (uint32_t *)preload_search_info(kmdp,
1634             MODINFO_METADATA | MODINFOMD_SMAP_XATTR);
1635         count = *((uint32_t *)smapbase - 1) / sizeof(*smapbase);
1636         error = 0;
1637         for (i = 0; i < count; i++) {
1638                 smap.base = smapbase[i].base;
1639                 smap.length = smapbase[i].length;
1640                 smap.type = smapbase[i].type;
1641                 if (smapattr != NULL)
1642                         smap.xattr = smapattr[i];
1643                 else
1644                         smap.xattr = 0;
1645                 error = SYSCTL_OUT(req, &smap, sizeof(smap));
1646         }
1647         return (error);
1648 }
1649 SYSCTL_PROC(_machdep, OID_AUTO, smap,
1650     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
1651     smap_sysctl_handler, "S,bios_smap_xattr",
1652     "Raw BIOS SMAP data");
1653
1654 static int
1655 efi_map_sysctl_handler(SYSCTL_HANDLER_ARGS)
1656 {
1657         struct efi_map_header *efihdr;
1658         caddr_t kmdp;
1659         uint32_t efisize;
1660
1661         kmdp = preload_search_by_type("elf kernel");
1662         if (kmdp == NULL)
1663                 kmdp = preload_search_by_type("elf64 kernel");
1664         efihdr = (struct efi_map_header *)preload_search_info(kmdp,
1665             MODINFO_METADATA | MODINFOMD_EFI_MAP);
1666         if (efihdr == NULL)
1667                 return (0);
1668         efisize = *((uint32_t *)efihdr - 1);
1669         return (SYSCTL_OUT(req, efihdr, efisize));
1670 }
1671 SYSCTL_PROC(_machdep, OID_AUTO, efi_map,
1672     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
1673     efi_map_sysctl_handler, "S,efi_map_header",
1674     "Raw EFI Memory Map");
1675
1676 void
1677 spinlock_enter(void)
1678 {
1679         struct thread *td;
1680         register_t flags;
1681
1682         td = curthread;
1683         if (td->td_md.md_spinlock_count == 0) {
1684                 flags = intr_disable();
1685                 td->td_md.md_spinlock_count = 1;
1686                 td->td_md.md_saved_flags = flags;
1687                 critical_enter();
1688         } else
1689                 td->td_md.md_spinlock_count++;
1690 }
1691
1692 void
1693 spinlock_exit(void)
1694 {
1695         struct thread *td;
1696         register_t flags;
1697
1698         td = curthread;
1699         flags = td->td_md.md_saved_flags;
1700         td->td_md.md_spinlock_count--;
1701         if (td->td_md.md_spinlock_count == 0) {
1702                 critical_exit();
1703                 intr_restore(flags);
1704         }
1705 }
1706
1707 /*
1708  * Construct a PCB from a trapframe. This is called from kdb_trap() where
1709  * we want to start a backtrace from the function that caused us to enter
1710  * the debugger. We have the context in the trapframe, but base the trace
1711  * on the PCB. The PCB doesn't have to be perfect, as long as it contains
1712  * enough for a backtrace.
1713  */
1714 void
1715 makectx(struct trapframe *tf, struct pcb *pcb)
1716 {
1717
1718         pcb->pcb_r12 = tf->tf_r12;
1719         pcb->pcb_r13 = tf->tf_r13;
1720         pcb->pcb_r14 = tf->tf_r14;
1721         pcb->pcb_r15 = tf->tf_r15;
1722         pcb->pcb_rbp = tf->tf_rbp;
1723         pcb->pcb_rbx = tf->tf_rbx;
1724         pcb->pcb_rip = tf->tf_rip;
1725         pcb->pcb_rsp = tf->tf_rsp;
1726 }
1727
1728 /*
1729  * The pcb_flags is only modified by current thread, or by other threads
1730  * when current thread is stopped.  However, current thread may change it
1731  * from the interrupt context in cpu_switch(), or in the trap handler.
1732  * When we read-modify-write pcb_flags from C sources, compiler may generate
1733  * code that is not atomic regarding the interrupt handler.  If a trap or
1734  * interrupt happens and any flag is modified from the handler, it can be
1735  * clobbered with the cached value later.  Therefore, we implement setting
1736  * and clearing flags with single-instruction functions, which do not race
1737  * with possible modification of the flags from the trap or interrupt context,
1738  * because traps and interrupts are executed only on instruction boundary.
1739  */
1740 void
1741 set_pcb_flags_raw(struct pcb *pcb, const u_int flags)
1742 {
1743
1744         __asm __volatile("orl %1,%0"
1745             : "=m" (pcb->pcb_flags) : "ir" (flags), "m" (pcb->pcb_flags)
1746             : "cc", "memory");
1747
1748 }
1749
1750 /*
1751  * The support for RDFSBASE, WRFSBASE and similar instructions for %gs
1752  * base requires that kernel saves MSR_FSBASE and MSR_{K,}GSBASE into
1753  * pcb if user space modified the bases.  We must save on the context
1754  * switch or if the return to usermode happens through the doreti.
1755  *
1756  * Tracking of both events is performed by the pcb flag PCB_FULL_IRET,
1757  * which have a consequence that the base MSRs must be saved each time
1758  * the PCB_FULL_IRET flag is set.  We disable interrupts to sync with
1759  * context switches.
1760  */
1761 static void
1762 set_pcb_flags_fsgsbase(struct pcb *pcb, const u_int flags)
1763 {
1764         register_t r;
1765
1766         if (curpcb == pcb &&
1767             (flags & PCB_FULL_IRET) != 0 &&
1768             (pcb->pcb_flags & PCB_FULL_IRET) == 0) {
1769                 r = intr_disable();
1770                 if ((pcb->pcb_flags & PCB_FULL_IRET) == 0) {
1771                         if (rfs() == _ufssel)
1772                                 pcb->pcb_fsbase = rdfsbase();
1773                         if (rgs() == _ugssel)
1774                                 pcb->pcb_gsbase = rdmsr(MSR_KGSBASE);
1775                 }
1776                 set_pcb_flags_raw(pcb, flags);
1777                 intr_restore(r);
1778         } else {
1779                 set_pcb_flags_raw(pcb, flags);
1780         }
1781 }
1782
1783 DEFINE_IFUNC(, void, set_pcb_flags, (struct pcb *, const u_int))
1784 {
1785
1786         return ((cpu_stdext_feature & CPUID_STDEXT_FSGSBASE) != 0 ?
1787             set_pcb_flags_fsgsbase : set_pcb_flags_raw);
1788 }
1789
1790 void
1791 clear_pcb_flags(struct pcb *pcb, const u_int flags)
1792 {
1793
1794         __asm __volatile("andl %1,%0"
1795             : "=m" (pcb->pcb_flags) : "ir" (~flags), "m" (pcb->pcb_flags)
1796             : "cc", "memory");
1797 }
1798
1799 #ifdef KDB
1800
1801 /*
1802  * Provide inb() and outb() as functions.  They are normally only available as
1803  * inline functions, thus cannot be called from the debugger.
1804  */
1805
1806 /* silence compiler warnings */
1807 u_char inb_(u_short);
1808 void outb_(u_short, u_char);
1809
1810 u_char
1811 inb_(u_short port)
1812 {
1813         return inb(port);
1814 }
1815
1816 void
1817 outb_(u_short port, u_char data)
1818 {
1819         outb(port, data);
1820 }
1821
1822 #endif /* KDB */
1823
1824 #undef memset
1825 #undef memmove
1826 #undef memcpy
1827
1828 void    *memset_std(void *buf, int c, size_t len);
1829 void    *memset_erms(void *buf, int c, size_t len);
1830 void    *memmove_std(void * _Nonnull dst, const void * _Nonnull src,
1831             size_t len);
1832 void    *memmove_erms(void * _Nonnull dst, const void * _Nonnull src,
1833             size_t len);
1834 void    *memcpy_std(void * _Nonnull dst, const void * _Nonnull src,
1835             size_t len);
1836 void    *memcpy_erms(void * _Nonnull dst, const void * _Nonnull src,
1837             size_t len);
1838
1839 #ifdef KCSAN
1840 /*
1841  * These fail to build as ifuncs when used with KCSAN.
1842  */
1843 void *
1844 memset(void *buf, int c, size_t len)
1845 {
1846
1847         return (memset_std(buf, c, len));
1848 }
1849
1850 void *
1851 memmove(void * _Nonnull dst, const void * _Nonnull src, size_t len)
1852 {
1853
1854         return (memmove_std(dst, src, len));
1855 }
1856
1857 void *
1858 memcpy(void * _Nonnull dst, const void * _Nonnull src, size_t len)
1859 {
1860
1861         return (memcpy_std(dst, src, len));
1862 }
1863 #else
1864 DEFINE_IFUNC(, void *, memset, (void *, int, size_t))
1865 {
1866
1867         return ((cpu_stdext_feature & CPUID_STDEXT_ERMS) != 0 ?
1868             memset_erms : memset_std);
1869 }
1870
1871 DEFINE_IFUNC(, void *, memmove, (void * _Nonnull, const void * _Nonnull,
1872     size_t))
1873 {
1874
1875         return ((cpu_stdext_feature & CPUID_STDEXT_ERMS) != 0 ?
1876             memmove_erms : memmove_std);
1877 }
1878
1879 DEFINE_IFUNC(, void *, memcpy, (void * _Nonnull, const void * _Nonnull,size_t))
1880 {
1881
1882         return ((cpu_stdext_feature & CPUID_STDEXT_ERMS) != 0 ?
1883             memcpy_erms : memcpy_std);
1884 }
1885 #endif
1886
1887 void    pagezero_std(void *addr);
1888 void    pagezero_erms(void *addr);
1889 DEFINE_IFUNC(, void , pagezero, (void *))
1890 {
1891
1892         return ((cpu_stdext_feature & CPUID_STDEXT_ERMS) != 0 ?
1893             pagezero_erms : pagezero_std);
1894 }