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