Home | History | Annotate | Line # | Download | only in x86
cpu.c revision 1.87
      1 /*	$NetBSD: cpu.c,v 1.87 2011/02/26 14:43:18 jruoho Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2000, 2006, 2007, 2008 The 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.87 2011/02/26 14:43:18 jruoho Exp $");
     66 
     67 #include "opt_ddb.h"
     68 #include "opt_mpbios.h"		/* for MPDEBUG */
     69 #include "opt_mtrr.h"
     70 
     71 #include "lapic.h"
     72 #include "ioapic.h"
     73 
     74 #ifdef i386
     75 #include "npx.h"
     76 #endif
     77 
     78 #include <sys/param.h>
     79 #include <sys/proc.h>
     80 #include <sys/systm.h>
     81 #include <sys/device.h>
     82 #include <sys/kmem.h>
     83 #include <sys/cpu.h>
     84 #include <sys/atomic.h>
     85 #include <sys/reboot.h>
     86 
     87 #include <uvm/uvm.h>
     88 
     89 #include <machine/cpufunc.h>
     90 #include <machine/cpuvar.h>
     91 #include <machine/pmap.h>
     92 #include <machine/vmparam.h>
     93 #include <machine/mpbiosvar.h>
     94 #include <machine/pcb.h>
     95 #include <machine/specialreg.h>
     96 #include <machine/segments.h>
     97 #include <machine/gdt.h>
     98 #include <machine/mtrr.h>
     99 #include <machine/pio.h>
    100 #include <machine/cpu_counter.h>
    101 
    102 #ifdef i386
    103 #include <machine/tlog.h>
    104 #endif
    105 
    106 #include <machine/apicvar.h>
    107 #include <machine/i82489reg.h>
    108 #include <machine/i82489var.h>
    109 
    110 #include <dev/ic/mc146818reg.h>
    111 #include <i386/isa/nvram.h>
    112 #include <dev/isa/isareg.h>
    113 
    114 #include "tsc.h"
    115 
    116 #if MAXCPUS > 32
    117 #error cpu_info contains 32bit bitmasks
    118 #endif
    119 
    120 static int	cpu_match(device_t, cfdata_t, void *);
    121 static void	cpu_attach(device_t, device_t, void *);
    122 static void	cpu_defer(device_t);
    123 static int	cpu_rescan(device_t, const char *, const int *);
    124 static void	cpu_childdetached(device_t, device_t);
    125 static bool	cpu_suspend(device_t, const pmf_qual_t *);
    126 static bool	cpu_resume(device_t, const pmf_qual_t *);
    127 static bool	cpu_shutdown(device_t, int);
    128 
    129 struct cpu_softc {
    130 	device_t sc_dev;		/* device tree glue */
    131 	struct cpu_info *sc_info;	/* pointer to CPU info */
    132 	bool sc_wasonline;
    133 };
    134 
    135 int mp_cpu_start(struct cpu_info *, paddr_t);
    136 void mp_cpu_start_cleanup(struct cpu_info *);
    137 const struct cpu_functions mp_cpu_funcs = { mp_cpu_start, NULL,
    138 					    mp_cpu_start_cleanup };
    139 
    140 
    141 CFATTACH_DECL2_NEW(cpu, sizeof(struct cpu_softc),
    142     cpu_match, cpu_attach, NULL, NULL, cpu_rescan, cpu_childdetached);
    143 
    144 /*
    145  * Statically-allocated CPU info for the primary CPU (or the only
    146  * CPU, on uniprocessors).  The CPU info list is initialized to
    147  * point at it.
    148  */
    149 #ifdef TRAPLOG
    150 struct tlog tlog_primary;
    151 #endif
    152 struct cpu_info cpu_info_primary __aligned(CACHE_LINE_SIZE) = {
    153 	.ci_dev = 0,
    154 	.ci_self = &cpu_info_primary,
    155 	.ci_idepth = -1,
    156 	.ci_curlwp = &lwp0,
    157 	.ci_curldt = -1,
    158 #ifdef TRAPLOG
    159 	.ci_tlog_base = &tlog_primary,
    160 #endif /* !TRAPLOG */
    161 };
    162 
    163 struct cpu_info *cpu_info_list = &cpu_info_primary;
    164 
    165 static void	cpu_set_tss_gates(struct cpu_info *);
    166 
    167 #ifdef i386
    168 static void	tss_init(struct i386tss *, void *, void *);
    169 #endif
    170 
    171 static void	cpu_init_idle_lwp(struct cpu_info *);
    172 
    173 uint32_t cpus_attached = 0;
    174 uint32_t cpus_running = 0;
    175 
    176 uint32_t cpu_feature[5]; /* X86 CPUID feature bits
    177 			  *	[0] basic features %edx
    178 			  *	[1] basic features %ecx
    179 			  *	[2] extended features %edx
    180 			  *	[3] extended features %ecx
    181 			  *	[4] VIA padlock features
    182 			  */
    183 
    184 extern char x86_64_doubleflt_stack[];
    185 
    186 bool x86_mp_online;
    187 paddr_t mp_trampoline_paddr = MP_TRAMPOLINE;
    188 static vaddr_t cmos_data_mapping;
    189 struct cpu_info *cpu_starting;
    190 
    191 void    	cpu_hatch(void *);
    192 static void    	cpu_boot_secondary(struct cpu_info *ci);
    193 static void    	cpu_start_secondary(struct cpu_info *ci);
    194 static void	cpu_copy_trampoline(void);
    195 
    196 /*
    197  * Runs once per boot once multiprocessor goo has been detected and
    198  * the local APIC on the boot processor has been mapped.
    199  *
    200  * Called from lapic_boot_init() (from mpbios_scan()).
    201  */
    202 void
    203 cpu_init_first(void)
    204 {
    205 
    206 	cpu_info_primary.ci_cpuid = lapic_cpu_number();
    207 	cpu_copy_trampoline();
    208 
    209 	cmos_data_mapping = uvm_km_alloc(kernel_map, PAGE_SIZE, 0, UVM_KMF_VAONLY);
    210 	if (cmos_data_mapping == 0)
    211 		panic("No KVA for page 0");
    212 	pmap_kenter_pa(cmos_data_mapping, 0, VM_PROT_READ|VM_PROT_WRITE, 0);
    213 	pmap_update(pmap_kernel());
    214 }
    215 
    216 static int
    217 cpu_match(device_t parent, cfdata_t match, void *aux)
    218 {
    219 
    220 	return 1;
    221 }
    222 
    223 static void
    224 cpu_vm_init(struct cpu_info *ci)
    225 {
    226 	int ncolors = 2, i;
    227 
    228 	for (i = CAI_ICACHE; i <= CAI_L2CACHE; i++) {
    229 		struct x86_cache_info *cai;
    230 		int tcolors;
    231 
    232 		cai = &ci->ci_cinfo[i];
    233 
    234 		tcolors = atop(cai->cai_totalsize);
    235 		switch(cai->cai_associativity) {
    236 		case 0xff:
    237 			tcolors = 1; /* fully associative */
    238 			break;
    239 		case 0:
    240 		case 1:
    241 			break;
    242 		default:
    243 			tcolors /= cai->cai_associativity;
    244 		}
    245 		ncolors = max(ncolors, tcolors);
    246 		/*
    247 		 * If the desired number of colors is not a power of
    248 		 * two, it won't be good.  Find the greatest power of
    249 		 * two which is an even divisor of the number of colors,
    250 		 * to preserve even coloring of pages.
    251 		 */
    252 		if (ncolors & (ncolors - 1) ) {
    253 			int try, picked = 1;
    254 			for (try = 1; try < ncolors; try *= 2) {
    255 				if (ncolors % try == 0) picked = try;
    256 			}
    257 			if (picked == 1) {
    258 				panic("desired number of cache colors %d is "
    259 			      	" > 1, but not even!", ncolors);
    260 			}
    261 			ncolors = picked;
    262 		}
    263 	}
    264 
    265 	/*
    266 	 * Knowing the size of the largest cache on this CPU, re-color
    267 	 * our pages.
    268 	 */
    269 	if (ncolors <= uvmexp.ncolors)
    270 		return;
    271 	aprint_debug_dev(ci->ci_dev, "%d page colors\n", ncolors);
    272 	uvm_page_recolor(ncolors);
    273 }
    274 
    275 
    276 static void
    277 cpu_attach(device_t parent, device_t self, void *aux)
    278 {
    279 	struct cpu_softc *sc = device_private(self);
    280 	struct cpu_attach_args *caa = aux;
    281 	struct cpu_info *ci;
    282 	uintptr_t ptr;
    283 	int cpunum = caa->cpu_number;
    284 	static bool again;
    285 
    286 	sc->sc_dev = self;
    287 
    288 	if (cpus_attached == ~0) {
    289 		aprint_error(": increase MAXCPUS\n");
    290 		return;
    291 	}
    292 
    293 	/*
    294 	 * If we're an Application Processor, allocate a cpu_info
    295 	 * structure, otherwise use the primary's.
    296 	 */
    297 	if (caa->cpu_role == CPU_ROLE_AP) {
    298 		if ((boothowto & RB_MD1) != 0) {
    299 			aprint_error(": multiprocessor boot disabled\n");
    300 			if (!pmf_device_register(self, NULL, NULL))
    301 				aprint_error_dev(self,
    302 				    "couldn't establish power handler\n");
    303 			return;
    304 		}
    305 		aprint_naive(": Application Processor\n");
    306 		ptr = (uintptr_t)kmem_zalloc(sizeof(*ci) + CACHE_LINE_SIZE - 1,
    307 		    KM_SLEEP);
    308 		ci = (struct cpu_info *)roundup2(ptr, CACHE_LINE_SIZE);
    309 		ci->ci_curldt = -1;
    310 #ifdef TRAPLOG
    311 		ci->ci_tlog_base = kmem_zalloc(sizeof(struct tlog), KM_SLEEP);
    312 #endif
    313 	} else {
    314 		aprint_naive(": %s Processor\n",
    315 		    caa->cpu_role == CPU_ROLE_SP ? "Single" : "Boot");
    316 		ci = &cpu_info_primary;
    317 		if (cpunum != lapic_cpu_number()) {
    318 			/* XXX should be done earlier. */
    319 			uint32_t reg;
    320 			aprint_verbose("\n");
    321 			aprint_verbose_dev(self, "running CPU at apic %d"
    322 			    " instead of at expected %d", lapic_cpu_number(),
    323 			    cpunum);
    324 			reg = i82489_readreg(LAPIC_ID);
    325 			i82489_writereg(LAPIC_ID, (reg & ~LAPIC_ID_MASK) |
    326 			    (cpunum << LAPIC_ID_SHIFT));
    327 		}
    328 		if (cpunum != lapic_cpu_number()) {
    329 			aprint_error_dev(self, "unable to reset apic id\n");
    330 		}
    331 	}
    332 
    333 	ci->ci_self = ci;
    334 	sc->sc_info = ci;
    335 	ci->ci_dev = self;
    336 	ci->ci_acpiid = caa->cpu_id;
    337 	ci->ci_cpuid = caa->cpu_number;
    338 	ci->ci_func = caa->cpu_func;
    339 
    340 	/* Must be before mi_cpu_attach(). */
    341 	cpu_vm_init(ci);
    342 
    343 	if (caa->cpu_role == CPU_ROLE_AP) {
    344 		int error;
    345 
    346 		error = mi_cpu_attach(ci);
    347 		if (error != 0) {
    348 			aprint_normal("\n");
    349 			aprint_error_dev(self,
    350 			    "mi_cpu_attach failed with %d\n", error);
    351 			return;
    352 		}
    353 		cpu_init_tss(ci);
    354 	} else {
    355 		KASSERT(ci->ci_data.cpu_idlelwp != NULL);
    356 	}
    357 
    358 	ci->ci_cpumask = (1 << cpu_index(ci));
    359 	pmap_reference(pmap_kernel());
    360 	ci->ci_pmap = pmap_kernel();
    361 	ci->ci_tlbstate = TLBSTATE_STALE;
    362 
    363 	/*
    364 	 * Boot processor may not be attached first, but the below
    365 	 * must be done to allow booting other processors.
    366 	 */
    367 	if (!again) {
    368 		atomic_or_32(&ci->ci_flags, CPUF_PRESENT | CPUF_PRIMARY);
    369 		/* Basic init. */
    370 		cpu_intr_init(ci);
    371 		cpu_get_tsc_freq(ci);
    372 		cpu_init(ci);
    373 		cpu_set_tss_gates(ci);
    374 		pmap_cpu_init_late(ci);
    375 		if (caa->cpu_role != CPU_ROLE_SP) {
    376 			/* Enable lapic. */
    377 			lapic_enable();
    378 			lapic_set_lvt();
    379 			lapic_calibrate_timer(ci);
    380 		}
    381 		/* Make sure DELAY() is initialized. */
    382 		DELAY(1);
    383 		again = true;
    384 	}
    385 
    386 	/* further PCB init done later. */
    387 
    388 	switch (caa->cpu_role) {
    389 	case CPU_ROLE_SP:
    390 		atomic_or_32(&ci->ci_flags, CPUF_SP);
    391 		cpu_identify(ci);
    392 		x86_errata();
    393 		x86_cpu_idle_init();
    394 		break;
    395 
    396 	case CPU_ROLE_BP:
    397 		atomic_or_32(&ci->ci_flags, CPUF_BSP);
    398 		cpu_identify(ci);
    399 		x86_errata();
    400 		x86_cpu_idle_init();
    401 		break;
    402 
    403 	case CPU_ROLE_AP:
    404 		/*
    405 		 * report on an AP
    406 		 */
    407 		cpu_intr_init(ci);
    408 		gdt_alloc_cpu(ci);
    409 		cpu_set_tss_gates(ci);
    410 		pmap_cpu_init_early(ci);
    411 		pmap_cpu_init_late(ci);
    412 		cpu_start_secondary(ci);
    413 		if (ci->ci_flags & CPUF_PRESENT) {
    414 			struct cpu_info *tmp;
    415 
    416 			cpu_identify(ci);
    417 			tmp = cpu_info_list;
    418 			while (tmp->ci_next)
    419 				tmp = tmp->ci_next;
    420 
    421 			tmp->ci_next = ci;
    422 		}
    423 		break;
    424 
    425 	default:
    426 		aprint_normal("\n");
    427 		panic("unknown processor type??\n");
    428 	}
    429 
    430 	pat_init(ci);
    431 	atomic_or_32(&cpus_attached, ci->ci_cpumask);
    432 
    433 	if (!pmf_device_register1(self, cpu_suspend, cpu_resume, cpu_shutdown))
    434 		aprint_error_dev(self, "couldn't establish power handler\n");
    435 
    436 	if (mp_verbose) {
    437 		struct lwp *l = ci->ci_data.cpu_idlelwp;
    438 		struct pcb *pcb = lwp_getpcb(l);
    439 
    440 		aprint_verbose_dev(self,
    441 		    "idle lwp at %p, idle sp at %p\n",
    442 		    l,
    443 #ifdef i386
    444 		    (void *)pcb->pcb_esp
    445 #else
    446 		    (void *)pcb->pcb_rsp
    447 #endif
    448 		);
    449 	}
    450 
    451 	(void)config_defer(self, cpu_defer);
    452 }
    453 
    454 static void
    455 cpu_defer(device_t self)
    456 {
    457 	cpu_rescan(self, NULL, NULL);
    458 }
    459 
    460 static int
    461 cpu_rescan(device_t self, const char *ifattr, const int *locators)
    462 {
    463 	struct cpu_softc *sc = device_private(self);
    464 	struct cpufeature_attach_args cfaa;
    465 	struct cpu_info *ci = sc->sc_info;
    466 
    467 	memset(&cfaa, 0, sizeof(cfaa));
    468 	cfaa.ci = ci;
    469 
    470 	if (ifattr_match(ifattr, "cpufeaturebus")) {
    471 
    472 		if (ci->ci_frequency == NULL) {
    473 			cfaa.name = "frequency";
    474 			ci->ci_frequency = config_found_ia(self,
    475 			    "cpufeaturebus", &cfaa, NULL);
    476 		}
    477 
    478 		if (ci->ci_padlock == NULL) {
    479 			cfaa.name = "padlock";
    480 			ci->ci_padlock = config_found_ia(self,
    481 			    "cpufeaturebus", &cfaa, NULL);
    482 		}
    483 
    484 		if (ci->ci_temperature == NULL) {
    485 			cfaa.name = "temperature";
    486 			ci->ci_temperature = config_found_ia(self,
    487 			    "cpufeaturebus", &cfaa, NULL);
    488 		}
    489 	}
    490 
    491 	return 0;
    492 }
    493 
    494 static void
    495 cpu_childdetached(device_t self, device_t child)
    496 {
    497 	struct cpu_softc *sc = device_private(self);
    498 	struct cpu_info *ci = sc->sc_info;
    499 
    500 	if (ci->ci_frequency == child)
    501 		ci->ci_frequency = NULL;
    502 
    503 	if (ci->ci_padlock == child)
    504 		ci->ci_padlock = NULL;
    505 
    506 	if (ci->ci_temperature == child)
    507 		ci->ci_temperature = NULL;
    508 }
    509 
    510 /*
    511  * Initialize the processor appropriately.
    512  */
    513 
    514 void
    515 cpu_init(struct cpu_info *ci)
    516 {
    517 
    518 	lcr0(rcr0() | CR0_WP);
    519 
    520 	/*
    521 	 * On a P6 or above, enable global TLB caching if the
    522 	 * hardware supports it.
    523 	 */
    524 	if (cpu_feature[0] & CPUID_PGE)
    525 		lcr4(rcr4() | CR4_PGE);	/* enable global TLB caching */
    526 
    527 	/*
    528 	 * If we have FXSAVE/FXRESTOR, use them.
    529 	 */
    530 	if (cpu_feature[0] & CPUID_FXSR) {
    531 		lcr4(rcr4() | CR4_OSFXSR);
    532 
    533 		/*
    534 		 * If we have SSE/SSE2, enable XMM exceptions.
    535 		 */
    536 		if (cpu_feature[0] & (CPUID_SSE|CPUID_SSE2))
    537 			lcr4(rcr4() | CR4_OSXMMEXCPT);
    538 	}
    539 
    540 #ifdef MTRR
    541 	/*
    542 	 * On a P6 or above, initialize MTRR's if the hardware supports them.
    543 	 */
    544 	if (cpu_feature[0] & CPUID_MTRR) {
    545 		if ((ci->ci_flags & CPUF_AP) == 0)
    546 			i686_mtrr_init_first();
    547 		mtrr_init_cpu(ci);
    548 	}
    549 
    550 #ifdef i386
    551 	if (strcmp((char *)(ci->ci_vendor), "AuthenticAMD") == 0) {
    552 		/*
    553 		 * Must be a K6-2 Step >= 7 or a K6-III.
    554 		 */
    555 		if (CPUID2FAMILY(ci->ci_signature) == 5) {
    556 			if (CPUID2MODEL(ci->ci_signature) > 8 ||
    557 			    (CPUID2MODEL(ci->ci_signature) == 8 &&
    558 			     CPUID2STEPPING(ci->ci_signature) >= 7)) {
    559 				mtrr_funcs = &k6_mtrr_funcs;
    560 				k6_mtrr_init_first();
    561 				mtrr_init_cpu(ci);
    562 			}
    563 		}
    564 	}
    565 #endif	/* i386 */
    566 #endif /* MTRR */
    567 
    568 	atomic_or_32(&cpus_running, ci->ci_cpumask);
    569 
    570 	if (ci != &cpu_info_primary) {
    571 		/* Synchronize TSC again, and check for drift. */
    572 		wbinvd();
    573 		atomic_or_32(&ci->ci_flags, CPUF_RUNNING);
    574 		tsc_sync_ap(ci);
    575 	} else {
    576 		atomic_or_32(&ci->ci_flags, CPUF_RUNNING);
    577 	}
    578 }
    579 
    580 void
    581 cpu_boot_secondary_processors(void)
    582 {
    583 	struct cpu_info *ci;
    584 	u_long i;
    585 
    586 	/* Now that we know the number of CPUs, patch the text segment. */
    587 	x86_patch(false);
    588 
    589 	for (i=0; i < maxcpus; i++) {
    590 		ci = cpu_lookup(i);
    591 		if (ci == NULL)
    592 			continue;
    593 		if (ci->ci_data.cpu_idlelwp == NULL)
    594 			continue;
    595 		if ((ci->ci_flags & CPUF_PRESENT) == 0)
    596 			continue;
    597 		if (ci->ci_flags & (CPUF_BSP|CPUF_SP|CPUF_PRIMARY))
    598 			continue;
    599 		cpu_boot_secondary(ci);
    600 	}
    601 
    602 	x86_mp_online = true;
    603 
    604 	/* Now that we know about the TSC, attach the timecounter. */
    605 	tsc_tc_init();
    606 
    607 	/* Enable zeroing of pages in the idle loop if we have SSE2. */
    608 	vm_page_zero_enable = ((cpu_feature[0] & CPUID_SSE2) != 0);
    609 }
    610 
    611 static void
    612 cpu_init_idle_lwp(struct cpu_info *ci)
    613 {
    614 	struct lwp *l = ci->ci_data.cpu_idlelwp;
    615 	struct pcb *pcb = lwp_getpcb(l);
    616 
    617 	pcb->pcb_cr0 = rcr0();
    618 }
    619 
    620 void
    621 cpu_init_idle_lwps(void)
    622 {
    623 	struct cpu_info *ci;
    624 	u_long i;
    625 
    626 	for (i = 0; i < maxcpus; i++) {
    627 		ci = cpu_lookup(i);
    628 		if (ci == NULL)
    629 			continue;
    630 		if (ci->ci_data.cpu_idlelwp == NULL)
    631 			continue;
    632 		if ((ci->ci_flags & CPUF_PRESENT) == 0)
    633 			continue;
    634 		cpu_init_idle_lwp(ci);
    635 	}
    636 }
    637 
    638 void
    639 cpu_start_secondary(struct cpu_info *ci)
    640 {
    641 	extern paddr_t mp_pdirpa;
    642 	u_long psl;
    643 	int i;
    644 
    645 	mp_pdirpa = pmap_init_tmp_pgtbl(mp_trampoline_paddr);
    646 	atomic_or_32(&ci->ci_flags, CPUF_AP);
    647 	ci->ci_curlwp = ci->ci_data.cpu_idlelwp;
    648 	if (CPU_STARTUP(ci, mp_trampoline_paddr) != 0) {
    649 		return;
    650 	}
    651 
    652 	/*
    653 	 * Wait for it to become ready.   Setting cpu_starting opens the
    654 	 * initial gate and allows the AP to start soft initialization.
    655 	 */
    656 	KASSERT(cpu_starting == NULL);
    657 	cpu_starting = ci;
    658 	for (i = 100000; (!(ci->ci_flags & CPUF_PRESENT)) && i > 0; i--) {
    659 #ifdef MPDEBUG
    660 		extern int cpu_trace[3];
    661 		static int otrace[3];
    662 		if (memcmp(otrace, cpu_trace, sizeof(otrace)) != 0) {
    663 			aprint_debug_dev(ci->ci_dev, "trace %02x %02x %02x\n",
    664 			    cpu_trace[0], cpu_trace[1], cpu_trace[2]);
    665 			memcpy(otrace, cpu_trace, sizeof(otrace));
    666 		}
    667 #endif
    668 		i8254_delay(10);
    669 	}
    670 
    671 	if ((ci->ci_flags & CPUF_PRESENT) == 0) {
    672 		aprint_error_dev(ci->ci_dev, "failed to become ready\n");
    673 #if defined(MPDEBUG) && defined(DDB)
    674 		printf("dropping into debugger; continue from here to resume boot\n");
    675 		Debugger();
    676 #endif
    677 	} else {
    678 		/*
    679 		 * Synchronize time stamp counters. Invalidate cache and do
    680 		 * twice to try and minimize possible cache effects. Disable
    681 		 * interrupts to try and rule out any external interference.
    682 		 */
    683 		psl = x86_read_psl();
    684 		x86_disable_intr();
    685 		wbinvd();
    686 		tsc_sync_bp(ci);
    687 		x86_write_psl(psl);
    688 	}
    689 
    690 	CPU_START_CLEANUP(ci);
    691 	cpu_starting = NULL;
    692 }
    693 
    694 void
    695 cpu_boot_secondary(struct cpu_info *ci)
    696 {
    697 	int64_t drift;
    698 	u_long psl;
    699 	int i;
    700 
    701 	atomic_or_32(&ci->ci_flags, CPUF_GO);
    702 	for (i = 100000; (!(ci->ci_flags & CPUF_RUNNING)) && i > 0; i--) {
    703 		i8254_delay(10);
    704 	}
    705 	if ((ci->ci_flags & CPUF_RUNNING) == 0) {
    706 		aprint_error_dev(ci->ci_dev, "failed to start\n");
    707 #if defined(MPDEBUG) && defined(DDB)
    708 		printf("dropping into debugger; continue from here to resume boot\n");
    709 		Debugger();
    710 #endif
    711 	} else {
    712 		/* Synchronize TSC again, check for drift. */
    713 		drift = ci->ci_data.cpu_cc_skew;
    714 		psl = x86_read_psl();
    715 		x86_disable_intr();
    716 		wbinvd();
    717 		tsc_sync_bp(ci);
    718 		x86_write_psl(psl);
    719 		drift -= ci->ci_data.cpu_cc_skew;
    720 		aprint_debug_dev(ci->ci_dev, "TSC skew=%lld drift=%lld\n",
    721 		    (long long)ci->ci_data.cpu_cc_skew, (long long)drift);
    722 		tsc_sync_drift(drift);
    723 	}
    724 }
    725 
    726 /*
    727  * The CPU ends up here when its ready to run
    728  * This is called from code in mptramp.s; at this point, we are running
    729  * in the idle pcb/idle stack of the new CPU.  When this function returns,
    730  * this processor will enter the idle loop and start looking for work.
    731  */
    732 void
    733 cpu_hatch(void *v)
    734 {
    735 	struct cpu_info *ci = (struct cpu_info *)v;
    736 	struct pcb *pcb;
    737 	int s, i;
    738 
    739 	cpu_init_msrs(ci, true);
    740 	cpu_probe(ci);
    741 
    742 	ci->ci_data.cpu_cc_freq = cpu_info_primary.ci_data.cpu_cc_freq;
    743 	/* cpu_get_tsc_freq(ci); */
    744 
    745 	KDASSERT((ci->ci_flags & CPUF_PRESENT) == 0);
    746 
    747 	/*
    748 	 * Synchronize time stamp counters.  Invalidate cache and do twice
    749 	 * to try and minimize possible cache effects.  Note that interrupts
    750 	 * are off at this point.
    751 	 */
    752 	wbinvd();
    753 	atomic_or_32(&ci->ci_flags, CPUF_PRESENT);
    754 	tsc_sync_ap(ci);
    755 
    756 	/*
    757 	 * Wait to be brought online.  Use 'monitor/mwait' if available,
    758 	 * in order to make the TSC drift as much as possible. so that
    759 	 * we can detect it later.  If not available, try 'pause'.
    760 	 * We'd like to use 'hlt', but we have interrupts off.
    761 	 */
    762 	while ((ci->ci_flags & CPUF_GO) == 0) {
    763 		if ((cpu_feature[1] & CPUID2_MONITOR) != 0) {
    764 			x86_monitor(&ci->ci_flags, 0, 0);
    765 			if ((ci->ci_flags & CPUF_GO) != 0) {
    766 				continue;
    767 			}
    768 			x86_mwait(0, 0);
    769 		} else {
    770 			for (i = 10000; i != 0; i--) {
    771 				x86_pause();
    772 			}
    773 		}
    774 	}
    775 
    776 	/* Because the text may have been patched in x86_patch(). */
    777 	wbinvd();
    778 	x86_flush();
    779 
    780 	KASSERT((ci->ci_flags & CPUF_RUNNING) == 0);
    781 
    782 #ifdef PAE
    783 	pd_entry_t * l3_pd = ci->ci_pae_l3_pdir;
    784 	for (i = 0 ; i < PDP_SIZE; i++) {
    785 		l3_pd[i] = pmap_kernel()->pm_pdirpa[i] | PG_V;
    786 	}
    787 	lcr3(ci->ci_pae_l3_pdirpa);
    788 #else
    789 	lcr3(pmap_pdirpa(pmap_kernel(), 0));
    790 #endif
    791 
    792 	pcb = lwp_getpcb(curlwp);
    793 	pcb->pcb_cr3 = rcr3();
    794 	pcb = lwp_getpcb(ci->ci_data.cpu_idlelwp);
    795 	lcr0(pcb->pcb_cr0);
    796 
    797 	cpu_init_idt();
    798 	gdt_init_cpu(ci);
    799 	lapic_enable();
    800 	lapic_set_lvt();
    801 	lapic_initclocks();
    802 
    803 #ifdef i386
    804 #if NNPX > 0
    805 	npxinit(ci);
    806 #endif
    807 #else
    808 	fpuinit(ci);
    809 #endif
    810 	lldt(GSYSSEL(GLDT_SEL, SEL_KPL));
    811 	ltr(ci->ci_tss_sel);
    812 
    813 	cpu_init(ci);
    814 	cpu_get_tsc_freq(ci);
    815 
    816 	s = splhigh();
    817 #ifdef i386
    818 	lapic_tpr = 0;
    819 #else
    820 	lcr8(0);
    821 #endif
    822 	x86_enable_intr();
    823 	splx(s);
    824 	x86_errata();
    825 
    826 	aprint_debug_dev(ci->ci_dev, "running\n");
    827 }
    828 
    829 #if defined(DDB)
    830 
    831 #include <ddb/db_output.h>
    832 #include <machine/db_machdep.h>
    833 
    834 /*
    835  * Dump CPU information from ddb.
    836  */
    837 void
    838 cpu_debug_dump(void)
    839 {
    840 	struct cpu_info *ci;
    841 	CPU_INFO_ITERATOR cii;
    842 
    843 	db_printf("addr		dev	id	flags	ipis	curlwp 		fpcurlwp\n");
    844 	for (CPU_INFO_FOREACH(cii, ci)) {
    845 		db_printf("%p	%s	%ld	%x	%x	%10p	%10p\n",
    846 		    ci,
    847 		    ci->ci_dev == NULL ? "BOOT" : device_xname(ci->ci_dev),
    848 		    (long)ci->ci_cpuid,
    849 		    ci->ci_flags, ci->ci_ipis,
    850 		    ci->ci_curlwp,
    851 		    ci->ci_fpcurlwp);
    852 	}
    853 }
    854 #endif
    855 
    856 static void
    857 cpu_copy_trampoline(void)
    858 {
    859 	/*
    860 	 * Copy boot code.
    861 	 */
    862 	extern u_char cpu_spinup_trampoline[];
    863 	extern u_char cpu_spinup_trampoline_end[];
    864 
    865 	vaddr_t mp_trampoline_vaddr;
    866 
    867 	mp_trampoline_vaddr = uvm_km_alloc(kernel_map, PAGE_SIZE, 0,
    868 	    UVM_KMF_VAONLY);
    869 
    870 	pmap_kenter_pa(mp_trampoline_vaddr, mp_trampoline_paddr,
    871 	    VM_PROT_READ | VM_PROT_WRITE, 0);
    872 	pmap_update(pmap_kernel());
    873 	memcpy((void *)mp_trampoline_vaddr,
    874 	    cpu_spinup_trampoline,
    875 	    cpu_spinup_trampoline_end - cpu_spinup_trampoline);
    876 
    877 	pmap_kremove(mp_trampoline_vaddr, PAGE_SIZE);
    878 	pmap_update(pmap_kernel());
    879 	uvm_km_free(kernel_map, mp_trampoline_vaddr, PAGE_SIZE, UVM_KMF_VAONLY);
    880 }
    881 
    882 #ifdef i386
    883 static void
    884 tss_init(struct i386tss *tss, void *stack, void *func)
    885 {
    886 	KASSERT(curcpu()->ci_pmap == pmap_kernel());
    887 
    888 	memset(tss, 0, sizeof *tss);
    889 	tss->tss_esp0 = tss->tss_esp = (int)((char *)stack + USPACE - 16);
    890 	tss->tss_ss0 = GSEL(GDATA_SEL, SEL_KPL);
    891 	tss->__tss_cs = GSEL(GCODE_SEL, SEL_KPL);
    892 	tss->tss_fs = GSEL(GCPU_SEL, SEL_KPL);
    893 	tss->tss_gs = tss->__tss_es = tss->__tss_ds =
    894 	    tss->__tss_ss = GSEL(GDATA_SEL, SEL_KPL);
    895 	/* %cr3 contains the value associated to pmap_kernel */
    896 	tss->tss_cr3 = rcr3();
    897 	tss->tss_esp = (int)((char *)stack + USPACE - 16);
    898 	tss->tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
    899 	tss->__tss_eflags = PSL_MBO | PSL_NT;	/* XXX not needed? */
    900 	tss->__tss_eip = (int)func;
    901 }
    902 
    903 /* XXX */
    904 #define IDTVEC(name)	__CONCAT(X, name)
    905 typedef void (vector)(void);
    906 extern vector IDTVEC(tss_trap08);
    907 #ifdef DDB
    908 extern vector Xintrddbipi;
    909 extern int ddb_vec;
    910 #endif
    911 
    912 static void
    913 cpu_set_tss_gates(struct cpu_info *ci)
    914 {
    915 	struct segment_descriptor sd;
    916 
    917 	ci->ci_doubleflt_stack = (char *)uvm_km_alloc(kernel_map, USPACE, 0,
    918 	    UVM_KMF_WIRED);
    919 	tss_init(&ci->ci_doubleflt_tss, ci->ci_doubleflt_stack,
    920 	    IDTVEC(tss_trap08));
    921 	setsegment(&sd, &ci->ci_doubleflt_tss, sizeof(struct i386tss) - 1,
    922 	    SDT_SYS386TSS, SEL_KPL, 0, 0);
    923 	ci->ci_gdt[GTRAPTSS_SEL].sd = sd;
    924 	setgate(&idt[8], NULL, 0, SDT_SYSTASKGT, SEL_KPL,
    925 	    GSEL(GTRAPTSS_SEL, SEL_KPL));
    926 
    927 #if defined(DDB)
    928 	/*
    929 	 * Set up separate handler for the DDB IPI, so that it doesn't
    930 	 * stomp on a possibly corrupted stack.
    931 	 *
    932 	 * XXX overwriting the gate set in db_machine_init.
    933 	 * Should rearrange the code so that it's set only once.
    934 	 */
    935 	ci->ci_ddbipi_stack = (char *)uvm_km_alloc(kernel_map, USPACE, 0,
    936 	    UVM_KMF_WIRED);
    937 	tss_init(&ci->ci_ddbipi_tss, ci->ci_ddbipi_stack, Xintrddbipi);
    938 
    939 	setsegment(&sd, &ci->ci_ddbipi_tss, sizeof(struct i386tss) - 1,
    940 	    SDT_SYS386TSS, SEL_KPL, 0, 0);
    941 	ci->ci_gdt[GIPITSS_SEL].sd = sd;
    942 
    943 	setgate(&idt[ddb_vec], NULL, 0, SDT_SYSTASKGT, SEL_KPL,
    944 	    GSEL(GIPITSS_SEL, SEL_KPL));
    945 #endif
    946 }
    947 #else
    948 static void
    949 cpu_set_tss_gates(struct cpu_info *ci)
    950 {
    951 
    952 }
    953 #endif	/* i386 */
    954 
    955 int
    956 mp_cpu_start(struct cpu_info *ci, paddr_t target)
    957 {
    958 	unsigned short dwordptr[2];
    959 	int error;
    960 
    961 	/*
    962 	 * Bootstrap code must be addressable in real mode
    963 	 * and it must be page aligned.
    964 	 */
    965 	KASSERT(target < 0x10000 && target % PAGE_SIZE == 0);
    966 
    967 	/*
    968 	 * "The BSP must initialize CMOS shutdown code to 0Ah ..."
    969 	 */
    970 
    971 	outb(IO_RTC, NVRAM_RESET);
    972 	outb(IO_RTC+1, NVRAM_RESET_JUMP);
    973 
    974 	/*
    975 	 * "and the warm reset vector (DWORD based at 40:67) to point
    976 	 * to the AP startup code ..."
    977 	 */
    978 
    979 	dwordptr[0] = 0;
    980 	dwordptr[1] = target >> 4;
    981 
    982 	memcpy((uint8_t *)cmos_data_mapping + 0x467, dwordptr, 4);
    983 
    984 	if ((cpu_feature[0] & CPUID_APIC) == 0) {
    985 		aprint_error("mp_cpu_start: CPU does not have APIC\n");
    986 		return ENODEV;
    987 	}
    988 
    989 	/*
    990 	 * ... prior to executing the following sequence:".  We'll also add in
    991 	 * local cache flush, in case the BIOS has left the AP with its cache
    992 	 * disabled.  It may not be able to cope with MP coherency.
    993 	 */
    994 	wbinvd();
    995 
    996 	if (ci->ci_flags & CPUF_AP) {
    997 		error = x86_ipi_init(ci->ci_cpuid);
    998 		if (error != 0) {
    999 			aprint_error_dev(ci->ci_dev, "%s: IPI not taken (1)\n",
   1000 			    __func__);
   1001 			return error;
   1002 		}
   1003 		i8254_delay(10000);
   1004 
   1005 		error = x86_ipi_startup(ci->ci_cpuid, target / PAGE_SIZE);
   1006 		if (error != 0) {
   1007 			aprint_error_dev(ci->ci_dev, "%s: IPI not taken (2)\n",
   1008 			    __func__);
   1009 			return error;
   1010 		}
   1011 		i8254_delay(200);
   1012 
   1013 		error = x86_ipi_startup(ci->ci_cpuid, target / PAGE_SIZE);
   1014 		if (error != 0) {
   1015 			aprint_error_dev(ci->ci_dev, "%s: IPI not taken (3)\n",
   1016 			    __func__);
   1017 			return error;
   1018 		}
   1019 		i8254_delay(200);
   1020 	}
   1021 
   1022 	return 0;
   1023 }
   1024 
   1025 void
   1026 mp_cpu_start_cleanup(struct cpu_info *ci)
   1027 {
   1028 	/*
   1029 	 * Ensure the NVRAM reset byte contains something vaguely sane.
   1030 	 */
   1031 
   1032 	outb(IO_RTC, NVRAM_RESET);
   1033 	outb(IO_RTC+1, NVRAM_RESET_RST);
   1034 }
   1035 
   1036 #ifdef __x86_64__
   1037 typedef void (vector)(void);
   1038 extern vector Xsyscall, Xsyscall32;
   1039 #endif
   1040 
   1041 void
   1042 cpu_init_msrs(struct cpu_info *ci, bool full)
   1043 {
   1044 #ifdef __x86_64__
   1045 	wrmsr(MSR_STAR,
   1046 	    ((uint64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
   1047 	    ((uint64_t)LSEL(LSYSRETBASE_SEL, SEL_UPL) << 48));
   1048 	wrmsr(MSR_LSTAR, (uint64_t)Xsyscall);
   1049 	wrmsr(MSR_CSTAR, (uint64_t)Xsyscall32);
   1050 	wrmsr(MSR_SFMASK, PSL_NT|PSL_T|PSL_I|PSL_C);
   1051 
   1052 	if (full) {
   1053 		wrmsr(MSR_FSBASE, 0);
   1054 		wrmsr(MSR_GSBASE, (uint64_t)ci);
   1055 		wrmsr(MSR_KERNELGSBASE, 0);
   1056 	}
   1057 #endif	/* __x86_64__ */
   1058 
   1059 	if (cpu_feature[2] & CPUID_NOX)
   1060 		wrmsr(MSR_EFER, rdmsr(MSR_EFER) | EFER_NXE);
   1061 }
   1062 
   1063 void
   1064 cpu_offline_md(void)
   1065 {
   1066 	int s;
   1067 
   1068 	s = splhigh();
   1069 #ifdef i386
   1070 #if NNPX > 0
   1071 	npxsave_cpu(true);
   1072 #endif
   1073 #else
   1074 	fpusave_cpu(true);
   1075 #endif
   1076 	splx(s);
   1077 }
   1078 
   1079 /* XXX joerg restructure and restart CPUs individually */
   1080 static bool
   1081 cpu_suspend(device_t dv, const pmf_qual_t *qual)
   1082 {
   1083 	struct cpu_softc *sc = device_private(dv);
   1084 	struct cpu_info *ci = sc->sc_info;
   1085 	int err;
   1086 
   1087 	if (ci->ci_flags & CPUF_PRIMARY)
   1088 		return true;
   1089 	if (ci->ci_data.cpu_idlelwp == NULL)
   1090 		return true;
   1091 	if ((ci->ci_flags & CPUF_PRESENT) == 0)
   1092 		return true;
   1093 
   1094 	sc->sc_wasonline = !(ci->ci_schedstate.spc_flags & SPCF_OFFLINE);
   1095 
   1096 	if (sc->sc_wasonline) {
   1097 		mutex_enter(&cpu_lock);
   1098 		err = cpu_setstate(ci, false);
   1099 		mutex_exit(&cpu_lock);
   1100 
   1101 		if (err)
   1102 			return false;
   1103 	}
   1104 
   1105 	return true;
   1106 }
   1107 
   1108 static bool
   1109 cpu_resume(device_t dv, const pmf_qual_t *qual)
   1110 {
   1111 	struct cpu_softc *sc = device_private(dv);
   1112 	struct cpu_info *ci = sc->sc_info;
   1113 	int err = 0;
   1114 
   1115 	if (ci->ci_flags & CPUF_PRIMARY)
   1116 		return true;
   1117 	if (ci->ci_data.cpu_idlelwp == NULL)
   1118 		return true;
   1119 	if ((ci->ci_flags & CPUF_PRESENT) == 0)
   1120 		return true;
   1121 
   1122 	if (sc->sc_wasonline) {
   1123 		mutex_enter(&cpu_lock);
   1124 		err = cpu_setstate(ci, true);
   1125 		mutex_exit(&cpu_lock);
   1126 	}
   1127 
   1128 	return err == 0;
   1129 }
   1130 
   1131 static bool
   1132 cpu_shutdown(device_t dv, int how)
   1133 {
   1134 	return cpu_suspend(dv, NULL);
   1135 }
   1136 
   1137 void
   1138 cpu_get_tsc_freq(struct cpu_info *ci)
   1139 {
   1140 	uint64_t last_tsc;
   1141 
   1142 	if (cpu_hascounter()) {
   1143 		last_tsc = cpu_counter_serializing();
   1144 		i8254_delay(100000);
   1145 		ci->ci_data.cpu_cc_freq =
   1146 		    (cpu_counter_serializing() - last_tsc) * 10;
   1147 	}
   1148 }
   1149 
   1150 void
   1151 x86_cpu_idle_mwait(void)
   1152 {
   1153 	struct cpu_info *ci = curcpu();
   1154 
   1155 	KASSERT(ci->ci_ilevel == IPL_NONE);
   1156 
   1157 	x86_monitor(&ci->ci_want_resched, 0, 0);
   1158 	if (__predict_false(ci->ci_want_resched)) {
   1159 		return;
   1160 	}
   1161 	x86_mwait(0, 0);
   1162 }
   1163 
   1164 void
   1165 x86_cpu_idle_halt(void)
   1166 {
   1167 	struct cpu_info *ci = curcpu();
   1168 
   1169 	KASSERT(ci->ci_ilevel == IPL_NONE);
   1170 
   1171 	x86_disable_intr();
   1172 	if (!__predict_false(ci->ci_want_resched)) {
   1173 		x86_stihlt();
   1174 	} else {
   1175 		x86_enable_intr();
   1176 	}
   1177 }
   1178 
   1179 /*
   1180  * Loads pmap for the current CPU.
   1181  */
   1182 void
   1183 cpu_load_pmap(struct pmap *pmap)
   1184 {
   1185 #ifdef PAE
   1186 	int i, s;
   1187 	struct cpu_info *ci;
   1188 
   1189 	s = splvm(); /* just to be safe */
   1190 	ci = curcpu();
   1191 	pd_entry_t *l3_pd = ci->ci_pae_l3_pdir;
   1192 	for (i = 0 ; i < PDP_SIZE; i++) {
   1193 		l3_pd[i] = pmap->pm_pdirpa[i] | PG_V;
   1194 	}
   1195 	splx(s);
   1196 	tlbflush();
   1197 #else /* PAE */
   1198 	lcr3(pmap_pdirpa(pmap, 0));
   1199 #endif /* PAE */
   1200 }
   1201