Home | History | Annotate | Line # | Download | only in x86
cpu.c revision 1.80.2.5
      1 /*	$NetBSD: cpu.c,v 1.80.2.5 2012/06/12 19:00:24 riz Exp $	*/
      2 /* NetBSD: cpu.c,v 1.18 2004/02/20 17:35:01 yamt Exp  */
      3 
      4 /*-
      5  * Copyright (c) 2000 The NetBSD Foundation, Inc.
      6  * Copyright (c) 2002, 2006, 2007 YAMAMOTO Takashi,
      7  * All rights reserved.
      8  *
      9  * This code is derived from software contributed to The NetBSD Foundation
     10  * by RedBack Networks Inc.
     11  *
     12  * Author: Bill Sommerfeld
     13  *
     14  * Redistribution and use in source and binary forms, with or without
     15  * modification, are permitted provided that the following conditions
     16  * are met:
     17  * 1. Redistributions of source code must retain the above copyright
     18  *    notice, this list of conditions and the following disclaimer.
     19  * 2. Redistributions in binary form must reproduce the above copyright
     20  *    notice, this list of conditions and the following disclaimer in the
     21  *    documentation and/or other materials provided with the distribution.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     24  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     26  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     27  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     33  * POSSIBILITY OF SUCH DAMAGE.
     34  */
     35 
     36 /*
     37  * Copyright (c) 1999 Stefan Grefen
     38  *
     39  * Redistribution and use in source and binary forms, with or without
     40  * modification, are permitted provided that the following conditions
     41  * are met:
     42  * 1. Redistributions of source code must retain the above copyright
     43  *    notice, this list of conditions and the following disclaimer.
     44  * 2. Redistributions in binary form must reproduce the above copyright
     45  *    notice, this list of conditions and the following disclaimer in the
     46  *    documentation and/or other materials provided with the distribution.
     47  * 3. All advertising materials mentioning features or use of this software
     48  *    must display the following acknowledgement:
     49  *      This product includes software developed by the NetBSD
     50  *      Foundation, Inc. and its contributors.
     51  * 4. Neither the name of The NetBSD Foundation nor the names of its
     52  *    contributors may be used to endorse or promote products derived
     53  *    from this software without specific prior written permission.
     54  *
     55  * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
     56  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     57  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     58  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR AND CONTRIBUTORS BE LIABLE
     59  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     60  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     61  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     62  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     63  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     64  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     65  * SUCH DAMAGE.
     66  */
     67 
     68 #include <sys/cdefs.h>
     69 __KERNEL_RCSID(0, "$NetBSD: cpu.c,v 1.80.2.5 2012/06/12 19:00:24 riz Exp $");
     70 
     71 #include "opt_ddb.h"
     72 #include "opt_multiprocessor.h"
     73 #include "opt_mpbios.h"		/* for MPDEBUG */
     74 #include "opt_mtrr.h"
     75 #include "opt_xen.h"
     76 
     77 #include "lapic.h"
     78 #include "ioapic.h"
     79 
     80 #include <sys/param.h>
     81 #include <sys/proc.h>
     82 #include <sys/systm.h>
     83 #include <sys/device.h>
     84 #include <sys/kmem.h>
     85 #include <sys/cpu.h>
     86 #include <sys/cpufreq.h>
     87 #include <sys/atomic.h>
     88 #include <sys/reboot.h>
     89 #include <sys/idle.h>
     90 
     91 #include <uvm/uvm.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/npx.h>
    107 #else
    108 #include <machine/fpu.h>
    109 #endif
    110 
    111 #include <xen/xen.h>
    112 #include <xen/xen-public/vcpu.h>
    113 #include <xen/vcpuvar.h>
    114 
    115 #if NLAPIC > 0
    116 #include <machine/apicvar.h>
    117 #include <machine/i82489reg.h>
    118 #include <machine/i82489var.h>
    119 #endif
    120 
    121 #include <dev/ic/mc146818reg.h>
    122 #include <dev/isa/isareg.h>
    123 
    124 static int	cpu_match(device_t, cfdata_t, void *);
    125 static void	cpu_attach(device_t, device_t, void *);
    126 static void	cpu_defer(device_t);
    127 static int	cpu_rescan(device_t, const char *, const int *);
    128 static void	cpu_childdetached(device_t, device_t);
    129 static int	vcpu_match(device_t, cfdata_t, void *);
    130 static void	vcpu_attach(device_t, device_t, void *);
    131 static void	cpu_attach_common(device_t, device_t, void *);
    132 void		cpu_offline_md(void);
    133 
    134 struct cpu_softc {
    135 	device_t sc_dev;		/* device tree glue */
    136 	struct cpu_info *sc_info;	/* pointer to CPU info */
    137 	bool sc_wasonline;
    138 };
    139 
    140 int mp_cpu_start(struct cpu_info *, vaddr_t);
    141 void mp_cpu_start_cleanup(struct cpu_info *);
    142 const struct cpu_functions mp_cpu_funcs = { mp_cpu_start, NULL,
    143 				      mp_cpu_start_cleanup };
    144 
    145 CFATTACH_DECL2_NEW(cpu, sizeof(struct cpu_softc),
    146     cpu_match, cpu_attach, NULL, NULL, cpu_rescan, cpu_childdetached);
    147 
    148 CFATTACH_DECL_NEW(vcpu, sizeof(struct cpu_softc),
    149     vcpu_match, vcpu_attach, NULL, NULL);
    150 
    151 /*
    152  * Statically-allocated CPU info for the primary CPU (or the only
    153  * CPU, on uniprocessors).  The CPU info list is initialized to
    154  * point at it.
    155  */
    156 #ifdef TRAPLOG
    157 #include <machine/tlog.h>
    158 struct tlog tlog_primary;
    159 #endif
    160 struct cpu_info cpu_info_primary __aligned(CACHE_LINE_SIZE) = {
    161 	.ci_dev = 0,
    162 	.ci_self = &cpu_info_primary,
    163 	.ci_idepth = -1,
    164 	.ci_curlwp = &lwp0,
    165 	.ci_curldt = -1,
    166 #ifdef TRAPLOG
    167 	.ci_tlog = &tlog_primary,
    168 #endif
    169 
    170 };
    171 struct cpu_info phycpu_info_primary __aligned(CACHE_LINE_SIZE) = {
    172 	.ci_dev = 0,
    173 	.ci_self = &phycpu_info_primary,
    174 };
    175 
    176 struct cpu_info *cpu_info_list = &cpu_info_primary;
    177 struct cpu_info *phycpu_info_list = &phycpu_info_primary;
    178 
    179 uint32_t cpu_feature[5]; /* X86 CPUID feature bits
    180 			  *	[0] basic features %edx
    181 			  *	[1] basic features %ecx
    182 			  *	[2] extended features %edx
    183 			  *	[3] extended features %ecx
    184 			  *	[4] VIA padlock features
    185 			  */
    186 
    187 bool x86_mp_online;
    188 paddr_t mp_trampoline_paddr = MP_TRAMPOLINE;
    189 
    190 #if defined(MULTIPROCESSOR)
    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 #endif	/* MULTIPROCESSOR */
    195 
    196 static int
    197 cpu_match(device_t parent, cfdata_t match, void *aux)
    198 {
    199 
    200 	return 1;
    201 }
    202 
    203 static void
    204 cpu_attach(device_t parent, device_t self, void *aux)
    205 {
    206 	struct cpu_softc *sc = device_private(self);
    207 	struct cpu_attach_args *caa = aux;
    208 	struct cpu_info *ci;
    209 	uintptr_t ptr;
    210 	static int nphycpu = 0;
    211 
    212 	sc->sc_dev = self;
    213 
    214 	/*
    215 	 * If we're an Application Processor, allocate a cpu_info
    216 	 * If we're the first attached CPU use the primary cpu_info,
    217 	 * otherwise allocate a new one
    218 	 */
    219 	aprint_naive("\n");
    220 	aprint_normal("\n");
    221 	if (nphycpu > 0) {
    222 		struct cpu_info *tmp;
    223 		ptr = (uintptr_t)kmem_zalloc(sizeof(*ci) + CACHE_LINE_SIZE - 1,
    224 		    KM_SLEEP);
    225 		ci = (struct cpu_info *)roundup2(ptr, CACHE_LINE_SIZE);
    226 		ci->ci_curldt = -1;
    227 
    228 		tmp = phycpu_info_list;
    229 		while (tmp->ci_next)
    230 			tmp = tmp->ci_next;
    231 
    232 		tmp->ci_next = ci;
    233 	} else {
    234 		ci = &phycpu_info_primary;
    235 	}
    236 
    237 	ci->ci_self = ci;
    238 	sc->sc_info = ci;
    239 
    240 	ci->ci_dev = self;
    241 	ci->ci_acpiid = caa->cpu_id;
    242 	ci->ci_cpuid = caa->cpu_number;
    243 	ci->ci_vcpu = NULL;
    244 	ci->ci_index = nphycpu++;
    245 
    246 	if (!pmf_device_register(self, NULL, NULL))
    247 		aprint_error_dev(self, "couldn't establish power handler\n");
    248 
    249 	(void)config_defer(self, cpu_defer);
    250 }
    251 
    252 static void
    253 cpu_defer(device_t self)
    254 {
    255 	cpu_rescan(self, NULL, NULL);
    256 }
    257 
    258 static int
    259 cpu_rescan(device_t self, const char *ifattr, const int *locators)
    260 {
    261 	struct cpu_softc *sc = device_private(self);
    262 	struct cpufeature_attach_args cfaa;
    263 	struct cpu_info *ci = sc->sc_info;
    264 
    265 	memset(&cfaa, 0, sizeof(cfaa));
    266 	cfaa.ci = ci;
    267 
    268 	if (ifattr_match(ifattr, "cpufeaturebus")) {
    269 
    270 		if (ci->ci_frequency == NULL) {
    271 			cfaa.name = "frequency";
    272 			ci->ci_frequency = config_found_ia(self,
    273 			    "cpufeaturebus", &cfaa, NULL);
    274 		}
    275 	}
    276 
    277 	return 0;
    278 }
    279 
    280 static void
    281 cpu_childdetached(device_t self, device_t child)
    282 {
    283 	struct cpu_softc *sc = device_private(self);
    284 	struct cpu_info *ci = sc->sc_info;
    285 
    286 	if (ci->ci_frequency == child)
    287 		ci->ci_frequency = NULL;
    288 }
    289 
    290 static int
    291 vcpu_match(device_t parent, cfdata_t match, void *aux)
    292 {
    293 	struct vcpu_attach_args *vcaa = aux;
    294 	struct vcpu_runstate_info vcr;
    295 	int error;
    296 
    297 	if (strcmp(vcaa->vcaa_name, match->cf_name) == 0) {
    298 		error = HYPERVISOR_vcpu_op(VCPUOP_get_runstate_info,
    299 					   vcaa->vcaa_caa.cpu_number,
    300 					   &vcr);
    301 		switch (error) {
    302 		case 0:
    303 			return 1;
    304 		case -ENOENT:
    305 			return 0;
    306 		default:
    307 			panic("Unknown hypervisor error %d returned on vcpu runstate probe\n", error);
    308 		}
    309 	}
    310 
    311 	return 0;
    312 }
    313 
    314 static void
    315 vcpu_attach(device_t parent, device_t self, void *aux)
    316 {
    317 	struct vcpu_attach_args *vcaa = aux;
    318 
    319 	KASSERT(vcaa->vcaa_caa.cpu_func == NULL);
    320 	vcaa->vcaa_caa.cpu_func = &mp_cpu_funcs;
    321 	cpu_attach_common(parent, self, &vcaa->vcaa_caa);
    322 
    323 	if (!pmf_device_register(self, NULL, NULL))
    324 		aprint_error_dev(self, "couldn't establish power handler\n");
    325 }
    326 
    327 static int
    328 vcpu_is_up(struct cpu_info *ci)
    329 {
    330 	KASSERT(ci != NULL);
    331 	return HYPERVISOR_vcpu_op(VCPUOP_is_up, ci->ci_cpuid, NULL);
    332 }
    333 
    334 static void
    335 cpu_vm_init(struct cpu_info *ci)
    336 {
    337 	int ncolors = 2, i;
    338 
    339 	for (i = CAI_ICACHE; i <= CAI_L2CACHE; i++) {
    340 		struct x86_cache_info *cai;
    341 		int tcolors;
    342 
    343 		cai = &ci->ci_cinfo[i];
    344 
    345 		tcolors = atop(cai->cai_totalsize);
    346 		switch(cai->cai_associativity) {
    347 		case 0xff:
    348 			tcolors = 1; /* fully associative */
    349 			break;
    350 		case 0:
    351 		case 1:
    352 			break;
    353 		default:
    354 			tcolors /= cai->cai_associativity;
    355 		}
    356 		ncolors = max(ncolors, tcolors);
    357 	}
    358 
    359 	/*
    360 	 * Knowing the size of the largest cache on this CPU, potentially
    361 	 * re-color our pages.
    362 	 */
    363 	aprint_debug_dev(ci->ci_dev, "%d page colors\n", ncolors);
    364 	uvm_page_recolor(ncolors);
    365 	pmap_tlb_cpu_init(ci);
    366 }
    367 
    368 static void
    369 cpu_attach_common(device_t parent, device_t self, void *aux)
    370 {
    371 	struct cpu_softc *sc = device_private(self);
    372 	struct cpu_attach_args *caa = aux;
    373 	struct cpu_info *ci;
    374 	uintptr_t ptr;
    375 	int cpunum = caa->cpu_number;
    376 	static bool again = false;
    377 
    378 	sc->sc_dev = self;
    379 
    380 	/*
    381 	 * If we're an Application Processor, allocate a cpu_info
    382 	 * structure, otherwise use the primary's.
    383 	 */
    384 	if (caa->cpu_role == CPU_ROLE_AP) {
    385 		aprint_naive(": Application Processor\n");
    386 		ptr = (uintptr_t)kmem_alloc(sizeof(*ci) + CACHE_LINE_SIZE - 1,
    387 		    KM_SLEEP);
    388 		ci = (struct cpu_info *)roundup2(ptr, CACHE_LINE_SIZE);
    389 		memset(ci, 0, sizeof(*ci));
    390 #ifdef TRAPLOG
    391 		ci->ci_tlog_base = kmem_zalloc(sizeof(struct tlog), KM_SLEEP);
    392 #endif
    393 	} else {
    394 		aprint_naive(": %s Processor\n",
    395 		    caa->cpu_role == CPU_ROLE_SP ? "Single" : "Boot");
    396 		ci = &cpu_info_primary;
    397 	}
    398 
    399 	ci->ci_self = ci;
    400 	sc->sc_info = ci;
    401 	ci->ci_dev = self;
    402 	ci->ci_cpuid = cpunum;
    403 
    404 	KASSERT(HYPERVISOR_shared_info != NULL);
    405 	ci->ci_vcpu = &HYPERVISOR_shared_info->vcpu_info[cpunum];
    406 
    407 	KASSERT(ci->ci_func == 0);
    408 	ci->ci_func = caa->cpu_func;
    409 
    410 	/* Must be called before mi_cpu_attach(). */
    411 	cpu_vm_init(ci);
    412 
    413 	if (caa->cpu_role == CPU_ROLE_AP) {
    414 		int error;
    415 
    416 		error = mi_cpu_attach(ci);
    417 
    418 		KASSERT(ci->ci_data.cpu_idlelwp != NULL);
    419 		if (error != 0) {
    420 			aprint_normal("\n");
    421 			aprint_error_dev(self,
    422 			    "mi_cpu_attach failed with %d\n", error);
    423 			return;
    424 		}
    425 
    426 	} else {
    427 		KASSERT(ci->ci_data.cpu_idlelwp != NULL);
    428 	}
    429 
    430 	pmap_reference(pmap_kernel());
    431 	ci->ci_pmap = pmap_kernel();
    432 	ci->ci_tlbstate = TLBSTATE_STALE;
    433 
    434 	/*
    435 	 * Boot processor may not be attached first, but the below
    436 	 * must be done to allow booting other processors.
    437 	 */
    438 	if (!again) {
    439 		atomic_or_32(&ci->ci_flags, CPUF_PRESENT | CPUF_PRIMARY);
    440 		/* Basic init. */
    441 		cpu_intr_init(ci);
    442 		cpu_get_tsc_freq(ci);
    443 		cpu_init(ci);
    444 		pmap_cpu_init_late(ci);
    445 
    446 		/* Every processor needs to init it's own ipi h/w (similar to lapic) */
    447 		xen_ipi_init();
    448 		/* XXX: clock_init() */
    449 
    450 		/* Make sure DELAY() is initialized. */
    451 		DELAY(1);
    452 		again = true;
    453 	}
    454 
    455 	/* further PCB init done later. */
    456 
    457 	switch (caa->cpu_role) {
    458 	case CPU_ROLE_SP:
    459 		atomic_or_32(&ci->ci_flags, CPUF_SP);
    460 		cpu_identify(ci);
    461 #if 0
    462 		x86_errata();
    463 #endif
    464 		x86_cpu_idle_init();
    465 
    466 		break;
    467 
    468 	case CPU_ROLE_BP:
    469 		atomic_or_32(&ci->ci_flags, CPUF_BSP);
    470 		cpu_identify(ci);
    471 #if 0
    472 		x86_errata();
    473 #endif
    474 		x86_cpu_idle_init();
    475 
    476 		break;
    477 
    478 	case CPU_ROLE_AP:
    479 		atomic_or_32(&ci->ci_flags, CPUF_AP);
    480 
    481 		/*
    482 		 * report on an AP
    483 		 */
    484 
    485 #if defined(MULTIPROCESSOR)
    486 		/* interrupt handler stack */
    487 		cpu_intr_init(ci);
    488 
    489 		/* Setup per-cpu memory for gdt */
    490 		gdt_alloc_cpu(ci);
    491 
    492 		pmap_cpu_init_late(ci);
    493 		cpu_start_secondary(ci);
    494 
    495 		if (ci->ci_flags & CPUF_PRESENT) {
    496 			struct cpu_info *tmp;
    497 
    498 			cpu_identify(ci);
    499 			tmp = cpu_info_list;
    500 			while (tmp->ci_next)
    501 				tmp = tmp->ci_next;
    502 
    503 			tmp->ci_next = ci;
    504 		}
    505 #else
    506 		aprint_error(": not started\n");
    507 #endif
    508 		break;
    509 
    510 	default:
    511 		aprint_normal("\n");
    512 		panic("unknown processor type??\n");
    513 	}
    514 
    515 #ifdef MPVERBOSE
    516 	if (mp_verbose) {
    517 		struct lwp *l = ci->ci_data.cpu_idlelwp;
    518 		struct pcb *pcb = lwp_getpcb(l);
    519 
    520 		aprint_verbose_dev(self,
    521 		    "idle lwp at %p, idle sp at 0x%p\n",
    522 		    l,
    523 #ifdef i386
    524 		    (void *)pcb->pcb_esp
    525 #else /* i386 */
    526 		    (void *)pcb->pcb_rsp
    527 #endif /* i386 */
    528 		);
    529 
    530 	}
    531 #endif /* MPVERBOSE */
    532 }
    533 
    534 /*
    535  * Initialize the processor appropriately.
    536  */
    537 
    538 void
    539 cpu_init(struct cpu_info *ci)
    540 {
    541 
    542 	/*
    543 	 * On a P6 or above, enable global TLB caching if the
    544 	 * hardware supports it.
    545 	 */
    546 	if (cpu_feature[0] & CPUID_PGE)
    547 		lcr4(rcr4() | CR4_PGE);	/* enable global TLB caching */
    548 
    549 #ifdef XXXMTRR
    550 	/*
    551 	 * On a P6 or above, initialize MTRR's if the hardware supports them.
    552 	 */
    553 	if (cpu_feature[0] & CPUID_MTRR) {
    554 		if ((ci->ci_flags & CPUF_AP) == 0)
    555 			i686_mtrr_init_first();
    556 		mtrr_init_cpu(ci);
    557 	}
    558 #endif
    559 	/*
    560 	 * If we have FXSAVE/FXRESTOR, use them.
    561 	 */
    562 	if (cpu_feature[0] & CPUID_FXSR) {
    563 		lcr4(rcr4() | CR4_OSFXSR);
    564 
    565 		/*
    566 		 * If we have SSE/SSE2, enable XMM exceptions.
    567 		 */
    568 		if (cpu_feature[0] & (CPUID_SSE|CPUID_SSE2))
    569 			lcr4(rcr4() | CR4_OSXMMEXCPT);
    570 	}
    571 
    572 #ifdef __x86_64__
    573 	/* No user PGD mapped for this CPU yet */
    574 	ci->ci_xen_current_user_pgd = 0;
    575 #endif
    576 #if defined(__x86_64__) || defined(PAE)
    577 	mutex_init(&ci->ci_kpm_mtx, MUTEX_DEFAULT, IPL_VM);
    578 #endif
    579 
    580 	atomic_or_32(&ci->ci_flags, CPUF_RUNNING);
    581 
    582 	/* XXX: register vcpu_register_runstate_memory_area, and figure out how to make sure this VCPU is running ? */
    583 }
    584 
    585 
    586 #ifdef MULTIPROCESSOR
    587 
    588 void
    589 cpu_boot_secondary_processors(void)
    590 {
    591 	struct cpu_info *ci;
    592 	u_long i;
    593 	for (i = 0; i < maxcpus; i++) {
    594 		ci = cpu_lookup(i);
    595 		if (ci == NULL)
    596 			continue;
    597 		if (ci->ci_data.cpu_idlelwp == NULL)
    598 			continue;
    599 		if ((ci->ci_flags & CPUF_PRESENT) == 0)
    600 			continue;
    601 		if (ci->ci_flags & (CPUF_BSP|CPUF_SP|CPUF_PRIMARY))
    602 			continue;
    603 		cpu_boot_secondary(ci);
    604 	}
    605 
    606 	x86_mp_online = true;
    607 }
    608 
    609 static void
    610 cpu_init_idle_lwp(struct cpu_info *ci)
    611 {
    612 	struct lwp *l = ci->ci_data.cpu_idlelwp;
    613 	struct pcb *pcb = lwp_getpcb(l);
    614 
    615 	pcb->pcb_cr0 = rcr0();
    616 }
    617 
    618 void
    619 cpu_init_idle_lwps(void)
    620 {
    621 	struct cpu_info *ci;
    622 	u_long i;
    623 
    624 	for (i = 0; i < maxcpus; i++) {
    625 		ci = cpu_lookup(i);
    626 		if (ci == NULL)
    627 			continue;
    628 		if (ci->ci_data.cpu_idlelwp == NULL)
    629 			continue;
    630 		if ((ci->ci_flags & CPUF_PRESENT) == 0)
    631 			continue;
    632 		cpu_init_idle_lwp(ci);
    633 	}
    634 }
    635 
    636 static void
    637 cpu_start_secondary(struct cpu_info *ci)
    638 {
    639 	int i;
    640 
    641 	aprint_debug_dev(ci->ci_dev, "starting\n");
    642 
    643 	ci->ci_curlwp = ci->ci_data.cpu_idlelwp;
    644 
    645 	if (CPU_STARTUP(ci, (vaddr_t) cpu_hatch) != 0) {
    646 		return;
    647 	}
    648 
    649 	/*
    650 	 * wait for it to become ready
    651 	 */
    652 	for (i = 100000; (!(ci->ci_flags & CPUF_PRESENT)) && i > 0; i--) {
    653 		delay(10);
    654 	}
    655 	if ((ci->ci_flags & CPUF_PRESENT) == 0) {
    656 		aprint_error_dev(ci->ci_dev, "failed to become ready\n");
    657 #if defined(MPDEBUG) && defined(DDB)
    658 		printf("dropping into debugger; continue from here to resume boot\n");
    659 		Debugger();
    660 #endif
    661 	}
    662 
    663 	CPU_START_CLEANUP(ci);
    664 }
    665 
    666 void
    667 cpu_boot_secondary(struct cpu_info *ci)
    668 {
    669 	int i;
    670 	atomic_or_32(&ci->ci_flags, CPUF_GO);
    671 	for (i = 100000; (!(ci->ci_flags & CPUF_RUNNING)) && i > 0; i--) {
    672 		delay(10);
    673 	}
    674 	if ((ci->ci_flags & CPUF_RUNNING) == 0) {
    675 		aprint_error_dev(ci->ci_dev, "CPU failed to start\n");
    676 #if defined(MPDEBUG) && defined(DDB)
    677 		printf("dropping into debugger; continue from here to resume boot\n");
    678 		Debugger();
    679 #endif
    680 	}
    681 }
    682 
    683 /*
    684  * APs end up here immediately after initialisation and VCPUOP_up in
    685  * mp_cpu_start().
    686  * At this point, we are running in the idle pcb/idle stack of the new
    687  * CPU.  This function jumps to the idle loop and starts looking for
    688  * work.
    689  */
    690 extern void x86_64_tls_switch(struct lwp *);
    691 void
    692 cpu_hatch(void *v)
    693 {
    694 	struct cpu_info *ci = (struct cpu_info *)v;
    695 	struct pcb *pcb;
    696 	int s, i;
    697 
    698 	/* Setup TLS and kernel GS/FS */
    699 	cpu_init_msrs(ci, true);
    700 	cpu_init_idt();
    701 	gdt_init_cpu(ci);
    702 
    703 	cpu_probe(ci);
    704 
    705 	atomic_or_32(&ci->ci_flags, CPUF_PRESENT);
    706 
    707 	while ((ci->ci_flags & CPUF_GO) == 0) {
    708 		/* Don't use delay, boot CPU may be patching the text. */
    709 		for (i = 10000; i != 0; i--)
    710 			x86_pause();
    711 	}
    712 
    713 	/* Because the text may have been patched in x86_patch(). */
    714 	x86_flush();
    715 	tlbflushg();
    716 
    717 	KASSERT((ci->ci_flags & CPUF_RUNNING) == 0);
    718 
    719 	pcb = lwp_getpcb(curlwp);
    720 	pcb->pcb_cr3 = pmap_pdirpa(pmap_kernel(), 0); /* XXX: consider using pmap_load() ? */
    721 	pcb = lwp_getpcb(ci->ci_data.cpu_idlelwp);
    722 
    723 	xen_ipi_init();
    724 
    725 	xen_initclocks();
    726 
    727 	/* XXX: lapic_initclocks(); */
    728 
    729 #ifdef __x86_64__
    730 	fpuinit(ci);
    731 #endif
    732 
    733 	lldt(GSEL(GLDT_SEL, SEL_KPL));
    734 
    735 	cpu_init(ci);
    736 	cpu_get_tsc_freq(ci);
    737 
    738 	s = splhigh();
    739 	x86_enable_intr();
    740 	splx(s);
    741 #if 0
    742 	x86_errata();
    743 #endif
    744 
    745 	aprint_debug_dev(ci->ci_dev, "running\n");
    746 
    747 	cpu_switchto(NULL, ci->ci_data.cpu_idlelwp, true);
    748 
    749 	idle_loop(NULL);
    750 	KASSERT(false);
    751 }
    752 
    753 #if defined(DDB)
    754 
    755 #include <ddb/db_output.h>
    756 #include <machine/db_machdep.h>
    757 
    758 /*
    759  * Dump CPU information from ddb.
    760  */
    761 void
    762 cpu_debug_dump(void)
    763 {
    764 	struct cpu_info *ci;
    765 	CPU_INFO_ITERATOR cii;
    766 
    767 	db_printf("addr		dev	id	flags	ipis	curlwp 		fpcurlwp\n");
    768 	for (CPU_INFO_FOREACH(cii, ci)) {
    769 		db_printf("%p	%s	%ld	%x	%x	%10p	%10p\n",
    770 		    ci,
    771 		    ci->ci_dev == NULL ? "BOOT" : device_xname(ci->ci_dev),
    772 		    (long)ci->ci_cpuid,
    773 		    ci->ci_flags, ci->ci_ipis,
    774 		    ci->ci_curlwp,
    775 		    ci->ci_fpcurlwp);
    776 	}
    777 }
    778 #endif /* DDB */
    779 
    780 #endif /* MULTIPROCESSOR */
    781 
    782 extern void hypervisor_callback(void);
    783 extern void failsafe_callback(void);
    784 #ifdef __x86_64__
    785 typedef void (vector)(void);
    786 extern vector Xsyscall, Xsyscall32;
    787 #endif
    788 
    789 /*
    790  * Setup the "trampoline". On Xen, we setup nearly all cpu context
    791  * outside a trampoline, so we prototype and call targetip like so:
    792  * void targetip(struct cpu_info *);
    793  */
    794 
    795 static void
    796 gdt_prepframes(paddr_t *frames, vaddr_t base, uint32_t entries)
    797 {
    798 	int i;
    799 	for (i = 0; i < roundup(entries, PAGE_SIZE) >> PAGE_SHIFT; i++) {
    800 
    801 		frames[i] = ((paddr_t) xpmap_ptetomach(
    802 				(pt_entry_t *) (base + (i << PAGE_SHIFT))))
    803 			>> PAGE_SHIFT;
    804 
    805 		/* Mark Read-only */
    806 		pmap_pte_clearbits(kvtopte(base + (i << PAGE_SHIFT)),
    807 		    PG_RW);
    808 	}
    809 }
    810 
    811 #ifdef __x86_64__
    812 extern char *ldtstore; /* XXX: Xen MP todo */
    813 
    814 static void
    815 xen_init_amd64_vcpuctxt(struct cpu_info *ci,
    816 			struct vcpu_guest_context *initctx,
    817 			void targetrip(struct cpu_info *))
    818 {
    819 	/* page frames to point at GDT */
    820 	extern int gdt_size;
    821 	paddr_t frames[16];
    822 	psize_t gdt_ents;
    823 
    824 	struct lwp *l;
    825 	struct pcb *pcb;
    826 
    827 	volatile struct vcpu_info *vci;
    828 
    829 	KASSERT(ci != NULL);
    830 	KASSERT(ci != &cpu_info_primary);
    831 	KASSERT(initctx != NULL);
    832 	KASSERT(targetrip != NULL);
    833 
    834 	memset(initctx, 0, sizeof *initctx);
    835 
    836 	gdt_ents = roundup(gdt_size, PAGE_SIZE) >> PAGE_SHIFT; /* XXX: re-investigate roundup(gdt_size... ) for gdt_ents. */
    837 	KASSERT(gdt_ents <= 16);
    838 
    839 	gdt_prepframes(frames, (vaddr_t) ci->ci_gdt, gdt_ents);
    840 
    841 	/* XXX: The stuff in here is amd64 specific. move to mptramp.[Sc] ? */
    842 
    843 	/* Initialise the vcpu context: We use idle_loop()'s pcb context. */
    844 
    845 	l = ci->ci_data.cpu_idlelwp;
    846 
    847 	KASSERT(l != NULL);
    848 	pcb = lwp_getpcb(l);
    849 	KASSERT(pcb != NULL);
    850 
    851 	/* resume with interrupts off */
    852 	vci = ci->ci_vcpu;
    853 	vci->evtchn_upcall_mask = 1;
    854 	xen_mb();
    855 
    856 	/* resume in kernel-mode */
    857 	initctx->flags = VGCF_in_kernel | VGCF_online;
    858 
    859 	/* Stack and entry points:
    860 	 * We arrange for the stack frame for cpu_hatch() to
    861 	 * appear as a callee frame of lwp_trampoline(). Being a
    862 	 * leaf frame prevents trampling on any of the MD stack setup
    863 	 * that x86/vm_machdep.c:cpu_lwp_fork() does for idle_loop()
    864 	 */
    865 
    866 	initctx->user_regs.rdi = (uint64_t) ci; /* targetrip(ci); */
    867 	initctx->user_regs.rip = (vaddr_t) targetrip;
    868 
    869 	initctx->user_regs.cs = GSEL(GCODE_SEL, SEL_KPL);
    870 
    871 	initctx->user_regs.rflags = pcb->pcb_flags;
    872 	initctx->user_regs.rsp = pcb->pcb_rsp;
    873 
    874 	/* Data segments */
    875 	initctx->user_regs.ss = GSEL(GDATA_SEL, SEL_KPL);
    876 	initctx->user_regs.es = GSEL(GDATA_SEL, SEL_KPL);
    877 	initctx->user_regs.ds = GSEL(GDATA_SEL, SEL_KPL);
    878 
    879 	/* GDT */
    880 	memcpy(initctx->gdt_frames, frames, sizeof frames);
    881 	initctx->gdt_ents = gdt_ents;
    882 
    883 	/* LDT */
    884 	initctx->ldt_base = (unsigned long) ldtstore;
    885 	initctx->ldt_ents = LDT_SIZE >> 3;
    886 
    887 	/* Kernel context state */
    888 	initctx->kernel_ss = GSEL(GDATA_SEL, SEL_KPL);
    889 	initctx->kernel_sp = pcb->pcb_rsp0;
    890 	initctx->ctrlreg[0] = pcb->pcb_cr0;
    891 	initctx->ctrlreg[1] = 0; /* "resuming" from kernel - no User cr3. */
    892 	initctx->ctrlreg[2] = pcb->pcb_cr2; /* XXX: */
    893 	/*
    894 	 * Use pmap_kernel() L4 PD directly, until we setup the
    895 	 * per-cpu L4 PD in pmap_cpu_init_late()
    896 	 */
    897 	initctx->ctrlreg[3] = xen_pfn_to_cr3(x86_btop(xpmap_ptom(ci->ci_kpm_pdirpa)));
    898 	initctx->ctrlreg[4] = CR4_PAE | CR4_OSFXSR | CR4_OSXMMEXCPT;
    899 
    900 
    901 	/* Xen callbacks */
    902 	initctx->event_callback_eip = (unsigned long) hypervisor_callback;
    903 	initctx->failsafe_callback_eip = (unsigned long) failsafe_callback;
    904 	initctx->syscall_callback_eip = (unsigned long) Xsyscall;
    905 
    906 	return;
    907 }
    908 #else /* i386 */
    909 extern union descriptor *ldt;
    910 extern void Xsyscall(void);
    911 
    912 static void
    913 xen_init_i386_vcpuctxt(struct cpu_info *ci,
    914 			struct vcpu_guest_context *initctx,
    915 			void targeteip(struct cpu_info *))
    916 {
    917 	/* page frames to point at GDT */
    918 	extern int gdt_size;
    919 	paddr_t frames[16];
    920 	psize_t gdt_ents;
    921 
    922 	struct lwp *l;
    923 	struct pcb *pcb;
    924 
    925 	volatile struct vcpu_info *vci;
    926 
    927 	KASSERT(ci != NULL);
    928 	KASSERT(ci != &cpu_info_primary);
    929 	KASSERT(initctx != NULL);
    930 	KASSERT(targeteip != NULL);
    931 
    932 	memset(initctx, 0, sizeof *initctx);
    933 
    934 	gdt_ents = roundup(gdt_size, PAGE_SIZE) >> PAGE_SHIFT; /* XXX: re-investigate roundup(gdt_size... ) for gdt_ents. */
    935 	KASSERT(gdt_ents <= 16);
    936 
    937 	gdt_prepframes(frames, (vaddr_t) ci->ci_gdt, gdt_ents);
    938 
    939 	/*
    940 	 * Initialise the vcpu context:
    941 	 * We use this cpu's idle_loop() pcb context.
    942 	 */
    943 
    944 	l = ci->ci_data.cpu_idlelwp;
    945 
    946 	KASSERT(l != NULL);
    947 	pcb = lwp_getpcb(l);
    948 	KASSERT(pcb != NULL);
    949 
    950 	/* resume with interrupts off */
    951 	vci = ci->ci_vcpu;
    952 	vci->evtchn_upcall_mask = 1;
    953 	xen_mb();
    954 
    955 	/* resume in kernel-mode */
    956 	initctx->flags = VGCF_in_kernel | VGCF_online;
    957 
    958 	/* Stack frame setup for cpu_hatch():
    959 	 * We arrange for the stack frame for cpu_hatch() to
    960 	 * appear as a callee frame of lwp_trampoline(). Being a
    961 	 * leaf frame prevents trampling on any of the MD stack setup
    962 	 * that x86/vm_machdep.c:cpu_lwp_fork() does for idle_loop()
    963 	 */
    964 
    965 	initctx->user_regs.esp = pcb->pcb_esp - 4; /* Leave word for
    966 						      arg1 */
    967 	{ /* targeteip(ci); */
    968 		uint32_t *arg = (uint32_t *) initctx->user_regs.esp;
    969 		arg[1] = (uint32_t) ci; /* arg1 */
    970 
    971 	}
    972 
    973 	initctx->user_regs.eip = (vaddr_t) targeteip;
    974 	initctx->user_regs.cs = GSEL(GCODE_SEL, SEL_KPL);
    975 	initctx->user_regs.eflags |= pcb->pcb_iopl;
    976 
    977 	/* Data segments */
    978 	initctx->user_regs.ss = GSEL(GDATA_SEL, SEL_KPL);
    979 	initctx->user_regs.es = GSEL(GDATA_SEL, SEL_KPL);
    980 	initctx->user_regs.ds = GSEL(GDATA_SEL, SEL_KPL);
    981 	initctx->user_regs.fs = GSEL(GDATA_SEL, SEL_KPL);
    982 
    983 	/* GDT */
    984 	memcpy(initctx->gdt_frames, frames, sizeof frames);
    985 	initctx->gdt_ents = gdt_ents;
    986 
    987 	/* LDT */
    988 	initctx->ldt_base = (unsigned long) ldt;
    989 	initctx->ldt_ents = NLDT;
    990 
    991 	/* Kernel context state */
    992 	initctx->kernel_ss = GSEL(GDATA_SEL, SEL_KPL);
    993 	initctx->kernel_sp = pcb->pcb_esp0;
    994 	initctx->ctrlreg[0] = pcb->pcb_cr0;
    995 	initctx->ctrlreg[1] = 0; /* "resuming" from kernel - no User cr3. */
    996 	initctx->ctrlreg[2] = pcb->pcb_cr2; /* XXX: */
    997 #ifdef PAE
    998 	initctx->ctrlreg[3] = xen_pfn_to_cr3(x86_btop(xpmap_ptom(ci->ci_pae_l3_pdirpa)));
    999 #else /* PAE */
   1000 	initctx->ctrlreg[3] = xen_pfn_to_cr3(x86_btop(xpmap_ptom(pcb->pcb_cr3)));
   1001 #endif /* PAE */
   1002 	initctx->ctrlreg[4] = /* CR4_PAE |  */CR4_OSFXSR | CR4_OSXMMEXCPT;
   1003 
   1004 
   1005 	/* Xen callbacks */
   1006 	initctx->event_callback_eip = (unsigned long) hypervisor_callback;
   1007 	initctx->event_callback_cs = GSEL(GCODE_SEL, SEL_KPL);
   1008 	initctx->failsafe_callback_eip = (unsigned long) failsafe_callback;
   1009 	initctx->failsafe_callback_cs = GSEL(GCODE_SEL, SEL_KPL);
   1010 
   1011 	return;
   1012 }
   1013 #endif /* __x86_64__ */
   1014 
   1015 int
   1016 mp_cpu_start(struct cpu_info *ci, vaddr_t target)
   1017 {
   1018 
   1019 	int hyperror;
   1020 	struct vcpu_guest_context vcpuctx;
   1021 
   1022 	KASSERT(ci != NULL);
   1023 	KASSERT(ci != &cpu_info_primary);
   1024 	KASSERT(ci->ci_flags & CPUF_AP);
   1025 
   1026 #ifdef __x86_64__
   1027 	xen_init_amd64_vcpuctxt(ci, &vcpuctx, (void (*)(struct cpu_info *))target);
   1028 #else  /* i386 */
   1029 	xen_init_i386_vcpuctxt(ci, &vcpuctx, (void (*)(struct cpu_info *))target);
   1030 #endif /* __x86_64__ */
   1031 
   1032 	/* Initialise the given vcpu to execute cpu_hatch(ci); */
   1033 	if ((hyperror = HYPERVISOR_vcpu_op(VCPUOP_initialise, ci->ci_cpuid, &vcpuctx))) {
   1034 		aprint_error(": context initialisation failed. errno = %d\n", hyperror);
   1035 		return hyperror;
   1036 	}
   1037 
   1038 	/* Start it up */
   1039 
   1040 	/* First bring it down */
   1041 	if ((hyperror = HYPERVISOR_vcpu_op(VCPUOP_down, ci->ci_cpuid, NULL))) {
   1042 		aprint_error(": VCPUOP_down hypervisor command failed. errno = %d\n", hyperror);
   1043 		return hyperror;
   1044 	}
   1045 
   1046 	if ((hyperror = HYPERVISOR_vcpu_op(VCPUOP_up, ci->ci_cpuid, NULL))) {
   1047 		aprint_error(": VCPUOP_up hypervisor command failed. errno = %d\n", hyperror);
   1048 		return hyperror;
   1049 	}
   1050 
   1051 	if (!vcpu_is_up(ci)) {
   1052 		aprint_error(": did not come up\n");
   1053 		return -1;
   1054 	}
   1055 
   1056 	return 0;
   1057 }
   1058 
   1059 void
   1060 mp_cpu_start_cleanup(struct cpu_info *ci)
   1061 {
   1062 #if 0
   1063 	/*
   1064 	 * Ensure the NVRAM reset byte contains something vaguely sane.
   1065 	 */
   1066 
   1067 	outb(IO_RTC, NVRAM_RESET);
   1068 	outb(IO_RTC+1, NVRAM_RESET_RST);
   1069 #endif
   1070 	if (vcpu_is_up(ci)) {
   1071 		aprint_debug_dev(ci->ci_dev, "is started.\n");
   1072 	}
   1073 	else {
   1074 		aprint_error_dev(ci->ci_dev, "did not start up.\n");
   1075 	}
   1076 
   1077 }
   1078 
   1079 /* curcpu() uses %fs - shim for until cpu_init_msrs(), below */
   1080 static struct cpu_info *cpu_primary(void)
   1081 {
   1082 	return &cpu_info_primary;
   1083 }
   1084 /* XXX: rename to something more generic. users other than xpq exist */
   1085 struct cpu_info	* (*xpq_cpu)(void) = cpu_primary;
   1086 
   1087 void
   1088 cpu_init_msrs(struct cpu_info *ci, bool full)
   1089 {
   1090 #ifdef __x86_64__
   1091 	if (full) {
   1092 		HYPERVISOR_set_segment_base (SEGBASE_FS, 0);
   1093 		HYPERVISOR_set_segment_base (SEGBASE_GS_KERNEL, (uint64_t) ci);
   1094 		HYPERVISOR_set_segment_base (SEGBASE_GS_USER, 0);
   1095 		xpq_cpu = x86_curcpu;
   1096 	}
   1097 #endif	/* __x86_64__ */
   1098 
   1099 	if (cpu_feature[2] & CPUID_NOX)
   1100 		wrmsr(MSR_EFER, rdmsr(MSR_EFER) | EFER_NXE);
   1101 
   1102 }
   1103 
   1104 void
   1105 cpu_offline_md(void)
   1106 {
   1107         int s;
   1108 
   1109         s = splhigh();
   1110 #ifdef __i386__
   1111         npxsave_cpu(true);
   1112 #else
   1113         fpusave_cpu(true);
   1114 #endif
   1115         splx(s);
   1116 }
   1117 
   1118 void
   1119 cpu_get_tsc_freq(struct cpu_info *ci)
   1120 {
   1121 	uint32_t vcpu_tversion;
   1122 	const volatile vcpu_time_info_t *tinfo = &ci->ci_vcpu->time;
   1123 
   1124 	vcpu_tversion = tinfo->version;
   1125 	while (tinfo->version == vcpu_tversion); /* Wait for a time update. XXX: timeout ? */
   1126 
   1127 	uint64_t freq = 1000000000ULL << 32;
   1128 	freq = freq / (uint64_t)tinfo->tsc_to_system_mul;
   1129 	if ( tinfo->tsc_shift < 0 )
   1130 		freq = freq << -tinfo->tsc_shift;
   1131 	else
   1132 		freq = freq >> tinfo->tsc_shift;
   1133 	ci->ci_data.cpu_cc_freq = freq;
   1134 }
   1135 
   1136 void
   1137 x86_cpu_idle_xen(void)
   1138 {
   1139 	struct cpu_info *ci = curcpu();
   1140 
   1141 	KASSERT(ci->ci_ilevel == IPL_NONE);
   1142 
   1143 	x86_disable_intr();
   1144 	if (!__predict_false(ci->ci_want_resched)) {
   1145 		idle_block();
   1146 	} else {
   1147 		x86_enable_intr();
   1148 	}
   1149 }
   1150 
   1151 /*
   1152  * Loads pmap for the current CPU.
   1153  */
   1154 void
   1155 cpu_load_pmap(struct pmap *pmap, struct pmap *oldpmap)
   1156 {
   1157 #if defined(__x86_64__) || defined(PAE)
   1158 	struct cpu_info *ci = curcpu();
   1159 	cpuid_t cid = cpu_index(ci);
   1160 
   1161 	mutex_enter(&ci->ci_kpm_mtx);
   1162 	/* make new pmap visible to pmap_kpm_sync_xcall() */
   1163 	kcpuset_atomic_set(pmap->pm_xen_ptp_cpus, cid);
   1164 #endif
   1165 #ifdef i386
   1166 #ifdef PAE
   1167 	{
   1168 		int i;
   1169 		paddr_t l3_pd = xpmap_ptom_masked(ci->ci_pae_l3_pdirpa);
   1170 		/* don't update the kernel L3 slot */
   1171 		for (i = 0 ; i < PDP_SIZE - 1; i++) {
   1172 			xpq_queue_pte_update(l3_pd + i * sizeof(pd_entry_t),
   1173 			    xpmap_ptom(pmap->pm_pdirpa[i]) | PG_V);
   1174 		}
   1175 		tlbflush();
   1176 	}
   1177 #else /* PAE */
   1178 	lcr3(pmap_pdirpa(pmap, 0));
   1179 #endif /* PAE */
   1180 #endif /* i386 */
   1181 
   1182 #ifdef __x86_64__
   1183 	{
   1184 		int i;
   1185 		pd_entry_t *new_pgd;
   1186 		paddr_t l4_pd_ma;
   1187 
   1188 		l4_pd_ma = xpmap_ptom_masked(ci->ci_kpm_pdirpa);
   1189 
   1190 		/*
   1191 		 * Map user space address in kernel space and load
   1192 		 * user cr3
   1193 		 */
   1194 		new_pgd = pmap->pm_pdir;
   1195 		KASSERT(pmap == ci->ci_pmap);
   1196 
   1197 		/* Copy user pmap L4 PDEs (in user addr. range) to per-cpu L4 */
   1198 		for (i = 0; i < PDIR_SLOT_PTE; i++) {
   1199 			KASSERT(pmap != pmap_kernel() || new_pgd[i] == 0);
   1200 			if (ci->ci_kpm_pdir[i] != new_pgd[i]) {
   1201 				xpq_queue_pte_update(
   1202 				   l4_pd_ma + i * sizeof(pd_entry_t),
   1203 				    new_pgd[i]);
   1204 			}
   1205 		}
   1206 
   1207 		if (__predict_true(pmap != pmap_kernel())) {
   1208 			xen_set_user_pgd(pmap_pdirpa(pmap, 0));
   1209 			ci->ci_xen_current_user_pgd = pmap_pdirpa(pmap, 0);
   1210 		}
   1211 		else {
   1212 			xpq_queue_pt_switch(l4_pd_ma);
   1213 			ci->ci_xen_current_user_pgd = 0;
   1214 		}
   1215 
   1216 		tlbflush();
   1217 	}
   1218 
   1219 #endif /* __x86_64__ */
   1220 #if defined(__x86_64__) || defined(PAE)
   1221 	/* old pmap no longer visible to pmap_kpm_sync_xcall() */
   1222 	if (oldpmap != pmap_kernel()) {
   1223 		kcpuset_atomic_clear(oldpmap->pm_xen_ptp_cpus, cid);
   1224 	}
   1225 	mutex_exit(&ci->ci_kpm_mtx);
   1226 #endif
   1227 }
   1228 
   1229  /*
   1230   * pmap_cpu_init_late: perform late per-CPU initialization.
   1231   * Short note about percpu PDIR pages:
   1232   * Both the PAE and __x86_64__ architectures have per-cpu PDIR
   1233   * tables. This is to get around Xen's pagetable setup constraints for
   1234   * PAE (multiple L3[3]s cannot point to the same L2 - Xen
   1235   * will refuse to pin a table setup this way.) and for multiple cpus
   1236   * to map in different user pmaps on __x86_64__ (see: cpu_load_pmap())
   1237   *
   1238   * What this means for us is that the PDIR of the pmap_kernel() is
   1239   * considered to be a canonical "SHADOW" PDIR with the following
   1240   * properties:
   1241   * - Its recursive mapping points to itself
   1242   * - per-cpu recurseive mappings point to themselves on __x86_64__
   1243   * - per-cpu L4 pages' kernel entries are expected to be in sync with
   1244   *   the shadow
   1245   */
   1246 
   1247 void
   1248 pmap_cpu_init_late(struct cpu_info *ci)
   1249 {
   1250 #if defined(PAE) || defined(__x86_64__)
   1251 	/*
   1252 	 * The BP has already its own PD page allocated during early
   1253 	 * MD startup.
   1254 	 */
   1255 
   1256 #if defined(__x86_64__)
   1257 	/* Setup per-cpu normal_pdes */
   1258 	int i;
   1259 	extern pd_entry_t * const normal_pdes[];
   1260 	for (i = 0;i < PTP_LEVELS - 1;i++) {
   1261 		ci->ci_normal_pdes[i] = normal_pdes[i];
   1262 	}
   1263 #endif /* __x86_64__ */
   1264 
   1265 	if (ci == &cpu_info_primary)
   1266 		return;
   1267 
   1268 	KASSERT(ci != NULL);
   1269 
   1270 #if defined(PAE)
   1271 	cpu_alloc_l3_page(ci);
   1272 	KASSERT(ci->ci_pae_l3_pdirpa != 0);
   1273 
   1274 	/* Initialise L2 entries 0 - 2: Point them to pmap_kernel() */
   1275 	int i;
   1276 	for (i = 0 ; i < PDP_SIZE - 1; i++) {
   1277 		ci->ci_pae_l3_pdir[i] =
   1278 		    xpmap_ptom_masked(pmap_kernel()->pm_pdirpa[i]) | PG_V;
   1279 	}
   1280 #endif /* PAE */
   1281 
   1282 	ci->ci_kpm_pdir = (pd_entry_t *)uvm_km_alloc(kernel_map, PAGE_SIZE, 0,
   1283 	    UVM_KMF_WIRED | UVM_KMF_ZERO | UVM_KMF_NOWAIT);
   1284 
   1285 	if (ci->ci_kpm_pdir == NULL) {
   1286 		panic("%s: failed to allocate L4 per-cpu PD for CPU %d\n",
   1287 		      __func__, cpu_index(ci));
   1288 	}
   1289 	ci->ci_kpm_pdirpa = vtophys((vaddr_t) ci->ci_kpm_pdir);
   1290 	KASSERT(ci->ci_kpm_pdirpa != 0);
   1291 
   1292 #if defined(__x86_64__)
   1293 	/*
   1294 	 * Copy over the pmap_kernel() shadow L4 entries
   1295 	 */
   1296 
   1297 	memcpy(ci->ci_kpm_pdir, pmap_kernel()->pm_pdir, PAGE_SIZE);
   1298 
   1299 	/* Recursive kernel mapping */
   1300 	ci->ci_kpm_pdir[PDIR_SLOT_PTE] = xpmap_ptom_masked(ci->ci_kpm_pdirpa) | PG_k | PG_V;
   1301 #elif defined(PAE)
   1302 	/* Copy over the pmap_kernel() shadow L2 entries that map the kernel */
   1303 	memcpy(ci->ci_kpm_pdir, pmap_kernel()->pm_pdir + PDIR_SLOT_KERN, nkptp[PTP_LEVELS - 1] * sizeof(pd_entry_t));
   1304 #endif /* __x86_64__ else PAE */
   1305 
   1306 	/* Xen wants R/O */
   1307 	pmap_protect(pmap_kernel(), (vaddr_t)ci->ci_kpm_pdir,
   1308 	    (vaddr_t)ci->ci_kpm_pdir + PAGE_SIZE, VM_PROT_READ);
   1309 	pmap_update(pmap_kernel());
   1310 #if defined(PAE)
   1311 	/* Initialise L3 entry 3. This mapping is shared across all
   1312 	 * pmaps and is static, ie; loading a new pmap will not update
   1313 	 * this entry.
   1314 	 */
   1315 
   1316 	ci->ci_pae_l3_pdir[3] = xpmap_ptom_masked(ci->ci_kpm_pdirpa) | PG_k | PG_V;
   1317 
   1318 	/* Mark L3 R/O (Xen wants this) */
   1319 	pmap_protect(pmap_kernel(), (vaddr_t)ci->ci_pae_l3_pdir,
   1320 	    (vaddr_t)ci->ci_pae_l3_pdir + PAGE_SIZE, VM_PROT_READ);
   1321 	pmap_update(pmap_kernel());
   1322 
   1323 	xpq_queue_pin_l3_table(xpmap_ptom_masked(ci->ci_pae_l3_pdirpa));
   1324 
   1325 #elif defined(__x86_64__)
   1326 	xpq_queue_pin_l4_table(xpmap_ptom_masked(ci->ci_kpm_pdirpa));
   1327 #endif /* PAE , __x86_64__ */
   1328 #endif /* defined(PAE) || defined(__x86_64__) */
   1329 }
   1330 
   1331 /*
   1332  * Notify all other cpus to halt.
   1333  */
   1334 
   1335 void
   1336 cpu_broadcast_halt(void)
   1337 {
   1338 	xen_broadcast_ipi(XEN_IPI_HALT);
   1339 }
   1340 
   1341 /*
   1342  * Send a dummy ipi to a cpu.
   1343  */
   1344 
   1345 void
   1346 cpu_kick(struct cpu_info *ci)
   1347 {
   1348 	(void)xen_send_ipi(ci, XEN_IPI_KICK);
   1349 }
   1350