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