Home | History | Annotate | Line # | Download | only in x86
cpu.c revision 1.200
      1 /*	$NetBSD: cpu.c,v 1.200 2021/04/24 23:36:51 thorpej Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2000-2020 NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Bill Sommerfeld of RedBack Networks Inc, and by Andrew Doran.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (c) 1999 Stefan Grefen
     34  *
     35  * Redistribution and use in source and binary forms, with or without
     36  * modification, are permitted provided that the following conditions
     37  * are met:
     38  * 1. Redistributions of source code must retain the above copyright
     39  *    notice, this list of conditions and the following disclaimer.
     40  * 2. Redistributions in binary form must reproduce the above copyright
     41  *    notice, this list of conditions and the following disclaimer in the
     42  *    documentation and/or other materials provided with the distribution.
     43  * 3. All advertising materials mentioning features or use of this software
     44  *    must display the following acknowledgement:
     45  *      This product includes software developed by the NetBSD
     46  *      Foundation, Inc. and its contributors.
     47  * 4. Neither the name of The NetBSD Foundation nor the names of its
     48  *    contributors may be used to endorse or promote products derived
     49  *    from this software without specific prior written permission.
     50  *
     51  * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
     52  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     53  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     54  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR AND CONTRIBUTORS BE LIABLE
     55  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     56  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     57  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     58  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     59  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     60  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     61  * SUCH DAMAGE.
     62  */
     63 
     64 #include <sys/cdefs.h>
     65 __KERNEL_RCSID(0, "$NetBSD: cpu.c,v 1.200 2021/04/24 23:36:51 thorpej Exp $");
     66 
     67 #include "opt_ddb.h"
     68 #include "opt_mpbios.h"		/* for MPDEBUG */
     69 #include "opt_mtrr.h"
     70 #include "opt_multiprocessor.h"
     71 #include "opt_svs.h"
     72 
     73 #include "lapic.h"
     74 #include "ioapic.h"
     75 #include "acpica.h"
     76 #include "hpet.h"
     77 
     78 #include <sys/param.h>
     79 #include <sys/proc.h>
     80 #include <sys/systm.h>
     81 #include <sys/device.h>
     82 #include <sys/cpu.h>
     83 #include <sys/cpufreq.h>
     84 #include <sys/idle.h>
     85 #include <sys/atomic.h>
     86 #include <sys/reboot.h>
     87 #include <sys/csan.h>
     88 
     89 #include <uvm/uvm.h>
     90 
     91 #include "acpica.h"		/* for NACPICA, for mp_verbose */
     92 
     93 #include <x86/machdep.h>
     94 #include <machine/cpufunc.h>
     95 #include <machine/cpuvar.h>
     96 #include <machine/pmap.h>
     97 #include <machine/vmparam.h>
     98 #if defined(MULTIPROCESSOR)
     99 #include <machine/mpbiosvar.h>
    100 #endif
    101 #include <machine/mpconfig.h>		/* for mp_verbose */
    102 #include <machine/pcb.h>
    103 #include <machine/specialreg.h>
    104 #include <machine/segments.h>
    105 #include <machine/gdt.h>
    106 #include <machine/mtrr.h>
    107 #include <machine/pio.h>
    108 #include <machine/cpu_counter.h>
    109 
    110 #include <x86/fpu.h>
    111 
    112 #if NACPICA > 0
    113 #include <dev/acpi/acpi_srat.h>
    114 #endif
    115 
    116 #if NLAPIC > 0
    117 #include <machine/apicvar.h>
    118 #include <machine/i82489reg.h>
    119 #include <machine/i82489var.h>
    120 #endif
    121 
    122 #include <dev/ic/mc146818reg.h>
    123 #include <dev/ic/hpetvar.h>
    124 #include <i386/isa/nvram.h>
    125 #include <dev/isa/isareg.h>
    126 
    127 #include "tsc.h"
    128 
    129 #ifndef XENPV
    130 #include "hyperv.h"
    131 #if NHYPERV > 0
    132 #include <x86/x86/hypervvar.h>
    133 #endif
    134 #endif
    135 
    136 #ifdef XEN
    137 #include <xen/hypervisor.h>
    138 #endif
    139 
    140 static int	cpu_match(device_t, cfdata_t, void *);
    141 static void	cpu_attach(device_t, device_t, void *);
    142 static void	cpu_defer(device_t);
    143 static int	cpu_rescan(device_t, const char *, const int *);
    144 static void	cpu_childdetached(device_t, device_t);
    145 static bool	cpu_stop(device_t);
    146 static bool	cpu_suspend(device_t, const pmf_qual_t *);
    147 static bool	cpu_resume(device_t, const pmf_qual_t *);
    148 static bool	cpu_shutdown(device_t, int);
    149 
    150 struct cpu_softc {
    151 	device_t sc_dev;		/* device tree glue */
    152 	struct cpu_info *sc_info;	/* pointer to CPU info */
    153 	bool sc_wasonline;
    154 };
    155 
    156 #ifdef MULTIPROCESSOR
    157 int mp_cpu_start(struct cpu_info *, paddr_t);
    158 void mp_cpu_start_cleanup(struct cpu_info *);
    159 const struct cpu_functions mp_cpu_funcs = { mp_cpu_start, NULL,
    160 					    mp_cpu_start_cleanup };
    161 #endif
    162 
    163 
    164 CFATTACH_DECL2_NEW(cpu, sizeof(struct cpu_softc),
    165     cpu_match, cpu_attach, NULL, NULL, cpu_rescan, cpu_childdetached);
    166 
    167 /*
    168  * Statically-allocated CPU info for the primary CPU (or the only
    169  * CPU, on uniprocessors).  The CPU info list is initialized to
    170  * point at it.
    171  */
    172 struct cpu_info cpu_info_primary __aligned(CACHE_LINE_SIZE) = {
    173 	.ci_dev = 0,
    174 	.ci_self = &cpu_info_primary,
    175 	.ci_idepth = -1,
    176 	.ci_curlwp = &lwp0,
    177 	.ci_curldt = -1,
    178 };
    179 
    180 struct cpu_info *cpu_info_list = &cpu_info_primary;
    181 
    182 #ifdef i386
    183 void		cpu_set_tss_gates(struct cpu_info *);
    184 #endif
    185 
    186 static void	cpu_init_idle_lwp(struct cpu_info *);
    187 
    188 uint32_t cpu_feature[7] __read_mostly; /* X86 CPUID feature bits */
    189 			/* [0] basic features cpuid.1:%edx
    190 			 * [1] basic features cpuid.1:%ecx (CPUID2_xxx bits)
    191 			 * [2] extended features cpuid:80000001:%edx
    192 			 * [3] extended features cpuid:80000001:%ecx
    193 			 * [4] VIA padlock features
    194 			 * [5] structured extended features cpuid.7:%ebx
    195 			 * [6] structured extended features cpuid.7:%ecx
    196 			 */
    197 
    198 #ifdef MULTIPROCESSOR
    199 bool x86_mp_online;
    200 paddr_t mp_trampoline_paddr = MP_TRAMPOLINE;
    201 #endif
    202 #if NLAPIC > 0
    203 static vaddr_t cmos_data_mapping;
    204 #endif
    205 struct cpu_info *cpu_starting;
    206 
    207 #ifdef MULTIPROCESSOR
    208 void		cpu_hatch(void *);
    209 static void	cpu_boot_secondary(struct cpu_info *ci);
    210 static void	cpu_start_secondary(struct cpu_info *ci);
    211 #if NLAPIC > 0
    212 static void	cpu_copy_trampoline(paddr_t);
    213 #endif
    214 #endif /* MULTIPROCESSOR */
    215 
    216 /*
    217  * Runs once per boot once multiprocessor goo has been detected and
    218  * the local APIC on the boot processor has been mapped.
    219  *
    220  * Called from lapic_boot_init() (from mpbios_scan()).
    221  */
    222 #if NLAPIC > 0
    223 void
    224 cpu_init_first(void)
    225 {
    226 
    227 	cpu_info_primary.ci_cpuid = lapic_cpu_number();
    228 
    229 	cmos_data_mapping = uvm_km_alloc(kernel_map, PAGE_SIZE, 0, UVM_KMF_VAONLY);
    230 	if (cmos_data_mapping == 0)
    231 		panic("No KVA for page 0");
    232 	pmap_kenter_pa(cmos_data_mapping, 0, VM_PROT_READ|VM_PROT_WRITE, 0);
    233 	pmap_update(pmap_kernel());
    234 }
    235 #endif
    236 
    237 static int
    238 cpu_match(device_t parent, cfdata_t match, void *aux)
    239 {
    240 
    241 	return 1;
    242 }
    243 
    244 #ifdef __HAVE_PCPU_AREA
    245 void
    246 cpu_pcpuarea_init(struct cpu_info *ci)
    247 {
    248 	struct vm_page *pg;
    249 	size_t i, npages;
    250 	vaddr_t base, va;
    251 	paddr_t pa;
    252 
    253 	CTASSERT(sizeof(struct pcpu_entry) % PAGE_SIZE == 0);
    254 
    255 	npages = sizeof(struct pcpu_entry) / PAGE_SIZE;
    256 	base = (vaddr_t)&pcpuarea->ent[cpu_index(ci)];
    257 
    258 	for (i = 0; i < npages; i++) {
    259 		pg = uvm_pagealloc(NULL, 0, NULL, UVM_PGA_ZERO);
    260 		if (pg == NULL) {
    261 			panic("failed to allocate pcpu PA");
    262 		}
    263 
    264 		va = base + i * PAGE_SIZE;
    265 		pa = VM_PAGE_TO_PHYS(pg);
    266 
    267 		pmap_kenter_pa(va, pa, VM_PROT_READ|VM_PROT_WRITE, 0);
    268 	}
    269 
    270 	pmap_update(pmap_kernel());
    271 }
    272 #endif
    273 
    274 static void
    275 cpu_vm_init(struct cpu_info *ci)
    276 {
    277 	unsigned int ncolors = 2;
    278 
    279 	/*
    280 	 * XXX: for AP's the cache info has not been initialized yet
    281 	 * but that does not matter because uvm only pays attention at
    282 	 * the maximum only. We should fix it once cpus have different
    283 	 * cache sizes.
    284 	 */
    285 	for (unsigned int i = CAI_ICACHE; i <= CAI_L2CACHE; i++) {
    286 		struct x86_cache_info *cai;
    287 		unsigned int tcolors;
    288 
    289 		cai = &ci->ci_cinfo[i];
    290 
    291 		tcolors = atop(cai->cai_totalsize);
    292 		switch (cai->cai_associativity) {
    293 		case 0xff:
    294 			tcolors = 1; /* fully associative */
    295 			break;
    296 		case 0:
    297 		case 1:
    298 			break;
    299 		default:
    300 			tcolors /= cai->cai_associativity;
    301 		}
    302 		if (tcolors <= ncolors)
    303 			continue;
    304 		ncolors = tcolors;
    305 	}
    306 
    307 	/*
    308 	 * If the desired number of colors is not a power of
    309 	 * two, it won't be good.  Find the greatest power of
    310 	 * two which is an even divisor of the number of colors,
    311 	 * to preserve even coloring of pages.
    312 	 */
    313 	if (ncolors & (ncolors - 1) ) {
    314 		unsigned int try, picked = 1;
    315 		for (try = 1; try < ncolors; try *= 2) {
    316 			if (ncolors % try == 0) picked = try;
    317 		}
    318 		if (picked == 1) {
    319 			panic("desired number of cache colors %u is "
    320 			" > 1, but not even!", ncolors);
    321 		}
    322 		ncolors = picked;
    323 	}
    324 
    325 	/*
    326 	 * Knowing the size of the largest cache on this CPU, potentially
    327 	 * re-color our pages.
    328 	 */
    329 	aprint_debug_dev(ci->ci_dev, "%d page colors\n", ncolors);
    330 	uvm_page_recolor(ncolors);
    331 
    332 	pmap_tlb_cpu_init(ci);
    333 #ifndef __HAVE_DIRECT_MAP
    334 	pmap_vpage_cpu_init(ci);
    335 #endif
    336 }
    337 
    338 static void
    339 cpu_attach(device_t parent, device_t self, void *aux)
    340 {
    341 	struct cpu_softc *sc = device_private(self);
    342 	struct cpu_attach_args *caa = aux;
    343 	struct cpu_info *ci;
    344 	uintptr_t ptr;
    345 #if NLAPIC > 0
    346 	int cpunum = caa->cpu_number;
    347 #endif
    348 	static bool again;
    349 
    350 	sc->sc_dev = self;
    351 
    352 	if (ncpu > maxcpus) {
    353 #ifndef _LP64
    354 		aprint_error(": too many CPUs, please use NetBSD/amd64\n");
    355 #else
    356 		aprint_error(": too many CPUs\n");
    357 #endif
    358 		return;
    359 	}
    360 
    361 	/*
    362 	 * If we're an Application Processor, allocate a cpu_info
    363 	 * structure, otherwise use the primary's.
    364 	 */
    365 	if (caa->cpu_role == CPU_ROLE_AP) {
    366 		if ((boothowto & RB_MD1) != 0) {
    367 			aprint_error(": multiprocessor boot disabled\n");
    368 			if (!pmf_device_register(self, NULL, NULL))
    369 				aprint_error_dev(self,
    370 				    "couldn't establish power handler\n");
    371 			return;
    372 		}
    373 		aprint_naive(": Application Processor\n");
    374 		ptr = (uintptr_t)uvm_km_alloc(kernel_map,
    375 		    sizeof(*ci) + CACHE_LINE_SIZE - 1, 0,
    376 		    UVM_KMF_WIRED|UVM_KMF_ZERO);
    377 		ci = (struct cpu_info *)roundup2(ptr, CACHE_LINE_SIZE);
    378 		ci->ci_curldt = -1;
    379 	} else {
    380 		aprint_naive(": %s Processor\n",
    381 		    caa->cpu_role == CPU_ROLE_SP ? "Single" : "Boot");
    382 		ci = &cpu_info_primary;
    383 #if NLAPIC > 0
    384 		if (cpunum != lapic_cpu_number()) {
    385 			/* XXX should be done earlier. */
    386 			uint32_t reg;
    387 			aprint_verbose("\n");
    388 			aprint_verbose_dev(self, "running CPU at apic %d"
    389 			    " instead of at expected %d", lapic_cpu_number(),
    390 			    cpunum);
    391 			reg = lapic_readreg(LAPIC_ID);
    392 			lapic_writereg(LAPIC_ID, (reg & ~LAPIC_ID_MASK) |
    393 			    (cpunum << LAPIC_ID_SHIFT));
    394 		}
    395 		if (cpunum != lapic_cpu_number()) {
    396 			aprint_error_dev(self, "unable to reset apic id\n");
    397 		}
    398 #endif
    399 	}
    400 
    401 	ci->ci_self = ci;
    402 	sc->sc_info = ci;
    403 	ci->ci_dev = self;
    404 	ci->ci_acpiid = caa->cpu_id;
    405 	ci->ci_cpuid = caa->cpu_number;
    406 	ci->ci_func = caa->cpu_func;
    407 	ci->ci_kfpu_spl = -1;
    408 	aprint_normal("\n");
    409 
    410 	/* Must be before mi_cpu_attach(). */
    411 	cpu_vm_init(ci);
    412 
    413 	if (caa->cpu_role == CPU_ROLE_AP) {
    414 		int error;
    415 
    416 		error = mi_cpu_attach(ci);
    417 		if (error != 0) {
    418 			aprint_error_dev(self,
    419 			    "mi_cpu_attach failed with %d\n", error);
    420 			return;
    421 		}
    422 #ifdef __HAVE_PCPU_AREA
    423 		cpu_pcpuarea_init(ci);
    424 #endif
    425 		cpu_init_tss(ci);
    426 	} else {
    427 		KASSERT(ci->ci_data.cpu_idlelwp != NULL);
    428 #if NACPICA > 0
    429 		/* Parse out NUMA info for cpu_identify(). */
    430 		acpisrat_init();
    431 #endif
    432 	}
    433 
    434 #ifdef SVS
    435 	cpu_svs_init(ci);
    436 #endif
    437 
    438 	pmap_reference(pmap_kernel());
    439 	ci->ci_pmap = pmap_kernel();
    440 	ci->ci_tlbstate = TLBSTATE_STALE;
    441 
    442 	/*
    443 	 * Boot processor may not be attached first, but the below
    444 	 * must be done to allow booting other processors.
    445 	 */
    446 	if (!again) {
    447 		/* Make sure DELAY() (likely i8254_delay()) is initialized. */
    448 		DELAY(1);
    449 
    450 		/*
    451 		 * Basic init.  Compute an approximate frequency for the TSC
    452 		 * using the i8254.  If there's a HPET we'll redo it later.
    453 		 */
    454 		atomic_or_32(&ci->ci_flags, CPUF_PRESENT | CPUF_PRIMARY);
    455 		cpu_intr_init(ci);
    456 		tsc_setfunc(ci);
    457 		cpu_get_tsc_freq(ci);
    458 		cpu_init(ci);
    459 #ifdef i386
    460 		cpu_set_tss_gates(ci);
    461 #endif
    462 		pmap_cpu_init_late(ci);
    463 #if NLAPIC > 0
    464 		if (caa->cpu_role != CPU_ROLE_SP) {
    465 			/* Enable lapic. */
    466 			lapic_enable();
    467 			lapic_set_lvt();
    468 			if (!vm_guest_is_xenpvh_or_pvhvm())
    469 				lapic_calibrate_timer(false);
    470 		}
    471 #endif
    472 		kcsan_cpu_init(ci);
    473 		again = true;
    474 	}
    475 
    476 	/* further PCB init done later. */
    477 
    478 	switch (caa->cpu_role) {
    479 	case CPU_ROLE_SP:
    480 		atomic_or_32(&ci->ci_flags, CPUF_SP);
    481 		cpu_identify(ci);
    482 		x86_errata();
    483 		x86_cpu_idle_init();
    484 #ifdef XENPVHVM
    485 		xen_hvm_init_cpu(ci);
    486 #endif
    487 		break;
    488 
    489 	case CPU_ROLE_BP:
    490 		atomic_or_32(&ci->ci_flags, CPUF_BSP);
    491 		cpu_identify(ci);
    492 		x86_errata();
    493 		x86_cpu_idle_init();
    494 #ifdef XENPVHVM
    495 		xen_hvm_init_cpu(ci);
    496 #endif
    497 		break;
    498 
    499 #ifdef MULTIPROCESSOR
    500 	case CPU_ROLE_AP:
    501 		/*
    502 		 * report on an AP
    503 		 */
    504 		cpu_intr_init(ci);
    505 		idt_vec_init_cpu_md(&ci->ci_idtvec, cpu_index(ci));
    506 		gdt_alloc_cpu(ci);
    507 #ifdef i386
    508 		cpu_set_tss_gates(ci);
    509 #endif
    510 		pmap_cpu_init_late(ci);
    511 		cpu_start_secondary(ci);
    512 		if (ci->ci_flags & CPUF_PRESENT) {
    513 			struct cpu_info *tmp;
    514 
    515 			cpu_identify(ci);
    516 			tmp = cpu_info_list;
    517 			while (tmp->ci_next)
    518 				tmp = tmp->ci_next;
    519 
    520 			tmp->ci_next = ci;
    521 		}
    522 		break;
    523 #endif
    524 
    525 	default:
    526 		panic("unknown processor type??\n");
    527 	}
    528 
    529 	pat_init(ci);
    530 
    531 	if (!pmf_device_register1(self, cpu_suspend, cpu_resume, cpu_shutdown))
    532 		aprint_error_dev(self, "couldn't establish power handler\n");
    533 
    534 #ifdef MULTIPROCESSOR
    535 	if (mp_verbose) {
    536 		struct lwp *l = ci->ci_data.cpu_idlelwp;
    537 		struct pcb *pcb = lwp_getpcb(l);
    538 
    539 		aprint_verbose_dev(self,
    540 		    "idle lwp at %p, idle sp at %p\n",
    541 		    l,
    542 #ifdef i386
    543 		    (void *)pcb->pcb_esp
    544 #else
    545 		    (void *)pcb->pcb_rsp
    546 #endif
    547 		);
    548 	}
    549 #endif
    550 
    551 	/*
    552 	 * Postpone the "cpufeaturebus" scan.
    553 	 * It is safe to scan the pseudo-bus
    554 	 * only after all CPUs have attached.
    555 	 */
    556 	(void)config_defer(self, cpu_defer);
    557 }
    558 
    559 static void
    560 cpu_defer(device_t self)
    561 {
    562 	cpu_rescan(self, NULL, NULL);
    563 }
    564 
    565 static int
    566 cpu_rescan(device_t self, const char *ifattr, const int *locators)
    567 {
    568 	struct cpu_softc *sc = device_private(self);
    569 	struct cpufeature_attach_args cfaa;
    570 	struct cpu_info *ci = sc->sc_info;
    571 
    572 	/*
    573 	 * If we booted with RB_MD1 to disable multiprocessor, the
    574 	 * auto-configuration data still contains the additional
    575 	 * CPUs.   But their initialization was mostly bypassed
    576 	 * during attach, so we have to make sure we don't look at
    577 	 * their featurebus info, since it wasn't retrieved.
    578 	 */
    579 	if (ci == NULL)
    580 		return 0;
    581 
    582 	memset(&cfaa, 0, sizeof(cfaa));
    583 	cfaa.ci = ci;
    584 
    585 	if (ifattr_match(ifattr, "cpufeaturebus")) {
    586 		if (ci->ci_frequency == NULL) {
    587 			cfaa.name = "frequency";
    588 			ci->ci_frequency =
    589 			    config_found(self, &cfaa, NULL,
    590 					 CFARG_IATTR, "cpufeaturebus",
    591 					 CFARG_EOL);
    592 		}
    593 
    594 		if (ci->ci_padlock == NULL) {
    595 			cfaa.name = "padlock";
    596 			ci->ci_padlock =
    597 			    config_found(self, &cfaa, NULL,
    598 					 CFARG_IATTR, "cpufeaturebus",
    599 					 CFARG_EOL);
    600 		}
    601 
    602 		if (ci->ci_temperature == NULL) {
    603 			cfaa.name = "temperature";
    604 			ci->ci_temperature =
    605 			    config_found(self, &cfaa, NULL,
    606 					 CFARG_IATTR, "cpufeaturebus",
    607 					 CFARG_EOL);
    608 		}
    609 
    610 		if (ci->ci_vm == NULL) {
    611 			cfaa.name = "vm";
    612 			ci->ci_vm =
    613 			    config_found(self, &cfaa, NULL,
    614 					 CFARG_IATTR, "cpufeaturebus",
    615 					 CFARG_EOL);
    616 		}
    617 	}
    618 
    619 	return 0;
    620 }
    621 
    622 static void
    623 cpu_childdetached(device_t self, device_t child)
    624 {
    625 	struct cpu_softc *sc = device_private(self);
    626 	struct cpu_info *ci = sc->sc_info;
    627 
    628 	if (ci->ci_frequency == child)
    629 		ci->ci_frequency = NULL;
    630 
    631 	if (ci->ci_padlock == child)
    632 		ci->ci_padlock = NULL;
    633 
    634 	if (ci->ci_temperature == child)
    635 		ci->ci_temperature = NULL;
    636 
    637 	if (ci->ci_vm == child)
    638 		ci->ci_vm = NULL;
    639 }
    640 
    641 /*
    642  * Initialize the processor appropriately.
    643  */
    644 
    645 void
    646 cpu_init(struct cpu_info *ci)
    647 {
    648 	extern int x86_fpu_save;
    649 	uint32_t cr4 = 0;
    650 
    651 	lcr0(rcr0() | CR0_WP);
    652 
    653 	/* If global TLB caching is supported, enable it */
    654 	if (cpu_feature[0] & CPUID_PGE)
    655 		cr4 |= CR4_PGE;
    656 
    657 	/*
    658 	 * If we have FXSAVE/FXRESTOR, use them.
    659 	 */
    660 	if (cpu_feature[0] & CPUID_FXSR) {
    661 		cr4 |= CR4_OSFXSR;
    662 
    663 		/*
    664 		 * If we have SSE/SSE2, enable XMM exceptions.
    665 		 */
    666 		if (cpu_feature[0] & (CPUID_SSE|CPUID_SSE2))
    667 			cr4 |= CR4_OSXMMEXCPT;
    668 	}
    669 
    670 	/* If xsave is supported, enable it */
    671 	if (cpu_feature[1] & CPUID2_XSAVE)
    672 		cr4 |= CR4_OSXSAVE;
    673 
    674 	/* If SMEP is supported, enable it */
    675 	if (cpu_feature[5] & CPUID_SEF_SMEP)
    676 		cr4 |= CR4_SMEP;
    677 
    678 	/* If SMAP is supported, enable it */
    679 	if (cpu_feature[5] & CPUID_SEF_SMAP)
    680 		cr4 |= CR4_SMAP;
    681 
    682 #ifdef SVS
    683 	/* If PCID is supported, enable it */
    684 	if (svs_pcid)
    685 		cr4 |= CR4_PCIDE;
    686 #endif
    687 
    688 	if (cr4) {
    689 		cr4 |= rcr4();
    690 		lcr4(cr4);
    691 	}
    692 
    693 	/*
    694 	 * Changing CR4 register may change cpuid values. For example, setting
    695 	 * CR4_OSXSAVE sets CPUID2_OSXSAVE. The CPUID2_OSXSAVE is in
    696 	 * ci_feat_val[1], so update it.
    697 	 * XXX Other than ci_feat_val[1] might be changed.
    698 	 */
    699 	if (cpuid_level >= 1) {
    700 		u_int descs[4];
    701 
    702 		x86_cpuid(1, descs);
    703 		ci->ci_feat_val[1] = descs[2];
    704 	}
    705 
    706 	if (x86_fpu_save >= FPU_SAVE_FXSAVE) {
    707 		fpuinit_mxcsr_mask();
    708 	}
    709 
    710 	/* If xsave is enabled, enable all fpu features */
    711 	if (cr4 & CR4_OSXSAVE)
    712 		wrxcr(0, x86_xsave_features & XCR0_FPU);
    713 
    714 #ifdef MTRR
    715 	/*
    716 	 * On a P6 or above, initialize MTRR's if the hardware supports them.
    717 	 */
    718 	if (cpu_feature[0] & CPUID_MTRR) {
    719 		if ((ci->ci_flags & CPUF_AP) == 0)
    720 			i686_mtrr_init_first();
    721 		mtrr_init_cpu(ci);
    722 	}
    723 
    724 #ifdef i386
    725 	if (strcmp((char *)(ci->ci_vendor), "AuthenticAMD") == 0) {
    726 		/*
    727 		 * Must be a K6-2 Step >= 7 or a K6-III.
    728 		 */
    729 		if (CPUID_TO_FAMILY(ci->ci_signature) == 5) {
    730 			if (CPUID_TO_MODEL(ci->ci_signature) > 8 ||
    731 			    (CPUID_TO_MODEL(ci->ci_signature) == 8 &&
    732 			     CPUID_TO_STEPPING(ci->ci_signature) >= 7)) {
    733 				mtrr_funcs = &k6_mtrr_funcs;
    734 				k6_mtrr_init_first();
    735 				mtrr_init_cpu(ci);
    736 			}
    737 		}
    738 	}
    739 #endif	/* i386 */
    740 #endif /* MTRR */
    741 
    742 	if (ci != &cpu_info_primary) {
    743 		/* Synchronize TSC */
    744 		atomic_or_32(&ci->ci_flags, CPUF_RUNNING);
    745 		tsc_sync_ap(ci);
    746 	} else {
    747 		atomic_or_32(&ci->ci_flags, CPUF_RUNNING);
    748 	}
    749 }
    750 
    751 #ifdef MULTIPROCESSOR
    752 void
    753 cpu_boot_secondary_processors(void)
    754 {
    755 	struct cpu_info *ci;
    756 	kcpuset_t *cpus;
    757 	u_long i;
    758 
    759 	/* Now that we know the number of CPUs, patch the text segment. */
    760 	x86_patch(false);
    761 
    762 #if NACPICA > 0
    763 	/* Finished with NUMA info for now. */
    764 	acpisrat_exit();
    765 #endif
    766 
    767 	kcpuset_create(&cpus, true);
    768 	kcpuset_set(cpus, cpu_index(curcpu()));
    769 	for (i = 0; i < maxcpus; i++) {
    770 		ci = cpu_lookup(i);
    771 		if (ci == NULL)
    772 			continue;
    773 		if (ci->ci_data.cpu_idlelwp == NULL)
    774 			continue;
    775 		if ((ci->ci_flags & CPUF_PRESENT) == 0)
    776 			continue;
    777 		if (ci->ci_flags & (CPUF_BSP|CPUF_SP|CPUF_PRIMARY))
    778 			continue;
    779 		cpu_boot_secondary(ci);
    780 		kcpuset_set(cpus, cpu_index(ci));
    781 	}
    782 	while (!kcpuset_match(cpus, kcpuset_running))
    783 		;
    784 	kcpuset_destroy(cpus);
    785 
    786 	x86_mp_online = true;
    787 
    788 	/* Now that we know about the TSC, attach the timecounter. */
    789 	tsc_tc_init();
    790 }
    791 #endif
    792 
    793 static void
    794 cpu_init_idle_lwp(struct cpu_info *ci)
    795 {
    796 	struct lwp *l = ci->ci_data.cpu_idlelwp;
    797 	struct pcb *pcb = lwp_getpcb(l);
    798 
    799 	pcb->pcb_cr0 = rcr0();
    800 }
    801 
    802 void
    803 cpu_init_idle_lwps(void)
    804 {
    805 	struct cpu_info *ci;
    806 	u_long i;
    807 
    808 	for (i = 0; i < maxcpus; i++) {
    809 		ci = cpu_lookup(i);
    810 		if (ci == NULL)
    811 			continue;
    812 		if (ci->ci_data.cpu_idlelwp == NULL)
    813 			continue;
    814 		if ((ci->ci_flags & CPUF_PRESENT) == 0)
    815 			continue;
    816 		cpu_init_idle_lwp(ci);
    817 	}
    818 }
    819 
    820 #ifdef MULTIPROCESSOR
    821 void
    822 cpu_start_secondary(struct cpu_info *ci)
    823 {
    824 	u_long psl;
    825 	int i;
    826 
    827 #if NLAPIC > 0
    828 	paddr_t mp_pdirpa;
    829 	mp_pdirpa = pmap_init_tmp_pgtbl(mp_trampoline_paddr);
    830 	cpu_copy_trampoline(mp_pdirpa);
    831 #endif
    832 
    833 	atomic_or_32(&ci->ci_flags, CPUF_AP);
    834 	ci->ci_curlwp = ci->ci_data.cpu_idlelwp;
    835 	if (CPU_STARTUP(ci, mp_trampoline_paddr) != 0) {
    836 		return;
    837 	}
    838 
    839 	/*
    840 	 * Wait for it to become ready.   Setting cpu_starting opens the
    841 	 * initial gate and allows the AP to start soft initialization.
    842 	 */
    843 	KASSERT(cpu_starting == NULL);
    844 	cpu_starting = ci;
    845 	for (i = 100000; (!(ci->ci_flags & CPUF_PRESENT)) && i > 0; i--) {
    846 		delay_func(10);
    847 	}
    848 
    849 	if ((ci->ci_flags & CPUF_PRESENT) == 0) {
    850 		aprint_error_dev(ci->ci_dev, "failed to become ready\n");
    851 #if defined(MPDEBUG) && defined(DDB)
    852 		printf("dropping into debugger; continue from here to resume boot\n");
    853 		Debugger();
    854 #endif
    855 	} else {
    856 		/*
    857 		 * Synchronize time stamp counters. Invalidate cache and do
    858 		 * twice (in tsc_sync_bp) to minimize possible cache effects.
    859 		 * Disable interrupts to try and rule out any external
    860 		 * interference.
    861 		 */
    862 		psl = x86_read_psl();
    863 		x86_disable_intr();
    864 		tsc_sync_bp(ci);
    865 		x86_write_psl(psl);
    866 	}
    867 
    868 	CPU_START_CLEANUP(ci);
    869 	cpu_starting = NULL;
    870 }
    871 
    872 void
    873 cpu_boot_secondary(struct cpu_info *ci)
    874 {
    875 	int64_t drift;
    876 	u_long psl;
    877 	int i;
    878 
    879 	atomic_or_32(&ci->ci_flags, CPUF_GO);
    880 	for (i = 100000; (!(ci->ci_flags & CPUF_RUNNING)) && i > 0; i--) {
    881 		delay_func(10);
    882 	}
    883 	if ((ci->ci_flags & CPUF_RUNNING) == 0) {
    884 		aprint_error_dev(ci->ci_dev, "failed to start\n");
    885 #if defined(MPDEBUG) && defined(DDB)
    886 		printf("dropping into debugger; continue from here to resume boot\n");
    887 		Debugger();
    888 #endif
    889 	} else {
    890 		/* Synchronize TSC again, check for drift. */
    891 		drift = ci->ci_data.cpu_cc_skew;
    892 		psl = x86_read_psl();
    893 		x86_disable_intr();
    894 		tsc_sync_bp(ci);
    895 		x86_write_psl(psl);
    896 		drift -= ci->ci_data.cpu_cc_skew;
    897 		aprint_debug_dev(ci->ci_dev, "TSC skew=%lld drift=%lld\n",
    898 		    (long long)ci->ci_data.cpu_cc_skew, (long long)drift);
    899 		tsc_sync_drift(drift);
    900 	}
    901 }
    902 
    903 /*
    904  * The CPU ends up here when it's ready to run.
    905  * This is called from code in mptramp.s; at this point, we are running
    906  * in the idle pcb/idle stack of the new CPU.  When this function returns,
    907  * this processor will enter the idle loop and start looking for work.
    908  */
    909 void
    910 cpu_hatch(void *v)
    911 {
    912 	struct cpu_info *ci = (struct cpu_info *)v;
    913 	struct pcb *pcb;
    914 	int s, i;
    915 
    916 	/* ------------------------------------------------------------- */
    917 
    918 	/*
    919 	 * This section of code must be compiled with SSP disabled, to
    920 	 * prevent a race against cpu0. See sys/conf/ssp.mk.
    921 	 */
    922 
    923 	cpu_init_msrs(ci, true);
    924 	cpu_probe(ci);
    925 	cpu_speculation_init(ci);
    926 #if NHYPERV > 0
    927 	hyperv_init_cpu(ci);
    928 #endif
    929 
    930 	ci->ci_data.cpu_cc_freq = cpu_info_primary.ci_data.cpu_cc_freq;
    931 	/* cpu_get_tsc_freq(ci); */
    932 
    933 	KDASSERT((ci->ci_flags & CPUF_PRESENT) == 0);
    934 
    935 	/*
    936 	 * Synchronize the TSC for the first time. Note that interrupts are
    937 	 * off at this point.
    938 	 */
    939 	atomic_or_32(&ci->ci_flags, CPUF_PRESENT);
    940 	tsc_sync_ap(ci);
    941 
    942 	/* ------------------------------------------------------------- */
    943 
    944 	/*
    945 	 * Wait to be brought online.
    946 	 *
    947 	 * Use MONITOR/MWAIT if available. These instructions put the CPU in
    948 	 * a low consumption mode (C-state), and if the TSC is not invariant,
    949 	 * this causes the TSC to drift. We want this to happen, so that we
    950 	 * can later detect (in tsc_tc_init) any abnormal drift with invariant
    951 	 * TSCs. That's just for safety; by definition such drifts should
    952 	 * never occur with invariant TSCs.
    953 	 *
    954 	 * If not available, try PAUSE. We'd like to use HLT, but we have
    955 	 * interrupts off.
    956 	 */
    957 	while ((ci->ci_flags & CPUF_GO) == 0) {
    958 		if ((cpu_feature[1] & CPUID2_MONITOR) != 0) {
    959 			x86_monitor(&ci->ci_flags, 0, 0);
    960 			if ((ci->ci_flags & CPUF_GO) != 0) {
    961 				continue;
    962 			}
    963 			x86_mwait(0, 0);
    964 		} else {
    965 	/*
    966 	 * XXX The loop repetition count could be a lot higher, but
    967 	 * XXX currently qemu emulator takes a _very_long_time_ to
    968 	 * XXX execute the pause instruction.  So for now, use a low
    969 	 * XXX value to allow the cpu to hatch before timing out.
    970 	 */
    971 			for (i = 50; i != 0; i--) {
    972 				x86_pause();
    973 			}
    974 		}
    975 	}
    976 
    977 	/* Because the text may have been patched in x86_patch(). */
    978 	wbinvd();
    979 	x86_flush();
    980 	tlbflushg();
    981 
    982 	KASSERT((ci->ci_flags & CPUF_RUNNING) == 0);
    983 
    984 #ifdef PAE
    985 	pd_entry_t * l3_pd = ci->ci_pae_l3_pdir;
    986 	for (i = 0 ; i < PDP_SIZE; i++) {
    987 		l3_pd[i] = pmap_kernel()->pm_pdirpa[i] | PTE_P;
    988 	}
    989 	lcr3(ci->ci_pae_l3_pdirpa);
    990 #else
    991 	lcr3(pmap_pdirpa(pmap_kernel(), 0));
    992 #endif
    993 
    994 	pcb = lwp_getpcb(curlwp);
    995 	pcb->pcb_cr3 = rcr3();
    996 	pcb = lwp_getpcb(ci->ci_data.cpu_idlelwp);
    997 	lcr0(pcb->pcb_cr0);
    998 
    999 	cpu_init_idt(ci);
   1000 	gdt_init_cpu(ci);
   1001 #if NLAPIC > 0
   1002 	lapic_enable();
   1003 	lapic_set_lvt();
   1004 #endif
   1005 
   1006 	fpuinit(ci);
   1007 	lldt(GSYSSEL(GLDT_SEL, SEL_KPL));
   1008 	ltr(ci->ci_tss_sel);
   1009 
   1010 	/*
   1011 	 * cpu_init will re-synchronize the TSC, and will detect any abnormal
   1012 	 * drift that would have been caused by the use of MONITOR/MWAIT
   1013 	 * above.
   1014 	 */
   1015 	cpu_init(ci);
   1016 #ifdef XENPVHVM
   1017 	xen_hvm_init_cpu(ci);
   1018 #endif
   1019 	(*x86_initclock_func)();
   1020 	cpu_get_tsc_freq(ci);
   1021 
   1022 	s = splhigh();
   1023 #if NLAPIC > 0
   1024 	lapic_write_tpri(0);
   1025 #endif
   1026 	x86_enable_intr();
   1027 	splx(s);
   1028 	x86_errata();
   1029 
   1030 	aprint_debug_dev(ci->ci_dev, "running\n");
   1031 
   1032 	kcsan_cpu_init(ci);
   1033 
   1034 	idle_loop(NULL);
   1035 	KASSERT(false);
   1036 }
   1037 #endif
   1038 
   1039 #if defined(DDB)
   1040 
   1041 #include <ddb/db_output.h>
   1042 #include <machine/db_machdep.h>
   1043 
   1044 /*
   1045  * Dump CPU information from ddb.
   1046  */
   1047 void
   1048 cpu_debug_dump(void)
   1049 {
   1050 	struct cpu_info *ci;
   1051 	CPU_INFO_ITERATOR cii;
   1052 	const char sixtyfour64space[] =
   1053 #ifdef _LP64
   1054 			   "        "
   1055 #endif
   1056 			   "";
   1057 
   1058 	db_printf("addr		%sdev	id	flags	ipis	spl curlwp 		"
   1059 		  "\n", sixtyfour64space);
   1060 	for (CPU_INFO_FOREACH(cii, ci)) {
   1061 		db_printf("%p	%s	%ld	%x	%x	%d  %10p\n",
   1062 		    ci,
   1063 		    ci->ci_dev == NULL ? "BOOT" : device_xname(ci->ci_dev),
   1064 		    (long)ci->ci_cpuid,
   1065 		    ci->ci_flags, ci->ci_ipis, ci->ci_ilevel,
   1066 		    ci->ci_curlwp);
   1067 	}
   1068 }
   1069 #endif
   1070 
   1071 #ifdef MULTIPROCESSOR
   1072 #if NLAPIC > 0
   1073 static void
   1074 cpu_copy_trampoline(paddr_t pdir_pa)
   1075 {
   1076 	extern uint32_t nox_flag;
   1077 	extern u_char cpu_spinup_trampoline[];
   1078 	extern u_char cpu_spinup_trampoline_end[];
   1079 	vaddr_t mp_trampoline_vaddr;
   1080 	struct {
   1081 		uint32_t large;
   1082 		uint32_t nox;
   1083 		uint32_t pdir;
   1084 	} smp_data;
   1085 	CTASSERT(sizeof(smp_data) == 3 * 4);
   1086 
   1087 	smp_data.large = (pmap_largepages != 0);
   1088 	smp_data.nox = nox_flag;
   1089 	smp_data.pdir = (uint32_t)(pdir_pa & 0xFFFFFFFF);
   1090 
   1091 	/* Enter the physical address */
   1092 	mp_trampoline_vaddr = uvm_km_alloc(kernel_map, PAGE_SIZE, 0,
   1093 	    UVM_KMF_VAONLY);
   1094 	pmap_kenter_pa(mp_trampoline_vaddr, mp_trampoline_paddr,
   1095 	    VM_PROT_READ | VM_PROT_WRITE, 0);
   1096 	pmap_update(pmap_kernel());
   1097 
   1098 	/* Copy boot code */
   1099 	memcpy((void *)mp_trampoline_vaddr,
   1100 	    cpu_spinup_trampoline,
   1101 	    cpu_spinup_trampoline_end - cpu_spinup_trampoline);
   1102 
   1103 	/* Copy smp_data at the end */
   1104 	memcpy((void *)(mp_trampoline_vaddr + PAGE_SIZE - sizeof(smp_data)),
   1105 	    &smp_data, sizeof(smp_data));
   1106 
   1107 	pmap_kremove(mp_trampoline_vaddr, PAGE_SIZE);
   1108 	pmap_update(pmap_kernel());
   1109 	uvm_km_free(kernel_map, mp_trampoline_vaddr, PAGE_SIZE, UVM_KMF_VAONLY);
   1110 }
   1111 #endif
   1112 
   1113 int
   1114 mp_cpu_start(struct cpu_info *ci, paddr_t target)
   1115 {
   1116 	int error;
   1117 
   1118 	/*
   1119 	 * Bootstrap code must be addressable in real mode
   1120 	 * and it must be page aligned.
   1121 	 */
   1122 	KASSERT(target < 0x10000 && target % PAGE_SIZE == 0);
   1123 
   1124 	/*
   1125 	 * "The BSP must initialize CMOS shutdown code to 0Ah ..."
   1126 	 */
   1127 
   1128 	outb(IO_RTC, NVRAM_RESET);
   1129 	outb(IO_RTC+1, NVRAM_RESET_JUMP);
   1130 
   1131 #if NLAPIC > 0
   1132 	/*
   1133 	 * "and the warm reset vector (DWORD based at 40:67) to point
   1134 	 * to the AP startup code ..."
   1135 	 */
   1136 	unsigned short dwordptr[2];
   1137 	dwordptr[0] = 0;
   1138 	dwordptr[1] = target >> 4;
   1139 
   1140 	memcpy((uint8_t *)cmos_data_mapping + 0x467, dwordptr, 4);
   1141 #endif
   1142 
   1143 	if ((cpu_feature[0] & CPUID_APIC) == 0) {
   1144 		aprint_error("mp_cpu_start: CPU does not have APIC\n");
   1145 		return ENODEV;
   1146 	}
   1147 
   1148 	/*
   1149 	 * ... prior to executing the following sequence:".  We'll also add in
   1150 	 * local cache flush, in case the BIOS has left the AP with its cache
   1151 	 * disabled.  It may not be able to cope with MP coherency.
   1152 	 */
   1153 	wbinvd();
   1154 
   1155 	if (ci->ci_flags & CPUF_AP) {
   1156 		error = x86_ipi_init(ci->ci_cpuid);
   1157 		if (error != 0) {
   1158 			aprint_error_dev(ci->ci_dev, "%s: IPI not taken (1)\n",
   1159 			    __func__);
   1160 			return error;
   1161 		}
   1162 		delay_func(10000);
   1163 
   1164 		error = x86_ipi_startup(ci->ci_cpuid, target / PAGE_SIZE);
   1165 		if (error != 0) {
   1166 			aprint_error_dev(ci->ci_dev, "%s: IPI not taken (2)\n",
   1167 			    __func__);
   1168 			return error;
   1169 		}
   1170 		delay_func(200);
   1171 
   1172 		error = x86_ipi_startup(ci->ci_cpuid, target / PAGE_SIZE);
   1173 		if (error != 0) {
   1174 			aprint_error_dev(ci->ci_dev, "%s: IPI not taken (3)\n",
   1175 			    __func__);
   1176 			return error;
   1177 		}
   1178 		delay_func(200);
   1179 	}
   1180 
   1181 	return 0;
   1182 }
   1183 
   1184 void
   1185 mp_cpu_start_cleanup(struct cpu_info *ci)
   1186 {
   1187 	/*
   1188 	 * Ensure the NVRAM reset byte contains something vaguely sane.
   1189 	 */
   1190 
   1191 	outb(IO_RTC, NVRAM_RESET);
   1192 	outb(IO_RTC+1, NVRAM_RESET_RST);
   1193 }
   1194 #endif
   1195 
   1196 #ifdef __x86_64__
   1197 typedef void (vector)(void);
   1198 extern vector Xsyscall, Xsyscall32, Xsyscall_svs;
   1199 #endif
   1200 
   1201 void
   1202 cpu_init_msrs(struct cpu_info *ci, bool full)
   1203 {
   1204 #ifdef __x86_64__
   1205 	wrmsr(MSR_STAR,
   1206 	    ((uint64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
   1207 	    ((uint64_t)LSEL(LSYSRETBASE_SEL, SEL_UPL) << 48));
   1208 	wrmsr(MSR_LSTAR, (uint64_t)Xsyscall);
   1209 	wrmsr(MSR_CSTAR, (uint64_t)Xsyscall32);
   1210 	wrmsr(MSR_SFMASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D|PSL_AC);
   1211 
   1212 #ifdef SVS
   1213 	if (svs_enabled)
   1214 		wrmsr(MSR_LSTAR, (uint64_t)Xsyscall_svs);
   1215 #endif
   1216 
   1217 	if (full) {
   1218 		wrmsr(MSR_FSBASE, 0);
   1219 		wrmsr(MSR_GSBASE, (uint64_t)ci);
   1220 		wrmsr(MSR_KERNELGSBASE, 0);
   1221 	}
   1222 #endif	/* __x86_64__ */
   1223 
   1224 	if (cpu_feature[2] & CPUID_NOX)
   1225 		wrmsr(MSR_EFER, rdmsr(MSR_EFER) | EFER_NXE);
   1226 }
   1227 
   1228 void
   1229 cpu_offline_md(void)
   1230 {
   1231 	return;
   1232 }
   1233 
   1234 /* XXX joerg restructure and restart CPUs individually */
   1235 static bool
   1236 cpu_stop(device_t dv)
   1237 {
   1238 	struct cpu_softc *sc = device_private(dv);
   1239 	struct cpu_info *ci = sc->sc_info;
   1240 	int err;
   1241 
   1242 	KASSERT((ci->ci_flags & CPUF_PRESENT) != 0);
   1243 
   1244 	if (CPU_IS_PRIMARY(ci))
   1245 		return true;
   1246 
   1247 	if (ci->ci_data.cpu_idlelwp == NULL)
   1248 		return true;
   1249 
   1250 	sc->sc_wasonline = !(ci->ci_schedstate.spc_flags & SPCF_OFFLINE);
   1251 
   1252 	if (sc->sc_wasonline) {
   1253 		mutex_enter(&cpu_lock);
   1254 		err = cpu_setstate(ci, false);
   1255 		mutex_exit(&cpu_lock);
   1256 
   1257 		if (err != 0)
   1258 			return false;
   1259 	}
   1260 
   1261 	return true;
   1262 }
   1263 
   1264 static bool
   1265 cpu_suspend(device_t dv, const pmf_qual_t *qual)
   1266 {
   1267 	struct cpu_softc *sc = device_private(dv);
   1268 	struct cpu_info *ci = sc->sc_info;
   1269 
   1270 	if ((ci->ci_flags & CPUF_PRESENT) == 0)
   1271 		return true;
   1272 	else {
   1273 		cpufreq_suspend(ci);
   1274 	}
   1275 
   1276 	return cpu_stop(dv);
   1277 }
   1278 
   1279 static bool
   1280 cpu_resume(device_t dv, const pmf_qual_t *qual)
   1281 {
   1282 	struct cpu_softc *sc = device_private(dv);
   1283 	struct cpu_info *ci = sc->sc_info;
   1284 	int err = 0;
   1285 
   1286 	if ((ci->ci_flags & CPUF_PRESENT) == 0)
   1287 		return true;
   1288 
   1289 	if (CPU_IS_PRIMARY(ci))
   1290 		goto out;
   1291 
   1292 	if (ci->ci_data.cpu_idlelwp == NULL)
   1293 		goto out;
   1294 
   1295 	if (sc->sc_wasonline) {
   1296 		mutex_enter(&cpu_lock);
   1297 		err = cpu_setstate(ci, true);
   1298 		mutex_exit(&cpu_lock);
   1299 	}
   1300 
   1301 out:
   1302 	if (err != 0)
   1303 		return false;
   1304 
   1305 	cpufreq_resume(ci);
   1306 
   1307 	return true;
   1308 }
   1309 
   1310 static bool
   1311 cpu_shutdown(device_t dv, int how)
   1312 {
   1313 	struct cpu_softc *sc = device_private(dv);
   1314 	struct cpu_info *ci = sc->sc_info;
   1315 
   1316 	if ((ci->ci_flags & CPUF_BSP) != 0)
   1317 		return false;
   1318 
   1319 	if ((ci->ci_flags & CPUF_PRESENT) == 0)
   1320 		return true;
   1321 
   1322 	return cpu_stop(dv);
   1323 }
   1324 
   1325 /* Get the TSC frequency and set it to ci->ci_data.cpu_cc_freq. */
   1326 void
   1327 cpu_get_tsc_freq(struct cpu_info *ci)
   1328 {
   1329 	uint64_t freq = 0, freq_from_cpuid, t0, t1;
   1330 	int64_t overhead;
   1331 
   1332 	if (CPU_IS_PRIMARY(ci) && cpu_hascounter()) {
   1333 		/*
   1334 		 * If it's the first call of this function, try to get TSC
   1335 		 * freq from CPUID by calling cpu_tsc_freq_cpuid().
   1336 		 * The function also set lapic_per_second variable if it's
   1337 		 * known. This is required for Intel's Comet Lake and newer
   1338 		 * processors to set LAPIC timer correctly.
   1339 		 */
   1340 		if (ci->ci_data.cpu_cc_freq == 0)
   1341 			freq = freq_from_cpuid = cpu_tsc_freq_cpuid(ci);
   1342 #if NHPET > 0
   1343 		if (freq == 0)
   1344 			freq = hpet_tsc_freq();
   1345 #endif
   1346 		if (freq == 0) {
   1347 			/*
   1348 			 * Work out the approximate overhead involved below.
   1349 			 * Discard the result of the first go around the
   1350 			 * loop.
   1351 			 */
   1352 			overhead = 0;
   1353 			for (int i = 0; i <= 8; i++) {
   1354 				t0 = cpu_counter();
   1355 				delay_func(0);
   1356 				t1 = cpu_counter();
   1357 				if (i > 0) {
   1358 					overhead += (t1 - t0);
   1359 				}
   1360 			}
   1361 			overhead >>= 3;
   1362 
   1363 			/* Now do the calibration. */
   1364 			t0 = cpu_counter();
   1365 			delay_func(100000);
   1366 			t1 = cpu_counter();
   1367 			freq = (t1 - t0 - overhead) * 10;
   1368 		}
   1369 		if (ci->ci_data.cpu_cc_freq != 0) {
   1370 			freq_from_cpuid = cpu_tsc_freq_cpuid(ci);
   1371 			if ((freq_from_cpuid != 0)
   1372 			    && (freq != freq_from_cpuid))
   1373 				aprint_verbose_dev(ci->ci_dev, "TSC freq "
   1374 				    "calibrated %" PRIu64 " Hz\n", freq);
   1375 		}
   1376 	} else {
   1377 		freq = cpu_info_primary.ci_data.cpu_cc_freq;
   1378 	}
   1379 
   1380 	ci->ci_data.cpu_cc_freq = freq;
   1381 }
   1382 
   1383 void
   1384 x86_cpu_idle_mwait(void)
   1385 {
   1386 	struct cpu_info *ci = curcpu();
   1387 
   1388 	KASSERT(ci->ci_ilevel == IPL_NONE);
   1389 
   1390 	x86_monitor(&ci->ci_want_resched, 0, 0);
   1391 	if (__predict_false(ci->ci_want_resched)) {
   1392 		return;
   1393 	}
   1394 	x86_mwait(0, 0);
   1395 }
   1396 
   1397 void
   1398 x86_cpu_idle_halt(void)
   1399 {
   1400 	struct cpu_info *ci = curcpu();
   1401 
   1402 	KASSERT(ci->ci_ilevel == IPL_NONE);
   1403 
   1404 	x86_disable_intr();
   1405 	if (!__predict_false(ci->ci_want_resched)) {
   1406 		x86_stihlt();
   1407 	} else {
   1408 		x86_enable_intr();
   1409 	}
   1410 }
   1411 
   1412 /*
   1413  * Loads pmap for the current CPU.
   1414  */
   1415 void
   1416 cpu_load_pmap(struct pmap *pmap, struct pmap *oldpmap)
   1417 {
   1418 #ifdef SVS
   1419 	if (svs_enabled) {
   1420 		svs_pdir_switch(pmap);
   1421 	}
   1422 #endif
   1423 
   1424 #ifdef PAE
   1425 	struct cpu_info *ci = curcpu();
   1426 	bool interrupts_enabled;
   1427 	pd_entry_t *l3_pd = ci->ci_pae_l3_pdir;
   1428 	int i;
   1429 
   1430 	/*
   1431 	 * disable interrupts to block TLB shootdowns, which can reload cr3.
   1432 	 * while this doesn't block NMIs, it's probably ok as NMIs unlikely
   1433 	 * reload cr3.
   1434 	 */
   1435 	interrupts_enabled = (x86_read_flags() & PSL_I) != 0;
   1436 	if (interrupts_enabled)
   1437 		x86_disable_intr();
   1438 
   1439 	for (i = 0 ; i < PDP_SIZE; i++) {
   1440 		l3_pd[i] = pmap->pm_pdirpa[i] | PTE_P;
   1441 	}
   1442 
   1443 	if (interrupts_enabled)
   1444 		x86_enable_intr();
   1445 	tlbflush();
   1446 #else
   1447 	lcr3(pmap_pdirpa(pmap, 0));
   1448 #endif
   1449 }
   1450 
   1451 /*
   1452  * Notify all other cpus to halt.
   1453  */
   1454 
   1455 void
   1456 cpu_broadcast_halt(void)
   1457 {
   1458 	x86_broadcast_ipi(X86_IPI_HALT);
   1459 }
   1460 
   1461 /*
   1462  * Send a dummy ipi to a cpu to force it to run splraise()/spllower(),
   1463  * and trigger an AST on the running LWP.
   1464  */
   1465 
   1466 void
   1467 cpu_kick(struct cpu_info *ci)
   1468 {
   1469 	x86_send_ipi(ci, X86_IPI_AST);
   1470 }
   1471