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