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