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