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