cpu.c revision 1.39 1 /* $NetBSD: cpu.c,v 1.39 2008/05/10 17:23:54 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.39 2008/05/10 17:23:54 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 if (cpunum >= X86_MAXPROCS) {
297 aprint_error(": apic id %d ignored, "
298 "please increase X86_MAXPROCS\n", cpunum);
299 return;
300 }
301 aprint_naive(": Application Processor\n");
302 ptr = (uintptr_t)malloc(sizeof(*ci) + CACHE_LINE_SIZE - 1,
303 M_DEVBUF, M_WAITOK);
304 ci = (struct cpu_info *)((ptr + CACHE_LINE_SIZE - 1) &
305 ~(CACHE_LINE_SIZE - 1));
306 memset(ci, 0, sizeof(*ci));
307 #if defined(MULTIPROCESSOR)
308 if (cpu_info[cpunum] != NULL) {
309 printf("\n");
310 panic("cpu at apic id %d already attached?", cpunum);
311 }
312 cpu_info[cpunum] = ci;
313 #endif
314 #ifdef TRAPLOG
315 ci->ci_tlog_base = malloc(sizeof(struct tlog),
316 M_DEVBUF, M_WAITOK);
317 #endif
318 } else {
319 aprint_naive(": %s Processor\n",
320 caa->cpu_role == CPU_ROLE_SP ? "Single" : "Boot");
321 ci = &cpu_info_primary;
322 #if defined(MULTIPROCESSOR)
323 if (cpunum != lapic_cpu_number()) {
324 uint32_t reg;
325 aprint_verbose("\n");
326 aprint_verbose("%s: running CPU is at apic %d"
327 " instead of at expected %d",
328 device_xname(sc->sc_dev), lapic_cpu_number(),
329 cpunum);
330 reg = i82489_readreg(LAPIC_ID);
331 i82489_writereg(LAPIC_ID, (reg & ~LAPIC_ID_MASK) |
332 (cpunum << LAPIC_ID_SHIFT));
333 }
334 #endif
335 }
336
337 ci->ci_self = ci;
338 sc->sc_info = ci;
339
340 ci->ci_dev = self;
341 ci->ci_apicid = caa->cpu_number;
342 #ifdef MULTIPROCESSOR
343 ci->ci_cpuid = ci->ci_apicid;
344 #else
345 ci->ci_cpuid = 0; /* False for APs, but they're not used anyway */
346 #endif
347 ci->ci_cpumask = (1 << ci->ci_cpuid);
348 ci->ci_func = caa->cpu_func;
349
350 if (caa->cpu_role == CPU_ROLE_AP) {
351 #ifdef MULTIPROCESSOR
352 int error;
353
354 error = mi_cpu_attach(ci);
355 if (error != 0) {
356 aprint_normal("\n");
357 aprint_error_dev(sc->sc_dev,
358 "mi_cpu_attach failed with %d\n", error);
359 return;
360 }
361 #endif
362 cpu_init_tss(ci);
363 } else {
364 KASSERT(ci->ci_data.cpu_idlelwp != NULL);
365 }
366
367 pmap_reference(pmap_kernel());
368 ci->ci_pmap = pmap_kernel();
369 ci->ci_tlbstate = TLBSTATE_STALE;
370
371 /* further PCB init done later. */
372
373 switch (caa->cpu_role) {
374 case CPU_ROLE_SP:
375 aprint_normal(": (uniprocessor)\n");
376 atomic_or_32(&ci->ci_flags,
377 CPUF_PRESENT | CPUF_SP | CPUF_PRIMARY);
378 cpu_intr_init(ci);
379 identifycpu(ci);
380 cpu_init(ci);
381 cpu_set_tss_gates(ci);
382 pmap_cpu_init_late(ci);
383 x86_errata();
384 x86_cpu_idle_init();
385 break;
386
387 case CPU_ROLE_BP:
388 aprint_normal(": (boot processor)\n");
389 atomic_or_32(&ci->ci_flags,
390 CPUF_PRESENT | CPUF_BSP | CPUF_PRIMARY);
391 cpu_intr_init(ci);
392 identifycpu(ci);
393 cpu_init(ci);
394 cpu_set_tss_gates(ci);
395 pmap_cpu_init_late(ci);
396 #if NLAPIC > 0
397 /*
398 * Enable local apic
399 */
400 lapic_enable();
401 lapic_set_lvt();
402 lapic_calibrate_timer(ci);
403 #endif
404 x86_errata();
405 x86_cpu_idle_init();
406 break;
407
408 case CPU_ROLE_AP:
409 /*
410 * report on an AP
411 */
412 aprint_normal(": (application processor)\n");
413
414 #if defined(MULTIPROCESSOR)
415 cpu_intr_init(ci);
416 gdt_alloc_cpu(ci);
417 cpu_set_tss_gates(ci);
418 pmap_cpu_init_early(ci);
419 pmap_cpu_init_late(ci);
420 cpu_start_secondary(ci);
421 if (ci->ci_flags & CPUF_PRESENT) {
422 identifycpu(ci);
423 ci->ci_next = cpu_info_list->ci_next;
424 cpu_info_list->ci_next = ci;
425 }
426 #else
427 aprint_normal_dev(sc->sc_dev, "not started\n");
428 #endif
429 break;
430
431 default:
432 aprint_normal("\n");
433 panic("unknown processor type??\n");
434 }
435 cpu_vm_init(ci);
436
437 cpus_attached |= ci->ci_cpumask;
438
439 if (!pmf_device_register(self, cpu_suspend, cpu_resume))
440 aprint_error_dev(self, "couldn't establish power handler\n");
441
442 #if defined(MULTIPROCESSOR)
443 if (mp_verbose) {
444 struct lwp *l = ci->ci_data.cpu_idlelwp;
445
446 aprint_verbose_dev(sc->sc_dev,
447 "idle lwp at %p, idle sp at %p\n",
448 l,
449 #ifdef i386
450 (void *)l->l_addr->u_pcb.pcb_esp
451 #else
452 (void *)l->l_addr->u_pcb.pcb_rsp
453 #endif
454 );
455 }
456 #endif
457 }
458
459 /*
460 * Initialize the processor appropriately.
461 */
462
463 void
464 cpu_init(struct cpu_info *ci)
465 {
466 /* configure the CPU if needed */
467 if (ci->cpu_setup != NULL)
468 (*ci->cpu_setup)(ci);
469
470 lcr0(rcr0() | CR0_WP);
471
472 /*
473 * On a P6 or above, enable global TLB caching if the
474 * hardware supports it.
475 */
476 if (cpu_feature & CPUID_PGE)
477 lcr4(rcr4() | CR4_PGE); /* enable global TLB caching */
478
479 /*
480 * If we have FXSAVE/FXRESTOR, use them.
481 */
482 if (cpu_feature & CPUID_FXSR) {
483 lcr4(rcr4() | CR4_OSFXSR);
484
485 /*
486 * If we have SSE/SSE2, enable XMM exceptions.
487 */
488 if (cpu_feature & (CPUID_SSE|CPUID_SSE2))
489 lcr4(rcr4() | CR4_OSXMMEXCPT);
490 }
491
492 #ifdef MTRR
493 /*
494 * On a P6 or above, initialize MTRR's if the hardware supports them.
495 */
496 if (cpu_feature & CPUID_MTRR) {
497 if ((ci->ci_flags & CPUF_AP) == 0)
498 i686_mtrr_init_first();
499 mtrr_init_cpu(ci);
500 }
501
502 #ifdef i386
503 if (strcmp((char *)(ci->ci_vendor), "AuthenticAMD") == 0) {
504 /*
505 * Must be a K6-2 Step >= 7 or a K6-III.
506 */
507 if (CPUID2FAMILY(ci->ci_signature) == 5) {
508 if (CPUID2MODEL(ci->ci_signature) > 8 ||
509 (CPUID2MODEL(ci->ci_signature) == 8 &&
510 CPUID2STEPPING(ci->ci_signature) >= 7)) {
511 mtrr_funcs = &k6_mtrr_funcs;
512 k6_mtrr_init_first();
513 mtrr_init_cpu(ci);
514 }
515 }
516 }
517 #endif /* i386 */
518 #endif /* MTRR */
519
520 atomic_or_32(&cpus_running, ci->ci_cpumask);
521
522 if (ci != &cpu_info_primary) {
523 /* Synchronize TSC again, and check for drift. */
524 wbinvd();
525 atomic_or_32(&ci->ci_flags, CPUF_RUNNING);
526 tsc_sync_ap(ci);
527 tsc_sync_ap(ci);
528 } else {
529 atomic_or_32(&ci->ci_flags, CPUF_RUNNING);
530 }
531
532 #ifndef MULTIPROCESSOR
533 /* XXX */
534 x86_patch();
535 #endif
536 }
537
538 #ifdef MULTIPROCESSOR
539 void
540 cpu_boot_secondary_processors(void)
541 {
542 struct cpu_info *ci;
543 u_long i;
544
545 /* Now that we know the number of CPUs, patch the text segment. */
546 x86_patch();
547
548 for (i=0; i < X86_MAXPROCS; i++) {
549 ci = cpu_info[i];
550 if (ci == NULL)
551 continue;
552 if (ci->ci_data.cpu_idlelwp == NULL)
553 continue;
554 if ((ci->ci_flags & CPUF_PRESENT) == 0)
555 continue;
556 if (ci->ci_flags & (CPUF_BSP|CPUF_SP|CPUF_PRIMARY))
557 continue;
558 cpu_boot_secondary(ci);
559 }
560
561 x86_mp_online = true;
562
563 /* Now that we know about the TSC, attach the timecounter. */
564 tsc_tc_init();
565 }
566
567 static void
568 cpu_init_idle_lwp(struct cpu_info *ci)
569 {
570 struct lwp *l = ci->ci_data.cpu_idlelwp;
571 struct pcb *pcb = &l->l_addr->u_pcb;
572
573 pcb->pcb_cr0 = rcr0();
574 }
575
576 void
577 cpu_init_idle_lwps(void)
578 {
579 struct cpu_info *ci;
580 u_long i;
581
582 for (i = 0; i < X86_MAXPROCS; i++) {
583 ci = cpu_info[i];
584 if (ci == NULL)
585 continue;
586 if (ci->ci_data.cpu_idlelwp == NULL)
587 continue;
588 if ((ci->ci_flags & CPUF_PRESENT) == 0)
589 continue;
590 cpu_init_idle_lwp(ci);
591 }
592 }
593
594 void
595 cpu_start_secondary(struct cpu_info *ci)
596 {
597 extern paddr_t mp_pdirpa;
598 u_long psl;
599 int i;
600
601 mp_pdirpa = pmap_init_tmp_pgtbl(mp_trampoline_paddr);
602
603 atomic_or_32(&ci->ci_flags, CPUF_AP);
604
605 ci->ci_curlwp = ci->ci_data.cpu_idlelwp;
606 if (CPU_STARTUP(ci, mp_trampoline_paddr) != 0)
607 return;
608
609 /*
610 * wait for it to become ready
611 */
612 for (i = 100000; (!(ci->ci_flags & CPUF_PRESENT)) && i > 0; i--) {
613 #ifdef MPDEBUG
614 extern int cpu_trace[3];
615 static int otrace[3];
616 if (memcmp(otrace, cpu_trace, sizeof(otrace)) != 0) {
617 aprint_debug_dev(ci->ci_dev, "trace %02x %02x %02x\n",
618 cpu_trace[0], cpu_trace[1], cpu_trace[2]);
619 memcpy(otrace, cpu_trace, sizeof(otrace));
620 }
621 #endif
622 i8254_delay(10);
623 }
624
625 if ((ci->ci_flags & CPUF_PRESENT) == 0) {
626 aprint_error_dev(ci->ci_dev, "failed to become ready\n");
627 #if defined(MPDEBUG) && defined(DDB)
628 printf("dropping into debugger; continue from here to resume boot\n");
629 Debugger();
630 #endif
631 } else {
632 /*
633 * Synchronize time stamp counters. Invalidate cache and do twice
634 * to try and minimize possible cache effects. Disable interrupts
635 * to try and rule out any external interference.
636 */
637 psl = x86_read_psl();
638 x86_disable_intr();
639 wbinvd();
640 tsc_sync_bp(ci);
641 tsc_sync_bp(ci);
642 x86_write_psl(psl);
643 }
644
645 CPU_START_CLEANUP(ci);
646 }
647
648 void
649 cpu_boot_secondary(struct cpu_info *ci)
650 {
651 int64_t drift;
652 u_long psl;
653 int i;
654
655 atomic_or_32(&ci->ci_flags, CPUF_GO);
656 for (i = 100000; (!(ci->ci_flags & CPUF_RUNNING)) && i > 0; i--) {
657 i8254_delay(10);
658 }
659 if ((ci->ci_flags & CPUF_RUNNING) == 0) {
660 aprint_error_dev(ci->ci_dev, "failed to start\n");
661 #if defined(MPDEBUG) && defined(DDB)
662 printf("dropping into debugger; continue from here to resume boot\n");
663 Debugger();
664 #endif
665 } else {
666 /* Synchronize TSC again, check for drift. */
667 drift = ci->ci_data.cpu_cc_skew;
668 psl = x86_read_psl();
669 x86_disable_intr();
670 wbinvd();
671 tsc_sync_bp(ci);
672 tsc_sync_bp(ci);
673 x86_write_psl(psl);
674 drift -= ci->ci_data.cpu_cc_skew;
675 aprint_debug_dev(ci->ci_dev, "TSC skew=%lld drift=%lld\n",
676 (long long)ci->ci_data.cpu_cc_skew, (long long)drift);
677 tsc_sync_drift(drift);
678 }
679 }
680
681 /*
682 * The CPU ends up here when its ready to run
683 * This is called from code in mptramp.s; at this point, we are running
684 * in the idle pcb/idle stack of the new CPU. When this function returns,
685 * this processor will enter the idle loop and start looking for work.
686 */
687 void
688 cpu_hatch(void *v)
689 {
690 struct cpu_info *ci = (struct cpu_info *)v;
691 int s, i;
692
693 #ifdef __x86_64__
694 cpu_init_msrs(ci, true);
695 #endif
696 cpu_probe_features(ci);
697 cpu_feature &= ci->ci_feature_flags;
698 cpu_feature2 &= ci->ci_feature2_flags;
699
700 /* XXX Until we have a proper calibration loop, just lie. */
701 ci->ci_data.cpu_cc_freq = cpu_info_primary.ci_data.cpu_cc_freq;
702
703 KDASSERT((ci->ci_flags & CPUF_PRESENT) == 0);
704
705 /*
706 * Synchronize time stamp counters. Invalidate cache and do twice
707 * to try and minimize possible cache effects. Note that interrupts
708 * are off at this point.
709 */
710 wbinvd();
711 atomic_or_32(&ci->ci_flags, CPUF_PRESENT);
712 tsc_sync_ap(ci);
713 tsc_sync_ap(ci);
714
715 /*
716 * Wait to be brought online. Use 'monitor/mwait' if available,
717 * in order to make the TSC drift as much as possible. so that
718 * we can detect it later. If not available, try 'pause'.
719 * We'd like to use 'hlt', but we have interrupts off.
720 */
721 while ((ci->ci_flags & CPUF_GO) == 0) {
722 if ((ci->ci_feature2_flags & CPUID2_MONITOR) != 0) {
723 x86_monitor(&ci->ci_flags, 0, 0);
724 if ((ci->ci_flags & CPUF_GO) != 0) {
725 continue;
726 }
727 x86_mwait(0, 0);
728 } else {
729 for (i = 10000; i != 0; i--) {
730 x86_pause();
731 }
732 }
733 }
734
735 /* Because the text may have been patched in x86_patch(). */
736 wbinvd();
737 x86_flush();
738
739 KASSERT((ci->ci_flags & CPUF_RUNNING) == 0);
740
741 lcr3(pmap_kernel()->pm_pdirpa);
742 curlwp->l_addr->u_pcb.pcb_cr3 = pmap_kernel()->pm_pdirpa;
743 lcr0(ci->ci_data.cpu_idlelwp->l_addr->u_pcb.pcb_cr0);
744 cpu_init_idt();
745 gdt_init_cpu(ci);
746 lapic_enable();
747 lapic_set_lvt();
748 lapic_initclocks();
749
750 #ifdef i386
751 npxinit(ci);
752 #else
753 fpuinit(ci);
754 #endif
755 lldt(GSYSSEL(GLDT_SEL, SEL_KPL));
756 ltr(ci->ci_tss_sel);
757
758 cpu_init(ci);
759 cpu_get_tsc_freq(ci);
760
761 s = splhigh();
762 #ifdef i386
763 lapic_tpr = 0;
764 #else
765 lcr8(0);
766 #endif
767 x86_enable_intr();
768 splx(s);
769 x86_errata();
770
771 aprint_debug_dev(ci->ci_dev, "CPU %ld running\n",
772 (long)ci->ci_cpuid);
773 }
774
775 #if defined(DDB)
776
777 #include <ddb/db_output.h>
778 #include <machine/db_machdep.h>
779
780 /*
781 * Dump CPU information from ddb.
782 */
783 void
784 cpu_debug_dump(void)
785 {
786 struct cpu_info *ci;
787 CPU_INFO_ITERATOR cii;
788
789 db_printf("addr dev id flags ipis curlwp fpcurlwp\n");
790 for (CPU_INFO_FOREACH(cii, ci)) {
791 db_printf("%p %s %ld %x %x %10p %10p\n",
792 ci,
793 ci->ci_dev == NULL ? "BOOT" : device_xname(ci->ci_dev),
794 (long)ci->ci_cpuid,
795 ci->ci_flags, ci->ci_ipis,
796 ci->ci_curlwp,
797 ci->ci_fpcurlwp);
798 }
799 }
800 #endif
801
802 static void
803 cpu_copy_trampoline(void)
804 {
805 /*
806 * Copy boot code.
807 */
808 extern u_char cpu_spinup_trampoline[];
809 extern u_char cpu_spinup_trampoline_end[];
810
811 vaddr_t mp_trampoline_vaddr;
812
813 mp_trampoline_vaddr = uvm_km_alloc(kernel_map, PAGE_SIZE, 0,
814 UVM_KMF_VAONLY);
815
816 pmap_kenter_pa(mp_trampoline_vaddr, mp_trampoline_paddr,
817 VM_PROT_READ | VM_PROT_WRITE);
818 pmap_update(pmap_kernel());
819 memcpy((void *)mp_trampoline_vaddr,
820 cpu_spinup_trampoline,
821 cpu_spinup_trampoline_end - cpu_spinup_trampoline);
822
823 pmap_kremove(mp_trampoline_vaddr, PAGE_SIZE);
824 pmap_update(pmap_kernel());
825 uvm_km_free(kernel_map, mp_trampoline_vaddr, PAGE_SIZE, UVM_KMF_VAONLY);
826 }
827
828 #endif
829
830 #ifdef i386
831 static void
832 tss_init(struct i386tss *tss, void *stack, void *func)
833 {
834 memset(tss, 0, sizeof *tss);
835 tss->tss_esp0 = tss->tss_esp = (int)((char *)stack + USPACE - 16);
836 tss->tss_ss0 = GSEL(GDATA_SEL, SEL_KPL);
837 tss->__tss_cs = GSEL(GCODE_SEL, SEL_KPL);
838 tss->tss_fs = GSEL(GCPU_SEL, SEL_KPL);
839 tss->tss_gs = tss->__tss_es = tss->__tss_ds =
840 tss->__tss_ss = GSEL(GDATA_SEL, SEL_KPL);
841 tss->tss_cr3 = pmap_kernel()->pm_pdirpa;
842 tss->tss_esp = (int)((char *)stack + USPACE - 16);
843 tss->tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
844 tss->__tss_eflags = PSL_MBO | PSL_NT; /* XXX not needed? */
845 tss->__tss_eip = (int)func;
846 }
847
848 /* XXX */
849 #define IDTVEC(name) __CONCAT(X, name)
850 typedef void (vector)(void);
851 extern vector IDTVEC(tss_trap08);
852 #ifdef DDB
853 extern vector Xintrddbipi;
854 extern int ddb_vec;
855 #endif
856
857 static void
858 cpu_set_tss_gates(struct cpu_info *ci)
859 {
860 struct segment_descriptor sd;
861
862 ci->ci_doubleflt_stack = (char *)uvm_km_alloc(kernel_map, USPACE, 0,
863 UVM_KMF_WIRED);
864 tss_init(&ci->ci_doubleflt_tss, ci->ci_doubleflt_stack,
865 IDTVEC(tss_trap08));
866 setsegment(&sd, &ci->ci_doubleflt_tss, sizeof(struct i386tss) - 1,
867 SDT_SYS386TSS, SEL_KPL, 0, 0);
868 ci->ci_gdt[GTRAPTSS_SEL].sd = sd;
869 setgate(&idt[8], NULL, 0, SDT_SYSTASKGT, SEL_KPL,
870 GSEL(GTRAPTSS_SEL, SEL_KPL));
871
872 #if defined(DDB) && defined(MULTIPROCESSOR)
873 /*
874 * Set up separate handler for the DDB IPI, so that it doesn't
875 * stomp on a possibly corrupted stack.
876 *
877 * XXX overwriting the gate set in db_machine_init.
878 * Should rearrange the code so that it's set only once.
879 */
880 ci->ci_ddbipi_stack = (char *)uvm_km_alloc(kernel_map, USPACE, 0,
881 UVM_KMF_WIRED);
882 tss_init(&ci->ci_ddbipi_tss, ci->ci_ddbipi_stack, Xintrddbipi);
883
884 setsegment(&sd, &ci->ci_ddbipi_tss, sizeof(struct i386tss) - 1,
885 SDT_SYS386TSS, SEL_KPL, 0, 0);
886 ci->ci_gdt[GIPITSS_SEL].sd = sd;
887
888 setgate(&idt[ddb_vec], NULL, 0, SDT_SYSTASKGT, SEL_KPL,
889 GSEL(GIPITSS_SEL, SEL_KPL));
890 #endif
891 }
892 #else
893 static void
894 cpu_set_tss_gates(struct cpu_info *ci)
895 {
896
897 }
898 #endif /* i386 */
899
900 int
901 mp_cpu_start(struct cpu_info *ci, paddr_t target)
902 {
903 #if NLAPIC > 0
904 int error;
905 #endif
906 unsigned short dwordptr[2];
907
908 /*
909 * Bootstrap code must be addressable in real mode
910 * and it must be page aligned.
911 */
912 KASSERT(target < 0x10000 && target % PAGE_SIZE == 0);
913
914 /*
915 * "The BSP must initialize CMOS shutdown code to 0Ah ..."
916 */
917
918 outb(IO_RTC, NVRAM_RESET);
919 outb(IO_RTC+1, NVRAM_RESET_JUMP);
920
921 /*
922 * "and the warm reset vector (DWORD based at 40:67) to point
923 * to the AP startup code ..."
924 */
925
926 dwordptr[0] = 0;
927 dwordptr[1] = target >> 4;
928
929 memcpy((uint8_t *)cmos_data_mapping + 0x467, dwordptr, 4);
930
931 #if NLAPIC > 0
932 if ((cpu_feature & CPUID_APIC) == 0) {
933 aprint_error("mp_cpu_start: CPU does not have APIC\n");
934 return ENODEV;
935 }
936
937 /*
938 * ... prior to executing the following sequence:"
939 */
940
941 if (ci->ci_flags & CPUF_AP) {
942 error = x86_ipi_init(ci->ci_apicid);
943 if (error != 0) {
944 aprint_error_dev(ci->ci_dev, "%s: IPI not taken (1)\n",
945 __func__);
946 return error;
947 }
948
949 i8254_delay(10000);
950
951 error = x86_ipi(target / PAGE_SIZE, ci->ci_apicid,
952 LAPIC_DLMODE_STARTUP);
953 if (error != 0) {
954 aprint_error_dev(ci->ci_dev, "%s: IPI not taken (2)\n",
955 __func__);
956 return error;
957 }
958 i8254_delay(200);
959
960 error = x86_ipi(target / PAGE_SIZE, ci->ci_apicid,
961 LAPIC_DLMODE_STARTUP);
962 if (error != 0) {
963 aprint_error_dev(ci->ci_dev, "%s: IPI not taken (3)\n",
964 __func__);
965 return error;
966 }
967 i8254_delay(200);
968 }
969 #endif
970 return 0;
971 }
972
973 void
974 mp_cpu_start_cleanup(struct cpu_info *ci)
975 {
976 /*
977 * Ensure the NVRAM reset byte contains something vaguely sane.
978 */
979
980 outb(IO_RTC, NVRAM_RESET);
981 outb(IO_RTC+1, NVRAM_RESET_RST);
982 }
983
984 #ifdef __x86_64__
985 typedef void (vector)(void);
986 extern vector Xsyscall, Xsyscall32;
987
988 void
989 cpu_init_msrs(struct cpu_info *ci, bool full)
990 {
991 wrmsr(MSR_STAR,
992 ((uint64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
993 ((uint64_t)LSEL(LSYSRETBASE_SEL, SEL_UPL) << 48));
994 wrmsr(MSR_LSTAR, (uint64_t)Xsyscall);
995 wrmsr(MSR_CSTAR, (uint64_t)Xsyscall32);
996 wrmsr(MSR_SFMASK, PSL_NT|PSL_T|PSL_I|PSL_C);
997
998 if (full) {
999 wrmsr(MSR_FSBASE, 0);
1000 wrmsr(MSR_GSBASE, (uint64_t)ci);
1001 wrmsr(MSR_KERNELGSBASE, 0);
1002 }
1003
1004 if (cpu_feature & CPUID_NOX)
1005 wrmsr(MSR_EFER, rdmsr(MSR_EFER) | EFER_NXE);
1006 }
1007 #endif /* __x86_64__ */
1008
1009 void
1010 cpu_offline_md(void)
1011 {
1012 int s;
1013
1014 s = splhigh();
1015 #ifdef __i386__
1016 npxsave_cpu(true);
1017 #else
1018 fpusave_cpu(true);
1019 #endif
1020 splx(s);
1021 }
1022
1023 /* XXX joerg restructure and restart CPUs individually */
1024 static bool
1025 cpu_suspend(device_t dv PMF_FN_ARGS)
1026 {
1027 struct cpu_softc *sc = device_private(dv);
1028 struct cpu_info *ci = sc->sc_info;
1029 int err;
1030
1031 if (ci->ci_flags & CPUF_PRIMARY)
1032 return true;
1033 if (ci->ci_data.cpu_idlelwp == NULL)
1034 return true;
1035 if ((ci->ci_flags & CPUF_PRESENT) == 0)
1036 return true;
1037
1038 sc->sc_wasonline = !(ci->ci_schedstate.spc_flags & SPCF_OFFLINE);
1039
1040 if (sc->sc_wasonline) {
1041 mutex_enter(&cpu_lock);
1042 err = cpu_setonline(ci, false);
1043 mutex_exit(&cpu_lock);
1044
1045 if (err)
1046 return false;
1047 }
1048
1049 return true;
1050 }
1051
1052 static bool
1053 cpu_resume(device_t dv PMF_FN_ARGS)
1054 {
1055 struct cpu_softc *sc = device_private(dv);
1056 struct cpu_info *ci = sc->sc_info;
1057 int err = 0;
1058
1059 if (ci->ci_flags & CPUF_PRIMARY)
1060 return true;
1061 if (ci->ci_data.cpu_idlelwp == NULL)
1062 return true;
1063 if ((ci->ci_flags & CPUF_PRESENT) == 0)
1064 return true;
1065
1066 if (sc->sc_wasonline) {
1067 mutex_enter(&cpu_lock);
1068 err = cpu_setonline(ci, true);
1069 mutex_exit(&cpu_lock);
1070 }
1071
1072 return err == 0;
1073 }
1074
1075 void
1076 cpu_get_tsc_freq(struct cpu_info *ci)
1077 {
1078 uint64_t last_tsc;
1079 u_int junk[4];
1080
1081 if (ci->ci_feature_flags & CPUID_TSC) {
1082 /* Serialize. */
1083 x86_cpuid(0, junk);
1084 last_tsc = cpu_counter();
1085 i8254_delay(100000);
1086 ci->ci_data.cpu_cc_freq = (cpu_counter() - last_tsc) * 10;
1087 }
1088 }
1089
1090 void
1091 x86_cpu_idle_mwait(void)
1092 {
1093 struct cpu_info *ci = curcpu();
1094
1095 KASSERT(ci->ci_ilevel == IPL_NONE);
1096
1097 x86_monitor(&ci->ci_want_resched, 0, 0);
1098 if (__predict_false(ci->ci_want_resched)) {
1099 return;
1100 }
1101 x86_mwait(0, 0);
1102 }
1103
1104 void
1105 x86_cpu_idle_halt(void)
1106 {
1107 struct cpu_info *ci = curcpu();
1108
1109 KASSERT(ci->ci_ilevel == IPL_NONE);
1110
1111 x86_disable_intr();
1112 if (!__predict_false(ci->ci_want_resched)) {
1113 x86_stihlt();
1114 } else {
1115 x86_enable_intr();
1116 }
1117 }
1118