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