cpu.c revision 1.181 1 /* $NetBSD: cpu.c,v 1.181 2020/01/14 01:41:37 pgoyette Exp $ */
2
3 /*
4 * Copyright (c) 2000-2012 NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Bill Sommerfeld of RedBack Networks Inc, and by Andrew Doran.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*
33 * Copyright (c) 1999 Stefan Grefen
34 *
35 * Redistribution and use in source and binary forms, with or without
36 * modification, are permitted provided that the following conditions
37 * are met:
38 * 1. Redistributions of source code must retain the above copyright
39 * notice, this list of conditions and the following disclaimer.
40 * 2. Redistributions in binary form must reproduce the above copyright
41 * notice, this list of conditions and the following disclaimer in the
42 * documentation and/or other materials provided with the distribution.
43 * 3. All advertising materials mentioning features or use of this software
44 * must display the following acknowledgement:
45 * This product includes software developed by the NetBSD
46 * Foundation, Inc. and its contributors.
47 * 4. Neither the name of The NetBSD Foundation nor the names of its
48 * contributors may be used to endorse or promote products derived
49 * from this software without specific prior written permission.
50 *
51 * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
52 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
53 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
54 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR AND CONTRIBUTORS BE LIABLE
55 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
56 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
57 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
58 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
59 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
60 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
61 * SUCH DAMAGE.
62 */
63
64 #include <sys/cdefs.h>
65 __KERNEL_RCSID(0, "$NetBSD: cpu.c,v 1.181 2020/01/14 01:41:37 pgoyette Exp $");
66
67 #include "opt_ddb.h"
68 #include "opt_mpbios.h" /* for MPDEBUG */
69 #include "opt_mtrr.h"
70 #include "opt_multiprocessor.h"
71 #include "opt_svs.h"
72
73 #include "lapic.h"
74 #include "ioapic.h"
75 #include "acpica.h"
76
77 #include <sys/param.h>
78 #include <sys/proc.h>
79 #include <sys/systm.h>
80 #include <sys/device.h>
81 #include <sys/cpu.h>
82 #include <sys/cpufreq.h>
83 #include <sys/idle.h>
84 #include <sys/atomic.h>
85 #include <sys/reboot.h>
86 #include <sys/csan.h>
87
88 #include <uvm/uvm.h>
89
90 #include "acpica.h" /* for NACPICA, for mp_verbose */
91
92 #include <machine/cpufunc.h>
93 #include <machine/cpuvar.h>
94 #include <machine/pmap.h>
95 #include <machine/vmparam.h>
96 #if defined(MULTIPROCESSOR)
97 #include <machine/mpbiosvar.h>
98 #endif
99 #include <machine/mpconfig.h> /* for mp_verbose */
100 #include <machine/pcb.h>
101 #include <machine/specialreg.h>
102 #include <machine/segments.h>
103 #include <machine/gdt.h>
104 #include <machine/mtrr.h>
105 #include <machine/pio.h>
106 #include <machine/cpu_counter.h>
107
108 #include <x86/fpu.h>
109
110 #if NACPICA > 0
111 #include <dev/acpi/acpi_srat.h>
112 #endif
113
114 #if NLAPIC > 0
115 #include <machine/apicvar.h>
116 #include <machine/i82489reg.h>
117 #include <machine/i82489var.h>
118 #endif
119
120 #include <dev/ic/mc146818reg.h>
121 #include <i386/isa/nvram.h>
122 #include <dev/isa/isareg.h>
123
124 #include "tsc.h"
125
126 #ifndef XEN
127 #include "hyperv.h"
128 #if NHYPERV > 0
129 #include <x86/x86/hypervvar.h>
130 #endif
131 #endif
132
133 static int cpu_match(device_t, cfdata_t, void *);
134 static void cpu_attach(device_t, device_t, void *);
135 static void cpu_defer(device_t);
136 static int cpu_rescan(device_t, const char *, const int *);
137 static void cpu_childdetached(device_t, device_t);
138 static bool cpu_stop(device_t);
139 static bool cpu_suspend(device_t, const pmf_qual_t *);
140 static bool cpu_resume(device_t, const pmf_qual_t *);
141 static bool cpu_shutdown(device_t, int);
142
143 struct cpu_softc {
144 device_t sc_dev; /* device tree glue */
145 struct cpu_info *sc_info; /* pointer to CPU info */
146 bool sc_wasonline;
147 };
148
149 #ifdef MULTIPROCESSOR
150 int mp_cpu_start(struct cpu_info *, paddr_t);
151 void mp_cpu_start_cleanup(struct cpu_info *);
152 const struct cpu_functions mp_cpu_funcs = { mp_cpu_start, NULL,
153 mp_cpu_start_cleanup };
154 #endif
155
156
157 CFATTACH_DECL2_NEW(cpu, sizeof(struct cpu_softc),
158 cpu_match, cpu_attach, NULL, NULL, cpu_rescan, cpu_childdetached);
159
160 /*
161 * Statically-allocated CPU info for the primary CPU (or the only
162 * CPU, on uniprocessors). The CPU info list is initialized to
163 * point at it.
164 */
165 struct cpu_info cpu_info_primary __aligned(CACHE_LINE_SIZE) = {
166 .ci_dev = 0,
167 .ci_self = &cpu_info_primary,
168 .ci_idepth = -1,
169 .ci_curlwp = &lwp0,
170 .ci_curldt = -1,
171 };
172
173 struct cpu_info *cpu_info_list = &cpu_info_primary;
174
175 #ifdef i386
176 void cpu_set_tss_gates(struct cpu_info *);
177 #endif
178
179 static void cpu_init_idle_lwp(struct cpu_info *);
180
181 uint32_t cpu_feature[7] __read_mostly; /* X86 CPUID feature bits */
182 /* [0] basic features cpuid.1:%edx
183 * [1] basic features cpuid.1:%ecx (CPUID2_xxx bits)
184 * [2] extended features cpuid:80000001:%edx
185 * [3] extended features cpuid:80000001:%ecx
186 * [4] VIA padlock features
187 * [5] structured extended features cpuid.7:%ebx
188 * [6] structured extended features cpuid.7:%ecx
189 */
190
191 #ifdef MULTIPROCESSOR
192 bool x86_mp_online;
193 paddr_t mp_trampoline_paddr = MP_TRAMPOLINE;
194 #endif
195 #if NLAPIC > 0
196 static vaddr_t cmos_data_mapping;
197 #endif
198 struct cpu_info *cpu_starting;
199
200 #ifdef MULTIPROCESSOR
201 void cpu_hatch(void *);
202 static void cpu_boot_secondary(struct cpu_info *ci);
203 static void cpu_start_secondary(struct cpu_info *ci);
204 #if NLAPIC > 0
205 static void cpu_copy_trampoline(paddr_t);
206 #endif
207 #endif /* MULTIPROCESSOR */
208
209 /*
210 * Runs once per boot once multiprocessor goo has been detected and
211 * the local APIC on the boot processor has been mapped.
212 *
213 * Called from lapic_boot_init() (from mpbios_scan()).
214 */
215 #if NLAPIC > 0
216 void
217 cpu_init_first(void)
218 {
219
220 cpu_info_primary.ci_cpuid = lapic_cpu_number();
221
222 cmos_data_mapping = uvm_km_alloc(kernel_map, PAGE_SIZE, 0, UVM_KMF_VAONLY);
223 if (cmos_data_mapping == 0)
224 panic("No KVA for page 0");
225 pmap_kenter_pa(cmos_data_mapping, 0, VM_PROT_READ|VM_PROT_WRITE, 0);
226 pmap_update(pmap_kernel());
227 }
228 #endif
229
230 static int
231 cpu_match(device_t parent, cfdata_t match, void *aux)
232 {
233
234 return 1;
235 }
236
237 #ifdef __HAVE_PCPU_AREA
238 void
239 cpu_pcpuarea_init(struct cpu_info *ci)
240 {
241 struct vm_page *pg;
242 size_t i, npages;
243 vaddr_t base, va;
244 paddr_t pa;
245
246 CTASSERT(sizeof(struct pcpu_entry) % PAGE_SIZE == 0);
247
248 npages = sizeof(struct pcpu_entry) / PAGE_SIZE;
249 base = (vaddr_t)&pcpuarea->ent[cpu_index(ci)];
250
251 for (i = 0; i < npages; i++) {
252 pg = uvm_pagealloc(NULL, 0, NULL, UVM_PGA_ZERO);
253 if (pg == NULL) {
254 panic("failed to allocate pcpu PA");
255 }
256
257 va = base + i * PAGE_SIZE;
258 pa = VM_PAGE_TO_PHYS(pg);
259
260 pmap_kenter_pa(va, pa, VM_PROT_READ|VM_PROT_WRITE, 0);
261 }
262
263 pmap_update(pmap_kernel());
264 }
265 #endif
266
267 static void
268 cpu_vm_init(struct cpu_info *ci)
269 {
270 int ncolors = 2, i;
271
272 for (i = CAI_ICACHE; i <= CAI_L2CACHE; i++) {
273 struct x86_cache_info *cai;
274 int tcolors;
275
276 cai = &ci->ci_cinfo[i];
277
278 tcolors = atop(cai->cai_totalsize);
279 switch(cai->cai_associativity) {
280 case 0xff:
281 tcolors = 1; /* fully associative */
282 break;
283 case 0:
284 case 1:
285 break;
286 default:
287 tcolors /= cai->cai_associativity;
288 }
289 ncolors = uimax(ncolors, tcolors);
290 /*
291 * If the desired number of colors is not a power of
292 * two, it won't be good. Find the greatest power of
293 * two which is an even divisor of the number of colors,
294 * to preserve even coloring of pages.
295 */
296 if (ncolors & (ncolors - 1) ) {
297 int try, picked = 1;
298 for (try = 1; try < ncolors; try *= 2) {
299 if (ncolors % try == 0) picked = try;
300 }
301 if (picked == 1) {
302 panic("desired number of cache colors %d is "
303 " > 1, but not even!", ncolors);
304 }
305 ncolors = picked;
306 }
307 }
308
309 /*
310 * Knowing the size of the largest cache on this CPU, potentially
311 * re-color our pages.
312 */
313 aprint_debug_dev(ci->ci_dev, "%d page colors\n", ncolors);
314 uvm_page_recolor(ncolors);
315
316 pmap_tlb_cpu_init(ci);
317 #ifndef __HAVE_DIRECT_MAP
318 pmap_vpage_cpu_init(ci);
319 #endif
320 }
321
322 static void
323 cpu_attach(device_t parent, device_t self, void *aux)
324 {
325 struct cpu_softc *sc = device_private(self);
326 struct cpu_attach_args *caa = aux;
327 struct cpu_info *ci;
328 uintptr_t ptr;
329 #if NLAPIC > 0
330 int cpunum = caa->cpu_number;
331 #endif
332 static bool again;
333
334 sc->sc_dev = self;
335
336 if (ncpu > maxcpus) {
337 #ifndef _LP64
338 aprint_error(": too many CPUs, please use NetBSD/amd64\n");
339 #else
340 aprint_error(": too many CPUs\n");
341 #endif
342 return;
343 }
344
345 /*
346 * If we're an Application Processor, allocate a cpu_info
347 * structure, otherwise use the primary's.
348 */
349 if (caa->cpu_role == CPU_ROLE_AP) {
350 if ((boothowto & RB_MD1) != 0) {
351 aprint_error(": multiprocessor boot disabled\n");
352 if (!pmf_device_register(self, NULL, NULL))
353 aprint_error_dev(self,
354 "couldn't establish power handler\n");
355 return;
356 }
357 aprint_naive(": Application Processor\n");
358 ptr = (uintptr_t)uvm_km_alloc(kernel_map,
359 sizeof(*ci) + CACHE_LINE_SIZE - 1, 0,
360 UVM_KMF_WIRED|UVM_KMF_ZERO);
361 ci = (struct cpu_info *)roundup2(ptr, CACHE_LINE_SIZE);
362 ci->ci_curldt = -1;
363 } else {
364 aprint_naive(": %s Processor\n",
365 caa->cpu_role == CPU_ROLE_SP ? "Single" : "Boot");
366 ci = &cpu_info_primary;
367 #if NLAPIC > 0
368 if (cpunum != lapic_cpu_number()) {
369 /* XXX should be done earlier. */
370 uint32_t reg;
371 aprint_verbose("\n");
372 aprint_verbose_dev(self, "running CPU at apic %d"
373 " instead of at expected %d", lapic_cpu_number(),
374 cpunum);
375 reg = lapic_readreg(LAPIC_ID);
376 lapic_writereg(LAPIC_ID, (reg & ~LAPIC_ID_MASK) |
377 (cpunum << LAPIC_ID_SHIFT));
378 }
379 if (cpunum != lapic_cpu_number()) {
380 aprint_error_dev(self, "unable to reset apic id\n");
381 }
382 #endif
383 }
384
385 ci->ci_self = ci;
386 sc->sc_info = ci;
387 ci->ci_dev = self;
388 ci->ci_acpiid = caa->cpu_id;
389 ci->ci_cpuid = caa->cpu_number;
390 ci->ci_func = caa->cpu_func;
391 ci->ci_kfpu_spl = -1;
392 aprint_normal("\n");
393
394 /* Must be before mi_cpu_attach(). */
395 cpu_vm_init(ci);
396
397 if (caa->cpu_role == CPU_ROLE_AP) {
398 int error;
399
400 error = mi_cpu_attach(ci);
401 if (error != 0) {
402 aprint_error_dev(self,
403 "mi_cpu_attach failed with %d\n", error);
404 return;
405 }
406 #ifdef __HAVE_PCPU_AREA
407 cpu_pcpuarea_init(ci);
408 #endif
409 cpu_init_tss(ci);
410 } else {
411 KASSERT(ci->ci_data.cpu_idlelwp != NULL);
412 #if NACPICA > 0
413 /* Parse out NUMA info for cpu_identify(). */
414 acpisrat_init();
415 #endif
416 }
417
418 #ifdef SVS
419 cpu_svs_init(ci);
420 #endif
421
422 pmap_reference(pmap_kernel());
423 ci->ci_pmap = pmap_kernel();
424 ci->ci_tlbstate = TLBSTATE_STALE;
425
426 /*
427 * Boot processor may not be attached first, but the below
428 * must be done to allow booting other processors.
429 */
430 if (!again) {
431 atomic_or_32(&ci->ci_flags, CPUF_PRESENT | CPUF_PRIMARY);
432 /* Basic init. */
433 cpu_intr_init(ci);
434 cpu_get_tsc_freq(ci);
435 cpu_init(ci);
436 #ifdef i386
437 cpu_set_tss_gates(ci);
438 #endif
439 pmap_cpu_init_late(ci);
440 #if NLAPIC > 0
441 if (caa->cpu_role != CPU_ROLE_SP) {
442 /* Enable lapic. */
443 lapic_enable();
444 lapic_set_lvt();
445 lapic_calibrate_timer(ci);
446 }
447 #endif
448 /* Make sure DELAY() is initialized. */
449 DELAY(1);
450 kcsan_cpu_init(ci);
451 again = true;
452 }
453
454 /* further PCB init done later. */
455
456 switch (caa->cpu_role) {
457 case CPU_ROLE_SP:
458 atomic_or_32(&ci->ci_flags, CPUF_SP);
459 cpu_identify(ci);
460 x86_errata();
461 x86_cpu_idle_init();
462 break;
463
464 case CPU_ROLE_BP:
465 atomic_or_32(&ci->ci_flags, CPUF_BSP);
466 cpu_identify(ci);
467 x86_errata();
468 x86_cpu_idle_init();
469 break;
470
471 #ifdef MULTIPROCESSOR
472 case CPU_ROLE_AP:
473 /*
474 * report on an AP
475 */
476 cpu_intr_init(ci);
477 gdt_alloc_cpu(ci);
478 #ifdef i386
479 cpu_set_tss_gates(ci);
480 #endif
481 pmap_cpu_init_late(ci);
482 cpu_start_secondary(ci);
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 break;
494 #endif
495
496 default:
497 panic("unknown processor type??\n");
498 }
499
500 pat_init(ci);
501
502 if (!pmf_device_register1(self, cpu_suspend, cpu_resume, cpu_shutdown))
503 aprint_error_dev(self, "couldn't establish power handler\n");
504
505 #ifdef MULTIPROCESSOR
506 if (mp_verbose) {
507 struct lwp *l = ci->ci_data.cpu_idlelwp;
508 struct pcb *pcb = lwp_getpcb(l);
509
510 aprint_verbose_dev(self,
511 "idle lwp at %p, idle sp at %p\n",
512 l,
513 #ifdef i386
514 (void *)pcb->pcb_esp
515 #else
516 (void *)pcb->pcb_rsp
517 #endif
518 );
519 }
520 #endif
521
522 /*
523 * Postpone the "cpufeaturebus" scan.
524 * It is safe to scan the pseudo-bus
525 * only after all CPUs have attached.
526 */
527 (void)config_defer(self, cpu_defer);
528 }
529
530 static void
531 cpu_defer(device_t self)
532 {
533 cpu_rescan(self, NULL, NULL);
534 }
535
536 static int
537 cpu_rescan(device_t self, const char *ifattr, const int *locators)
538 {
539 struct cpu_softc *sc = device_private(self);
540 struct cpufeature_attach_args cfaa;
541 struct cpu_info *ci = sc->sc_info;
542
543 /*
544 * If we booted with RB_MD1 to disable multiprocessor, the
545 * auto-configuration data still contains the additional
546 * CPUs. But their initialization was mostly bypassed
547 * during attach, so we have to make sure we don't look at
548 * their featurebus info, since it wasn't retrieved.
549 */
550 if (ci == NULL)
551 return 0;
552
553 memset(&cfaa, 0, sizeof(cfaa));
554 cfaa.ci = ci;
555
556 if (ifattr_match(ifattr, "cpufeaturebus")) {
557 if (ci->ci_frequency == NULL) {
558 cfaa.name = "frequency";
559 ci->ci_frequency = config_found_ia(self,
560 "cpufeaturebus", &cfaa, NULL);
561 }
562
563 if (ci->ci_padlock == NULL) {
564 cfaa.name = "padlock";
565 ci->ci_padlock = config_found_ia(self,
566 "cpufeaturebus", &cfaa, NULL);
567 }
568
569 if (ci->ci_temperature == NULL) {
570 cfaa.name = "temperature";
571 ci->ci_temperature = config_found_ia(self,
572 "cpufeaturebus", &cfaa, NULL);
573 }
574
575 if (ci->ci_vm == NULL) {
576 cfaa.name = "vm";
577 ci->ci_vm = config_found_ia(self,
578 "cpufeaturebus", &cfaa, NULL);
579 }
580 }
581
582 return 0;
583 }
584
585 static void
586 cpu_childdetached(device_t self, device_t child)
587 {
588 struct cpu_softc *sc = device_private(self);
589 struct cpu_info *ci = sc->sc_info;
590
591 if (ci->ci_frequency == child)
592 ci->ci_frequency = NULL;
593
594 if (ci->ci_padlock == child)
595 ci->ci_padlock = NULL;
596
597 if (ci->ci_temperature == child)
598 ci->ci_temperature = NULL;
599
600 if (ci->ci_vm == child)
601 ci->ci_vm = NULL;
602 }
603
604 /*
605 * Initialize the processor appropriately.
606 */
607
608 void
609 cpu_init(struct cpu_info *ci)
610 {
611 extern int x86_fpu_save;
612 uint32_t cr4 = 0;
613
614 lcr0(rcr0() | CR0_WP);
615
616 /* If global TLB caching is supported, enable it */
617 if (cpu_feature[0] & CPUID_PGE)
618 cr4 |= CR4_PGE;
619
620 /*
621 * If we have FXSAVE/FXRESTOR, use them.
622 */
623 if (cpu_feature[0] & CPUID_FXSR) {
624 cr4 |= CR4_OSFXSR;
625
626 /*
627 * If we have SSE/SSE2, enable XMM exceptions.
628 */
629 if (cpu_feature[0] & (CPUID_SSE|CPUID_SSE2))
630 cr4 |= CR4_OSXMMEXCPT;
631 }
632
633 /* If xsave is supported, enable it */
634 if (cpu_feature[1] & CPUID2_XSAVE)
635 cr4 |= CR4_OSXSAVE;
636
637 /* If SMEP is supported, enable it */
638 if (cpu_feature[5] & CPUID_SEF_SMEP)
639 cr4 |= CR4_SMEP;
640
641 /* If SMAP is supported, enable it */
642 if (cpu_feature[5] & CPUID_SEF_SMAP)
643 cr4 |= CR4_SMAP;
644
645 #ifdef SVS
646 /* If PCID is supported, enable it */
647 if (svs_pcid)
648 cr4 |= CR4_PCIDE;
649 #endif
650
651 if (cr4) {
652 cr4 |= rcr4();
653 lcr4(cr4);
654 }
655
656 /*
657 * Changing CR4 register may change cpuid values. For example, setting
658 * CR4_OSXSAVE sets CPUID2_OSXSAVE. The CPUID2_OSXSAVE is in
659 * ci_feat_val[1], so update it.
660 * XXX Other than ci_feat_val[1] might be changed.
661 */
662 if (cpuid_level >= 1) {
663 u_int descs[4];
664
665 x86_cpuid(1, descs);
666 ci->ci_feat_val[1] = descs[2];
667 }
668
669 if (x86_fpu_save >= FPU_SAVE_FXSAVE) {
670 fpuinit_mxcsr_mask();
671 }
672
673 /* If xsave is enabled, enable all fpu features */
674 if (cr4 & CR4_OSXSAVE)
675 wrxcr(0, x86_xsave_features & XCR0_FPU);
676
677 #ifdef MTRR
678 /*
679 * On a P6 or above, initialize MTRR's if the hardware supports them.
680 */
681 if (cpu_feature[0] & CPUID_MTRR) {
682 if ((ci->ci_flags & CPUF_AP) == 0)
683 i686_mtrr_init_first();
684 mtrr_init_cpu(ci);
685 }
686
687 #ifdef i386
688 if (strcmp((char *)(ci->ci_vendor), "AuthenticAMD") == 0) {
689 /*
690 * Must be a K6-2 Step >= 7 or a K6-III.
691 */
692 if (CPUID_TO_FAMILY(ci->ci_signature) == 5) {
693 if (CPUID_TO_MODEL(ci->ci_signature) > 8 ||
694 (CPUID_TO_MODEL(ci->ci_signature) == 8 &&
695 CPUID_TO_STEPPING(ci->ci_signature) >= 7)) {
696 mtrr_funcs = &k6_mtrr_funcs;
697 k6_mtrr_init_first();
698 mtrr_init_cpu(ci);
699 }
700 }
701 }
702 #endif /* i386 */
703 #endif /* MTRR */
704
705 if (ci != &cpu_info_primary) {
706 /* Synchronize TSC */
707 wbinvd();
708 atomic_or_32(&ci->ci_flags, CPUF_RUNNING);
709 tsc_sync_ap(ci);
710 } else {
711 atomic_or_32(&ci->ci_flags, CPUF_RUNNING);
712 }
713 }
714
715 #ifdef MULTIPROCESSOR
716 void
717 cpu_boot_secondary_processors(void)
718 {
719 struct cpu_info *ci;
720 kcpuset_t *cpus;
721 u_long i;
722
723 #ifndef XEN
724 /* Now that we know the number of CPUs, patch the text segment. */
725 x86_patch(false);
726 #endif
727
728 #if NACPICA > 0
729 /* Finished with NUMA info for now. */
730 acpisrat_exit();
731 #endif
732
733 kcpuset_create(&cpus, true);
734 kcpuset_set(cpus, cpu_index(curcpu()));
735 for (i = 0; i < maxcpus; i++) {
736 ci = cpu_lookup(i);
737 if (ci == NULL)
738 continue;
739 if (ci->ci_data.cpu_idlelwp == NULL)
740 continue;
741 if ((ci->ci_flags & CPUF_PRESENT) == 0)
742 continue;
743 if (ci->ci_flags & (CPUF_BSP|CPUF_SP|CPUF_PRIMARY))
744 continue;
745 cpu_boot_secondary(ci);
746 kcpuset_set(cpus, cpu_index(ci));
747 }
748 while (!kcpuset_match(cpus, kcpuset_running))
749 ;
750 kcpuset_destroy(cpus);
751
752 x86_mp_online = true;
753
754 /* Now that we know about the TSC, attach the timecounter. */
755 tsc_tc_init();
756
757 /* Enable zeroing of pages in the idle loop if we have SSE2. */
758 vm_page_zero_enable = false; /* ((cpu_feature[0] & CPUID_SSE2) != 0); */
759 }
760 #endif
761
762 static void
763 cpu_init_idle_lwp(struct cpu_info *ci)
764 {
765 struct lwp *l = ci->ci_data.cpu_idlelwp;
766 struct pcb *pcb = lwp_getpcb(l);
767
768 pcb->pcb_cr0 = rcr0();
769 }
770
771 void
772 cpu_init_idle_lwps(void)
773 {
774 struct cpu_info *ci;
775 u_long i;
776
777 for (i = 0; i < maxcpus; i++) {
778 ci = cpu_lookup(i);
779 if (ci == NULL)
780 continue;
781 if (ci->ci_data.cpu_idlelwp == NULL)
782 continue;
783 if ((ci->ci_flags & CPUF_PRESENT) == 0)
784 continue;
785 cpu_init_idle_lwp(ci);
786 }
787 }
788
789 #ifdef MULTIPROCESSOR
790 void
791 cpu_start_secondary(struct cpu_info *ci)
792 {
793 u_long psl;
794 int i;
795
796 #if NLAPIC > 0
797 paddr_t mp_pdirpa;
798 mp_pdirpa = pmap_init_tmp_pgtbl(mp_trampoline_paddr);
799 cpu_copy_trampoline(mp_pdirpa);
800 #endif
801
802 atomic_or_32(&ci->ci_flags, CPUF_AP);
803 ci->ci_curlwp = ci->ci_data.cpu_idlelwp;
804 if (CPU_STARTUP(ci, mp_trampoline_paddr) != 0) {
805 return;
806 }
807
808 /*
809 * Wait for it to become ready. Setting cpu_starting opens the
810 * initial gate and allows the AP to start soft initialization.
811 */
812 KASSERT(cpu_starting == NULL);
813 cpu_starting = ci;
814 for (i = 100000; (!(ci->ci_flags & CPUF_PRESENT)) && i > 0; i--) {
815 x86_delay(10);
816 }
817
818 if ((ci->ci_flags & CPUF_PRESENT) == 0) {
819 aprint_error_dev(ci->ci_dev, "failed to become ready\n");
820 #if defined(MPDEBUG) && defined(DDB)
821 printf("dropping into debugger; continue from here to resume boot\n");
822 Debugger();
823 #endif
824 } else {
825 /*
826 * Synchronize time stamp counters. Invalidate cache and do
827 * twice (in tsc_sync_bp) to minimize possible cache effects.
828 * Disable interrupts to try and rule out any external
829 * interference.
830 */
831 psl = x86_read_psl();
832 x86_disable_intr();
833 wbinvd();
834 tsc_sync_bp(ci);
835 x86_write_psl(psl);
836 }
837
838 CPU_START_CLEANUP(ci);
839 cpu_starting = NULL;
840 }
841
842 void
843 cpu_boot_secondary(struct cpu_info *ci)
844 {
845 int64_t drift;
846 u_long psl;
847 int i;
848
849 atomic_or_32(&ci->ci_flags, CPUF_GO);
850 for (i = 100000; (!(ci->ci_flags & CPUF_RUNNING)) && i > 0; i--) {
851 x86_delay(10);
852 }
853 if ((ci->ci_flags & CPUF_RUNNING) == 0) {
854 aprint_error_dev(ci->ci_dev, "failed to start\n");
855 #if defined(MPDEBUG) && defined(DDB)
856 printf("dropping into debugger; continue from here to resume boot\n");
857 Debugger();
858 #endif
859 } else {
860 /* Synchronize TSC again, check for drift. */
861 drift = ci->ci_data.cpu_cc_skew;
862 psl = x86_read_psl();
863 x86_disable_intr();
864 wbinvd();
865 tsc_sync_bp(ci);
866 x86_write_psl(psl);
867 drift -= ci->ci_data.cpu_cc_skew;
868 aprint_debug_dev(ci->ci_dev, "TSC skew=%lld drift=%lld\n",
869 (long long)ci->ci_data.cpu_cc_skew, (long long)drift);
870 tsc_sync_drift(drift);
871 }
872 }
873
874 /*
875 * The CPU ends up here when it's ready to run.
876 * This is called from code in mptramp.s; at this point, we are running
877 * in the idle pcb/idle stack of the new CPU. When this function returns,
878 * this processor will enter the idle loop and start looking for work.
879 */
880 void
881 cpu_hatch(void *v)
882 {
883 struct cpu_info *ci = (struct cpu_info *)v;
884 struct pcb *pcb;
885 int s, i;
886
887 /* ------------------------------------------------------------- */
888
889 /*
890 * This section of code must be compiled with SSP disabled, to
891 * prevent a race against cpu0. See sys/conf/ssp.mk.
892 */
893
894 cpu_init_msrs(ci, true);
895 cpu_probe(ci);
896 cpu_speculation_init(ci);
897 #if NHYPERV > 0
898 hyperv_init_cpu(ci);
899 #endif
900
901 ci->ci_data.cpu_cc_freq = cpu_info_primary.ci_data.cpu_cc_freq;
902 /* cpu_get_tsc_freq(ci); */
903
904 KDASSERT((ci->ci_flags & CPUF_PRESENT) == 0);
905
906 /*
907 * Synchronize the TSC for the first time. Note that interrupts are
908 * off at this point.
909 */
910 wbinvd();
911 atomic_or_32(&ci->ci_flags, CPUF_PRESENT);
912 tsc_sync_ap(ci);
913
914 /* ------------------------------------------------------------- */
915
916 /*
917 * Wait to be brought online.
918 *
919 * Use MONITOR/MWAIT if available. These instructions put the CPU in
920 * a low consumption mode (C-state), and if the TSC is not invariant,
921 * this causes the TSC to drift. We want this to happen, so that we
922 * can later detect (in tsc_tc_init) any abnormal drift with invariant
923 * TSCs. That's just for safety; by definition such drifts should
924 * never occur with invariant TSCs.
925 *
926 * If not available, try PAUSE. We'd like to use HLT, but we have
927 * interrupts off.
928 */
929 while ((ci->ci_flags & CPUF_GO) == 0) {
930 if ((cpu_feature[1] & CPUID2_MONITOR) != 0) {
931 x86_monitor(&ci->ci_flags, 0, 0);
932 if ((ci->ci_flags & CPUF_GO) != 0) {
933 continue;
934 }
935 x86_mwait(0, 0);
936 } else {
937 /*
938 * XXX The loop repetition count could be a lot higher, but
939 * XXX currently qemu emulator takes a _very_long_time_ to
940 * XXX execute the pause instruction. So for now, use a low
941 * XXX value to allow the cpu to hatch before timing out.
942 */
943 for (i = 50; i != 0; i--) {
944 x86_pause();
945 }
946 }
947 }
948
949 /* Because the text may have been patched in x86_patch(). */
950 wbinvd();
951 x86_flush();
952 tlbflushg();
953
954 KASSERT((ci->ci_flags & CPUF_RUNNING) == 0);
955
956 #ifdef PAE
957 pd_entry_t * l3_pd = ci->ci_pae_l3_pdir;
958 for (i = 0 ; i < PDP_SIZE; i++) {
959 l3_pd[i] = pmap_kernel()->pm_pdirpa[i] | PTE_P;
960 }
961 lcr3(ci->ci_pae_l3_pdirpa);
962 #else
963 lcr3(pmap_pdirpa(pmap_kernel(), 0));
964 #endif
965
966 pcb = lwp_getpcb(curlwp);
967 pcb->pcb_cr3 = rcr3();
968 pcb = lwp_getpcb(ci->ci_data.cpu_idlelwp);
969 lcr0(pcb->pcb_cr0);
970
971 cpu_init_idt();
972 gdt_init_cpu(ci);
973 #if NLAPIC > 0
974 lapic_enable();
975 lapic_set_lvt();
976 lapic_initclocks();
977 #endif
978
979 fpuinit(ci);
980 lldt(GSYSSEL(GLDT_SEL, SEL_KPL));
981 ltr(ci->ci_tss_sel);
982
983 /*
984 * cpu_init will re-synchronize the TSC, and will detect any abnormal
985 * drift that would have been caused by the use of MONITOR/MWAIT
986 * above.
987 */
988 cpu_init(ci);
989 cpu_get_tsc_freq(ci);
990
991 s = splhigh();
992 #if NLAPIC > 0
993 lapic_write_tpri(0);
994 #endif
995 x86_enable_intr();
996 splx(s);
997 x86_errata();
998
999 aprint_debug_dev(ci->ci_dev, "running\n");
1000
1001 kcsan_cpu_init(ci);
1002
1003 idle_loop(NULL);
1004 KASSERT(false);
1005 }
1006 #endif
1007
1008 #if defined(DDB)
1009
1010 #include <ddb/db_output.h>
1011 #include <machine/db_machdep.h>
1012
1013 /*
1014 * Dump CPU information from ddb.
1015 */
1016 void
1017 cpu_debug_dump(void)
1018 {
1019 struct cpu_info *ci;
1020 CPU_INFO_ITERATOR cii;
1021 const char sixtyfour64space[] =
1022 #ifdef _LP64
1023 " "
1024 #endif
1025 "";
1026
1027 db_printf("addr %sdev id flags ipis spl curlwp "
1028 "\n", sixtyfour64space);
1029 for (CPU_INFO_FOREACH(cii, ci)) {
1030 db_printf("%p %s %ld %x %x %d %10p\n",
1031 ci,
1032 ci->ci_dev == NULL ? "BOOT" : device_xname(ci->ci_dev),
1033 (long)ci->ci_cpuid,
1034 ci->ci_flags, ci->ci_ipis, ci->ci_ilevel,
1035 ci->ci_curlwp);
1036 }
1037 }
1038 #endif
1039
1040 #ifdef MULTIPROCESSOR
1041 #if NLAPIC > 0
1042 static void
1043 cpu_copy_trampoline(paddr_t pdir_pa)
1044 {
1045 extern uint32_t nox_flag;
1046 extern u_char cpu_spinup_trampoline[];
1047 extern u_char cpu_spinup_trampoline_end[];
1048 vaddr_t mp_trampoline_vaddr;
1049 struct {
1050 uint32_t large;
1051 uint32_t nox;
1052 uint32_t pdir;
1053 } smp_data;
1054 CTASSERT(sizeof(smp_data) == 3 * 4);
1055
1056 smp_data.large = (pmap_largepages != 0);
1057 smp_data.nox = nox_flag;
1058 smp_data.pdir = (uint32_t)(pdir_pa & 0xFFFFFFFF);
1059
1060 /* Enter the physical address */
1061 mp_trampoline_vaddr = uvm_km_alloc(kernel_map, PAGE_SIZE, 0,
1062 UVM_KMF_VAONLY);
1063 pmap_kenter_pa(mp_trampoline_vaddr, mp_trampoline_paddr,
1064 VM_PROT_READ | VM_PROT_WRITE, 0);
1065 pmap_update(pmap_kernel());
1066
1067 /* Copy boot code */
1068 memcpy((void *)mp_trampoline_vaddr,
1069 cpu_spinup_trampoline,
1070 cpu_spinup_trampoline_end - cpu_spinup_trampoline);
1071
1072 /* Copy smp_data at the end */
1073 memcpy((void *)(mp_trampoline_vaddr + PAGE_SIZE - sizeof(smp_data)),
1074 &smp_data, sizeof(smp_data));
1075
1076 pmap_kremove(mp_trampoline_vaddr, PAGE_SIZE);
1077 pmap_update(pmap_kernel());
1078 uvm_km_free(kernel_map, mp_trampoline_vaddr, PAGE_SIZE, UVM_KMF_VAONLY);
1079 }
1080 #endif
1081
1082 int
1083 mp_cpu_start(struct cpu_info *ci, paddr_t target)
1084 {
1085 int error;
1086
1087 /*
1088 * Bootstrap code must be addressable in real mode
1089 * and it must be page aligned.
1090 */
1091 KASSERT(target < 0x10000 && target % PAGE_SIZE == 0);
1092
1093 /*
1094 * "The BSP must initialize CMOS shutdown code to 0Ah ..."
1095 */
1096
1097 outb(IO_RTC, NVRAM_RESET);
1098 outb(IO_RTC+1, NVRAM_RESET_JUMP);
1099
1100 #if NLAPIC > 0
1101 /*
1102 * "and the warm reset vector (DWORD based at 40:67) to point
1103 * to the AP startup code ..."
1104 */
1105 unsigned short dwordptr[2];
1106 dwordptr[0] = 0;
1107 dwordptr[1] = target >> 4;
1108
1109 memcpy((uint8_t *)cmos_data_mapping + 0x467, dwordptr, 4);
1110 #endif
1111
1112 if ((cpu_feature[0] & CPUID_APIC) == 0) {
1113 aprint_error("mp_cpu_start: CPU does not have APIC\n");
1114 return ENODEV;
1115 }
1116
1117 /*
1118 * ... prior to executing the following sequence:". We'll also add in
1119 * local cache flush, in case the BIOS has left the AP with its cache
1120 * disabled. It may not be able to cope with MP coherency.
1121 */
1122 wbinvd();
1123
1124 if (ci->ci_flags & CPUF_AP) {
1125 error = x86_ipi_init(ci->ci_cpuid);
1126 if (error != 0) {
1127 aprint_error_dev(ci->ci_dev, "%s: IPI not taken (1)\n",
1128 __func__);
1129 return error;
1130 }
1131 x86_delay(10000);
1132
1133 error = x86_ipi_startup(ci->ci_cpuid, target / PAGE_SIZE);
1134 if (error != 0) {
1135 aprint_error_dev(ci->ci_dev, "%s: IPI not taken (2)\n",
1136 __func__);
1137 return error;
1138 }
1139 x86_delay(200);
1140
1141 error = x86_ipi_startup(ci->ci_cpuid, target / PAGE_SIZE);
1142 if (error != 0) {
1143 aprint_error_dev(ci->ci_dev, "%s: IPI not taken (3)\n",
1144 __func__);
1145 return error;
1146 }
1147 x86_delay(200);
1148 }
1149
1150 return 0;
1151 }
1152
1153 void
1154 mp_cpu_start_cleanup(struct cpu_info *ci)
1155 {
1156 /*
1157 * Ensure the NVRAM reset byte contains something vaguely sane.
1158 */
1159
1160 outb(IO_RTC, NVRAM_RESET);
1161 outb(IO_RTC+1, NVRAM_RESET_RST);
1162 }
1163 #endif
1164
1165 #ifdef __x86_64__
1166 typedef void (vector)(void);
1167 extern vector Xsyscall, Xsyscall32, Xsyscall_svs;
1168 #endif
1169
1170 void
1171 cpu_init_msrs(struct cpu_info *ci, bool full)
1172 {
1173 #ifdef __x86_64__
1174 wrmsr(MSR_STAR,
1175 ((uint64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
1176 ((uint64_t)LSEL(LSYSRETBASE_SEL, SEL_UPL) << 48));
1177 wrmsr(MSR_LSTAR, (uint64_t)Xsyscall);
1178 wrmsr(MSR_CSTAR, (uint64_t)Xsyscall32);
1179 wrmsr(MSR_SFMASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D|PSL_AC);
1180
1181 #ifdef SVS
1182 if (svs_enabled)
1183 wrmsr(MSR_LSTAR, (uint64_t)Xsyscall_svs);
1184 #endif
1185
1186 if (full) {
1187 wrmsr(MSR_FSBASE, 0);
1188 wrmsr(MSR_GSBASE, (uint64_t)ci);
1189 wrmsr(MSR_KERNELGSBASE, 0);
1190 }
1191 #endif /* __x86_64__ */
1192
1193 if (cpu_feature[2] & CPUID_NOX)
1194 wrmsr(MSR_EFER, rdmsr(MSR_EFER) | EFER_NXE);
1195 }
1196
1197 void
1198 cpu_offline_md(void)
1199 {
1200 return;
1201 }
1202
1203 /* XXX joerg restructure and restart CPUs individually */
1204 static bool
1205 cpu_stop(device_t dv)
1206 {
1207 struct cpu_softc *sc = device_private(dv);
1208 struct cpu_info *ci = sc->sc_info;
1209 int err;
1210
1211 KASSERT((ci->ci_flags & CPUF_PRESENT) != 0);
1212
1213 if ((ci->ci_flags & CPUF_PRIMARY) != 0)
1214 return true;
1215
1216 if (ci->ci_data.cpu_idlelwp == NULL)
1217 return true;
1218
1219 sc->sc_wasonline = !(ci->ci_schedstate.spc_flags & SPCF_OFFLINE);
1220
1221 if (sc->sc_wasonline) {
1222 mutex_enter(&cpu_lock);
1223 err = cpu_setstate(ci, false);
1224 mutex_exit(&cpu_lock);
1225
1226 if (err != 0)
1227 return false;
1228 }
1229
1230 return true;
1231 }
1232
1233 static bool
1234 cpu_suspend(device_t dv, const pmf_qual_t *qual)
1235 {
1236 struct cpu_softc *sc = device_private(dv);
1237 struct cpu_info *ci = sc->sc_info;
1238
1239 if ((ci->ci_flags & CPUF_PRESENT) == 0)
1240 return true;
1241 else {
1242 cpufreq_suspend(ci);
1243 }
1244
1245 return cpu_stop(dv);
1246 }
1247
1248 static bool
1249 cpu_resume(device_t dv, const pmf_qual_t *qual)
1250 {
1251 struct cpu_softc *sc = device_private(dv);
1252 struct cpu_info *ci = sc->sc_info;
1253 int err = 0;
1254
1255 if ((ci->ci_flags & CPUF_PRESENT) == 0)
1256 return true;
1257
1258 if ((ci->ci_flags & CPUF_PRIMARY) != 0)
1259 goto out;
1260
1261 if (ci->ci_data.cpu_idlelwp == NULL)
1262 goto out;
1263
1264 if (sc->sc_wasonline) {
1265 mutex_enter(&cpu_lock);
1266 err = cpu_setstate(ci, true);
1267 mutex_exit(&cpu_lock);
1268 }
1269
1270 out:
1271 if (err != 0)
1272 return false;
1273
1274 cpufreq_resume(ci);
1275
1276 return true;
1277 }
1278
1279 static bool
1280 cpu_shutdown(device_t dv, int how)
1281 {
1282 struct cpu_softc *sc = device_private(dv);
1283 struct cpu_info *ci = sc->sc_info;
1284
1285 if ((ci->ci_flags & CPUF_BSP) != 0)
1286 return false;
1287
1288 if ((ci->ci_flags & CPUF_PRESENT) == 0)
1289 return true;
1290
1291 return cpu_stop(dv);
1292 }
1293
1294 void
1295 cpu_get_tsc_freq(struct cpu_info *ci)
1296 {
1297 uint64_t last_tsc;
1298
1299 if (cpu_hascounter()) {
1300 last_tsc = cpu_counter_serializing();
1301 x86_delay(100000);
1302 ci->ci_data.cpu_cc_freq =
1303 (cpu_counter_serializing() - last_tsc) * 10;
1304 }
1305 }
1306
1307 void
1308 x86_cpu_idle_mwait(void)
1309 {
1310 struct cpu_info *ci = curcpu();
1311
1312 KASSERT(ci->ci_ilevel == IPL_NONE);
1313
1314 x86_monitor(&ci->ci_want_resched, 0, 0);
1315 if (__predict_false(ci->ci_want_resched)) {
1316 return;
1317 }
1318 x86_mwait(0, 0);
1319 }
1320
1321 void
1322 x86_cpu_idle_halt(void)
1323 {
1324 struct cpu_info *ci = curcpu();
1325
1326 KASSERT(ci->ci_ilevel == IPL_NONE);
1327
1328 x86_disable_intr();
1329 if (!__predict_false(ci->ci_want_resched)) {
1330 x86_stihlt();
1331 } else {
1332 x86_enable_intr();
1333 }
1334 }
1335
1336 /*
1337 * Loads pmap for the current CPU.
1338 */
1339 void
1340 cpu_load_pmap(struct pmap *pmap, struct pmap *oldpmap)
1341 {
1342 #ifdef SVS
1343 if (svs_enabled) {
1344 svs_pdir_switch(pmap);
1345 }
1346 #endif
1347
1348 #ifdef PAE
1349 struct cpu_info *ci = curcpu();
1350 bool interrupts_enabled;
1351 pd_entry_t *l3_pd = ci->ci_pae_l3_pdir;
1352 int i;
1353
1354 /*
1355 * disable interrupts to block TLB shootdowns, which can reload cr3.
1356 * while this doesn't block NMIs, it's probably ok as NMIs unlikely
1357 * reload cr3.
1358 */
1359 interrupts_enabled = (x86_read_flags() & PSL_I) != 0;
1360 if (interrupts_enabled)
1361 x86_disable_intr();
1362
1363 for (i = 0 ; i < PDP_SIZE; i++) {
1364 l3_pd[i] = pmap->pm_pdirpa[i] | PTE_P;
1365 }
1366
1367 if (interrupts_enabled)
1368 x86_enable_intr();
1369 tlbflush();
1370 #else
1371 lcr3(pmap_pdirpa(pmap, 0));
1372 #endif
1373 }
1374
1375 /*
1376 * Notify all other cpus to halt.
1377 */
1378
1379 void
1380 cpu_broadcast_halt(void)
1381 {
1382 x86_broadcast_ipi(X86_IPI_HALT);
1383 }
1384
1385 /*
1386 * Send a dummy ipi to a cpu to force it to run splraise()/spllower(),
1387 * and trigger an AST on the running LWP.
1388 */
1389
1390 void
1391 cpu_kick(struct cpu_info *ci)
1392 {
1393 x86_send_ipi(ci, X86_IPI_AST);
1394 }
1395