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