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