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