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