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