cpu.c revision 1.100 1 /* $NetBSD: cpu.c,v 1.100 2014/11/27 16:29:44 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.100 2014/11/27 16:29:44 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 #include <x86/fpu.h>
106
107 #include <xen/xen.h>
108 #include <xen/xen-public/vcpu.h>
109 #include <xen/vcpuvar.h>
110
111 #if NLAPIC > 0
112 #include <machine/apicvar.h>
113 #include <machine/i82489reg.h>
114 #include <machine/i82489var.h>
115 #endif
116
117 #include <dev/ic/mc146818reg.h>
118 #include <dev/isa/isareg.h>
119
120 static int cpu_match(device_t, cfdata_t, void *);
121 static void cpu_attach(device_t, device_t, void *);
122 static void cpu_defer(device_t);
123 static int cpu_rescan(device_t, const char *, const int *);
124 static void cpu_childdetached(device_t, device_t);
125 static int vcpu_match(device_t, cfdata_t, void *);
126 static void vcpu_attach(device_t, device_t, void *);
127 static void cpu_attach_common(device_t, device_t, void *);
128 void cpu_offline_md(void);
129
130 struct cpu_softc {
131 device_t sc_dev; /* device tree glue */
132 struct cpu_info *sc_info; /* pointer to CPU info */
133 bool sc_wasonline;
134 };
135
136 int mp_cpu_start(struct cpu_info *, vaddr_t);
137 void mp_cpu_start_cleanup(struct cpu_info *);
138 const struct cpu_functions mp_cpu_funcs = { mp_cpu_start, NULL,
139 mp_cpu_start_cleanup };
140
141 CFATTACH_DECL2_NEW(cpu, sizeof(struct cpu_softc),
142 cpu_match, cpu_attach, NULL, NULL, cpu_rescan, cpu_childdetached);
143
144 CFATTACH_DECL_NEW(vcpu, sizeof(struct cpu_softc),
145 vcpu_match, vcpu_attach, NULL, NULL);
146
147 /*
148 * Statically-allocated CPU info for the primary CPU (or the only
149 * CPU, on uniprocessors). The CPU info list is initialized to
150 * point at it.
151 */
152 #ifdef TRAPLOG
153 #include <machine/tlog.h>
154 struct tlog tlog_primary;
155 #endif
156 struct cpu_info cpu_info_primary __aligned(CACHE_LINE_SIZE) = {
157 .ci_dev = 0,
158 .ci_self = &cpu_info_primary,
159 .ci_idepth = -1,
160 .ci_curlwp = &lwp0,
161 .ci_curldt = -1,
162 #ifdef TRAPLOG
163 .ci_tlog = &tlog_primary,
164 #endif
165
166 };
167 struct cpu_info phycpu_info_primary __aligned(CACHE_LINE_SIZE) = {
168 .ci_dev = 0,
169 .ci_self = &phycpu_info_primary,
170 };
171
172 struct cpu_info *cpu_info_list = &cpu_info_primary;
173 struct cpu_info *phycpu_info_list = &phycpu_info_primary;
174
175 uint32_t cpu_feature[5]; /* X86 CPUID feature bits
176 * [0] basic features %edx
177 * [1] basic features %ecx
178 * [2] extended features %edx
179 * [3] extended features %ecx
180 * [4] VIA padlock features
181 */
182
183 bool x86_mp_online;
184 paddr_t mp_trampoline_paddr = MP_TRAMPOLINE;
185
186 #if defined(MULTIPROCESSOR)
187 void cpu_hatch(void *);
188 static void cpu_boot_secondary(struct cpu_info *ci);
189 static void cpu_start_secondary(struct cpu_info *ci);
190 #endif /* MULTIPROCESSOR */
191
192 static int
193 cpu_match(device_t parent, cfdata_t match, void *aux)
194 {
195
196 return 1;
197 }
198
199 static void
200 cpu_attach(device_t parent, device_t self, void *aux)
201 {
202 struct cpu_softc *sc = device_private(self);
203 struct cpu_attach_args *caa = aux;
204 struct cpu_info *ci;
205 uintptr_t ptr;
206 static int nphycpu = 0;
207
208 sc->sc_dev = self;
209
210 /*
211 * If we're an Application Processor, allocate a cpu_info
212 * If we're the first attached CPU use the primary cpu_info,
213 * otherwise allocate a new one
214 */
215 aprint_naive("\n");
216 aprint_normal("\n");
217 if (nphycpu > 0) {
218 struct cpu_info *tmp;
219 ptr = (uintptr_t)kmem_zalloc(sizeof(*ci) + CACHE_LINE_SIZE - 1,
220 KM_SLEEP);
221 ci = (struct cpu_info *)roundup2(ptr, CACHE_LINE_SIZE);
222 ci->ci_curldt = -1;
223
224 tmp = phycpu_info_list;
225 while (tmp->ci_next)
226 tmp = tmp->ci_next;
227
228 tmp->ci_next = ci;
229 } else {
230 ci = &phycpu_info_primary;
231 }
232
233 ci->ci_self = ci;
234 sc->sc_info = ci;
235
236 ci->ci_dev = self;
237 ci->ci_acpiid = caa->cpu_id;
238 ci->ci_cpuid = caa->cpu_number;
239 ci->ci_vcpu = NULL;
240 ci->ci_index = nphycpu++;
241
242 if (!pmf_device_register(self, NULL, NULL))
243 aprint_error_dev(self, "couldn't establish power handler\n");
244
245 (void)config_defer(self, cpu_defer);
246 }
247
248 static void
249 cpu_defer(device_t self)
250 {
251 cpu_rescan(self, NULL, NULL);
252 }
253
254 static int
255 cpu_rescan(device_t self, const char *ifattr, const int *locators)
256 {
257 struct cpu_softc *sc = device_private(self);
258 struct cpufeature_attach_args cfaa;
259 struct cpu_info *ci = sc->sc_info;
260
261 memset(&cfaa, 0, sizeof(cfaa));
262 cfaa.ci = ci;
263
264 if (ifattr_match(ifattr, "cpufeaturebus")) {
265
266 if (ci->ci_frequency == NULL) {
267 cfaa.name = "frequency";
268 ci->ci_frequency = config_found_ia(self,
269 "cpufeaturebus", &cfaa, NULL);
270 }
271 }
272
273 return 0;
274 }
275
276 static void
277 cpu_childdetached(device_t self, device_t child)
278 {
279 struct cpu_softc *sc = device_private(self);
280 struct cpu_info *ci = sc->sc_info;
281
282 if (ci->ci_frequency == child)
283 ci->ci_frequency = NULL;
284 }
285
286 static int
287 vcpu_match(device_t parent, cfdata_t match, void *aux)
288 {
289 struct vcpu_attach_args *vcaa = aux;
290 struct vcpu_runstate_info vcr;
291 int error;
292
293 if (strcmp(vcaa->vcaa_name, match->cf_name) == 0) {
294 error = HYPERVISOR_vcpu_op(VCPUOP_get_runstate_info,
295 vcaa->vcaa_caa.cpu_number,
296 &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 }
363
364 static void
365 cpu_attach_common(device_t parent, device_t self, void *aux)
366 {
367 struct cpu_softc *sc = device_private(self);
368 struct cpu_attach_args *caa = aux;
369 struct cpu_info *ci;
370 uintptr_t ptr;
371 int cpunum = caa->cpu_number;
372 static bool again = false;
373
374 sc->sc_dev = self;
375
376 /*
377 * If we're an Application Processor, allocate a cpu_info
378 * structure, otherwise use the primary's.
379 */
380 if (caa->cpu_role == CPU_ROLE_AP) {
381 aprint_naive(": Application Processor\n");
382 ptr = (uintptr_t)kmem_alloc(sizeof(*ci) + CACHE_LINE_SIZE - 1,
383 KM_SLEEP);
384 ci = (struct cpu_info *)roundup2(ptr, CACHE_LINE_SIZE);
385 memset(ci, 0, sizeof(*ci));
386 #ifdef TRAPLOG
387 ci->ci_tlog_base = kmem_zalloc(sizeof(struct tlog), KM_SLEEP);
388 #endif
389 } else {
390 aprint_naive(": %s Processor\n",
391 caa->cpu_role == CPU_ROLE_SP ? "Single" : "Boot");
392 ci = &cpu_info_primary;
393 }
394
395 ci->ci_self = ci;
396 sc->sc_info = ci;
397 ci->ci_dev = self;
398 ci->ci_cpuid = cpunum;
399
400 KASSERT(HYPERVISOR_shared_info != NULL);
401 KASSERT(cpunum < XEN_LEGACY_MAX_VCPUS);
402 ci->ci_vcpu = &HYPERVISOR_shared_info->vcpu_info[cpunum];
403
404 KASSERT(ci->ci_func == 0);
405 ci->ci_func = caa->cpu_func;
406
407 /* Must be called before mi_cpu_attach(). */
408 cpu_vm_init(ci);
409
410 if (caa->cpu_role == CPU_ROLE_AP) {
411 int error;
412
413 error = mi_cpu_attach(ci);
414
415 KASSERT(ci->ci_data.cpu_idlelwp != NULL);
416 if (error != 0) {
417 aprint_normal("\n");
418 aprint_error_dev(self,
419 "mi_cpu_attach failed with %d\n", error);
420 return;
421 }
422
423 } else {
424 KASSERT(ci->ci_data.cpu_idlelwp != NULL);
425 }
426
427 KASSERT(ci->ci_cpuid == ci->ci_index);
428 #ifdef __x86_64__
429 /* No user PGD mapped for this CPU yet */
430 ci->ci_xen_current_user_pgd = 0;
431 #endif
432 #if defined(__x86_64__) || defined(PAE)
433 mutex_init(&ci->ci_kpm_mtx, MUTEX_DEFAULT, IPL_VM);
434 #endif
435 pmap_reference(pmap_kernel());
436 ci->ci_pmap = pmap_kernel();
437 ci->ci_tlbstate = TLBSTATE_STALE;
438
439 /*
440 * Boot processor may not be attached first, but the below
441 * must be done to allow booting other processors.
442 */
443 if (!again) {
444 atomic_or_32(&ci->ci_flags, CPUF_PRESENT | CPUF_PRIMARY);
445 /* Basic init. */
446 cpu_intr_init(ci);
447 cpu_get_tsc_freq(ci);
448 cpu_init(ci);
449 pmap_cpu_init_late(ci);
450
451 /* Every processor needs to init its own ipi h/w (similar to lapic) */
452 xen_ipi_init();
453
454 /* Make sure DELAY() is initialized. */
455 DELAY(1);
456 again = true;
457 }
458
459 /* further PCB init done later. */
460
461 switch (caa->cpu_role) {
462 case CPU_ROLE_SP:
463 atomic_or_32(&ci->ci_flags, CPUF_SP);
464 cpu_identify(ci);
465 x86_cpu_idle_init();
466
467 break;
468
469 case CPU_ROLE_BP:
470 atomic_or_32(&ci->ci_flags, CPUF_BSP);
471 cpu_identify(ci);
472 x86_cpu_idle_init();
473
474 break;
475
476 case CPU_ROLE_AP:
477 atomic_or_32(&ci->ci_flags, CPUF_AP);
478
479 /*
480 * report on an AP
481 */
482
483 #if defined(MULTIPROCESSOR)
484 /* interrupt handler stack */
485 cpu_intr_init(ci);
486
487 /* Setup per-cpu memory for gdt */
488 gdt_alloc_cpu(ci);
489
490 pmap_cpu_init_late(ci);
491 cpu_start_secondary(ci);
492
493 if (ci->ci_flags & CPUF_PRESENT) {
494 struct cpu_info *tmp;
495
496 cpu_identify(ci);
497 tmp = cpu_info_list;
498 while (tmp->ci_next)
499 tmp = tmp->ci_next;
500
501 tmp->ci_next = ci;
502 }
503 #else
504 aprint_error(": not started\n");
505 #endif
506 break;
507
508 default:
509 aprint_normal("\n");
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 /* i386 */
524 (void *)pcb->pcb_rsp
525 #endif /* i386 */
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 < roundup(entries, PAGE_SIZE) >> PAGE_SHIFT; i++) {
766
767 frames[i] = ((paddr_t) xpmap_ptetomach(
768 (pt_entry_t *) (base + (i << PAGE_SHIFT))))
769 >> PAGE_SHIFT;
770
771 /* Mark Read-only */
772 pmap_pte_clearbits(kvtopte(base + (i << PAGE_SHIFT)),
773 PG_RW);
774 }
775 }
776
777 #ifdef __x86_64__
778 extern char *ldtstore;
779
780 static void
781 xen_init_amd64_vcpuctxt(struct cpu_info *ci,
782 struct vcpu_guest_context *initctx,
783 void targetrip(struct cpu_info *))
784 {
785 /* page frames to point at GDT */
786 extern int gdt_size;
787 paddr_t frames[16];
788 psize_t gdt_ents;
789
790 struct lwp *l;
791 struct pcb *pcb;
792
793 volatile struct vcpu_info *vci;
794
795 KASSERT(ci != NULL);
796 KASSERT(ci != &cpu_info_primary);
797 KASSERT(initctx != NULL);
798 KASSERT(targetrip != NULL);
799
800 memset(initctx, 0, sizeof *initctx);
801
802 gdt_ents = roundup(gdt_size, PAGE_SIZE) >> PAGE_SHIFT;
803 KASSERT(gdt_ents <= 16);
804
805 gdt_prepframes(frames, (vaddr_t) ci->ci_gdt, gdt_ents);
806
807 /* Initialise the vcpu context: We use idle_loop()'s pcb context. */
808
809 l = ci->ci_data.cpu_idlelwp;
810
811 KASSERT(l != NULL);
812 pcb = lwp_getpcb(l);
813 KASSERT(pcb != NULL);
814
815 /* resume with interrupts off */
816 vci = ci->ci_vcpu;
817 vci->evtchn_upcall_mask = 1;
818 xen_mb();
819
820 /* resume in kernel-mode */
821 initctx->flags = VGCF_in_kernel | VGCF_online;
822
823 /* Stack and entry points:
824 * We arrange for the stack frame for cpu_hatch() to
825 * appear as a callee frame of lwp_trampoline(). Being a
826 * leaf frame prevents trampling on any of the MD stack setup
827 * that x86/vm_machdep.c:cpu_lwp_fork() does for idle_loop()
828 */
829
830 initctx->user_regs.rdi = (uint64_t) ci; /* targetrip(ci); */
831 initctx->user_regs.rip = (vaddr_t) targetrip;
832
833 initctx->user_regs.cs = GSEL(GCODE_SEL, SEL_KPL);
834
835 initctx->user_regs.rflags = pcb->pcb_flags;
836 initctx->user_regs.rsp = pcb->pcb_rsp;
837
838 /* Data segments */
839 initctx->user_regs.ss = GSEL(GDATA_SEL, SEL_KPL);
840 initctx->user_regs.es = GSEL(GDATA_SEL, SEL_KPL);
841 initctx->user_regs.ds = GSEL(GDATA_SEL, SEL_KPL);
842
843 /* GDT */
844 memcpy(initctx->gdt_frames, frames, sizeof frames);
845 initctx->gdt_ents = gdt_ents;
846
847 /* LDT */
848 initctx->ldt_base = (unsigned long) ldtstore;
849 initctx->ldt_ents = LDT_SIZE >> 3;
850
851 /* Kernel context state */
852 initctx->kernel_ss = GSEL(GDATA_SEL, SEL_KPL);
853 initctx->kernel_sp = pcb->pcb_rsp0;
854 initctx->ctrlreg[0] = pcb->pcb_cr0;
855 initctx->ctrlreg[1] = 0; /* "resuming" from kernel - no User cr3. */
856 initctx->ctrlreg[2] = (vaddr_t) targetrip;
857 /*
858 * Use pmap_kernel() L4 PD directly, until we setup the
859 * per-cpu L4 PD in pmap_cpu_init_late()
860 */
861 initctx->ctrlreg[3] = xen_pfn_to_cr3(x86_btop(xpmap_ptom(ci->ci_kpm_pdirpa)));
862 initctx->ctrlreg[4] = CR4_PAE | CR4_OSFXSR | CR4_OSXMMEXCPT;
863
864
865 /* Xen callbacks */
866 initctx->event_callback_eip = (unsigned long) hypervisor_callback;
867 initctx->failsafe_callback_eip = (unsigned long) failsafe_callback;
868 initctx->syscall_callback_eip = (unsigned long) Xsyscall;
869
870 return;
871 }
872 #else /* i386 */
873 extern union descriptor *ldt;
874 extern void Xsyscall(void);
875
876 static void
877 xen_init_i386_vcpuctxt(struct cpu_info *ci,
878 struct vcpu_guest_context *initctx,
879 void targeteip(struct cpu_info *))
880 {
881 /* page frames to point at GDT */
882 extern int gdt_size;
883 paddr_t frames[16];
884 psize_t gdt_ents;
885
886 struct lwp *l;
887 struct pcb *pcb;
888
889 volatile struct vcpu_info *vci;
890
891 KASSERT(ci != NULL);
892 KASSERT(ci != &cpu_info_primary);
893 KASSERT(initctx != NULL);
894 KASSERT(targeteip != NULL);
895
896 memset(initctx, 0, sizeof *initctx);
897
898 gdt_ents = roundup(gdt_size, PAGE_SIZE) >> PAGE_SHIFT;
899 KASSERT(gdt_ents <= 16);
900
901 gdt_prepframes(frames, (vaddr_t) ci->ci_gdt, gdt_ents);
902
903 /*
904 * Initialise the vcpu context:
905 * We use this cpu's idle_loop() pcb context.
906 */
907
908 l = ci->ci_data.cpu_idlelwp;
909
910 KASSERT(l != NULL);
911 pcb = lwp_getpcb(l);
912 KASSERT(pcb != NULL);
913
914 /* resume with interrupts off */
915 vci = ci->ci_vcpu;
916 vci->evtchn_upcall_mask = 1;
917 xen_mb();
918
919 /* resume in kernel-mode */
920 initctx->flags = VGCF_in_kernel | VGCF_online;
921
922 /* Stack frame setup for cpu_hatch():
923 * We arrange for the stack frame for cpu_hatch() to
924 * appear as a callee frame of lwp_trampoline(). Being a
925 * leaf frame prevents trampling on any of the MD stack setup
926 * that x86/vm_machdep.c:cpu_lwp_fork() does for idle_loop()
927 */
928
929 initctx->user_regs.esp = pcb->pcb_esp - 4; /* Leave word for
930 arg1 */
931 { /* targeteip(ci); */
932 uint32_t *arg = (uint32_t *) initctx->user_regs.esp;
933 arg[1] = (uint32_t) ci; /* arg1 */
934
935 }
936
937 initctx->user_regs.eip = (vaddr_t) targeteip;
938 initctx->user_regs.cs = GSEL(GCODE_SEL, SEL_KPL);
939 initctx->user_regs.eflags |= pcb->pcb_iopl;
940
941 /* Data segments */
942 initctx->user_regs.ss = GSEL(GDATA_SEL, SEL_KPL);
943 initctx->user_regs.es = GSEL(GDATA_SEL, SEL_KPL);
944 initctx->user_regs.ds = GSEL(GDATA_SEL, SEL_KPL);
945 initctx->user_regs.fs = GSEL(GDATA_SEL, SEL_KPL);
946
947 /* GDT */
948 memcpy(initctx->gdt_frames, frames, sizeof frames);
949 initctx->gdt_ents = gdt_ents;
950
951 /* LDT */
952 initctx->ldt_base = (unsigned long) ldt;
953 initctx->ldt_ents = NLDT;
954
955 /* Kernel context state */
956 initctx->kernel_ss = GSEL(GDATA_SEL, SEL_KPL);
957 initctx->kernel_sp = pcb->pcb_esp0;
958 initctx->ctrlreg[0] = pcb->pcb_cr0;
959 initctx->ctrlreg[1] = 0; /* "resuming" from kernel - no User cr3. */
960 initctx->ctrlreg[2] = (vaddr_t) targeteip;
961 #ifdef PAE
962 initctx->ctrlreg[3] = xen_pfn_to_cr3(x86_btop(xpmap_ptom(ci->ci_pae_l3_pdirpa)));
963 #else /* PAE */
964 initctx->ctrlreg[3] = xen_pfn_to_cr3(x86_btop(xpmap_ptom(pcb->pcb_cr3)));
965 #endif /* PAE */
966 initctx->ctrlreg[4] = /* CR4_PAE | */CR4_OSFXSR | CR4_OSXMMEXCPT;
967
968
969 /* Xen callbacks */
970 initctx->event_callback_eip = (unsigned long) hypervisor_callback;
971 initctx->event_callback_cs = GSEL(GCODE_SEL, SEL_KPL);
972 initctx->failsafe_callback_eip = (unsigned long) failsafe_callback;
973 initctx->failsafe_callback_cs = GSEL(GCODE_SEL, SEL_KPL);
974
975 return;
976 }
977 #endif /* __x86_64__ */
978
979 int
980 mp_cpu_start(struct cpu_info *ci, vaddr_t target)
981 {
982
983 int hyperror;
984 struct vcpu_guest_context vcpuctx;
985
986 KASSERT(ci != NULL);
987 KASSERT(ci != &cpu_info_primary);
988 KASSERT(ci->ci_flags & CPUF_AP);
989
990 #ifdef __x86_64__
991 xen_init_amd64_vcpuctxt(ci, &vcpuctx, (void (*)(struct cpu_info *))target);
992 #else /* i386 */
993 xen_init_i386_vcpuctxt(ci, &vcpuctx, (void (*)(struct cpu_info *))target);
994 #endif /* __x86_64__ */
995
996 /* Initialise the given vcpu to execute cpu_hatch(ci); */
997 if ((hyperror = HYPERVISOR_vcpu_op(VCPUOP_initialise, ci->ci_cpuid, &vcpuctx))) {
998 aprint_error(": context initialisation failed. errno = %d\n", hyperror);
999 return hyperror;
1000 }
1001
1002 /* Start it up */
1003
1004 /* First bring it down */
1005 if ((hyperror = HYPERVISOR_vcpu_op(VCPUOP_down, ci->ci_cpuid, NULL))) {
1006 aprint_error(": VCPUOP_down hypervisor command failed. errno = %d\n", hyperror);
1007 return hyperror;
1008 }
1009
1010 if ((hyperror = HYPERVISOR_vcpu_op(VCPUOP_up, ci->ci_cpuid, NULL))) {
1011 aprint_error(": VCPUOP_up hypervisor command failed. errno = %d\n", hyperror);
1012 return hyperror;
1013 }
1014
1015 if (!vcpu_is_up(ci)) {
1016 aprint_error(": did not come up\n");
1017 return -1;
1018 }
1019
1020 return 0;
1021 }
1022
1023 void
1024 mp_cpu_start_cleanup(struct cpu_info *ci)
1025 {
1026 if (vcpu_is_up(ci)) {
1027 aprint_debug_dev(ci->ci_dev, "is started.\n");
1028 }
1029 else {
1030 aprint_error_dev(ci->ci_dev, "did not start up.\n");
1031 }
1032
1033 }
1034
1035 void
1036 cpu_init_msrs(struct cpu_info *ci, bool full)
1037 {
1038 #ifdef __x86_64__
1039 if (full) {
1040 HYPERVISOR_set_segment_base (SEGBASE_FS, 0);
1041 HYPERVISOR_set_segment_base (SEGBASE_GS_KERNEL, (uint64_t) ci);
1042 HYPERVISOR_set_segment_base (SEGBASE_GS_USER, 0);
1043 }
1044 #endif /* __x86_64__ */
1045
1046 if (cpu_feature[2] & CPUID_NOX)
1047 wrmsr(MSR_EFER, rdmsr(MSR_EFER) | EFER_NXE);
1048
1049 }
1050
1051 void
1052 cpu_offline_md(void)
1053 {
1054 int s;
1055
1056 s = splhigh();
1057 fpusave_cpu(true);
1058 splx(s);
1059 }
1060
1061 void
1062 cpu_get_tsc_freq(struct cpu_info *ci)
1063 {
1064 uint32_t vcpu_tversion;
1065 const volatile vcpu_time_info_t *tinfo = &ci->ci_vcpu->time;
1066
1067 vcpu_tversion = tinfo->version;
1068 while (tinfo->version == vcpu_tversion); /* Wait for a time update. XXX: timeout ? */
1069
1070 uint64_t freq = 1000000000ULL << 32;
1071 freq = freq / (uint64_t)tinfo->tsc_to_system_mul;
1072 if ( tinfo->tsc_shift < 0 )
1073 freq = freq << -tinfo->tsc_shift;
1074 else
1075 freq = freq >> tinfo->tsc_shift;
1076 ci->ci_data.cpu_cc_freq = freq;
1077 }
1078
1079 void
1080 x86_cpu_idle_xen(void)
1081 {
1082 struct cpu_info *ci = curcpu();
1083
1084 KASSERT(ci->ci_ilevel == IPL_NONE);
1085
1086 x86_disable_intr();
1087 if (!__predict_false(ci->ci_want_resched)) {
1088 idle_block();
1089 } else {
1090 x86_enable_intr();
1091 }
1092 }
1093
1094 /*
1095 * Loads pmap for the current CPU.
1096 */
1097 void
1098 cpu_load_pmap(struct pmap *pmap, struct pmap *oldpmap)
1099 {
1100 KASSERT(pmap != pmap_kernel());
1101
1102 #if defined(__x86_64__) || defined(PAE)
1103 struct cpu_info *ci = curcpu();
1104 cpuid_t cid = cpu_index(ci);
1105
1106 mutex_enter(&ci->ci_kpm_mtx);
1107 /* make new pmap visible to xen_kpm_sync() */
1108 kcpuset_atomic_set(pmap->pm_xen_ptp_cpus, cid);
1109 #endif
1110 #ifdef i386
1111 #ifdef PAE
1112 {
1113 int i;
1114 paddr_t l3_pd = xpmap_ptom_masked(ci->ci_pae_l3_pdirpa);
1115 /* don't update the kernel L3 slot */
1116 for (i = 0 ; i < PDP_SIZE - 1; i++) {
1117 xpq_queue_pte_update(l3_pd + i * sizeof(pd_entry_t),
1118 xpmap_ptom(pmap->pm_pdirpa[i]) | PG_V);
1119 }
1120 tlbflush();
1121 }
1122 #else /* PAE */
1123 lcr3(pmap_pdirpa(pmap, 0));
1124 #endif /* PAE */
1125 #endif /* i386 */
1126
1127 #ifdef __x86_64__
1128 {
1129 int i;
1130 pd_entry_t *new_pgd;
1131 paddr_t l4_pd_ma;
1132
1133 l4_pd_ma = xpmap_ptom_masked(ci->ci_kpm_pdirpa);
1134
1135 /*
1136 * Map user space address in kernel space and load
1137 * user cr3
1138 */
1139 new_pgd = pmap->pm_pdir;
1140 KASSERT(pmap == ci->ci_pmap);
1141
1142 /* Copy user pmap L4 PDEs (in user addr. range) to per-cpu L4 */
1143 for (i = 0; i < PDIR_SLOT_PTE; i++) {
1144 KASSERT(pmap != pmap_kernel() || new_pgd[i] == 0);
1145 if (ci->ci_kpm_pdir[i] != new_pgd[i]) {
1146 xpq_queue_pte_update(
1147 l4_pd_ma + i * sizeof(pd_entry_t),
1148 new_pgd[i]);
1149 }
1150 }
1151
1152 xen_set_user_pgd(pmap_pdirpa(pmap, 0));
1153 ci->ci_xen_current_user_pgd = pmap_pdirpa(pmap, 0);
1154
1155 tlbflush();
1156 }
1157
1158 #endif /* __x86_64__ */
1159 #if defined(__x86_64__) || defined(PAE)
1160 /* old pmap no longer visible to xen_kpm_sync() */
1161 if (oldpmap != pmap_kernel()) {
1162 kcpuset_atomic_clear(oldpmap->pm_xen_ptp_cpus, cid);
1163 }
1164 mutex_exit(&ci->ci_kpm_mtx);
1165 #endif
1166 }
1167
1168 /*
1169 * pmap_cpu_init_late: perform late per-CPU initialization.
1170 * Short note about percpu PDIR pages:
1171 * Both the PAE and __x86_64__ architectures have per-cpu PDIR
1172 * tables. This is to get around Xen's pagetable setup constraints for
1173 * PAE (multiple L3[3]s cannot point to the same L2 - Xen
1174 * will refuse to pin a table setup this way.) and for multiple cpus
1175 * to map in different user pmaps on __x86_64__ (see: cpu_load_pmap())
1176 *
1177 * What this means for us is that the PDIR of the pmap_kernel() is
1178 * considered to be a canonical "SHADOW" PDIR with the following
1179 * properties:
1180 * - Its recursive mapping points to itself
1181 * - per-cpu recursive mappings point to themselves on __x86_64__
1182 * - per-cpu L4 pages' kernel entries are expected to be in sync with
1183 * the shadow
1184 */
1185
1186 void
1187 pmap_cpu_init_late(struct cpu_info *ci)
1188 {
1189 #if defined(PAE) || defined(__x86_64__)
1190 /*
1191 * The BP has already its own PD page allocated during early
1192 * MD startup.
1193 */
1194
1195 #if defined(__x86_64__)
1196 /* Setup per-cpu normal_pdes */
1197 int i;
1198 extern pd_entry_t * const normal_pdes[];
1199 for (i = 0;i < PTP_LEVELS - 1;i++) {
1200 ci->ci_normal_pdes[i] = normal_pdes[i];
1201 }
1202 #endif /* __x86_64__ */
1203
1204 if (ci == &cpu_info_primary)
1205 return;
1206
1207 KASSERT(ci != NULL);
1208
1209 #if defined(PAE)
1210 cpu_alloc_l3_page(ci);
1211 KASSERT(ci->ci_pae_l3_pdirpa != 0);
1212
1213 /* Initialise L2 entries 0 - 2: Point them to pmap_kernel() */
1214 int i;
1215 for (i = 0 ; i < PDP_SIZE - 1; i++) {
1216 ci->ci_pae_l3_pdir[i] =
1217 xpmap_ptom_masked(pmap_kernel()->pm_pdirpa[i]) | PG_V;
1218 }
1219 #endif /* PAE */
1220
1221 ci->ci_kpm_pdir = (pd_entry_t *)uvm_km_alloc(kernel_map, PAGE_SIZE, 0,
1222 UVM_KMF_WIRED | UVM_KMF_ZERO | UVM_KMF_NOWAIT);
1223
1224 if (ci->ci_kpm_pdir == NULL) {
1225 panic("%s: failed to allocate L4 per-cpu PD for CPU %d\n",
1226 __func__, cpu_index(ci));
1227 }
1228 ci->ci_kpm_pdirpa = vtophys((vaddr_t) ci->ci_kpm_pdir);
1229 KASSERT(ci->ci_kpm_pdirpa != 0);
1230
1231 #if defined(__x86_64__)
1232 /*
1233 * Copy over the pmap_kernel() shadow L4 entries
1234 */
1235
1236 memcpy(ci->ci_kpm_pdir, pmap_kernel()->pm_pdir, PAGE_SIZE);
1237
1238 /* Recursive kernel mapping */
1239 ci->ci_kpm_pdir[PDIR_SLOT_PTE] = xpmap_ptom_masked(ci->ci_kpm_pdirpa) | PG_k | PG_V;
1240 #elif defined(PAE)
1241 /* Copy over the pmap_kernel() shadow L2 entries that map the kernel */
1242 memcpy(ci->ci_kpm_pdir, pmap_kernel()->pm_pdir + PDIR_SLOT_KERN, nkptp[PTP_LEVELS - 1] * sizeof(pd_entry_t));
1243 #endif /* __x86_64__ else PAE */
1244
1245 /* Xen wants R/O */
1246 pmap_protect(pmap_kernel(), (vaddr_t)ci->ci_kpm_pdir,
1247 (vaddr_t)ci->ci_kpm_pdir + PAGE_SIZE, VM_PROT_READ);
1248 pmap_update(pmap_kernel());
1249 #if defined(PAE)
1250 /* Initialise L3 entry 3. This mapping is shared across all
1251 * pmaps and is static, ie; loading a new pmap will not update
1252 * this entry.
1253 */
1254
1255 ci->ci_pae_l3_pdir[3] = xpmap_ptom_masked(ci->ci_kpm_pdirpa) | PG_k | PG_V;
1256
1257 /* Mark L3 R/O (Xen wants this) */
1258 pmap_protect(pmap_kernel(), (vaddr_t)ci->ci_pae_l3_pdir,
1259 (vaddr_t)ci->ci_pae_l3_pdir + PAGE_SIZE, VM_PROT_READ);
1260 pmap_update(pmap_kernel());
1261
1262 xpq_queue_pin_l3_table(xpmap_ptom_masked(ci->ci_pae_l3_pdirpa));
1263
1264 #elif defined(__x86_64__)
1265 xpq_queue_pin_l4_table(xpmap_ptom_masked(ci->ci_kpm_pdirpa));
1266 #endif /* PAE , __x86_64__ */
1267 #endif /* defined(PAE) || defined(__x86_64__) */
1268 }
1269
1270 /*
1271 * Notify all other cpus to halt.
1272 */
1273
1274 void
1275 cpu_broadcast_halt(void)
1276 {
1277 xen_broadcast_ipi(XEN_IPI_HALT);
1278 }
1279
1280 /*
1281 * Send a dummy ipi to a cpu.
1282 */
1283
1284 void
1285 cpu_kick(struct cpu_info *ci)
1286 {
1287 (void)xen_send_ipi(ci, XEN_IPI_KICK);
1288 }
1289