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