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