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