Home | History | Annotate | Line # | Download | only in i386
      1 /*	$NetBSD: machdep.c,v 1.854 2026/11/10 03:43:25 thorpej Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1996, 1997, 1998, 2000, 2004, 2006, 2008, 2009, 2017
      5  *     The NetBSD Foundation, Inc.
      6  * All rights reserved.
      7  *
      8  * This code is derived from software contributed to The NetBSD Foundation
      9  * by Charles M. Hannum, by Jason R. Thorpe of the Numerical Aerospace
     10  * Simulation Facility NASA Ames Research Center, by Julio M. Merino Vidal,
     11  * by Andrew Doran, and by Maxime Villard.
     12  *
     13  * Redistribution and use in source and binary forms, with or without
     14  * modification, are permitted provided that the following conditions
     15  * are met:
     16  * 1. Redistributions of source code must retain the above copyright
     17  *    notice, this list of conditions and the following disclaimer.
     18  * 2. Redistributions in binary form must reproduce the above copyright
     19  *    notice, this list of conditions and the following disclaimer in the
     20  *    documentation and/or other materials provided with the distribution.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     24  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     32  * POSSIBILITY OF SUCH DAMAGE.
     33  */
     34 
     35 /*
     36  * Copyright (c) 1982, 1987, 1990 The Regents of the University of California.
     37  * All rights reserved.
     38  *
     39  * This code is derived from software contributed to Berkeley by
     40  * William Jolitz.
     41  *
     42  * Redistribution and use in source and binary forms, with or without
     43  * modification, are permitted provided that the following conditions
     44  * are met:
     45  * 1. Redistributions of source code must retain the above copyright
     46  *    notice, this list of conditions and the following disclaimer.
     47  * 2. Redistributions in binary form must reproduce the above copyright
     48  *    notice, this list of conditions and the following disclaimer in the
     49  *    documentation and/or other materials provided with the distribution.
     50  * 3. Neither the name of the University nor the names of its contributors
     51  *    may be used to endorse or promote products derived from this software
     52  *    without specific prior written permission.
     53  *
     54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     64  * SUCH DAMAGE.
     65  *
     66  *	@(#)machdep.c	7.4 (Berkeley) 6/3/91
     67  */
     68 
     69 #include <sys/cdefs.h>
     70 __KERNEL_RCSID(0, "$NetBSD: machdep.c,v 1.854 2026/11/10 03:43:25 thorpej Exp $");
     71 
     72 #include "opt_beep.h"
     73 #include "opt_compat_freebsd.h"
     74 #include "opt_compat_netbsd.h"
     75 #include "opt_cpureset_delay.h"
     76 #include "opt_ddb.h"
     77 #include "opt_kgdb.h"
     78 #include "opt_mtrr.h"
     79 #include "opt_modular.h"
     80 #include "opt_multiboot.h"
     81 #include "opt_multiprocessor.h"
     82 #include "opt_physmem.h"
     83 #include "opt_realmem.h"
     84 #include "opt_user_ldt.h"
     85 #include "opt_xen.h"
     86 #include "isa.h"
     87 #include "pci.h"
     88 
     89 #include <sys/param.h>
     90 #include <sys/systm.h>
     91 #include <sys/signal.h>
     92 #include <sys/signalvar.h>
     93 #include <sys/kernel.h>
     94 #include <sys/cpu.h>
     95 #include <sys/exec.h>
     96 #include <sys/fcntl.h>
     97 #include <sys/reboot.h>
     98 #include <sys/conf.h>
     99 #include <sys/kauth.h>
    100 #include <sys/msgbuf.h>
    101 #include <sys/mount.h>
    102 #include <sys/syscallargs.h>
    103 #include <sys/core.h>
    104 #include <sys/kcore.h>
    105 #include <sys/ucontext.h>
    106 #include <sys/ras.h>
    107 #include <sys/ksyms.h>
    108 #include <sys/device.h>
    109 #include <sys/timevar.h>
    110 
    111 #ifdef KGDB
    112 #include <sys/kgdb.h>
    113 #endif
    114 
    115 #include <dev/cons.h>
    116 #include <dev/mm.h>
    117 
    118 #include <uvm/uvm.h>
    119 #include <uvm/uvm_page.h>
    120 
    121 #include <sys/sysctl.h>
    122 
    123 #include <x86/efi.h>
    124 
    125 #include <machine/cpu.h>
    126 #include <machine/cpu_rng.h>
    127 #include <machine/cpufunc.h>
    128 #include <machine/cpuvar.h>
    129 #include <machine/gdt.h>
    130 #include <machine/intr.h>
    131 #include <machine/kcore.h>
    132 #include <machine/pio.h>
    133 #include <machine/psl.h>
    134 #include <machine/reg.h>
    135 #include <machine/specialreg.h>
    136 #include <machine/bootinfo.h>
    137 #include <machine/mtrr.h>
    138 #include <machine/pmap_private.h>
    139 #include <x86/x86/tsc.h>
    140 
    141 #include <x86/bootspace.h>
    142 #include <x86/fpu.h>
    143 #include <x86/dbregs.h>
    144 #include <x86/machdep.h>
    145 
    146 #include <machine/multiboot.h>
    147 
    148 #ifdef XEN
    149 #include <xen/evtchn.h>
    150 #include <xen/xen.h>
    151 #include <xen/hypervisor.h>
    152 #endif
    153 
    154 #include <dev/isa/isareg.h>
    155 #include <machine/isa_machdep.h>
    156 #include <dev/ic/i8042reg.h>
    157 
    158 #ifdef DDB
    159 #include <machine/db_machdep.h>
    160 #include <ddb/db_extern.h>
    161 #endif
    162 #include <ddb/db_active.h>
    163 
    164 #include "acpica.h"
    165 #include "bioscall.h"
    166 
    167 #if NBIOSCALL > 0
    168 #include <machine/bioscall.h>
    169 #endif
    170 
    171 #if NACPICA > 0
    172 #include <dev/acpi/acpivar.h>
    173 #define ACPI_MACHDEP_PRIVATE
    174 #include <machine/acpi_machdep.h>
    175 #else
    176 #include <machine/i82489var.h>
    177 #endif
    178 
    179 #include "isa.h"
    180 #include "isadma.h"
    181 #include "ksyms.h"
    182 
    183 #include "cardbus.h"
    184 #if NCARDBUS > 0
    185 /* For rbus_min_start hint. */
    186 #include <sys/bus.h>
    187 #include <dev/cardbus/rbus.h>
    188 #include <machine/rbus_machdep.h>
    189 #endif
    190 
    191 #include "mca.h"
    192 #if NMCA > 0
    193 #include <machine/mca_machdep.h>	/* for mca_busprobe() */
    194 #endif
    195 
    196 #ifdef MULTIPROCESSOR		/* XXX */
    197 #include <machine/mpbiosvar.h>	/* XXX */
    198 #endif				/* XXX */
    199 
    200 /* the following is used externally (sysctl_hw) */
    201 char machine[] = "i386";		/* CPU "architecture" */
    202 char machine_arch[] = "i386";		/* machine == machine_arch */
    203 
    204 #ifdef CPURESET_DELAY
    205 int cpureset_delay = CPURESET_DELAY;
    206 #else
    207 int cpureset_delay = 2000; /* default to 2s */
    208 #endif
    209 
    210 #ifdef MTRR
    211 const struct mtrr_funcs *mtrr_funcs;
    212 #endif
    213 
    214 int cpu_class;
    215 int use_pae;
    216 int i386_fpu_fdivbug;
    217 
    218 int i386_use_fxsave;
    219 int i386_has_sse;
    220 int i386_has_sse2;
    221 
    222 vaddr_t idt_vaddr;
    223 paddr_t idt_paddr;
    224 vaddr_t gdt_vaddr;
    225 paddr_t gdt_paddr;
    226 vaddr_t ldt_vaddr;
    227 paddr_t ldt_paddr;
    228 
    229 vaddr_t pentium_idt_vaddr;
    230 
    231 struct vm_map *phys_map = NULL;
    232 
    233 extern struct bootspace bootspace;
    234 
    235 extern paddr_t lowmem_rsvd;
    236 extern paddr_t avail_start, avail_end;
    237 #ifdef XENPV
    238 extern paddr_t pmap_pa_start, pmap_pa_end;
    239 void hypervisor_callback(void);
    240 void failsafe_callback(void);
    241 #endif
    242 
    243 /*
    244  * Size of memory segments, before any memory is stolen.
    245  */
    246 phys_ram_seg_t mem_clusters[VM_PHYSSEG_MAX];
    247 int mem_cluster_cnt = 0;
    248 
    249 void init_bootspace(void);
    250 void init386(paddr_t);
    251 void initgdt(union descriptor *);
    252 
    253 static void i386_proc0_pcb_ldt_init(void);
    254 
    255 static int cpu_getmcontext_xsave(struct lwp *, mcontext_t *, unsigned *,
    256     const struct xsave_header *, size_t, struct xsave_header *);
    257 
    258 int *esym;
    259 int *eblob;
    260 extern int boothowto;
    261 
    262 #ifndef XENPV
    263 
    264 /* Base memory reported by BIOS. */
    265 #ifndef REALBASEMEM
    266 int biosbasemem = 0;
    267 #else
    268 int biosbasemem = REALBASEMEM;
    269 #endif
    270 
    271 /* Extended memory reported by BIOS. */
    272 #ifndef REALEXTMEM
    273 int biosextmem = 0;
    274 #else
    275 int biosextmem = REALEXTMEM;
    276 #endif
    277 
    278 /* Set if any boot-loader set biosbasemem/biosextmem. */
    279 int biosmem_implicit;
    280 
    281 /*
    282  * Representation of the bootinfo structure constructed by a NetBSD native
    283  * boot loader.  Only be used by native_loader().
    284  */
    285 struct bootinfo_source {
    286 	uint32_t bs_naddrs;
    287 	void *bs_addrs[1]; /* Actually longer. */
    288 };
    289 
    290 /* Only called by locore.S; no need to be in a header file. */
    291 void native_loader(int, int, struct bootinfo_source *, paddr_t, int, int);
    292 
    293 /*
    294  * Called as one of the very first things during system startup (just after
    295  * the boot loader gave control to the kernel image), this routine is in
    296  * charge of retrieving the parameters passed in by the boot loader and
    297  * storing them in the appropriate kernel variables.
    298  *
    299  * WARNING: Because the kernel has not yet relocated itself to KERNBASE,
    300  * special care has to be taken when accessing memory because absolute
    301  * addresses (referring to kernel symbols) do not work.  So:
    302  *
    303  *     1) Avoid jumps to absolute addresses (such as gotos and switches).
    304  *     2) To access global variables use their physical address, which
    305  *        can be obtained using the RELOC macro.
    306  */
    307 void
    308 native_loader(int bl_boothowto, int bl_bootdev,
    309     struct bootinfo_source *bl_bootinfo, paddr_t bl_esym,
    310     int bl_biosextmem, int bl_biosbasemem)
    311 {
    312 #define RELOC(type, x) ((type)((vaddr_t)(x) - KERNBASE))
    313 
    314 	*RELOC(int *, &boothowto) = bl_boothowto;
    315 
    316 	/*
    317 	 * The boot loader provides a physical, non-relocated address
    318 	 * for the symbols table's end.  We need to convert it to a
    319 	 * virtual address.
    320 	 */
    321 	if (bl_esym != 0)
    322 		*RELOC(int **, &esym) = (int *)((vaddr_t)bl_esym + KERNBASE);
    323 	else
    324 		*RELOC(int **, &esym) = 0;
    325 
    326 	/*
    327 	 * Copy bootinfo entries (if any) from the boot loader's
    328 	 * representation to the kernel's bootinfo space.
    329 	 */
    330 	if (bl_bootinfo != NULL) {
    331 		size_t i;
    332 		uint8_t *data;
    333 		struct bootinfo *bidest;
    334 		struct btinfo_modulelist *bi;
    335 
    336 		bidest = RELOC(struct bootinfo *, &bootinfo);
    337 
    338 		data = &bidest->bi_data[0];
    339 
    340 		for (i = 0; i < bl_bootinfo->bs_naddrs; i++) {
    341 			struct btinfo_common *bc;
    342 
    343 			bc = bl_bootinfo->bs_addrs[i];
    344 
    345 			if ((data + bc->len) >
    346 			    (&bidest->bi_data[0] + BOOTINFO_MAXSIZE))
    347 				break;
    348 
    349 			memcpy(data, bc, bc->len);
    350 			/*
    351 			 * If any modules were loaded, record where they
    352 			 * end.  We'll need to skip over them.
    353 			 */
    354 			bi = (struct btinfo_modulelist *)data;
    355 			if (bi->common.type == BTINFO_MODULELIST) {
    356 				*RELOC(int **, &eblob) =
    357 				    (int *)(bi->endpa + KERNBASE);
    358 			}
    359 			data += bc->len;
    360 		}
    361 		bidest->bi_nentries = i;
    362 	}
    363 
    364 	/*
    365 	 * Configure biosbasemem and biosextmem only if they were not
    366 	 * explicitly given during the kernel's build.
    367 	 */
    368 	if (*RELOC(int *, &biosbasemem) == 0) {
    369 		*RELOC(int *, &biosbasemem) = bl_biosbasemem;
    370 		*RELOC(int *, &biosmem_implicit) = 1;
    371 	}
    372 	if (*RELOC(int *, &biosextmem) == 0) {
    373 		*RELOC(int *, &biosextmem) = bl_biosextmem;
    374 		*RELOC(int *, &biosmem_implicit) = 1;
    375 	}
    376 #undef RELOC
    377 }
    378 
    379 #endif /* XENPV */
    380 
    381 /*
    382  * Machine-dependent startup code
    383  */
    384 void
    385 cpu_startup(void)
    386 {
    387 	int x, y;
    388 	vaddr_t minaddr, maxaddr;
    389 	psize_t sz;
    390 
    391 	/*
    392 	 * For console drivers that require uvm and pmap to be initialized,
    393 	 * we'll give them one more chance here...
    394 	 */
    395 	consinit();
    396 
    397 	/*
    398 	 * Initialize error message buffer (et end of core).
    399 	 */
    400 	if (msgbuf_p_cnt == 0)
    401 		panic("msgbuf paddr map has not been set up");
    402 	for (x = 0, sz = 0; x < msgbuf_p_cnt; sz += msgbuf_p_seg[x++].sz)
    403 		continue;
    404 
    405 	msgbuf_vaddr = uvm_km_alloc(kernel_map, sz, 0, UVM_KMF_VAONLY);
    406 	if (msgbuf_vaddr == 0)
    407 		panic("failed to valloc msgbuf_vaddr");
    408 
    409 	for (y = 0, sz = 0; y < msgbuf_p_cnt; y++) {
    410 		for (x = 0; x < btoc(msgbuf_p_seg[y].sz); x++, sz += PAGE_SIZE)
    411 			pmap_kenter_pa((vaddr_t)msgbuf_vaddr + sz,
    412 			    msgbuf_p_seg[y].paddr + x * PAGE_SIZE,
    413 			    VM_PROT_READ|VM_PROT_WRITE, 0);
    414 	}
    415 
    416 	pmap_update(pmap_kernel());
    417 
    418 	initmsgbuf((void *)msgbuf_vaddr, sz);
    419 
    420 #ifdef MULTIBOOT
    421 	multiboot1_print_info();
    422 	multiboot2_print_info();
    423 #endif
    424 
    425 #if NCARDBUS > 0
    426 	/* Tell RBUS how much RAM we have, so it can use heuristics. */
    427 	rbus_min_start_hint(ctob((psize_t)physmem));
    428 #endif
    429 
    430 	minaddr = 0;
    431 
    432 	/*
    433 	 * Allocate a submap for physio
    434 	 */
    435 	phys_map = uvm_km_suballoc(kernel_map, &minaddr, &maxaddr,
    436 	    VM_PHYS_SIZE, 0, false, NULL);
    437 
    438 	/* Say hello. */
    439 	banner();
    440 
    441 	/* Safe for i/o port / memory space allocation to use malloc now. */
    442 #if NISA > 0 || NPCI > 0
    443 	x86_bus_space_mallocok();
    444 #endif
    445 
    446 	gdt_init();
    447 	i386_proc0_pcb_ldt_init();
    448 
    449 	cpu_init_tss(&cpu_info_primary);
    450 #ifndef XENPV
    451 	ltr(cpu_info_primary.ci_tss_sel);
    452 #endif
    453 
    454 	x86_startup();
    455 }
    456 
    457 /*
    458  * Set up proc0's PCB and LDT.
    459  */
    460 static void
    461 i386_proc0_pcb_ldt_init(void)
    462 {
    463 	struct lwp *l = &lwp0;
    464 	struct pcb *pcb = lwp_getpcb(l);
    465 
    466 	pcb->pcb_cr0 = rcr0() & ~CR0_TS;
    467 	pcb->pcb_esp0 = uvm_lwp_getuarea(l) + USPACE - 16;
    468 	pcb->pcb_iopl = IOPL_KPL;
    469 	l->l_md.md_regs = (struct trapframe *)pcb->pcb_esp0 - 1;
    470 	memcpy(&pcb->pcb_fsd, &gdtstore[GUDATA_SEL], sizeof(pcb->pcb_fsd));
    471 	memcpy(&pcb->pcb_gsd, &gdtstore[GUDATA_SEL], sizeof(pcb->pcb_gsd));
    472 	pcb->pcb_dbregs = NULL;
    473 
    474 #ifndef XENPV
    475 	lldt(GSEL(GLDT_SEL, SEL_KPL));
    476 #else
    477 	HYPERVISOR_fpu_taskswitch(1);
    478 	HYPERVISOR_stack_switch(GSEL(GDATA_SEL, SEL_KPL), pcb->pcb_esp0);
    479 #endif
    480 }
    481 
    482 #ifdef XENPV
    483 /* used in assembly */
    484 void i386_switch_context(lwp_t *);
    485 void i386_tls_switch(lwp_t *);
    486 
    487 /*
    488  * Switch context:
    489  * - switch stack pointer for user->kernel transition
    490  */
    491 void
    492 i386_switch_context(lwp_t *l)
    493 {
    494 	struct pcb *pcb;
    495 
    496 	pcb = lwp_getpcb(l);
    497 
    498 	HYPERVISOR_stack_switch(GSEL(GDATA_SEL, SEL_KPL), pcb->pcb_esp0);
    499 
    500 	struct physdev_set_iopl set_iopl;
    501 	set_iopl.iopl = pcb->pcb_iopl;
    502 	HYPERVISOR_physdev_op(PHYSDEVOP_set_iopl, &set_iopl);
    503 }
    504 
    505 void
    506 i386_tls_switch(lwp_t *l)
    507 {
    508 	struct cpu_info *ci = curcpu();
    509 	struct pcb *pcb = lwp_getpcb(l);
    510 
    511 	/*
    512 	 * Raise the IPL to IPL_HIGH. XXX Still needed?
    513 	 */
    514 	(void)splhigh();
    515 
    516 	/* Update TLS segment pointers */
    517 	update_descriptor(&ci->ci_gdt[GUFS_SEL],
    518 	    (union descriptor *)&pcb->pcb_fsd);
    519 	update_descriptor(&ci->ci_gdt[GUGS_SEL],
    520 	    (union descriptor *)&pcb->pcb_gsd);
    521 }
    522 #endif /* XENPV */
    523 
    524 /* XXX */
    525 #define IDTVEC(name)	__CONCAT(X, name)
    526 typedef void (vector)(void);
    527 
    528 #ifndef XENPV
    529 static void	tss_init(struct i386tss *, void *, void *);
    530 
    531 static void
    532 tss_init(struct i386tss *tss, void *stack, void *func)
    533 {
    534 	KASSERT(curcpu()->ci_pmap == pmap_kernel());
    535 
    536 	memset(tss, 0, sizeof *tss);
    537 	tss->tss_esp0 = tss->tss_esp = (int)((char *)stack + USPACE - 16);
    538 	tss->tss_ss0 = GSEL(GDATA_SEL, SEL_KPL);
    539 	tss->__tss_cs = GSEL(GCODE_SEL, SEL_KPL);
    540 	tss->tss_fs = GSEL(GCPU_SEL, SEL_KPL);
    541 	tss->tss_gs = tss->__tss_es = tss->__tss_ds =
    542 	    tss->__tss_ss = GSEL(GDATA_SEL, SEL_KPL);
    543 	/* %cr3 contains the value associated to pmap_kernel */
    544 	tss->tss_cr3 = rcr3();
    545 	tss->tss_esp = (int)((char *)stack + USPACE - 16);
    546 	tss->tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
    547 	tss->__tss_eflags = PSL_MBO | PSL_NT;	/* XXX not needed? */
    548 	tss->__tss_eip = (int)func;
    549 }
    550 
    551 extern vector IDTVEC(tss_trap08);
    552 #if defined(DDB) && defined(MULTIPROCESSOR)
    553 extern vector Xintr_ddbipi, Xintr_x2apic_ddbipi;
    554 extern int ddb_vec;
    555 #endif
    556 
    557 void
    558 cpu_set_tss_gates(struct cpu_info *ci)
    559 {
    560 	struct segment_descriptor sd;
    561 	void *doubleflt_stack;
    562 	idt_descriptor_t *idt;
    563 
    564 	doubleflt_stack = (void *)uvm_km_alloc(kernel_map, USPACE, 0,
    565 	    UVM_KMF_WIRED);
    566 	tss_init(&ci->ci_tss->dblflt_tss, doubleflt_stack, IDTVEC(tss_trap08));
    567 
    568 	setsegment(&sd, &ci->ci_tss->dblflt_tss, sizeof(struct i386tss) - 1,
    569 	    SDT_SYS386TSS, SEL_KPL, 0, 0);
    570 	ci->ci_gdt[GTRAPTSS_SEL].sd = sd;
    571 
    572 	idt = cpu_info_primary.ci_idtvec.iv_idt;
    573 	set_idtgate(&idt[8], NULL, 0, SDT_SYSTASKGT, SEL_KPL,
    574 	    GSEL(GTRAPTSS_SEL, SEL_KPL));
    575 
    576 #if defined(DDB) && defined(MULTIPROCESSOR)
    577 	/*
    578 	 * Set up separate handler for the DDB IPI, so that it doesn't
    579 	 * stomp on a possibly corrupted stack.
    580 	 *
    581 	 * XXX overwriting the gate set in db_machine_init.
    582 	 * Should rearrange the code so that it's set only once.
    583 	 */
    584 	void *ddbipi_stack;
    585 
    586 	ddbipi_stack = (void *)uvm_km_alloc(kernel_map, USPACE, 0,
    587 	    UVM_KMF_WIRED);
    588 	tss_init(&ci->ci_tss->ddbipi_tss, ddbipi_stack,
    589 	    x2apic_mode ? Xintr_x2apic_ddbipi : Xintr_ddbipi);
    590 
    591 	setsegment(&sd, &ci->ci_tss->ddbipi_tss, sizeof(struct i386tss) - 1,
    592 	    SDT_SYS386TSS, SEL_KPL, 0, 0);
    593 	ci->ci_gdt[GIPITSS_SEL].sd = sd;
    594 
    595 	set_idtgate(&idt[ddb_vec], NULL, 0, SDT_SYSTASKGT, SEL_KPL,
    596 	    GSEL(GIPITSS_SEL, SEL_KPL));
    597 #endif
    598 }
    599 #endif /* XENPV */
    600 
    601 /*
    602  * Set up TSS and I/O bitmap.
    603  */
    604 void
    605 cpu_init_tss(struct cpu_info *ci)
    606 {
    607 	struct cpu_tss *cputss;
    608 
    609 	cputss = (struct cpu_tss *)uvm_km_alloc(kernel_map,
    610 	    sizeof(struct cpu_tss), 0, UVM_KMF_WIRED|UVM_KMF_ZERO);
    611 
    612 	cputss->tss.tss_iobase = IOMAP_INVALOFF << 16;
    613 #ifndef XENPV
    614 	cputss->tss.tss_ss0 = GSEL(GDATA_SEL, SEL_KPL);
    615 	cputss->tss.tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
    616 	cputss->tss.tss_cr3 = rcr3();
    617 #endif
    618 
    619 	ci->ci_tss = cputss;
    620 #ifndef XENPV
    621 	ci->ci_tss_sel = tss_alloc(&cputss->tss);
    622 #endif
    623 }
    624 
    625 void *
    626 getframe(struct lwp *l, int sig, int *onstack)
    627 {
    628 	struct proc *p = l->l_proc;
    629 	struct trapframe *tf = l->l_md.md_regs;
    630 
    631 	/* Do we need to jump onto the signal stack? */
    632 	*onstack = (l->l_sigstk.ss_flags & (SS_DISABLE | SS_ONSTACK)) == 0
    633 	    && (SIGACTION(p, sig).sa_flags & SA_ONSTACK) != 0;
    634 	if (*onstack)
    635 		return (char *)l->l_sigstk.ss_sp + l->l_sigstk.ss_size;
    636 	return (void *)tf->tf_esp;
    637 }
    638 
    639 /*
    640  * Build context to run handler in.  We invoke the handler
    641  * directly, only returning via the trampoline.  Note the
    642  * trampoline version numbers are coordinated with machine-
    643  * dependent code in libc.
    644  */
    645 void
    646 buildcontext(struct lwp *l, int sel, void *catcher, void *fp)
    647 {
    648 	struct trapframe *tf = l->l_md.md_regs;
    649 
    650 	tf->tf_gs = GSEL(GUGS_SEL, SEL_UPL);
    651 	tf->tf_fs = GSEL(GUFS_SEL, SEL_UPL);
    652 	tf->tf_es = GSEL(GUDATA_SEL, SEL_UPL);
    653 	tf->tf_ds = GSEL(GUDATA_SEL, SEL_UPL);
    654 	tf->tf_eip = (int)catcher;
    655 	tf->tf_cs = GSEL(sel, SEL_UPL);
    656 	tf->tf_eflags &= ~PSL_CLEARSIG;
    657 	tf->tf_esp = (int)fp;
    658 	tf->tf_ss = GSEL(GUDATA_SEL, SEL_UPL);
    659 
    660 	/* Ensure FP state is reset. */
    661 	fpu_sigreset(l);
    662 }
    663 
    664 void
    665 sendsig_siginfo(const ksiginfo_t *ksi, const sigset_t *mask)
    666 {
    667 	struct lwp *l = curlwp;
    668 	struct proc *p = l->l_proc;
    669 	struct pmap *pmap = vm_map_pmap(&p->p_vmspace->vm_map);
    670 	int sel = pmap->pm_hiexec > I386_MAX_EXE_ADDR ?
    671 	    GUCODEBIG_SEL : GUCODE_SEL;
    672 	struct sigacts *ps = p->p_sigacts;
    673 	int onstack, error;
    674 	int sig = ksi->ksi_signo;
    675 	struct sigframe_siginfo *fp, frame;
    676 	sig_t catcher = SIGACTION(p, sig).sa_handler;
    677 	struct trapframe *tf = l->l_md.md_regs;
    678 	const struct xsave_header *xsavebuf = NULL;
    679 	size_t xsavelen = 0;
    680 	struct xsave_header *user_xsave = NULL;
    681 	char *sp;
    682 
    683 	KASSERT(mutex_owned(p->p_lock));
    684 
    685 	/* Do we need to jump onto the signal stack? */
    686 	onstack =
    687 	    (l->l_sigstk.ss_flags & (SS_DISABLE | SS_ONSTACK)) == 0 &&
    688 	    (SIGACTION(p, sig).sa_flags & SA_ONSTACK) != 0;
    689 
    690 	/* Allocate space for the signal handler context. */
    691 	if (onstack) {
    692 		KASSERT(l->l_sigstk.ss_size >= MINSIGSTKSZ);
    693 		sp = ((char *)l->l_sigstk.ss_sp + l->l_sigstk.ss_size);
    694 	} else {
    695 		sp = (char *)tf->tf_esp;
    696 	}
    697 
    698 	/*
    699 	 * The maximum amount of space we might use, including padding
    700 	 * for alignment, had better fit in MINSIGSTKSZ.
    701 	 *
    702 	 * If this changes because you have increased XSAVE_MAX_BYTES,
    703 	 * you need to work out the ABI change for MINSIGSTKSZ.
    704 	 */
    705 	__CTASSERT(STACK_ALIGNBYTES + sizeof(struct sigframe_siginfo) +
    706 	    (XSAVE_ALIGN - 1) + XSAVE_MAX_BYTES <= MINSIGSTKSZ);
    707 
    708 	/*
    709 	 * Find whether we need to allocate a separate XSAVE area,
    710 	 * because the user program has used extended CPU state beyond
    711 	 * the x87/SSE registers, or whether we can get by with just an
    712 	 * FXSAVE area.
    713 	 */
    714 	if (process_xsave_needed_p(l)) {
    715 		process_read_xsave(l, &xsavebuf, &xsavelen);
    716 		KASSERT(xsavebuf != NULL);
    717 		KASSERT(xsavelen <= XSAVE_MAX_BYTES);
    718 
    719 		KASSERT(!onstack || sp >= (char *)l->l_sigstk.ss_sp);
    720 		KASSERT(!onstack ||
    721 		    sp - (char *)l->l_sigstk.ss_sp >= xsavelen);
    722 		sp -= xsavelen;
    723 
    724 		KASSERT(!onstack || sp >= (char *)l->l_sigstk.ss_sp);
    725 		KASSERT(!onstack ||
    726 		    sp - (char *)l->l_sigstk.ss_sp >= XSAVE_ALIGN - 1);
    727 		sp = (char *)((uintptr_t)sp & ~(XSAVE_ALIGN - 1));
    728 
    729 		KASSERT(!onstack || sp >= (char *)l->l_sigstk.ss_sp);
    730 		KASSERT(((uintptr_t)sp & (XSAVE_ALIGN - 1)) == 0);
    731 		user_xsave = (void *)sp;
    732 	}
    733 
    734 	/*
    735 	 * Reserve space for an aligned struct sigframe_siginfo.
    736 	 */
    737 	KASSERT(!onstack || sp >= (char *)l->l_sigstk.ss_sp);
    738 	KASSERT(!onstack || (size_t)(sp - (char *)l->l_sigstk.ss_sp) >=
    739 	    STACK_ALIGNBYTES + sizeof(struct sigframe_siginfo));
    740 	fp = (struct sigframe_siginfo *)sp;
    741 	fp--;
    742 	fp = (struct sigframe_siginfo *)((uintptr_t)fp & ~STACK_ALIGNBYTES);
    743 
    744 	memset(&frame, 0, sizeof(frame));
    745 	frame.sf_ra = (int)ps->sa_sigdesc[sig].sd_tramp;
    746 	frame.sf_signum = sig;
    747 	frame.sf_sip = &fp->sf_si;
    748 	frame.sf_ucp = &fp->sf_uc;
    749 	frame.sf_si._info = ksi->ksi_info;
    750 	frame.sf_uc.uc_flags = _UC_SIGMASK|_UC_VM;
    751 	frame.sf_uc.uc_sigmask = *mask;
    752 	frame.sf_uc.uc_link = l->l_ctxlink;
    753 	frame.sf_uc.uc_flags |= (l->l_sigstk.ss_flags & SS_ONSTACK)
    754 	    ? _UC_SETSTACK : _UC_CLRSTACK;
    755 
    756 	sendsig_reset(l, sig);
    757 
    758 	mutex_exit(p->p_lock);
    759 	cpu_getmcontext(l, &frame.sf_uc.uc_mcontext, &frame.sf_uc.uc_flags);
    760 
    761 	/*
    762 	 * If we have to use XSAVE, copy out that area separately --
    763 	 * and be ready to bail if it failed.
    764 	 */
    765 	if (xsavebuf) {
    766 		error = cpu_getmcontext_xsave(l, &frame.sf_uc.uc_mcontext,
    767 		    &frame.sf_uc.uc_flags, xsavebuf, xsavelen, user_xsave);
    768 		if (error != 0)
    769 			goto relock;
    770 	}
    771 
    772 	error = copyout(&frame, fp, sizeof(frame));
    773 relock:
    774 	mutex_enter(p->p_lock);
    775 
    776 	if (error != 0) {
    777 		/*
    778 		 * Process has trashed its stack; give it an illegal
    779 		 * instruction to halt it in its tracks.
    780 		 */
    781 		sigexit(l, SIGILL);
    782 		/* NOTREACHED */
    783 	}
    784 
    785 	buildcontext(l, sel, catcher, fp);
    786 
    787 	/* Remember that we're now on the signal stack. */
    788 	if (onstack)
    789 		l->l_sigstk.ss_flags |= SS_ONSTACK;
    790 }
    791 
    792 static void
    793 maybe_dump(int howto)
    794 {
    795 	int s;
    796 
    797 	/* Disable interrupts. */
    798 	s = splhigh();
    799 
    800 	/* Do a dump if requested. */
    801 	if ((howto & (RB_DUMP | RB_HALT)) == RB_DUMP)
    802 		dumpsys();
    803 
    804 	splx(s);
    805 }
    806 
    807 void
    808 cpu_reboot(int howto, char *bootstr)
    809 {
    810 	static bool syncdone = false;
    811 	int s = IPL_NONE;
    812 
    813 	if (cold) {
    814 		howto |= RB_HALT;
    815 		goto haltsys;
    816 	}
    817 
    818 	boothowto = howto;
    819 
    820 	/* XXX used to dump after vfs_shutdown() and before
    821 	 * detaching devices / shutdown hooks / pmf_system_shutdown().
    822 	 */
    823 	maybe_dump(howto);
    824 
    825 	/*
    826 	 * If we've panic'd, don't make the situation potentially
    827 	 * worse by syncing or unmounting the file systems.
    828 	 */
    829 	if ((howto & RB_NOSYNC) == 0 && panicstr == NULL) {
    830 		if (!syncdone) {
    831 			syncdone = true;
    832 			/* XXX used to force unmount as well, here */
    833 			vfs_sync_all(curlwp);
    834 		}
    835 
    836 		while (vfs_unmountall1(curlwp, false, false) ||
    837 		       config_detach_all(boothowto) ||
    838 		       vfs_unmount_forceone(curlwp))
    839 			;	/* do nothing */
    840 	} else {
    841 		if (!db_active)
    842 			suspendsched();
    843 	}
    844 
    845 	pmf_system_shutdown(boothowto);
    846 
    847 	s = splhigh();
    848 
    849 	/* amd64 maybe_dump() */
    850 
    851 haltsys:
    852 	doshutdownhooks();
    853 
    854 	if ((howto & RB_POWERDOWN) == RB_POWERDOWN) {
    855 #if NACPICA > 0
    856 		if (s != IPL_NONE)
    857 			splx(s);
    858 
    859 		acpi_enter_sleep_state(ACPI_STATE_S5);
    860 #else
    861 		__USE(s);
    862 #endif
    863 #ifdef XEN
    864 		if (vm_guest == VM_GUEST_XENPV ||
    865 		    vm_guest == VM_GUEST_XENPVH ||
    866 		    vm_guest == VM_GUEST_XENPVHVM)
    867 			HYPERVISOR_shutdown();
    868 #endif /* XEN */
    869 	}
    870 
    871 #ifdef MULTIPROCESSOR
    872 	cpu_broadcast_halt();
    873 #endif /* MULTIPROCESSOR */
    874 
    875 	if (howto & RB_HALT) {
    876 #if NACPICA > 0
    877 		acpi_disable();
    878 #endif
    879 
    880 		printf("\n");
    881 		printf("The operating system has halted.\n");
    882 		printf("Please press any key to reboot.\n\n");
    883 
    884 #ifdef BEEP_ONHALT
    885 		{
    886 			int c;
    887 			for (c = BEEP_ONHALT_COUNT; c > 0; c--) {
    888 				sysbeep(BEEP_ONHALT_PITCH,
    889 					BEEP_ONHALT_PERIOD * hz / 1000);
    890 				delay(BEEP_ONHALT_PERIOD * 1000);
    891 				sysbeep(0, BEEP_ONHALT_PERIOD * hz / 1000);
    892 				delay(BEEP_ONHALT_PERIOD * 1000);
    893 			}
    894 		}
    895 #endif
    896 
    897 		cnpollc(true);	/* for proper keyboard command handling */
    898 		if (cngetc() == 0) {
    899 			/* no console attached, so just hlt */
    900 			printf("No keyboard - cannot reboot after all.\n");
    901 			for(;;) {
    902 				x86_hlt();
    903 			}
    904 		}
    905 		cnpollc(false);
    906 	}
    907 
    908 	printf("rebooting...\n");
    909 	if (cpureset_delay > 0)
    910 		delay(cpureset_delay * 1000);
    911 	cpu_reset();
    912 	for(;;) ;
    913 	/*NOTREACHED*/
    914 }
    915 
    916 /*
    917  * Clear registers on exec
    918  */
    919 void
    920 setregs(struct lwp *l, struct exec_package *pack, vaddr_t stack)
    921 {
    922 	struct pmap *pmap = vm_map_pmap(&l->l_proc->p_vmspace->vm_map);
    923 	struct pcb *pcb = lwp_getpcb(l);
    924 	struct trapframe *tf;
    925 
    926 #ifdef USER_LDT
    927 	pmap_ldt_cleanup(l);
    928 #endif
    929 
    930 	fpu_clear(l, pack->ep_osversion >= 699002600
    931 	    ? __INITIAL_NPXCW__ : __NetBSD_COMPAT_NPXCW__);
    932 
    933 	memcpy(&pcb->pcb_fsd, &gdtstore[GUDATA_SEL], sizeof(pcb->pcb_fsd));
    934 	memcpy(&pcb->pcb_gsd, &gdtstore[GUDATA_SEL], sizeof(pcb->pcb_gsd));
    935 
    936 	x86_dbregs_clear(l);
    937 
    938 	tf = l->l_md.md_regs;
    939 	memset(tf, 0, sizeof(*tf));
    940 
    941 	tf->tf_trapno = T_ASTFLT;
    942 	tf->tf_gs = GSEL(GUGS_SEL, SEL_UPL);
    943 	tf->tf_fs = GSEL(GUFS_SEL, SEL_UPL);
    944 	tf->tf_es = LSEL(LUDATA_SEL, SEL_UPL);
    945 	tf->tf_ds = LSEL(LUDATA_SEL, SEL_UPL);
    946 	tf->tf_edi = 0;
    947 	tf->tf_esi = 0;
    948 	tf->tf_ebp = 0;
    949 	tf->tf_ebx = l->l_proc->p_psstrp;
    950 	tf->tf_edx = 0;
    951 	tf->tf_ecx = 0;
    952 	tf->tf_eax = 0;
    953 	tf->tf_eip = pack->ep_entry;
    954 	tf->tf_cs = pmap->pm_hiexec > I386_MAX_EXE_ADDR ?
    955 	    LSEL(LUCODEBIG_SEL, SEL_UPL) : LSEL(LUCODE_SEL, SEL_UPL);
    956 	tf->tf_eflags = PSL_USERSET;
    957 	tf->tf_esp = stack;
    958 	tf->tf_ss = LSEL(LUDATA_SEL, SEL_UPL);
    959 }
    960 
    961 /*
    962  * Initialize segments and descriptor tables
    963  */
    964 
    965 union descriptor *gdtstore, *ldtstore;
    966 union descriptor *pentium_idt;
    967 extern vaddr_t lwp0uarea;
    968 
    969 void
    970 setgate(struct gate_descriptor *gd, void *func, int args, int type, int dpl,
    971     int sel)
    972 {
    973 
    974 	gd->gd_looffset = (int)func;
    975 	gd->gd_selector = sel;
    976 	gd->gd_stkcpy = args;
    977 	gd->gd_xx = 0;
    978 	gd->gd_type = type;
    979 	gd->gd_dpl = dpl;
    980 	gd->gd_p = 1;
    981 	gd->gd_hioffset = (int)func >> 16;
    982 }
    983 
    984 void
    985 unsetgate(struct gate_descriptor *gd)
    986 {
    987 
    988 	gd->gd_p = 0;
    989 	gd->gd_hioffset = 0;
    990 	gd->gd_looffset = 0;
    991 	gd->gd_selector = 0;
    992 	gd->gd_xx = 0;
    993 	gd->gd_stkcpy = 0;
    994 	gd->gd_type = 0;
    995 	gd->gd_dpl = 0;
    996 }
    997 
    998 void
    999 setregion(struct region_descriptor *rd, void *base, size_t limit)
   1000 {
   1001 
   1002 	rd->rd_limit = (int)limit;
   1003 	rd->rd_base = (int)base;
   1004 }
   1005 
   1006 void
   1007 setsegment(struct segment_descriptor *sd, const void *base, size_t limit,
   1008     int type, int dpl, int def32, int gran)
   1009 {
   1010 
   1011 	sd->sd_lolimit = (int)limit;
   1012 	sd->sd_lobase = (int)base;
   1013 	sd->sd_type = type;
   1014 	sd->sd_dpl = dpl;
   1015 	sd->sd_p = 1;
   1016 	sd->sd_hilimit = (int)limit >> 16;
   1017 	sd->sd_xx = 0;
   1018 	sd->sd_def32 = def32;
   1019 	sd->sd_gran = gran;
   1020 	sd->sd_hibase = (int)base >> 24;
   1021 }
   1022 
   1023 /* XXX */
   1024 extern vector IDTVEC(syscall);
   1025 extern vector *IDTVEC(exceptions)[];
   1026 #ifdef XENPV
   1027 extern union descriptor tmpgdt[];
   1028 #endif
   1029 
   1030 void
   1031 cpu_init_idt(struct cpu_info *ci)
   1032 {
   1033 	struct region_descriptor region;
   1034 	struct idt_vec *iv;
   1035 	idt_descriptor_t *idt;
   1036 
   1037 	iv = &ci->ci_idtvec;
   1038 	idt = iv->iv_idt_pentium;
   1039 	setregion(&region, idt, NIDT * sizeof(idt[0]) - 1);
   1040 	lidt(&region);
   1041 }
   1042 
   1043 /*
   1044  * initgdt(tgdt)
   1045  *
   1046  *	Initialize a temporary Global Descriptor Table (GDT) using
   1047  *	storage space at tgdt.
   1048  *
   1049  *	1. Set up segment descriptors for our purposes, including a
   1050  *	   CPU-local segment descriptor pointing at &cpu_info_primary.
   1051  *
   1052  *	2. Load the address into the Global Descriptor Table Register.
   1053  *
   1054  *	3. Set up segment selectors for all the segment registers using
   1055  *	   it so that %fs-relative addressing works for the CPU-local
   1056  *	   data.
   1057  *
   1058  *	After this put, CPUVAR(...), curcpu(), and curlwp will work.
   1059  *
   1060  *	Eventually the kernel will switch to a second temporary GDT
   1061  *	allocated with pmap_bootstrap_valloc in pmap_bootstrap, and
   1062  *	then to permanent GDT allocated with uvm_km(9) in gdt_init.
   1063  *	But the first temporary GDT is needed now to get us going with
   1064  *	early access to curcpu() and curlwp before we enter kernel
   1065  *	main.
   1066  *
   1067  *	XXX The purpose of each of the segment descriptors should be
   1068  *	written down somewhere in a single place that can be cross-
   1069  *	referenced.
   1070  *
   1071  *	References:
   1072  *
   1073  *	- Intel 64 and IA-32 Architectures Software Developer's Manual,
   1074  *	  Volume 3: System Programming Guide, Order Number 325384,
   1075  *	  April 2022, Sec. 3.5.1 `Segment Descriptor Tables',
   1076  *	  pp. 3-14 through 3-16.
   1077  */
   1078 void
   1079 initgdt(union descriptor *tgdt)
   1080 {
   1081 	KASSERT(tgdt != NULL);
   1082 
   1083 	gdtstore = tgdt;
   1084 #ifdef XENPV
   1085 	u_long	frames[16];
   1086 #else
   1087 	struct region_descriptor region;
   1088 	memset(gdtstore, 0, NGDT * sizeof(*gdtstore));
   1089 #endif
   1090 
   1091 	/* make gdt gates and memory segments */
   1092 	setsegment(&gdtstore[GCODE_SEL].sd, 0, 0xfffff,
   1093 	    SDT_MEMERA, SEL_KPL, 1, 1);
   1094 	setsegment(&gdtstore[GDATA_SEL].sd, 0, 0xfffff,
   1095 	    SDT_MEMRWA, SEL_KPL, 1, 1);
   1096 	setsegment(&gdtstore[GUCODE_SEL].sd, 0, x86_btop(I386_MAX_EXE_ADDR) - 1,
   1097 	    SDT_MEMERA, SEL_UPL, 1, 1);
   1098 	setsegment(&gdtstore[GUCODEBIG_SEL].sd, 0, 0xfffff,
   1099 	    SDT_MEMERA, SEL_UPL, 1, 1);
   1100 	setsegment(&gdtstore[GUDATA_SEL].sd, 0, 0xfffff,
   1101 	    SDT_MEMRWA, SEL_UPL, 1, 1);
   1102 #if NBIOSCALL > 0 && !defined(XENPV)
   1103 	/* bios trampoline GDT entries */
   1104 	setsegment(&gdtstore[GBIOSCODE_SEL].sd, 0, 0xfffff,
   1105 	    SDT_MEMERA, SEL_KPL, 0, 0);
   1106 	setsegment(&gdtstore[GBIOSDATA_SEL].sd, 0, 0xfffff,
   1107 	    SDT_MEMRWA, SEL_KPL, 0, 0);
   1108 #endif
   1109 	setsegment(&gdtstore[GCPU_SEL].sd, &cpu_info_primary,
   1110 	    sizeof(struct cpu_info) - 1, SDT_MEMRWA, SEL_KPL, 1, 0);
   1111 
   1112 #ifndef XENPV
   1113 	setregion(&region, gdtstore, NGDT * sizeof(gdtstore[0]) - 1);
   1114 	lgdt(&region);
   1115 #else /* !XENPV */
   1116 	/*
   1117 	 * We jumpstart the bootstrap process a bit so we can update
   1118 	 * page permissions. This is done redundantly later from
   1119 	 * x86_xpmap.c:xen_locore() - harmless.
   1120 	 */
   1121 	xpmap_phys_to_machine_mapping =
   1122 	    (unsigned long *)xen_start_info.mfn_list;
   1123 
   1124 	frames[0] = xpmap_ptom((uint32_t)gdtstore - KERNBASE) >> PAGE_SHIFT;
   1125 	{	/*
   1126 		 * Enter the gdt page RO into the kernel map. We can't
   1127 		 * use pmap_kenter_pa() here, because %fs is not
   1128 		 * usable until the gdt is loaded, and %fs is used as
   1129 		 * the base pointer for curcpu() and curlwp(), both of
   1130 		 * which are in the callpath of pmap_kenter_pa().
   1131 		 * So we mash up our own - this is MD code anyway.
   1132 		 */
   1133 		extern pt_entry_t xpmap_pg_nx;
   1134 		pt_entry_t pte;
   1135 
   1136 		pte = pmap_pa2pte((vaddr_t)gdtstore - KERNBASE);
   1137 		pte |= xpmap_pg_nx | PTE_P;
   1138 
   1139 		if (HYPERVISOR_update_va_mapping((vaddr_t)gdtstore, pte,
   1140 		    UVMF_INVLPG) < 0) {
   1141 			panic("gdt page RO update failed.\n");
   1142 		}
   1143 	}
   1144 
   1145 	if (HYPERVISOR_set_gdt(frames, NGDT /* XXX is it right ? */))
   1146 		panic("HYPERVISOR_set_gdt failed!\n");
   1147 
   1148 	lgdt_finish();
   1149 #endif /* !XENPV */
   1150 }
   1151 
   1152 #if !defined(XENPV)  && NBIOSCALL > 0
   1153 static void
   1154 init386_pte0(void)
   1155 {
   1156 	paddr_t paddr;
   1157 	vaddr_t vaddr;
   1158 
   1159 	paddr = 4 * PAGE_SIZE;
   1160 	vaddr = (vaddr_t)vtopte(0);
   1161 	pmap_kenter_pa(vaddr, paddr, VM_PROT_ALL, 0);
   1162 	pmap_update(pmap_kernel());
   1163 	/* make sure it is clean before using */
   1164 	memset((void *)vaddr, 0, PAGE_SIZE);
   1165 }
   1166 #endif /* !XENPV && NBIOSCALL > 0 */
   1167 
   1168 #ifndef XENPV
   1169 static void
   1170 init386_ksyms(void)
   1171 {
   1172 #if NKSYMS || defined(DDB) || defined(MODULAR)
   1173 	extern int end;
   1174 	struct btinfo_symtab *symtab;
   1175 
   1176 #ifdef DDB
   1177 	db_machine_init();
   1178 #endif
   1179 
   1180 #if defined(MULTIBOOT)
   1181 	if (multiboot1_ksyms_addsyms_elf())
   1182 		return;
   1183 
   1184 	if (multiboot2_ksyms_addsyms_elf())
   1185 		return;
   1186 #endif
   1187 
   1188 #ifdef XEN
   1189 	if (pvh_boot && vm_guest != VM_GUEST_XENPVH) {
   1190 		ksyms_addsyms_elf(0, ((int *)&end) + 1, esym);
   1191 		return;
   1192 	}
   1193 #endif
   1194 
   1195 	if ((symtab = lookup_bootinfo(BTINFO_SYMTAB)) == NULL) {
   1196 		ksyms_addsyms_elf(*(int *)&end, ((int *)&end) + 1, esym);
   1197 		return;
   1198 	}
   1199 
   1200 	symtab->ssym += KERNBASE;
   1201 	symtab->esym += KERNBASE;
   1202 	ksyms_addsyms_elf(symtab->nsym, (int *)symtab->ssym, (int *)symtab->esym);
   1203 #endif
   1204 }
   1205 #endif /* XENPV */
   1206 
   1207 void
   1208 init_bootspace(void)
   1209 {
   1210 	extern char __rodata_start;
   1211 	extern char __data_start;
   1212 	extern char __kernel_end;
   1213 	size_t i = 0;
   1214 
   1215 	memset(&bootspace, 0, sizeof(bootspace));
   1216 
   1217 	bootspace.head.va = KERNTEXTOFF;
   1218 	bootspace.head.pa = KERNTEXTOFF - KERNBASE;
   1219 	bootspace.head.sz = 0;
   1220 
   1221 	bootspace.segs[i].type = BTSEG_TEXT;
   1222 	bootspace.segs[i].va = KERNTEXTOFF;
   1223 	bootspace.segs[i].pa = KERNTEXTOFF - KERNBASE;
   1224 	bootspace.segs[i].sz = (size_t)&__rodata_start - KERNTEXTOFF;
   1225 	i++;
   1226 
   1227 	bootspace.segs[i].type = BTSEG_RODATA;
   1228 	bootspace.segs[i].va = (vaddr_t)&__rodata_start;
   1229 	bootspace.segs[i].pa = (paddr_t)(vaddr_t)&__rodata_start - KERNBASE;
   1230 	bootspace.segs[i].sz = (size_t)&__data_start - (size_t)&__rodata_start;
   1231 	i++;
   1232 
   1233 	bootspace.segs[i].type = BTSEG_DATA;
   1234 	bootspace.segs[i].va = (vaddr_t)&__data_start;
   1235 	bootspace.segs[i].pa = (paddr_t)(vaddr_t)&__data_start - KERNBASE;
   1236 	bootspace.segs[i].sz = (size_t)&__kernel_end - (size_t)&__data_start;
   1237 	i++;
   1238 
   1239 	bootspace.boot.va = (vaddr_t)&__kernel_end;
   1240 	bootspace.boot.pa = (paddr_t)(vaddr_t)&__kernel_end - KERNBASE;
   1241 	bootspace.boot.sz = (size_t)(atdevbase + IOM_SIZE) -
   1242 	    (size_t)&__kernel_end;
   1243 
   1244 	/* Virtual address of the top level page */
   1245 	bootspace.pdir = (vaddr_t)(PDPpaddr + KERNBASE);
   1246 }
   1247 
   1248 void
   1249 init386(paddr_t first_avail)
   1250 {
   1251 	extern void consinit(void);
   1252 	int x;
   1253 #ifndef XENPV
   1254 	extern paddr_t local_apic_pa;
   1255 	union descriptor *tgdt;
   1256 	struct region_descriptor region;
   1257 #if NBIOSCALL > 0
   1258 	extern int biostramp_image_size;
   1259 	extern u_char biostramp_image[];
   1260 #endif
   1261 #endif /* !XENPV */
   1262 	struct pcb *pcb;
   1263 	struct idt_vec *iv;
   1264 	idt_descriptor_t *idt;
   1265 
   1266 	KASSERT(first_avail % PAGE_SIZE == 0);
   1267 
   1268 #ifdef XENPV
   1269 	KASSERT(HYPERVISOR_shared_info != NULL);
   1270 	cpu_info_primary.ci_vcpu = &HYPERVISOR_shared_info->vcpu_info[0];
   1271 #endif
   1272 
   1273 #ifdef XEN
   1274 	if (pvh_boot)
   1275 		xen_parse_cmdline(XEN_PARSE_BOOTFLAGS, NULL);
   1276 #endif
   1277 
   1278 	uvm_lwp_setuarea(&lwp0, lwp0uarea);
   1279 
   1280 	cpu_probe(&cpu_info_primary);
   1281 
   1282 	/*
   1283 	 * Initialize the no-execute bit on cpu0, if supported.
   1284 	 *
   1285 	 * Note: The call to cpu_init_msrs for secondary CPUs happens
   1286 	 * in cpu_hatch.
   1287 	 */
   1288 	cpu_init_msrs(&cpu_info_primary, true);
   1289 
   1290 #ifndef XENPV
   1291 	cpu_speculation_init(&cpu_info_primary);
   1292 #endif
   1293 
   1294 #ifdef PAE
   1295 	use_pae = 1;
   1296 #else
   1297 	use_pae = 0;
   1298 #endif
   1299 
   1300 	pcb = lwp_getpcb(&lwp0);
   1301 #ifdef XENPV
   1302 	pcb->pcb_cr3 = PDPpaddr;
   1303 #endif
   1304 
   1305 #if defined(PAE) && !defined(XENPV)
   1306 	/*
   1307 	 * Save VA and PA of L3 PD of boot processor (for Xen, this is done
   1308 	 * in xen_locore())
   1309 	 */
   1310 	cpu_info_primary.ci_pae_l3_pdirpa = rcr3();
   1311 	cpu_info_primary.ci_pae_l3_pdir = (pd_entry_t *)(rcr3() + KERNBASE);
   1312 #endif
   1313 
   1314 	uvm_md_init();
   1315 
   1316 	/*
   1317 	 * Start with 2 color bins -- this is just a guess to get us
   1318 	 * started.  We'll recolor when we determine the largest cache
   1319 	 * sizes on the system.
   1320 	 */
   1321 	uvmexp.ncolors = 2;
   1322 
   1323 	avail_start = first_avail;
   1324 
   1325 #ifndef XENPV
   1326 	/*
   1327 	 * Low memory reservations:
   1328 	 * Page 0:	BIOS data
   1329 	 * Page 1:	BIOS callback
   1330 	 * Page 2:	MP bootstrap code (MP_TRAMPOLINE)
   1331 	 * Page 3:	ACPI wakeup code (ACPI_WAKEUP_ADDR)
   1332 	 * Page 4:	Temporary page table for 0MB-4MB
   1333 	 * Page 5:	Temporary page directory
   1334 	 */
   1335 	lowmem_rsvd = 6 * PAGE_SIZE;
   1336 #else /* !XENPV */
   1337 	/* Parse Xen command line (replace bootinfo) */
   1338 	xen_parse_cmdline(XEN_PARSE_BOOTFLAGS, NULL);
   1339 
   1340 	/* Use the dummy page as a gdt */
   1341 	extern vaddr_t xen_dummy_page;
   1342 	gdtstore = (void *)xen_dummy_page;
   1343 
   1344 	/* Determine physical address space */
   1345 	avail_end = ctob((paddr_t)xen_start_info.nr_pages);
   1346 	pmap_pa_start = (KERNTEXTOFF - KERNBASE);
   1347 	pmap_pa_end = pmap_pa_start + ctob((paddr_t)xen_start_info.nr_pages);
   1348 	mem_clusters[0].start = avail_start;
   1349 	mem_clusters[0].size = avail_end - avail_start;
   1350 	mem_cluster_cnt++;
   1351 	physmem += xen_start_info.nr_pages;
   1352 	uvmexp.wired += atop(avail_start);
   1353 
   1354 	/*
   1355 	 * initgdt() has to be done before consinit(), so that %fs is properly
   1356 	 * initialised. initgdt() uses pmap_kenter_pa so it can't be called
   1357 	 * before the above variables are set.
   1358 	 */
   1359 	initgdt(gdtstore);
   1360 
   1361 	mutex_init(&pte_lock, MUTEX_DEFAULT, IPL_VM);
   1362 #endif /* XENPV */
   1363 
   1364 #if NISA > 0 || NPCI > 0
   1365 	x86_bus_space_init();
   1366 #endif
   1367 
   1368 	consinit();	/* XXX SHOULD NOT BE DONE HERE */
   1369 
   1370 #ifdef DEBUG_MEMLOAD
   1371 	printf("mem_cluster_count: %d\n", mem_cluster_cnt);
   1372 #endif
   1373 
   1374 	/*
   1375 	 * Call pmap initialization to make new kernel address space.
   1376 	 * We must do this before loading pages into the VM system.
   1377 	 */
   1378 	pmap_bootstrap((vaddr_t)atdevbase + IOM_SIZE);
   1379 
   1380 	/*
   1381 	 * Initialize RNG to get entropy ASAP either from CPU
   1382 	 * RDRAND/RDSEED or from seed on disk.  Constraints:
   1383 	 *
   1384 	 * - Must happen after cpu_init_msrs so that curcpu() and
   1385 	 *   curlwp work.
   1386 	 *
   1387 	 * - Must happen after consinit so we have the opportunity to
   1388 	 *   print useful feedback.
   1389 	 *
   1390 	 * - On KASLR kernels, must happen after pmap_bootstrap because
   1391 	 *   x86_rndseed requires access to the direct map.
   1392 	 */
   1393 	cpu_rng_init();
   1394 	x86_rndseed();
   1395 
   1396 #ifndef XENPV
   1397 	/* Initialize the memory clusters. */
   1398 	init_x86_clusters();
   1399 
   1400 	/* Internalize the physical pages into the VM system. */
   1401 	init_x86_vm(avail_start);
   1402 #else /* !XENPV */
   1403 	uvm_page_physload(atop(avail_start), atop(avail_end),
   1404 	    atop(avail_start), atop(avail_end),
   1405 	    VM_FREELIST_DEFAULT);
   1406 
   1407 	/* Reclaim the boot gdt page - see locore.s */
   1408 	{
   1409 		extern pt_entry_t xpmap_pg_nx;
   1410 		pt_entry_t pte;
   1411 
   1412 		pte = pmap_pa2pte((vaddr_t)tmpgdt - KERNBASE);
   1413 		pte |= PTE_W | xpmap_pg_nx | PTE_P;
   1414 
   1415 		if (HYPERVISOR_update_va_mapping((vaddr_t)tmpgdt, pte, UVMF_INVLPG) < 0) {
   1416 			panic("tmpgdt page relaim RW update failed.\n");
   1417 		}
   1418 	}
   1419 #endif /* !XENPV */
   1420 
   1421 	init_x86_msgbuf();
   1422 
   1423 #if !defined(XENPV) && NBIOSCALL > 0
   1424 	/*
   1425 	 * XXX Remove this
   1426 	 *
   1427 	 * Setup a temporary Page Table Entry to allow identity mappings of
   1428 	 * the real mode address. This is required by bioscall.
   1429 	 */
   1430 	init386_pte0();
   1431 
   1432 	KASSERT(biostramp_image_size <= PAGE_SIZE);
   1433 	pmap_kenter_pa((vaddr_t)BIOSTRAMP_BASE, (paddr_t)BIOSTRAMP_BASE,
   1434 	    VM_PROT_ALL, 0);
   1435 	pmap_update(pmap_kernel());
   1436 	memcpy((void *)BIOSTRAMP_BASE, biostramp_image, biostramp_image_size);
   1437 
   1438 	/* Needed early, for bioscall() */
   1439 	cpu_info_primary.ci_pmap = pmap_kernel();
   1440 #endif
   1441 
   1442 #ifndef XENPV
   1443 	pmap_kenter_pa(local_apic_va, local_apic_pa,
   1444 	    VM_PROT_READ|VM_PROT_WRITE, 0);
   1445 	pmap_update(pmap_kernel());
   1446 	memset((void *)local_apic_va, 0, PAGE_SIZE);
   1447 #endif
   1448 
   1449 	pmap_kenter_pa(idt_vaddr, idt_paddr, VM_PROT_READ|VM_PROT_WRITE, 0);
   1450 	pmap_kenter_pa(gdt_vaddr, gdt_paddr, VM_PROT_READ|VM_PROT_WRITE, 0);
   1451 	pmap_kenter_pa(ldt_vaddr, ldt_paddr, VM_PROT_READ|VM_PROT_WRITE, 0);
   1452 	pmap_update(pmap_kernel());
   1453 	memset((void *)idt_vaddr, 0, PAGE_SIZE);
   1454 	memset((void *)gdt_vaddr, 0, PAGE_SIZE);
   1455 	memset((void *)ldt_vaddr, 0, PAGE_SIZE);
   1456 
   1457 	pmap_kenter_pa(pentium_idt_vaddr, idt_paddr, VM_PROT_READ, 0);
   1458 	pmap_update(pmap_kernel());
   1459 	iv = &(cpu_info_primary.ci_idtvec);
   1460 	idt_vec_init_cpu_md(iv, cpu_index(&cpu_info_primary));
   1461 	idt = (idt_descriptor_t *)iv->iv_idt;
   1462 
   1463 #ifndef XENPV
   1464 	/*
   1465 	 * Switch from the initial temporary GDT that was allocated on
   1466 	 * the stack by our caller, start.  That temporary GDT will be
   1467 	 * popped off the stack when init386 returns before start calls
   1468 	 * main, so we need to use a second temporary GDT allocated in
   1469 	 * pmap_bootstrap with pmap_bootstrap_valloc/palloc to make
   1470 	 * sure at least the CPU-local data area, used by CPUVAR(...),
   1471 	 * curcpu(), and curlwp via %fs-relative addressing, will
   1472 	 * continue to work.
   1473 	 *
   1474 	 * Later, in gdt_init via cpu_startup, we will finally allocate
   1475 	 * a permanent GDT with uvm_km(9).
   1476 	 *
   1477 	 * The content of the second temporary GDT is the same as the
   1478 	 * content of the initial GDT, initialized in initgdt, except
   1479 	 * for the address of the LDT, which is also that we are also
   1480 	 * switching to a new temporary LDT at a new address.
   1481 	 */
   1482 	tgdt = gdtstore;
   1483 	gdtstore = (union descriptor *)gdt_vaddr;
   1484 	ldtstore = (union descriptor *)ldt_vaddr;
   1485 
   1486 	memcpy(gdtstore, tgdt, NGDT * sizeof(*gdtstore));
   1487 
   1488 	setsegment(&gdtstore[GLDT_SEL].sd, ldtstore,
   1489 	    NLDT * sizeof(ldtstore[0]) - 1, SDT_SYSLDT, SEL_KPL, 0, 0);
   1490 #else
   1491 	HYPERVISOR_set_callbacks(
   1492 	    GSEL(GCODE_SEL, SEL_KPL), (unsigned long)hypervisor_callback,
   1493 	    GSEL(GCODE_SEL, SEL_KPL), (unsigned long)failsafe_callback);
   1494 
   1495 	ldtstore = (union descriptor *)ldt_vaddr;
   1496 #endif /* XENPV */
   1497 
   1498 	/* make ldt gates and memory segments */
   1499 	ldtstore[LUCODE_SEL] = gdtstore[GUCODE_SEL];
   1500 	ldtstore[LUCODEBIG_SEL] = gdtstore[GUCODEBIG_SEL];
   1501 	ldtstore[LUDATA_SEL] = gdtstore[GUDATA_SEL];
   1502 
   1503 	/* exceptions */
   1504 	for (x = 0; x < 32; x++) {
   1505 		/* Reset to default. Special cases below */
   1506 		int sel;
   1507 #ifdef XENPV
   1508 		sel = SEL_XEN;
   1509 #else
   1510 		sel = SEL_KPL;
   1511 #endif /* XENPV */
   1512 
   1513 		idt_vec_reserve(iv, x);
   1514 
   1515  		switch (x) {
   1516 #ifdef XENPV
   1517 		case 2:  /* NMI */
   1518 		case 18: /* MCA */
   1519 			sel |= 0x4; /* Auto EOI/mask */
   1520 			break;
   1521 #endif /* XENPV */
   1522 		case 3:
   1523 		case 4:
   1524 			sel = SEL_UPL;
   1525 			break;
   1526 		default:
   1527 			break;
   1528 		}
   1529 		set_idtgate(&idt[x], IDTVEC(exceptions)[x], 0, SDT_SYS386IGT,
   1530 		    sel, GSEL(GCODE_SEL, SEL_KPL));
   1531 	}
   1532 
   1533 	/* new-style interrupt gate for syscalls */
   1534 	idt_vec_reserve(iv, 128);
   1535 	set_idtgate(&idt[128], &IDTVEC(syscall), 0, SDT_SYS386IGT, SEL_UPL,
   1536 	    GSEL(GCODE_SEL, SEL_KPL));
   1537 
   1538 #ifndef XENPV
   1539 	/*
   1540 	 * Activate the second temporary GDT, allocated in
   1541 	 * pmap_bootstrap with pmap_bootstrap_valloc/palloc, and
   1542 	 * initialized with the content of the initial temporary GDT in
   1543 	 * initgdt, plus an updated LDT.
   1544 	 *
   1545 	 * This ensures the %fs-relative addressing for the CPU-local
   1546 	 * area used by CPUVAR(...), curcpu(), and curlwp will continue
   1547 	 * to work after init386 returns and the initial temporary GDT
   1548 	 * is popped off, before we call main and later create a
   1549 	 * permanent GDT in gdt_init via cpu_startup.
   1550 	 */
   1551 	setregion(&region, gdtstore, NGDT * sizeof(gdtstore[0]) - 1);
   1552 	lgdt(&region);
   1553 #endif
   1554 
   1555 	lldt(GSEL(GLDT_SEL, SEL_KPL));
   1556 	cpu_init_idt(&cpu_info_primary);
   1557 
   1558 #ifdef XENPV
   1559 	xen_init_ksyms();
   1560 #else /* XENPV */
   1561 #ifdef XEN
   1562 	if (vm_guest == VM_GUEST_XENPVH)
   1563 		xen_init_ksyms();
   1564 	else
   1565 #endif /* XEN */
   1566 		init386_ksyms();
   1567 #endif /* XENPV */
   1568 
   1569 #if NMCA > 0
   1570 	/*
   1571 	 * check for MCA bus, needed to be done before ISA stuff - if
   1572 	 * MCA is detected, ISA needs to use level triggered interrupts
   1573 	 * by default
   1574 	 * And we do not search for MCA using bioscall() on EFI systems
   1575 	 * that lacks it (they lack MCA too, anyway).
   1576 	 */
   1577 	if (lookup_bootinfo(BTINFO_EFI) == NULL && vm_guest != VM_GUEST_XENPVH)
   1578 		mca_busprobe();
   1579 #endif
   1580 
   1581 #ifdef XENPV
   1582 	extern int tmpstk;
   1583 	cpu_info_primary.ci_intrstack = &tmpstk;
   1584 	events_default_setup();
   1585 #else
   1586 	intr_default_setup();
   1587 #endif
   1588 
   1589 	splraise(IPL_HIGH);
   1590 	x86_enable_intr();
   1591 
   1592 #ifdef DDB
   1593 	if (boothowto & RB_KDB)
   1594 		Debugger();
   1595 #endif
   1596 #ifdef KGDB
   1597 	kgdb_port_init();
   1598 	if (boothowto & RB_KDB) {
   1599 		kgdb_debug_init = 1;
   1600 		kgdb_connect(1);
   1601 	}
   1602 #endif
   1603 
   1604 	if (physmem < btoc(2 * 1024 * 1024)) {
   1605 		printf("warning: too little memory available; "
   1606 		       "have %lu bytes, want %lu bytes\n"
   1607 		       "running in degraded mode\n"
   1608 		       "press a key to confirm\n\n",
   1609 		       (unsigned long)ptoa(physmem), 2*1024*1024UL);
   1610 		cngetc();
   1611 	}
   1612 
   1613 	pcb->pcb_dbregs = NULL;
   1614 	x86_dbregs_init();
   1615 }
   1616 
   1617 #include <dev/ic/mc146818reg.h>		/* for NVRAM POST */
   1618 #include <i386/isa/nvram.h>		/* for NVRAM POST */
   1619 
   1620 void
   1621 cpu_reset(void)
   1622 {
   1623 #ifdef XENPV
   1624 	HYPERVISOR_reboot();
   1625 	for (;;);
   1626 #else /* XENPV */
   1627 	struct region_descriptor region;
   1628 	idt_descriptor_t *idt;
   1629 
   1630 	idt = (idt_descriptor_t *)cpu_info_primary.ci_idtvec.iv_idt;
   1631 	x86_disable_intr();
   1632 
   1633 	/*
   1634 	 * Ensure the NVRAM reset byte contains something vaguely sane.
   1635 	 */
   1636 
   1637 	outb(IO_RTC, NVRAM_RESET);
   1638 	outb(IO_RTC+1, NVRAM_RESET_RST);
   1639 
   1640 	/*
   1641 	 * Reset AMD Geode SC1100.
   1642 	 *
   1643 	 * 1) Write PCI Configuration Address Register (0xcf8) to
   1644 	 *    select Function 0, Register 0x44: Bridge Configuration,
   1645 	 *    GPIO and LPC Configuration Register Space, Reset
   1646 	 *    Control Register.
   1647 	 *
   1648 	 * 2) Write 0xf to PCI Configuration Data Register (0xcfc)
   1649 	 *    to reset IDE controller, IDE bus, and PCI bus, and
   1650 	 *    to trigger a system-wide reset.
   1651 	 *
   1652 	 * See AMD Geode SC1100 Processor Data Book, Revision 2.0,
   1653 	 * sections 6.3.1, 6.3.2, and 6.4.1.
   1654 	 */
   1655 	if (cpu_info_primary.ci_signature == 0x540) {
   1656 		outl(0xcf8, 0x80009044);
   1657 		outl(0xcfc, 0xf);
   1658 	}
   1659 
   1660 	x86_reset();
   1661 
   1662 	/*
   1663 	 * Try to cause a triple fault and watchdog reset by making the IDT
   1664 	 * invalid and causing a fault.
   1665 	 */
   1666 	memset((void *)idt, 0, NIDT * sizeof(idt[0]));
   1667 	setregion(&region, idt, NIDT * sizeof(idt[0]) - 1);
   1668 	lidt(&region);
   1669 	breakpoint();
   1670 
   1671 #if 0
   1672 	/*
   1673 	 * Try to cause a triple fault and watchdog reset by unmapping the
   1674 	 * entire address space and doing a TLB flush.
   1675 	 */
   1676 	memset((void *)PTD, 0, PAGE_SIZE);
   1677 	tlbflush();
   1678 #endif
   1679 
   1680 	for (;;);
   1681 #endif /* XENPV */
   1682 }
   1683 
   1684 void
   1685 cpu_getmcontext(struct lwp *l, mcontext_t *mcp, unsigned int *flags)
   1686 {
   1687 	const struct trapframe *tf = l->l_md.md_regs;
   1688 	__greg_t *gr = mcp->__gregs;
   1689 	__greg_t ras_eip;
   1690 
   1691 	/* Save register context. */
   1692 	gr[_REG_GS]  = tf->tf_gs;
   1693 	gr[_REG_FS]  = tf->tf_fs;
   1694 	gr[_REG_ES]  = tf->tf_es;
   1695 	gr[_REG_DS]  = tf->tf_ds;
   1696 	gr[_REG_EFL] = tf->tf_eflags;
   1697 
   1698 	gr[_REG_EDI]    = tf->tf_edi;
   1699 	gr[_REG_ESI]    = tf->tf_esi;
   1700 	gr[_REG_EBP]    = tf->tf_ebp;
   1701 	gr[_REG_EBX]    = tf->tf_ebx;
   1702 	gr[_REG_EDX]    = tf->tf_edx;
   1703 	gr[_REG_ECX]    = tf->tf_ecx;
   1704 	gr[_REG_EAX]    = tf->tf_eax;
   1705 	gr[_REG_EIP]    = tf->tf_eip;
   1706 	gr[_REG_CS]     = tf->tf_cs;
   1707 	gr[_REG_ESP]    = tf->tf_esp;
   1708 	gr[_REG_UESP]   = tf->tf_esp;
   1709 	gr[_REG_SS]     = tf->tf_ss;
   1710 	gr[_REG_TRAPNO] = tf->tf_trapno;
   1711 	gr[_REG_ERR]    = tf->tf_err;
   1712 
   1713 	if ((ras_eip = (__greg_t)ras_lookup(l->l_proc,
   1714 	    (void *) gr[_REG_EIP])) != -1)
   1715 		gr[_REG_EIP] = ras_eip;
   1716 
   1717 	*flags |= _UC_CPU;
   1718 
   1719 	mcp->_mc_tlsbase = (uintptr_t)l->l_private;
   1720 	*flags |= _UC_TLSBASE;
   1721 
   1722 	/*
   1723 	 * Save floating point register context.
   1724 	 *
   1725 	 * If the cpu doesn't support fxsave we must still write to
   1726 	 * the entire 512 byte area - otherwise we leak kernel memory
   1727 	 * contents to userspace.
   1728 	 * It wouldn't matter if we were doing the copyout here.
   1729 	 * So we might as well convert to fxsave format.
   1730 	 */
   1731 	__CTASSERT(sizeof (struct fxsave) ==
   1732 	    sizeof mcp->__fpregs.__fp_reg_set.__fp_xmm_state);
   1733 	process_read_fpregs_xmm(l, (struct fxsave *)
   1734 	    &mcp->__fpregs.__fp_reg_set.__fp_xmm_state);
   1735 	memset(&mcp->__fpregs.__fp_pad, 0, sizeof mcp->__fpregs.__fp_pad);
   1736 	*flags |= _UC_FXSAVE | _UC_FPU;
   1737 }
   1738 
   1739 /*
   1740  * cpu_getmcontext_xsave(l, mcp, flags, xsavebuf, xsavelen, user_xsave)
   1741  *
   1742  *	Copy out xsavebuf[0..xsavelen) to user_xsave, set mcp to point
   1743  *	there, and set _UC_XSAVE in flags.  Caller must have already
   1744  *	used cpu_getmcontext to initialize mcp's FXSAVE area.
   1745  *
   1746  *	May fail if the copyout fails.
   1747  */
   1748 static int
   1749 cpu_getmcontext_xsave(struct lwp *l, mcontext_t *mcp, unsigned int *flags,
   1750     const struct xsave_header *xsavebuf, size_t xsavelen,
   1751     struct xsave_header *user_xsave)
   1752 {
   1753 	int error;
   1754 
   1755 	KASSERT(*flags & _UC_FPU);
   1756 	KASSERT(*flags & _UC_FXSAVE);
   1757 
   1758 	/*
   1759 	 * Copy out the XSAVE area.
   1760 	 */
   1761 	error = copyout(xsavebuf, user_xsave, xsavelen);
   1762 	if (error != 0)
   1763 		return error;
   1764 
   1765 	/*
   1766 	 * Record a pointer to the real XSAVE area in the
   1767 	 * architecturally unused bits mcontext_t's FXSAVE area.
   1768 	 */
   1769 	mcp->__fpregs.__fp_reg_set.__xsave.__xsaveptr =
   1770 	    (__greg_t)(uintptr_t)user_xsave;
   1771 	mcp->__fpregs.__fp_reg_set.__xsave.__xsavelen = (__greg_t)xsavelen;
   1772 
   1773 	/*
   1774 	 * Set the _UC_XSAVE flag so cpu_setmcontext will be able to
   1775 	 * restore the full state from the XSAVE area.
   1776 	 */
   1777 	*flags |= _UC_XSAVE;
   1778 
   1779 	/* Success! */
   1780 	return 0;
   1781 }
   1782 
   1783 int
   1784 cpu_mcontext_validate(struct lwp *l, const mcontext_t *mcp)
   1785 {
   1786 	const __greg_t *gr = mcp->__gregs;
   1787 	struct trapframe *tf = l->l_md.md_regs;
   1788 
   1789 	/*
   1790 	 * Check for security violations.  If we're returning
   1791 	 * to protected mode, the CPU will validate the segment
   1792 	 * registers automatically and generate a trap on
   1793 	 * violations.  We handle the trap, rather than doing
   1794 	 * all of the checking here.
   1795 	 */
   1796 	if (((gr[_REG_EFL] ^ tf->tf_eflags) & PSL_USERSTATIC) ||
   1797 	    !USERMODE(gr[_REG_CS]))
   1798 		return EINVAL;
   1799 
   1800 	return 0;
   1801 }
   1802 
   1803 int
   1804 cpu_setmcontext(struct lwp *l, const mcontext_t *mcp, unsigned int flags)
   1805 {
   1806 	struct trapframe *tf = l->l_md.md_regs;
   1807 	const __greg_t *gr = mcp->__gregs;
   1808 	struct proc *p = l->l_proc;
   1809 	struct xsave_header *xsavebuf = NULL;
   1810 	size_t xsavelen = 0;
   1811 	int error;
   1812 
   1813 	/*
   1814 	 * If there's an external XSAVE area, copy it in and validate
   1815 	 * it before we irreversibly modify the trapframe.
   1816 	 *
   1817 	 * We could check the length against the state components
   1818 	 * included, but we currently don't: if it's truncated, it will
   1819 	 * be as if the truncated part were zero-filled -- this is
   1820 	 * implemented in process_write_xsave, called a little below.
   1821 	 */
   1822 	if ((flags & _UC_XSAVE) != 0) {
   1823 		const __greg_t user_xsave =
   1824 		    mcp->__fpregs.__fp_reg_set.__xsave.__xsaveptr;
   1825 
   1826 		xsavelen = mcp->__fpregs.__fp_reg_set.__xsave.__xsavelen;
   1827 		error = process_verify_xsavelen(l, xsavelen);
   1828 		if (error != 0)
   1829 			goto out;
   1830 		xsavebuf = kmem_alloc(xsavelen, KM_SLEEP);
   1831 		error = copyin((const void *)user_xsave, xsavebuf, xsavelen);
   1832 		if (error != 0)
   1833 			goto out;
   1834 		error = process_verify_xsave(l, xsavebuf, xsavelen);
   1835 		if (error != 0)
   1836 			goto out;
   1837 	}
   1838 
   1839 	/* Restore register context, if any. */
   1840 	if ((flags & _UC_CPU) != 0) {
   1841 		error = cpu_mcontext_validate(l, mcp);
   1842 		if (error)
   1843 			return error;
   1844 
   1845 		tf->tf_gs = gr[_REG_GS];
   1846 		tf->tf_fs = gr[_REG_FS];
   1847 		tf->tf_es = gr[_REG_ES];
   1848 		tf->tf_ds = gr[_REG_DS];
   1849 		/* Only change the user-alterable part of eflags */
   1850 		tf->tf_eflags &= ~PSL_USER;
   1851 		tf->tf_eflags |= (gr[_REG_EFL] & PSL_USER);
   1852 
   1853 		tf->tf_edi    = gr[_REG_EDI];
   1854 		tf->tf_esi    = gr[_REG_ESI];
   1855 		tf->tf_ebp    = gr[_REG_EBP];
   1856 		tf->tf_ebx    = gr[_REG_EBX];
   1857 		tf->tf_edx    = gr[_REG_EDX];
   1858 		tf->tf_ecx    = gr[_REG_ECX];
   1859 		tf->tf_eax    = gr[_REG_EAX];
   1860 		tf->tf_eip    = gr[_REG_EIP];
   1861 		tf->tf_cs     = gr[_REG_CS];
   1862 		tf->tf_esp    = gr[_REG_UESP];
   1863 		tf->tf_ss     = gr[_REG_SS];
   1864 	}
   1865 
   1866 	if ((flags & _UC_TLSBASE) != 0)
   1867 		lwp_setprivate(l, (void *)(uintptr_t)mcp->_mc_tlsbase);
   1868 
   1869 	/* Restore floating point register context, if given. */
   1870 	if ((flags & _UC_XSAVE) != 0) {
   1871 		KASSERT(xsavebuf != NULL);
   1872 		process_write_xsave(l, xsavebuf, xsavelen);
   1873 	} else if ((flags & _UC_FPU) != 0) {
   1874 		__CTASSERT(sizeof (struct fxsave) ==
   1875 		    sizeof mcp->__fpregs.__fp_reg_set.__fp_xmm_state);
   1876 		__CTASSERT(sizeof (struct save87) ==
   1877 		    sizeof mcp->__fpregs.__fp_reg_set.__fpchip_state);
   1878 
   1879 		if (flags & _UC_FXSAVE) {
   1880 			process_write_fpregs_xmm(l, (const struct fxsave *)
   1881 				    &mcp->__fpregs.__fp_reg_set.__fp_xmm_state);
   1882 		} else {
   1883 			process_write_fpregs_s87(l, (const struct save87 *)
   1884 				    &mcp->__fpregs.__fp_reg_set.__fpchip_state);
   1885 		}
   1886 	}
   1887 
   1888 	mutex_enter(p->p_lock);
   1889 	if (flags & _UC_SETSTACK)
   1890 		l->l_sigstk.ss_flags |= SS_ONSTACK;
   1891 	if (flags & _UC_CLRSTACK)
   1892 		l->l_sigstk.ss_flags &= ~SS_ONSTACK;
   1893 	mutex_exit(p->p_lock);
   1894 
   1895 	/* Success! */
   1896 	error = 0;
   1897 
   1898 out:	if (xsavebuf)
   1899 		kmem_free(xsavebuf, xsavelen);
   1900 	return error;
   1901 }
   1902 
   1903 #define	DEV_IO 14		/* iopl for compat_10 */
   1904 
   1905 int
   1906 mm_md_open(dev_t dev, int flag, int mode, struct lwp *l)
   1907 {
   1908 
   1909 	switch (minor(dev)) {
   1910 	case DEV_IO:
   1911 		/*
   1912 		 * This is done by i386_iopl(3) now.
   1913 		 *
   1914 		 * #if defined(COMPAT_10) || defined(COMPAT_FREEBSD)
   1915 		 */
   1916 		if (flag & FWRITE) {
   1917 			struct trapframe *fp;
   1918 			int error;
   1919 
   1920 			error = kauth_authorize_machdep(l->l_cred,
   1921 			    KAUTH_MACHDEP_IOPL, NULL, NULL, NULL, NULL);
   1922 			if (error)
   1923 				return (error);
   1924 			fp = curlwp->l_md.md_regs;
   1925 			fp->tf_eflags |= PSL_IOPL;
   1926 		}
   1927 		break;
   1928 	default:
   1929 		break;
   1930 	}
   1931 	return 0;
   1932 }
   1933 
   1934 #ifdef PAE
   1935 void
   1936 cpu_alloc_l3_page(struct cpu_info *ci)
   1937 {
   1938 	int ret;
   1939 	struct pglist pg;
   1940 	struct vm_page *vmap;
   1941 
   1942 	KASSERT(ci != NULL);
   1943 	/*
   1944 	 * Allocate a page for the per-CPU L3 PD. cr3 being 32 bits, PA musts
   1945 	 * resides below the 4GB boundary.
   1946 	 */
   1947 	ret = uvm_pglistalloc(PAGE_SIZE, 0, 0x100000000ULL, 32, 0, &pg, 1, 0);
   1948 	vmap = TAILQ_FIRST(&pg);
   1949 
   1950 	if (ret != 0 || vmap == NULL)
   1951 		panic("%s: failed to allocate L3 pglist for CPU %d (ret %d)\n",
   1952 			__func__, cpu_index(ci), ret);
   1953 
   1954 	ci->ci_pae_l3_pdirpa = VM_PAGE_TO_PHYS(vmap);
   1955 
   1956 	ci->ci_pae_l3_pdir = (paddr_t *)uvm_km_alloc(kernel_map, PAGE_SIZE, 0,
   1957 		UVM_KMF_VAONLY | UVM_KMF_NOWAIT);
   1958 	if (ci->ci_pae_l3_pdir == NULL)
   1959 		panic("%s: failed to allocate L3 PD for CPU %d\n",
   1960 			__func__, cpu_index(ci));
   1961 
   1962 	pmap_kenter_pa((vaddr_t)ci->ci_pae_l3_pdir, ci->ci_pae_l3_pdirpa,
   1963 		VM_PROT_READ | VM_PROT_WRITE, 0);
   1964 
   1965 	pmap_update(pmap_kernel());
   1966 }
   1967 #endif /* PAE */
   1968 
   1969 static void
   1970 idt_vec_copy(struct idt_vec *dst, struct idt_vec *src)
   1971 {
   1972 	idt_descriptor_t *idt_dst;
   1973 
   1974 	idt_dst = dst->iv_idt;
   1975 	memcpy(idt_dst, src->iv_idt, PAGE_SIZE);
   1976 	memcpy(dst->iv_allocmap, src->iv_allocmap, sizeof(dst->iv_allocmap));
   1977 }
   1978 
   1979 void
   1980 idt_vec_init_cpu_md(struct idt_vec *iv, cpuid_t cid)
   1981 {
   1982 	vaddr_t va_idt, va_pentium_idt;
   1983 	struct vm_page *pg;
   1984 
   1985 	if (idt_vec_is_pcpu() &&
   1986 	    cid != cpu_index(&cpu_info_primary)) {
   1987 		va_idt = uvm_km_alloc(kernel_map, PAGE_SIZE,
   1988 		    0, UVM_KMF_VAONLY);
   1989 		pg = uvm_pagealloc(NULL, 0, NULL, UVM_PGA_ZERO);
   1990 		if (pg == NULL) {
   1991 			panic("failed to allocate pcpu idt PA");
   1992 		}
   1993 		pmap_kenter_pa(va_idt, VM_PAGE_TO_PHYS(pg),
   1994 		    VM_PROT_READ|VM_PROT_WRITE, 0);
   1995 		pmap_update(pmap_kernel());
   1996 
   1997 		memset((void *)va_idt, 0, PAGE_SIZE);
   1998 
   1999 		/* pentium f00f bug stuff */
   2000 		va_pentium_idt = uvm_km_alloc(kernel_map, PAGE_SIZE,
   2001 		    0, UVM_KMF_VAONLY);
   2002 		pmap_kenter_pa(va_pentium_idt, VM_PAGE_TO_PHYS(pg),
   2003 		    VM_PROT_READ, 0);
   2004 		pmap_update(pmap_kernel());
   2005 
   2006 		iv->iv_idt = (void *)va_idt;
   2007 		iv->iv_idt_pentium = (void *)va_pentium_idt;
   2008 
   2009 		idt_vec_copy(iv, &(cpu_info_primary.ci_idtvec));
   2010 	} else {
   2011 		iv->iv_idt = (void *)idt_vaddr;
   2012 		iv->iv_idt_pentium = (void *)pentium_idt_vaddr;
   2013 	}
   2014 }
   2015