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