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