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