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