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