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