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