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