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