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