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