Home | History | Annotate | Line # | Download | only in x86
cpu.c revision 1.20
      1 /*	$NetBSD: cpu.c,v 1.20 2008/01/30 01:10:21 jmcneill Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2000, 2006, 2007 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  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *        This product includes software developed by the NetBSD
     21  *        Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 /*
     40  * Copyright (c) 1999 Stefan Grefen
     41  *
     42  * Redistribution and use in source and binary forms, with or without
     43  * modification, are permitted provided that the following conditions
     44  * are met:
     45  * 1. Redistributions of source code must retain the above copyright
     46  *    notice, this list of conditions and the following disclaimer.
     47  * 2. Redistributions in binary form must reproduce the above copyright
     48  *    notice, this list of conditions and the following disclaimer in the
     49  *    documentation and/or other materials provided with the distribution.
     50  * 3. All advertising materials mentioning features or use of this software
     51  *    must display the following acknowledgement:
     52  *      This product includes software developed by the NetBSD
     53  *      Foundation, Inc. and its contributors.
     54  * 4. Neither the name of The NetBSD Foundation nor the names of its
     55  *    contributors may be used to endorse or promote products derived
     56  *    from this software without specific prior written permission.
     57  *
     58  * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
     59  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR AND CONTRIBUTORS BE LIABLE
     62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     68  * SUCH DAMAGE.
     69  */
     70 
     71 #include <sys/cdefs.h>
     72 __KERNEL_RCSID(0, "$NetBSD: cpu.c,v 1.20 2008/01/30 01:10:21 jmcneill Exp $");
     73 
     74 #include "opt_ddb.h"
     75 #include "opt_multiprocessor.h"
     76 #include "opt_mpbios.h"		/* for MPDEBUG */
     77 #include "opt_mtrr.h"
     78 
     79 #include "lapic.h"
     80 #include "ioapic.h"
     81 
     82 #include <sys/param.h>
     83 #include <sys/proc.h>
     84 #include <sys/user.h>
     85 #include <sys/systm.h>
     86 #include <sys/device.h>
     87 #include <sys/malloc.h>
     88 #include <sys/cpu.h>
     89 #include <sys/atomic.h>
     90 
     91 #include <uvm/uvm_extern.h>
     92 
     93 #include <machine/cpufunc.h>
     94 #include <machine/cpuvar.h>
     95 #include <machine/pmap.h>
     96 #include <machine/vmparam.h>
     97 #include <machine/mpbiosvar.h>
     98 #include <machine/pcb.h>
     99 #include <machine/specialreg.h>
    100 #include <machine/segments.h>
    101 #include <machine/gdt.h>
    102 #include <machine/mtrr.h>
    103 #include <machine/pio.h>
    104 
    105 #ifdef i386
    106 #include <machine/tlog.h>
    107 #endif
    108 
    109 #if NLAPIC > 0
    110 #include <machine/apicvar.h>
    111 #include <machine/i82489reg.h>
    112 #include <machine/i82489var.h>
    113 #endif
    114 
    115 #if NIOAPIC > 0
    116 #include <machine/i82093var.h>
    117 #endif
    118 
    119 #include <dev/ic/mc146818reg.h>
    120 #include <i386/isa/nvram.h>
    121 #include <dev/isa/isareg.h>
    122 
    123 int     cpu_match(struct device *, struct cfdata *, void *);
    124 void    cpu_attach(struct device *, struct device *, void *);
    125 
    126 static bool	cpu_suspend(device_t);
    127 static bool	cpu_resume(device_t);
    128 
    129 struct cpu_softc {
    130 	struct device sc_dev;		/* device tree glue */
    131 	struct cpu_info *sc_info;	/* pointer to CPU info */
    132 	bool sc_wasonline;
    133 };
    134 
    135 int mp_cpu_start(struct cpu_info *, paddr_t);
    136 void mp_cpu_start_cleanup(struct cpu_info *);
    137 const struct cpu_functions mp_cpu_funcs = { mp_cpu_start, NULL,
    138 					    mp_cpu_start_cleanup };
    139 
    140 
    141 CFATTACH_DECL(cpu, sizeof(struct cpu_softc),
    142     cpu_match, cpu_attach, NULL, NULL);
    143 
    144 /*
    145  * Statically-allocated CPU info for the primary CPU (or the only
    146  * CPU, on uniprocessors).  The CPU info list is initialized to
    147  * point at it.
    148  */
    149 #ifdef TRAPLOG
    150 struct tlog tlog_primary;
    151 #endif
    152 struct cpu_info cpu_info_primary = {
    153 	.ci_dev = 0,
    154 	.ci_self = &cpu_info_primary,
    155 	.ci_idepth = -1,
    156 	.ci_curlwp = &lwp0,
    157 #ifdef TRAPLOG
    158 	.ci_tlog_base = &tlog_primary,
    159 #endif /* !TRAPLOG */
    160 };
    161 
    162 struct cpu_info *cpu_info_list = &cpu_info_primary;
    163 
    164 static void	cpu_set_tss_gates(struct cpu_info *);
    165 
    166 #ifdef i386
    167 static void	tss_init(struct i386tss *, void *, void *);
    168 #endif
    169 
    170 #ifdef MULTIPROCESSOR
    171 static void	cpu_init_idle_lwp(struct cpu_info *);
    172 #endif
    173 
    174 uint32_t cpus_attached = 0;
    175 uint32_t cpus_running = 0;
    176 
    177 extern char x86_64_doubleflt_stack[];
    178 
    179 bool x86_mp_online;
    180 paddr_t mp_trampoline_paddr = MP_TRAMPOLINE;
    181 
    182 static vaddr_t cmos_data_mapping;
    183 
    184 #ifdef MULTIPROCESSOR
    185 /*
    186  * Array of CPU info structures.  Must be statically-allocated because
    187  * curproc, etc. are used early.
    188  */
    189 struct cpu_info *cpu_info[X86_MAXPROCS] = { &cpu_info_primary, };
    190 
    191 void    	cpu_hatch(void *);
    192 static void    	cpu_boot_secondary(struct cpu_info *ci);
    193 static void    	cpu_start_secondary(struct cpu_info *ci);
    194 static void	cpu_copy_trampoline(void);
    195 
    196 /*
    197  * Runs once per boot once multiprocessor goo has been detected and
    198  * the local APIC on the boot processor has been mapped.
    199  *
    200  * Called from lapic_boot_init() (from mpbios_scan()).
    201  */
    202 void
    203 cpu_init_first(void)
    204 {
    205 	int cpunum = lapic_cpu_number();
    206 
    207 	if (cpunum != 0) {
    208 		cpu_info[0] = NULL;
    209 		cpu_info[cpunum] = &cpu_info_primary;
    210 	}
    211 
    212 	cpu_info_primary.ci_cpuid = cpunum;
    213 	cpu_copy_trampoline();
    214 
    215 	cmos_data_mapping = uvm_km_alloc(kernel_map, PAGE_SIZE, 0, UVM_KMF_VAONLY);
    216 	if (cmos_data_mapping == 0)
    217 		panic("No KVA for page 0");
    218 	pmap_kenter_pa(cmos_data_mapping, 0, VM_PROT_READ|VM_PROT_WRITE);
    219 	pmap_update(pmap_kernel());
    220 }
    221 #endif
    222 
    223 int
    224 cpu_match(struct device *parent, struct cfdata *match,
    225     void *aux)
    226 {
    227 
    228 	return 1;
    229 }
    230 
    231 static void
    232 cpu_vm_init(struct cpu_info *ci)
    233 {
    234 	int ncolors = 2, i;
    235 
    236 	for (i = CAI_ICACHE; i <= CAI_L2CACHE; i++) {
    237 		struct x86_cache_info *cai;
    238 		int tcolors;
    239 
    240 		cai = &ci->ci_cinfo[i];
    241 
    242 		tcolors = atop(cai->cai_totalsize);
    243 		switch(cai->cai_associativity) {
    244 		case 0xff:
    245 			tcolors = 1; /* fully associative */
    246 			break;
    247 		case 0:
    248 		case 1:
    249 			break;
    250 		default:
    251 			tcolors /= cai->cai_associativity;
    252 		}
    253 		ncolors = max(ncolors, tcolors);
    254 	}
    255 
    256 	/*
    257 	 * Knowing the size of the largest cache on this CPU, re-color
    258 	 * our pages.
    259 	 */
    260 	if (ncolors <= uvmexp.ncolors)
    261 		return;
    262 	aprint_verbose("%s: %d page colors\n", ci->ci_dev->dv_xname, ncolors);
    263 	uvm_page_recolor(ncolors);
    264 }
    265 
    266 
    267 void
    268 cpu_attach(struct device *parent, struct device *self, void *aux)
    269 {
    270 	struct cpu_softc *sc = (void *) self;
    271 	struct cpu_attach_args *caa = aux;
    272 	struct cpu_info *ci;
    273 #if defined(MULTIPROCESSOR)
    274 	int cpunum = caa->cpu_number;
    275 #endif
    276 
    277 	/*
    278 	 * If we're an Application Processor, allocate a cpu_info
    279 	 * structure, otherwise use the primary's.
    280 	 */
    281 	if (caa->cpu_role == CPU_ROLE_AP) {
    282 		aprint_naive(": Application Processor\n");
    283 		ci = malloc(sizeof(*ci), M_DEVBUF, M_WAITOK);
    284 		memset(ci, 0, sizeof(*ci));
    285 #if defined(MULTIPROCESSOR)
    286 		if (cpu_info[cpunum] != NULL) {
    287 			printf("\n");
    288 			panic("cpu at apic id %d already attached?", cpunum);
    289 		}
    290 		cpu_info[cpunum] = ci;
    291 #endif
    292 #ifdef TRAPLOG
    293 		ci->ci_tlog_base = malloc(sizeof(struct tlog),
    294 		    M_DEVBUF, M_WAITOK);
    295 #endif
    296 	} else {
    297 		aprint_naive(": %s Processor\n",
    298 		    caa->cpu_role == CPU_ROLE_SP ? "Single" : "Boot");
    299 		ci = &cpu_info_primary;
    300 #if defined(MULTIPROCESSOR)
    301 		if (cpunum != lapic_cpu_number()) {
    302 			printf("\n");
    303 			panic("%s: running CPU is at apic %d"
    304 			    " instead of at expected %d",
    305 			    sc->sc_dev.dv_xname, lapic_cpu_number(), cpunum);
    306 		}
    307 #endif
    308 	}
    309 
    310 	ci->ci_self = ci;
    311 	sc->sc_info = ci;
    312 
    313 	ci->ci_dev = self;
    314 	ci->ci_apicid = caa->cpu_number;
    315 #ifdef MULTIPROCESSOR
    316 	ci->ci_cpuid = ci->ci_apicid;
    317 #else
    318 	ci->ci_cpuid = 0;	/* False for APs, but they're not used anyway */
    319 #endif
    320 	ci->ci_cpumask = (1 << ci->ci_cpuid);
    321 	ci->ci_func = caa->cpu_func;
    322 
    323 	if (caa->cpu_role == CPU_ROLE_AP) {
    324 #ifdef MULTIPROCESSOR
    325 		int error;
    326 
    327 		error = mi_cpu_attach(ci);
    328 		if (error != 0) {
    329 			aprint_normal("\n");
    330 			aprint_error("%s: mi_cpu_attach failed with %d\n",
    331 			    sc->sc_dev.dv_xname, error);
    332 			return;
    333 		}
    334 #endif
    335 		cpu_init_tss(ci);
    336 	} else {
    337 		KASSERT(ci->ci_data.cpu_idlelwp != NULL);
    338 	}
    339 
    340 	pmap_reference(pmap_kernel());
    341 	ci->ci_pmap = pmap_kernel();
    342 	ci->ci_tlbstate = TLBSTATE_STALE;
    343 
    344 	/* further PCB init done later. */
    345 
    346 	switch (caa->cpu_role) {
    347 	case CPU_ROLE_SP:
    348 		aprint_normal(": (uniprocessor)\n");
    349 		atomic_or_32(&ci->ci_flags,
    350 		    CPUF_PRESENT | CPUF_SP | CPUF_PRIMARY);
    351 		cpu_intr_init(ci);
    352 		identifycpu(ci);
    353 		cpu_init(ci);
    354 		cpu_set_tss_gates(ci);
    355 		pmap_cpu_init_late(ci);
    356 		x86_errata();
    357 		break;
    358 
    359 	case CPU_ROLE_BP:
    360 		aprint_normal(": (boot processor)\n");
    361 		atomic_or_32(&ci->ci_flags,
    362 		    CPUF_PRESENT | CPUF_BSP | CPUF_PRIMARY);
    363 		cpu_intr_init(ci);
    364 		identifycpu(ci);
    365 		cpu_init(ci);
    366 		cpu_set_tss_gates(ci);
    367 		pmap_cpu_init_late(ci);
    368 #if NLAPIC > 0
    369 		/*
    370 		 * Enable local apic
    371 		 */
    372 		lapic_enable();
    373 		lapic_set_lvt();
    374 		lapic_calibrate_timer(ci);
    375 #endif
    376 #if NIOAPIC > 0
    377 		ioapic_bsp_id = caa->cpu_number;
    378 #endif
    379 		x86_errata();
    380 		break;
    381 
    382 	case CPU_ROLE_AP:
    383 		/*
    384 		 * report on an AP
    385 		 */
    386 		aprint_normal(": (application processor)\n");
    387 
    388 #if defined(MULTIPROCESSOR)
    389 		cpu_intr_init(ci);
    390 		gdt_alloc_cpu(ci);
    391 		cpu_set_tss_gates(ci);
    392 		pmap_cpu_init_early(ci);
    393 		pmap_cpu_init_late(ci);
    394 		cpu_start_secondary(ci);
    395 		if (ci->ci_flags & CPUF_PRESENT) {
    396 			identifycpu(ci);
    397 			ci->ci_next = cpu_info_list->ci_next;
    398 			cpu_info_list->ci_next = ci;
    399 		}
    400 #else
    401 		aprint_normal("%s: not started\n", sc->sc_dev.dv_xname);
    402 #endif
    403 		break;
    404 
    405 	default:
    406 		printf("\n");
    407 		panic("unknown processor type??\n");
    408 	}
    409 	cpu_vm_init(ci);
    410 
    411 	cpus_attached |= ci->ci_cpumask;
    412 
    413 	if (!pmf_device_register(self, cpu_suspend, cpu_resume))
    414 		aprint_error_dev(self, "couldn't establish power handler\n");
    415 
    416 #if defined(MULTIPROCESSOR)
    417 	if (mp_verbose) {
    418 		struct lwp *l = ci->ci_data.cpu_idlelwp;
    419 
    420 		aprint_verbose(
    421 		    "%s: idle lwp at %p, idle sp at %p\n",
    422 		    sc->sc_dev.dv_xname, l,
    423 #ifdef i386
    424 		    (void *)l->l_addr->u_pcb.pcb_esp
    425 #else
    426 		    (void *)l->l_addr->u_pcb.pcb_rsp
    427 #endif
    428 		);
    429 	}
    430 #endif
    431 }
    432 
    433 /*
    434  * Initialize the processor appropriately.
    435  */
    436 
    437 void
    438 cpu_init(struct cpu_info *ci)
    439 {
    440 	/* configure the CPU if needed */
    441 	if (ci->cpu_setup != NULL)
    442 		(*ci->cpu_setup)(ci);
    443 
    444 #ifdef i386
    445 	/*
    446 	 * On a 486 or above, enable ring 0 write protection.
    447 	 */
    448 	if (ci->ci_cpu_class >= CPUCLASS_486)
    449 		lcr0(rcr0() | CR0_WP);
    450 #else
    451 	lcr0(rcr0() | CR0_WP);
    452 #endif
    453 
    454 	/*
    455 	 * On a P6 or above, enable global TLB caching if the
    456 	 * hardware supports it.
    457 	 */
    458 	if (cpu_feature & CPUID_PGE)
    459 		lcr4(rcr4() | CR4_PGE);	/* enable global TLB caching */
    460 
    461 	/*
    462 	 * If we have FXSAVE/FXRESTOR, use them.
    463 	 */
    464 	if (cpu_feature & CPUID_FXSR) {
    465 		lcr4(rcr4() | CR4_OSFXSR);
    466 
    467 		/*
    468 		 * If we have SSE/SSE2, enable XMM exceptions.
    469 		 */
    470 		if (cpu_feature & (CPUID_SSE|CPUID_SSE2))
    471 			lcr4(rcr4() | CR4_OSXMMEXCPT);
    472 	}
    473 
    474 #ifdef MTRR
    475 	/*
    476 	 * On a P6 or above, initialize MTRR's if the hardware supports them.
    477 	 */
    478 	if (cpu_feature & CPUID_MTRR) {
    479 		if ((ci->ci_flags & CPUF_AP) == 0)
    480 			i686_mtrr_init_first();
    481 		mtrr_init_cpu(ci);
    482 	}
    483 
    484 #ifdef i386
    485 	if (strcmp((char *)(ci->ci_vendor), "AuthenticAMD") == 0) {
    486 		/*
    487 		 * Must be a K6-2 Step >= 7 or a K6-III.
    488 		 */
    489 		if (CPUID2FAMILY(ci->ci_signature) == 5) {
    490 			if (CPUID2MODEL(ci->ci_signature) > 8 ||
    491 			    (CPUID2MODEL(ci->ci_signature) == 8 &&
    492 			     CPUID2STEPPING(ci->ci_signature) >= 7)) {
    493 				mtrr_funcs = &k6_mtrr_funcs;
    494 				k6_mtrr_init_first();
    495 				mtrr_init_cpu(ci);
    496 			}
    497 		}
    498 	}
    499 #endif	/* i386 */
    500 #endif /* MTRR */
    501 
    502 	atomic_or_32(&ci->ci_flags, CPUF_RUNNING);
    503 	atomic_or_32(&cpus_running, ci->ci_cpumask);
    504 
    505 #ifndef MULTIPROCESSOR
    506 	/* XXX */
    507 	x86_patch();
    508 #endif
    509 }
    510 
    511 #ifdef MULTIPROCESSOR
    512 void
    513 cpu_boot_secondary_processors(void)
    514 {
    515 	struct cpu_info *ci;
    516 	u_long i;
    517 
    518 	/* Now that we know the number of CPUs, patch the text segment. */
    519 	x86_patch();
    520 
    521 	for (i=0; i < X86_MAXPROCS; i++) {
    522 		ci = cpu_info[i];
    523 		if (ci == NULL)
    524 			continue;
    525 		if (ci->ci_data.cpu_idlelwp == NULL)
    526 			continue;
    527 		if ((ci->ci_flags & CPUF_PRESENT) == 0)
    528 			continue;
    529 		if (ci->ci_flags & (CPUF_BSP|CPUF_SP|CPUF_PRIMARY))
    530 			continue;
    531 		cpu_boot_secondary(ci);
    532 	}
    533 
    534 	x86_mp_online = true;
    535 }
    536 
    537 static void
    538 cpu_init_idle_lwp(struct cpu_info *ci)
    539 {
    540 	struct lwp *l = ci->ci_data.cpu_idlelwp;
    541 	struct pcb *pcb = &l->l_addr->u_pcb;
    542 
    543 	pcb->pcb_cr0 = rcr0();
    544 }
    545 
    546 void
    547 cpu_init_idle_lwps(void)
    548 {
    549 	struct cpu_info *ci;
    550 	u_long i;
    551 
    552 	for (i = 0; i < X86_MAXPROCS; i++) {
    553 		ci = cpu_info[i];
    554 		if (ci == NULL)
    555 			continue;
    556 		if (ci->ci_data.cpu_idlelwp == NULL)
    557 			continue;
    558 		if ((ci->ci_flags & CPUF_PRESENT) == 0)
    559 			continue;
    560 		cpu_init_idle_lwp(ci);
    561 	}
    562 }
    563 
    564 void
    565 cpu_start_secondary(struct cpu_info *ci)
    566 {
    567 	int i;
    568 	extern paddr_t mp_pdirpa;
    569 
    570 	mp_pdirpa = pmap_init_tmp_pgtbl(mp_trampoline_paddr);
    571 
    572 	atomic_or_32(&ci->ci_flags, CPUF_AP);
    573 
    574 	aprint_debug("%s: starting\n", ci->ci_dev->dv_xname);
    575 
    576 	ci->ci_curlwp = ci->ci_data.cpu_idlelwp;
    577 	CPU_STARTUP(ci, mp_trampoline_paddr);
    578 
    579 	/*
    580 	 * wait for it to become ready
    581 	 */
    582 	for (i = 100000; (!(ci->ci_flags & CPUF_PRESENT)) && i>0;i--) {
    583 		i8254_delay(10);
    584 	}
    585 	if ((ci->ci_flags & CPUF_PRESENT) == 0) {
    586 		aprint_error("%s: failed to become ready\n",
    587 		    ci->ci_dev->dv_xname);
    588 #if defined(MPDEBUG) && defined(DDB)
    589 		printf("dropping into debugger; continue from here to resume boot\n");
    590 		Debugger();
    591 #endif
    592 	}
    593 
    594 	CPU_START_CLEANUP(ci);
    595 }
    596 
    597 void
    598 cpu_boot_secondary(struct cpu_info *ci)
    599 {
    600 	int i;
    601 
    602 	atomic_or_32(&ci->ci_flags, CPUF_GO);
    603 	for (i = 100000; (!(ci->ci_flags & CPUF_RUNNING)) && i>0;i--) {
    604 		i8254_delay(10);
    605 	}
    606 	if ((ci->ci_flags & CPUF_RUNNING) == 0) {
    607 		aprint_error("%s: failed to start\n", ci->ci_dev->dv_xname);
    608 #if defined(MPDEBUG) && defined(DDB)
    609 		printf("dropping into debugger; continue from here to resume boot\n");
    610 		Debugger();
    611 #endif
    612 	}
    613 }
    614 
    615 /*
    616  * The CPU ends up here when its ready to run
    617  * This is called from code in mptramp.s; at this point, we are running
    618  * in the idle pcb/idle stack of the new CPU.  When this function returns,
    619  * this processor will enter the idle loop and start looking for work.
    620  */
    621 void
    622 cpu_hatch(void *v)
    623 {
    624 	struct cpu_info *ci = (struct cpu_info *)v;
    625 	int s, i;
    626 
    627 #ifdef __x86_64__
    628 	cpu_init_msrs(ci, true);
    629 #endif
    630 	cpu_probe_features(ci);
    631 	cpu_feature &= ci->ci_feature_flags;
    632 	cpu_feature2 &= ci->ci_feature2_flags;
    633 
    634 	KDASSERT((ci->ci_flags & CPUF_PRESENT) == 0);
    635 	atomic_or_32(&ci->ci_flags, CPUF_PRESENT);
    636 	while ((ci->ci_flags & CPUF_GO) == 0) {
    637 		/* Don't use delay, boot CPU may be patching the text. */
    638 		for (i = 10000; i != 0; i--)
    639 			x86_pause();
    640 	}
    641 
    642 	/* Beacuse the text may have been patched in x86_patch(). */
    643 	wbinvd();
    644 	x86_flush();
    645 
    646 	KASSERT((ci->ci_flags & CPUF_RUNNING) == 0);
    647 
    648 	lcr3(pmap_kernel()->pm_pdirpa);
    649 	curlwp->l_addr->u_pcb.pcb_cr3 = pmap_kernel()->pm_pdirpa;
    650 	lcr0(ci->ci_data.cpu_idlelwp->l_addr->u_pcb.pcb_cr0);
    651 	cpu_init_idt();
    652 	gdt_init_cpu(ci);
    653 	lapic_enable();
    654 	lapic_set_lvt();
    655 	lapic_initclocks();
    656 
    657 #ifdef i386
    658 	npxinit(ci);
    659 #else
    660 	fpuinit(ci);
    661 #endif
    662 	lldt(GSYSSEL(GLDT_SEL, SEL_KPL));
    663 	ltr(ci->ci_tss_sel);
    664 
    665 	cpu_init(ci);
    666 	cpu_get_tsc_freq(ci);
    667 
    668 	s = splhigh();
    669 #ifdef i386
    670 	lapic_tpr = 0;
    671 #else
    672 	lcr8(0);
    673 #endif
    674 	x86_enable_intr();
    675 	splx(s);
    676 	x86_errata();
    677 
    678 	aprint_debug("%s: CPU %ld running\n", ci->ci_dev->dv_xname,
    679 	    (long)ci->ci_cpuid);
    680 }
    681 
    682 #if defined(DDB)
    683 
    684 #include <ddb/db_output.h>
    685 #include <machine/db_machdep.h>
    686 
    687 /*
    688  * Dump CPU information from ddb.
    689  */
    690 void
    691 cpu_debug_dump(void)
    692 {
    693 	struct cpu_info *ci;
    694 	CPU_INFO_ITERATOR cii;
    695 
    696 	db_printf("addr		dev	id	flags	ipis	curproc		fpcurproc\n");
    697 	for (CPU_INFO_FOREACH(cii, ci)) {
    698 		db_printf("%p	%s	%ld	%x	%x	%10p	%10p\n",
    699 		    ci,
    700 		    ci->ci_dev == NULL ? "BOOT" : ci->ci_dev->dv_xname,
    701 		    (long)ci->ci_cpuid,
    702 		    ci->ci_flags, ci->ci_ipis,
    703 		    ci->ci_curlwp,
    704 		    ci->ci_fpcurlwp);
    705 	}
    706 }
    707 #endif
    708 
    709 static void
    710 cpu_copy_trampoline(void)
    711 {
    712 	/*
    713 	 * Copy boot code.
    714 	 */
    715 	extern u_char cpu_spinup_trampoline[];
    716 	extern u_char cpu_spinup_trampoline_end[];
    717 
    718 	vaddr_t mp_trampoline_vaddr;
    719 
    720 	mp_trampoline_vaddr = uvm_km_alloc(kernel_map, PAGE_SIZE, 0,
    721 	    UVM_KMF_VAONLY);
    722 
    723 	pmap_kenter_pa(mp_trampoline_vaddr, mp_trampoline_paddr,
    724 	    VM_PROT_READ | VM_PROT_WRITE);
    725 	pmap_update(pmap_kernel());
    726 	memcpy((void *)mp_trampoline_vaddr,
    727 	    cpu_spinup_trampoline,
    728 	    cpu_spinup_trampoline_end-cpu_spinup_trampoline);
    729 
    730 	pmap_kremove(mp_trampoline_vaddr, PAGE_SIZE);
    731 	pmap_update(pmap_kernel());
    732 	uvm_km_free(kernel_map, mp_trampoline_vaddr, PAGE_SIZE, UVM_KMF_VAONLY);
    733 }
    734 
    735 #endif
    736 
    737 #ifdef i386
    738 static void
    739 tss_init(struct i386tss *tss, void *stack, void *func)
    740 {
    741 	memset(tss, 0, sizeof *tss);
    742 	tss->tss_esp0 = tss->tss_esp = (int)((char *)stack + USPACE - 16);
    743 	tss->tss_ss0 = GSEL(GDATA_SEL, SEL_KPL);
    744 	tss->__tss_cs = GSEL(GCODE_SEL, SEL_KPL);
    745 	tss->tss_fs = GSEL(GCPU_SEL, SEL_KPL);
    746 	tss->tss_gs = tss->__tss_es = tss->__tss_ds =
    747 	    tss->__tss_ss = GSEL(GDATA_SEL, SEL_KPL);
    748 	tss->tss_cr3 = pmap_kernel()->pm_pdirpa;
    749 	tss->tss_esp = (int)((char *)stack + USPACE - 16);
    750 	tss->tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
    751 	tss->__tss_eflags = PSL_MBO | PSL_NT;	/* XXX not needed? */
    752 	tss->__tss_eip = (int)func;
    753 }
    754 
    755 /* XXX */
    756 #define IDTVEC(name)	__CONCAT(X, name)
    757 typedef void (vector)(void);
    758 extern vector IDTVEC(tss_trap08);
    759 #ifdef DDB
    760 extern vector Xintrddbipi;
    761 extern int ddb_vec;
    762 #endif
    763 
    764 static void
    765 cpu_set_tss_gates(struct cpu_info *ci)
    766 {
    767 	struct segment_descriptor sd;
    768 
    769 	ci->ci_doubleflt_stack = (char *)uvm_km_alloc(kernel_map, USPACE, 0,
    770 	    UVM_KMF_WIRED);
    771 	tss_init(&ci->ci_doubleflt_tss, ci->ci_doubleflt_stack,
    772 	    IDTVEC(tss_trap08));
    773 	setsegment(&sd, &ci->ci_doubleflt_tss, sizeof(struct i386tss) - 1,
    774 	    SDT_SYS386TSS, SEL_KPL, 0, 0);
    775 	ci->ci_gdt[GTRAPTSS_SEL].sd = sd;
    776 	setgate(&idt[8], NULL, 0, SDT_SYSTASKGT, SEL_KPL,
    777 	    GSEL(GTRAPTSS_SEL, SEL_KPL));
    778 
    779 #if defined(DDB) && defined(MULTIPROCESSOR)
    780 	/*
    781 	 * Set up separate handler for the DDB IPI, so that it doesn't
    782 	 * stomp on a possibly corrupted stack.
    783 	 *
    784 	 * XXX overwriting the gate set in db_machine_init.
    785 	 * Should rearrange the code so that it's set only once.
    786 	 */
    787 	ci->ci_ddbipi_stack = (char *)uvm_km_alloc(kernel_map, USPACE, 0,
    788 	    UVM_KMF_WIRED);
    789 	tss_init(&ci->ci_ddbipi_tss, ci->ci_ddbipi_stack, Xintrddbipi);
    790 
    791 	setsegment(&sd, &ci->ci_ddbipi_tss, sizeof(struct i386tss) - 1,
    792 	    SDT_SYS386TSS, SEL_KPL, 0, 0);
    793 	ci->ci_gdt[GIPITSS_SEL].sd = sd;
    794 
    795 	setgate(&idt[ddb_vec], NULL, 0, SDT_SYSTASKGT, SEL_KPL,
    796 	    GSEL(GIPITSS_SEL, SEL_KPL));
    797 #endif
    798 }
    799 #else
    800 static void
    801 cpu_set_tss_gates(struct cpu_info *ci)
    802 {
    803 
    804 }
    805 #endif	/* i386 */
    806 
    807 int
    808 mp_cpu_start(struct cpu_info *ci, paddr_t target)
    809 {
    810 #if NLAPIC > 0
    811 	int error;
    812 #endif
    813 	unsigned short dwordptr[2];
    814 
    815 	/*
    816 	 * Bootstrap code must be addressable in real mode
    817 	 * and it must be page aligned.
    818 	 */
    819 	KASSERT(target < 0x10000 && target % PAGE_SIZE == 0);
    820 
    821 	/*
    822 	 * "The BSP must initialize CMOS shutdown code to 0Ah ..."
    823 	 */
    824 
    825 	outb(IO_RTC, NVRAM_RESET);
    826 	outb(IO_RTC+1, NVRAM_RESET_JUMP);
    827 
    828 	/*
    829 	 * "and the warm reset vector (DWORD based at 40:67) to point
    830 	 * to the AP startup code ..."
    831 	 */
    832 
    833 	dwordptr[0] = 0;
    834 	dwordptr[1] = target >> 4;
    835 
    836 	memcpy((uint8_t *)(cmos_data_mapping + 0x467), dwordptr, 4);
    837 
    838 #if NLAPIC > 0
    839 	/*
    840 	 * ... prior to executing the following sequence:"
    841 	 */
    842 
    843 	if (ci->ci_flags & CPUF_AP) {
    844 		if ((error = x86_ipi_init(ci->ci_apicid)) != 0)
    845 			return error;
    846 
    847 		i8254_delay(10000);
    848 
    849 		if (cpu_feature & CPUID_APIC) {
    850 
    851 			if ((error = x86_ipi(target / PAGE_SIZE,
    852 					     ci->ci_apicid,
    853 					     LAPIC_DLMODE_STARTUP)) != 0)
    854 				return error;
    855 			i8254_delay(200);
    856 
    857 			if ((error = x86_ipi(target / PAGE_SIZE,
    858 					     ci->ci_apicid,
    859 					     LAPIC_DLMODE_STARTUP)) != 0)
    860 				return error;
    861 			i8254_delay(200);
    862 		}
    863 	}
    864 #endif
    865 	return 0;
    866 }
    867 
    868 void
    869 mp_cpu_start_cleanup(struct cpu_info *ci)
    870 {
    871 	/*
    872 	 * Ensure the NVRAM reset byte contains something vaguely sane.
    873 	 */
    874 
    875 	outb(IO_RTC, NVRAM_RESET);
    876 	outb(IO_RTC+1, NVRAM_RESET_RST);
    877 }
    878 
    879 #ifdef __x86_64__
    880 typedef void (vector)(void);
    881 extern vector Xsyscall, Xsyscall32;
    882 
    883 void
    884 cpu_init_msrs(struct cpu_info *ci, bool full)
    885 {
    886 	wrmsr(MSR_STAR,
    887 	    ((uint64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
    888 	    ((uint64_t)LSEL(LSYSRETBASE_SEL, SEL_UPL) << 48));
    889 	wrmsr(MSR_LSTAR, (uint64_t)Xsyscall);
    890 	wrmsr(MSR_CSTAR, (uint64_t)Xsyscall32);
    891 	wrmsr(MSR_SFMASK, PSL_NT|PSL_T|PSL_I|PSL_C);
    892 
    893 	if (full) {
    894 		wrmsr(MSR_FSBASE, 0);
    895 		wrmsr(MSR_GSBASE, (u_int64_t)ci);
    896 		wrmsr(MSR_KERNELGSBASE, 0);
    897 	}
    898 
    899 	if (cpu_feature & CPUID_NOX)
    900 		wrmsr(MSR_EFER, rdmsr(MSR_EFER) | EFER_NXE);
    901 }
    902 #endif	/* __x86_64__ */
    903 
    904 void
    905 cpu_offline_md(void)
    906 {
    907 	int s;
    908 
    909 	s = splhigh();
    910 #ifdef __i386__
    911 	npxsave_cpu(true);
    912 #else
    913 	fpusave_cpu(true);
    914 #endif
    915 	splx(s);
    916 }
    917 
    918 /* XXX joerg restructure and restart CPUs individually */
    919 static bool
    920 cpu_suspend(device_t dv)
    921 {
    922 	struct cpu_softc *sc = device_private(dv);
    923 	struct cpu_info *ci = sc->sc_info;
    924 	int err;
    925 
    926 	if (ci->ci_flags & CPUF_PRIMARY)
    927 		return true;
    928 	if (ci->ci_data.cpu_idlelwp == NULL)
    929 		return true;
    930 	if ((ci->ci_flags & CPUF_PRESENT) == 0)
    931 		return true;
    932 
    933 	sc->sc_wasonline = !(ci->ci_schedstate.spc_flags & SPCF_OFFLINE);
    934 
    935 	if (sc->sc_wasonline) {
    936 		mutex_enter(&cpu_lock);
    937 		err = cpu_setonline(ci, false);
    938 		mutex_exit(&cpu_lock);
    939 
    940 		if (err)
    941 			return false;
    942 	}
    943 
    944 	return true;
    945 }
    946 
    947 static bool
    948 cpu_resume(device_t dv)
    949 {
    950 	struct cpu_softc *sc = device_private(dv);
    951 	struct cpu_info *ci = sc->sc_info;
    952 	int err = 0;
    953 
    954 	if (ci->ci_flags & CPUF_PRIMARY)
    955 		return true;
    956 	if (ci->ci_data.cpu_idlelwp == NULL)
    957 		return true;
    958 	if ((ci->ci_flags & CPUF_PRESENT) == 0)
    959 		return true;
    960 
    961 	if (sc->sc_wasonline) {
    962 		mutex_enter(&cpu_lock);
    963 		err = cpu_setonline(ci, true);
    964 		mutex_exit(&cpu_lock);
    965 	}
    966 
    967 	return err == 0;
    968 }
    969 
    970 void
    971 cpu_get_tsc_freq(struct cpu_info *ci)
    972 {
    973 	uint64_t last_tsc;
    974 	u_int junk[4];
    975 
    976 	if (ci->ci_feature_flags & CPUID_TSC) {
    977 		/* Serialize. */
    978 		x86_cpuid(0, junk);
    979 		last_tsc = rdtsc();
    980 		i8254_delay(100000);
    981 		ci->ci_tsc_freq = (rdtsc() - last_tsc) * 10;
    982 	}
    983 }
    984