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