2 * Copyright (c) 1996, by Steve Passe
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. The name of the developer may NOT be used to endorse or promote products
11 * derived from this software without specific prior written permission.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
31 #include "opt_kstack_pages.h"
33 #include "opt_sched.h"
38 #error How did you get here?
42 #error The apic device is required for SMP, add "device apic" to your config file.
44 #if defined(CPU_DISABLE_CMPXCHG) && !defined(COMPILING_LINT)
45 #error SMP not supported with CPU_DISABLE_CMPXCHG
49 #include <sys/param.h>
50 #include <sys/systm.h>
52 #include <sys/cons.h> /* cngetc() */
53 #include <sys/cpuset.h>
57 #include <sys/kernel.h>
60 #include <sys/malloc.h>
61 #include <sys/memrange.h>
62 #include <sys/mutex.h>
65 #include <sys/sched.h>
67 #include <sys/sysctl.h>
70 #include <vm/vm_param.h>
72 #include <vm/vm_kern.h>
73 #include <vm/vm_extern.h>
75 #include <x86/apicreg.h>
76 #include <machine/clock.h>
77 #include <machine/cputypes.h>
79 #include <machine/md_var.h>
80 #include <machine/pcb.h>
81 #include <machine/psl.h>
82 #include <machine/smp.h>
83 #include <machine/specialreg.h>
84 #include <machine/cpu.h>
86 #define WARMBOOT_TARGET 0
87 #define WARMBOOT_OFF (KERNBASE + 0x0467)
88 #define WARMBOOT_SEG (KERNBASE + 0x0469)
90 #define CMOS_REG (0x70)
91 #define CMOS_DATA (0x71)
92 #define BIOS_RESET (0x0f)
93 #define BIOS_WARM (0x0a)
96 * this code MUST be enabled here and in mpboot.s.
97 * it follows the very early stages of AP boot by placing values in CMOS ram.
98 * it NORMALLY will never be needed and thus the primitive method for enabling.
103 #if defined(CHECK_POINTS) && !defined(PC98)
104 #define CHECK_READ(A) (outb(CMOS_REG, (A)), inb(CMOS_DATA))
105 #define CHECK_WRITE(A,D) (outb(CMOS_REG, (A)), outb(CMOS_DATA, (D)))
107 #define CHECK_INIT(D); \
108 CHECK_WRITE(0x34, (D)); \
109 CHECK_WRITE(0x35, (D)); \
110 CHECK_WRITE(0x36, (D)); \
111 CHECK_WRITE(0x37, (D)); \
112 CHECK_WRITE(0x38, (D)); \
113 CHECK_WRITE(0x39, (D));
115 #define CHECK_PRINT(S); \
116 printf("%s: %d, %d, %d, %d, %d, %d\n", \
125 #else /* CHECK_POINTS */
127 #define CHECK_INIT(D)
128 #define CHECK_PRINT(S)
129 #define CHECK_WRITE(A, D)
131 #endif /* CHECK_POINTS */
133 /* lock region used by kernel profiling */
136 int mp_naps; /* # of Applications processors */
137 int boot_cpu_id = -1; /* designated BSP */
139 extern struct pcpu __pcpu[];
141 /* AP uses this during bootstrap. Do not staticize. */
145 /* Free these after use */
146 void *bootstacks[MAXCPU];
149 struct pcb stoppcbs[MAXCPU];
150 struct susppcb **susppcbs;
152 /* Variables needed for SMP tlb shootdown. */
153 vm_offset_t smp_tlb_addr1;
154 vm_offset_t smp_tlb_addr2;
155 volatile int smp_tlb_wait;
158 /* Interrupt counts. */
159 static u_long *ipi_preempt_counts[MAXCPU];
160 static u_long *ipi_ast_counts[MAXCPU];
161 u_long *ipi_invltlb_counts[MAXCPU];
162 u_long *ipi_invlrng_counts[MAXCPU];
163 u_long *ipi_invlpg_counts[MAXCPU];
164 u_long *ipi_invlcache_counts[MAXCPU];
165 u_long *ipi_rendezvous_counts[MAXCPU];
166 u_long *ipi_lazypmap_counts[MAXCPU];
167 static u_long *ipi_hardclock_counts[MAXCPU];
170 /* Default cpu_ops implementation. */
171 struct cpu_ops cpu_ops;
174 * Local data and functions.
177 static volatile cpuset_t ipi_nmi_pending;
179 /* used to hold the AP's until we are ready to release them */
180 static struct mtx ap_boot_mtx;
182 /* Set to 1 once we're ready to let the APs out of the pen. */
183 static volatile int aps_ready = 0;
186 * Store data from cpu_add() until later in the boot when we actually setup
193 int cpu_hyperthread:1;
194 } static cpu_info[MAX_APIC_ID + 1];
195 int cpu_apic_ids[MAXCPU];
196 int apic_cpuids[MAX_APIC_ID + 1];
198 /* Holds pending bitmap based IPIs per CPU */
199 volatile u_int cpu_ipi_pending[MAXCPU];
201 static u_int boot_address;
202 static int cpu_logical; /* logical cpus per core */
203 static int cpu_cores; /* cores per package */
205 static void assign_cpu_ids(void);
206 static void install_ap_tramp(void);
207 static void set_interrupt_apic_ids(void);
208 static int start_all_aps(void);
209 static int start_ap(int apic_id);
210 static void release_aps(void *dummy);
212 static u_int hyperthreading_cpus; /* logical cpus sharing L1 cache */
213 static int hyperthreading_allowed = 1;
216 mem_range_AP_init(void)
218 if (mem_range_softc.mr_op && mem_range_softc.mr_op->initAP)
219 mem_range_softc.mr_op->initAP(&mem_range_softc);
228 /* AMD processors do not support HTT. */
231 if ((amd_feature2 & AMDID2_CMP) == 0) {
236 core_id_bits = (cpu_procinfo2 & AMDID_COREID_SIZE) >>
237 AMDID_COREID_SIZE_SHIFT;
238 if (core_id_bits == 0) {
239 cpu_cores = (cpu_procinfo2 & AMDID_CMP_CORES) + 1;
243 /* Fam 10h and newer should get here. */
244 for (id = 0; id <= MAX_APIC_ID; id++) {
245 /* Check logical CPU availability. */
246 if (!cpu_info[id].cpu_present || cpu_info[id].cpu_disabled)
248 /* Check if logical CPU has the same package ID. */
249 if ((id >> core_id_bits) != (boot_cpu_id >> core_id_bits))
256 * Round up to the next power of two, if necessary, and then
258 * Returns -1 if argument is zero.
264 return (fls(x << (1 - powerof2(x))) - 1);
277 /* Both zero and one here mean one logical processor per package. */
278 max_logical = (cpu_feature & CPUID_HTT) != 0 ?
279 (cpu_procinfo & CPUID_HTT_CORES) >> 16 : 1;
280 if (max_logical <= 1)
284 * Because of uniformity assumption we examine only
285 * those logical processors that belong to the same
286 * package as BSP. Further, we count number of
287 * logical processors that belong to the same core
288 * as BSP thus deducing number of threads per core.
290 if (cpu_high >= 0x4) {
291 cpuid_count(0x04, 0, p);
292 max_cores = ((p[0] >> 26) & 0x3f) + 1;
295 core_id_bits = mask_width(max_logical/max_cores);
296 if (core_id_bits < 0)
298 pkg_id_bits = core_id_bits + mask_width(max_cores);
300 for (id = 0; id <= MAX_APIC_ID; id++) {
301 /* Check logical CPU availability. */
302 if (!cpu_info[id].cpu_present || cpu_info[id].cpu_disabled)
304 /* Check if logical CPU has the same package ID. */
305 if ((id >> pkg_id_bits) != (boot_cpu_id >> pkg_id_bits))
308 /* Check if logical CPU has the same package and core IDs. */
309 if ((id >> core_id_bits) == (boot_cpu_id >> core_id_bits))
313 KASSERT(cpu_cores >= 1 && cpu_logical >= 1,
314 ("topo_probe_0x4 couldn't find BSP"));
316 cpu_cores /= cpu_logical;
317 hyperthreading_cpus = cpu_logical;
331 /* We only support three levels for now. */
332 for (i = 0; i < 3; i++) {
333 cpuid_count(0x0b, i, p);
335 /* Fall back if CPU leaf 11 doesn't really exist. */
336 if (i == 0 && p[1] == 0) {
342 logical = p[1] &= 0xffff;
343 type = (p[2] >> 8) & 0xff;
344 if (type == 0 || logical == 0)
347 * Because of uniformity assumption we examine only
348 * those logical processors that belong to the same
351 for (cnt = 0, x = 0; x <= MAX_APIC_ID; x++) {
352 if (!cpu_info[x].cpu_present ||
353 cpu_info[x].cpu_disabled)
355 if (x >> bits == boot_cpu_id >> bits)
358 if (type == CPUID_TYPE_SMT)
360 else if (type == CPUID_TYPE_CORE)
363 if (cpu_logical == 0)
365 cpu_cores /= cpu_logical;
369 * Both topology discovery code and code that consumes topology
370 * information assume top-down uniformity of the topology.
371 * That is, all physical packages must be identical and each
372 * core in a package must have the same number of threads.
373 * Topology information is queried only on BSP, on which this
374 * code runs and for which it can query CPUID information.
375 * Then topology is extrapolated on all packages using the
376 * uniformity assumption.
381 static int cpu_topo_probed = 0;
386 CPU_ZERO(&logical_cpus_mask);
388 cpu_cores = cpu_logical = 1;
389 else if (cpu_vendor_id == CPU_VENDOR_AMD)
391 else if (cpu_vendor_id == CPU_VENDOR_INTEL) {
393 * See Intel(R) 64 Architecture Processor
394 * Topology Enumeration article for details.
396 * Note that 0x1 <= cpu_high < 4 case should be
397 * compatible with topo_probe_0x4() logic when
398 * CPUID.1:EBX[23:16] > 0 (cpu_cores will be 1)
399 * or it should trigger the fallback otherwise.
403 else if (cpu_high >= 0x1)
408 * Fallback: assume each logical CPU is in separate
409 * physical package. That is, no multi-core, no SMT.
411 if (cpu_cores == 0 || cpu_logical == 0)
412 cpu_cores = cpu_logical = 1;
422 * Determine whether any threading flags are
426 if (cpu_logical > 1 && hyperthreading_cpus)
427 cg_flags = CG_FLAG_HTT;
428 else if (cpu_logical > 1)
429 cg_flags = CG_FLAG_SMT;
432 if (mp_ncpus % (cpu_cores * cpu_logical) != 0) {
433 printf("WARNING: Non-uniform processors.\n");
434 printf("WARNING: Using suboptimal topology.\n");
435 return (smp_topo_none());
438 * No multi-core or hyper-threaded.
440 if (cpu_logical * cpu_cores == 1)
441 return (smp_topo_none());
443 * Only HTT no multi-core.
445 if (cpu_logical > 1 && cpu_cores == 1)
446 return (smp_topo_1level(CG_SHARE_L1, cpu_logical, cg_flags));
448 * Only multi-core no HTT.
450 if (cpu_cores > 1 && cpu_logical == 1)
451 return (smp_topo_1level(CG_SHARE_L2, cpu_cores, cg_flags));
453 * Both HTT and multi-core.
455 return (smp_topo_2level(CG_SHARE_L2, cpu_cores,
456 CG_SHARE_L1, cpu_logical, cg_flags));
461 * Calculate usable address in base memory for AP trampoline code.
464 mp_bootaddress(u_int basemem)
467 boot_address = trunc_page(basemem); /* round down to 4k boundary */
468 if ((basemem - boot_address) < bootMP_size)
469 boot_address -= PAGE_SIZE; /* not enough, lower by 4k */
475 cpu_add(u_int apic_id, char boot_cpu)
478 if (apic_id > MAX_APIC_ID) {
479 panic("SMP: APIC ID %d too high", apic_id);
482 KASSERT(cpu_info[apic_id].cpu_present == 0, ("CPU %d added twice",
484 cpu_info[apic_id].cpu_present = 1;
486 KASSERT(boot_cpu_id == -1,
487 ("CPU %d claims to be BSP, but CPU %d already is", apic_id,
489 boot_cpu_id = apic_id;
490 cpu_info[apic_id].cpu_bsp = 1;
492 if (mp_ncpus < MAXCPU) {
494 mp_maxid = mp_ncpus - 1;
497 printf("SMP: Added CPU %d (%s)\n", apic_id, boot_cpu ? "BSP" :
502 cpu_mp_setmaxid(void)
506 * mp_maxid should be already set by calls to cpu_add().
507 * Just sanity check its value here.
510 KASSERT(mp_maxid == 0,
511 ("%s: mp_ncpus is zero, but mp_maxid is not", __func__));
512 else if (mp_ncpus == 1)
515 KASSERT(mp_maxid >= mp_ncpus - 1,
516 ("%s: counters out of sync: max %d, count %d", __func__,
517 mp_maxid, mp_ncpus));
525 * Always record BSP in CPU map so that the mbuf init code works
528 CPU_SETOF(0, &all_cpus);
531 * No CPUs were found, so this must be a UP system. Setup
532 * the variables to represent a system with a single CPU
539 /* At least one CPU was found. */
542 * One CPU was found, so this must be a UP system with
549 /* At least two CPUs were found. */
554 * Initialize the IPI handlers and start up the AP's.
561 /* Initialize the logical ID to APIC ID table. */
562 for (i = 0; i < MAXCPU; i++) {
563 cpu_apic_ids[i] = -1;
564 cpu_ipi_pending[i] = 0;
567 /* Install an inter-CPU IPI for TLB invalidation */
568 setidt(IPI_INVLTLB, IDTVEC(invltlb),
569 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
570 setidt(IPI_INVLPG, IDTVEC(invlpg),
571 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
572 setidt(IPI_INVLRNG, IDTVEC(invlrng),
573 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
575 /* Install an inter-CPU IPI for cache invalidation. */
576 setidt(IPI_INVLCACHE, IDTVEC(invlcache),
577 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
579 /* Install an inter-CPU IPI for lazy pmap release */
580 setidt(IPI_LAZYPMAP, IDTVEC(lazypmap),
581 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
583 /* Install an inter-CPU IPI for all-CPU rendezvous */
584 setidt(IPI_RENDEZVOUS, IDTVEC(rendezvous),
585 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
587 /* Install generic inter-CPU IPI handler */
588 setidt(IPI_BITMAP_VECTOR, IDTVEC(ipi_intr_bitmap_handler),
589 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
591 /* Install an inter-CPU IPI for CPU stop/restart */
592 setidt(IPI_STOP, IDTVEC(cpustop),
593 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
595 /* Install an inter-CPU IPI for CPU suspend/resume */
596 setidt(IPI_SUSPEND, IDTVEC(cpususpend),
597 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
599 /* Set boot_cpu_id if needed. */
600 if (boot_cpu_id == -1) {
601 boot_cpu_id = PCPU_GET(apic_id);
602 cpu_info[boot_cpu_id].cpu_bsp = 1;
604 KASSERT(boot_cpu_id == PCPU_GET(apic_id),
605 ("BSP's APIC ID doesn't match boot_cpu_id"));
607 /* Probe logical/physical core configuration. */
612 /* Start each Application Processor */
615 set_interrupt_apic_ids();
620 * Print various information about the SMP system hardware and setup.
623 cpu_mp_announce(void)
625 const char *hyperthread;
628 printf("FreeBSD/SMP: %d package(s) x %d core(s)",
629 mp_ncpus / (cpu_cores * cpu_logical), cpu_cores);
630 if (hyperthreading_cpus > 1)
631 printf(" x %d HTT threads", cpu_logical);
632 else if (cpu_logical > 1)
633 printf(" x %d SMT threads", cpu_logical);
636 /* List active CPUs first. */
637 printf(" cpu0 (BSP): APIC ID: %2d\n", boot_cpu_id);
638 for (i = 1; i < mp_ncpus; i++) {
639 if (cpu_info[cpu_apic_ids[i]].cpu_hyperthread)
643 printf(" cpu%d (AP%s): APIC ID: %2d\n", i, hyperthread,
647 /* List disabled CPUs last. */
648 for (i = 0; i <= MAX_APIC_ID; i++) {
649 if (!cpu_info[i].cpu_present || !cpu_info[i].cpu_disabled)
651 if (cpu_info[i].cpu_hyperthread)
655 printf(" cpu (AP%s): APIC ID: %2d (disabled)\n", hyperthread,
661 * AP CPU's call this to initialize themselves.
672 /* bootAP is set in start_ap() to our ID. */
675 /* Get per-cpu data */
678 /* prime data page for it to use */
679 pcpu_init(pc, myid, sizeof(struct pcpu));
680 dpcpu_init(dpcpu, myid);
681 pc->pc_apic_id = cpu_apic_ids[myid];
682 pc->pc_prvspace = pc;
683 pc->pc_curthread = 0;
685 gdt_segs[GPRIV_SEL].ssd_base = (int) pc;
686 gdt_segs[GPROC0_SEL].ssd_base = (int) &pc->pc_common_tss;
688 for (x = 0; x < NGDT; x++) {
689 ssdtosd(&gdt_segs[x], &gdt[myid * NGDT + x].sd);
692 r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
693 r_gdt.rd_base = (int) &gdt[myid * NGDT];
694 lgdt(&r_gdt); /* does magic intra-segment return */
699 PCPU_SET(currentldt, _default_ldt);
701 gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
702 gdt[myid * NGDT + GPROC0_SEL].sd.sd_type = SDT_SYS386TSS;
703 PCPU_SET(common_tss.tss_esp0, 0); /* not used until after switch */
704 PCPU_SET(common_tss.tss_ss0, GSEL(GDATA_SEL, SEL_KPL));
705 PCPU_SET(common_tss.tss_ioopt, (sizeof (struct i386tss)) << 16);
706 PCPU_SET(tss_gdt, &gdt[myid * NGDT + GPROC0_SEL].sd);
707 PCPU_SET(common_tssd, *PCPU_GET(tss_gdt));
710 PCPU_SET(fsgs_gdt, &gdt[myid * NGDT + GUFS_SEL].sd);
713 * Set to a known state:
714 * Set by mpboot.s: CR0_PG, CR0_PE
715 * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
718 cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
720 CHECK_WRITE(0x38, 5);
722 /* Disable local APIC just to be sure. */
725 /* signal our startup to the BSP. */
727 CHECK_WRITE(0x39, 6);
729 /* Spin until the BSP releases the AP's. */
733 /* BSP may have changed PTD while we were waiting */
735 for (addr = 0; addr < NKPT * NBPDR - 1; addr += PAGE_SIZE)
738 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
742 /* Initialize the PAT MSR if present. */
745 /* set up CPU registers and state */
751 /* set up FPU state on the AP */
754 if (cpu_ops.cpu_init)
757 /* A quick check from sanity claus */
758 cpuid = PCPU_GET(cpuid);
759 if (PCPU_GET(apic_id) != lapic_id()) {
760 printf("SMP: cpuid = %d\n", cpuid);
761 printf("SMP: actual apic_id = %d\n", lapic_id());
762 printf("SMP: correct apic_id = %d\n", PCPU_GET(apic_id));
763 panic("cpuid mismatch! boom!!");
766 /* Initialize curthread. */
767 KASSERT(PCPU_GET(idlethread) != NULL, ("no idle thread"));
768 PCPU_SET(curthread, PCPU_GET(idlethread));
772 mtx_lock_spin(&ap_boot_mtx);
774 /* Init local apic for irq's */
777 /* Set memory range attributes for this CPU to match the BSP */
782 CTR1(KTR_SMP, "SMP: AP CPU #%d Launched", cpuid);
783 printf("SMP: AP CPU #%d Launched!\n", cpuid);
785 /* Determine if we are a logical CPU. */
786 /* XXX Calculation depends on cpu_logical being a power of 2, e.g. 2 */
787 if (cpu_logical > 1 && PCPU_GET(apic_id) % cpu_logical != 0)
788 CPU_SET(cpuid, &logical_cpus_mask);
793 if (smp_cpus == mp_ncpus) {
794 /* enable IPI's, tlb shootdown, freezes etc */
795 atomic_store_rel_int(&smp_started, 1);
798 mtx_unlock_spin(&ap_boot_mtx);
800 /* Wait until all the AP's are up. */
801 while (smp_started == 0)
804 /* Start per-CPU event timers. */
807 /* Enter the scheduler. */
810 panic("scheduler returned us to %s", __func__);
814 /*******************************************************************
815 * local functions and data
819 * We tell the I/O APIC code about all the CPUs we want to receive
820 * interrupts. If we don't want certain CPUs to receive IRQs we
821 * can simply not tell the I/O APIC code about them in this function.
822 * We also do not tell it about the BSP since it tells itself about
823 * the BSP internally to work with UP kernels and on UP machines.
826 set_interrupt_apic_ids(void)
830 for (i = 0; i < MAXCPU; i++) {
831 apic_id = cpu_apic_ids[i];
834 if (cpu_info[apic_id].cpu_bsp)
836 if (cpu_info[apic_id].cpu_disabled)
839 /* Don't let hyperthreads service interrupts. */
840 if (hyperthreading_cpus > 1 &&
841 apic_id % hyperthreading_cpus != 0)
849 * Assign logical CPU IDs to local APICs.
856 TUNABLE_INT_FETCH("machdep.hyperthreading_allowed",
857 &hyperthreading_allowed);
859 /* Check for explicitly disabled CPUs. */
860 for (i = 0; i <= MAX_APIC_ID; i++) {
861 if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp)
864 if (hyperthreading_cpus > 1 && i % hyperthreading_cpus != 0) {
865 cpu_info[i].cpu_hyperthread = 1;
868 * Don't use HT CPU if it has been disabled by a
871 if (hyperthreading_allowed == 0) {
872 cpu_info[i].cpu_disabled = 1;
877 /* Don't use this CPU if it has been disabled by a tunable. */
878 if (resource_disabled("lapic", i)) {
879 cpu_info[i].cpu_disabled = 1;
884 if (hyperthreading_allowed == 0 && hyperthreading_cpus > 1) {
885 hyperthreading_cpus = 0;
890 * Assign CPU IDs to local APIC IDs and disable any CPUs
891 * beyond MAXCPU. CPU 0 is always assigned to the BSP.
893 * To minimize confusion for userland, we attempt to number
894 * CPUs such that all threads and cores in a package are
895 * grouped together. For now we assume that the BSP is always
896 * the first thread in a package and just start adding APs
897 * starting with the BSP's APIC ID.
900 cpu_apic_ids[0] = boot_cpu_id;
901 apic_cpuids[boot_cpu_id] = 0;
902 for (i = boot_cpu_id + 1; i != boot_cpu_id;
903 i == MAX_APIC_ID ? i = 0 : i++) {
904 if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp ||
905 cpu_info[i].cpu_disabled)
908 if (mp_ncpus < MAXCPU) {
909 cpu_apic_ids[mp_ncpus] = i;
910 apic_cpuids[i] = mp_ncpus;
913 cpu_info[i].cpu_disabled = 1;
915 KASSERT(mp_maxid >= mp_ncpus - 1,
916 ("%s: counters out of sync: max %d, count %d", __func__, mp_maxid,
921 * start each AP in our list
923 /* Lowest 1MB is already mapped: don't touch*/
924 #define TMPMAP_START 1
931 u_int32_t mpbioswarmvec;
934 mtx_init(&ap_boot_mtx, "ap boot", NULL, MTX_SPIN);
936 /* install the AP 1st level boot code */
939 /* save the current value of the warm-start vector */
940 mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
942 outb(CMOS_REG, BIOS_RESET);
943 mpbiosreason = inb(CMOS_DATA);
946 /* set up temporary P==V mapping for AP boot */
947 /* XXX this is a hack, we should boot the AP on its own stack/PTD */
948 for (i = TMPMAP_START; i < NKPT; i++)
949 PTD[i] = PTD[KPTDI + i];
953 for (cpu = 1; cpu < mp_ncpus; cpu++) {
954 apic_id = cpu_apic_ids[cpu];
956 /* allocate and set up a boot stack data page */
958 (char *)kmem_malloc(kernel_arena, KSTACK_PAGES * PAGE_SIZE,
960 dpcpu = (void *)kmem_malloc(kernel_arena, DPCPU_SIZE,
962 /* setup a vector to our boot code */
963 *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
964 *((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
966 outb(CMOS_REG, BIOS_RESET);
967 outb(CMOS_DATA, BIOS_WARM); /* 'warm-start' */
970 bootSTK = (char *)bootstacks[cpu] + KSTACK_PAGES * PAGE_SIZE - 4;
973 /* attempt to start the Application Processor */
974 CHECK_INIT(99); /* setup checkpoints */
975 if (!start_ap(apic_id)) {
976 printf("AP #%d (PHY# %d) failed!\n", cpu, apic_id);
977 CHECK_PRINT("trace"); /* show checkpoints */
978 /* better panic as the AP may be running loose */
979 printf("panic y/n? [y] ");
983 CHECK_PRINT("trace"); /* show checkpoints */
985 CPU_SET(cpu, &all_cpus); /* record AP in CPU map */
988 /* restore the warmstart vector */
989 *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
992 outb(CMOS_REG, BIOS_RESET);
993 outb(CMOS_DATA, mpbiosreason);
996 /* Undo V==P hack from above */
997 for (i = TMPMAP_START; i < NKPT; i++)
999 pmap_invalidate_range(kernel_pmap, 0, NKPT * NBPDR - 1);
1001 /* number of APs actually started */
1006 * load the 1st level AP boot code into base memory.
1009 /* targets for relocation */
1010 extern void bigJump(void);
1011 extern void bootCodeSeg(void);
1012 extern void bootDataSeg(void);
1013 extern void MPentry(void);
1014 extern u_int MP_GDT;
1015 extern u_int mp_gdtbase;
1018 install_ap_tramp(void)
1021 int size = *(int *) ((u_long) & bootMP_size);
1022 vm_offset_t va = boot_address + KERNBASE;
1023 u_char *src = (u_char *) ((u_long) bootMP);
1024 u_char *dst = (u_char *) va;
1025 u_int boot_base = (u_int) bootMP;
1030 KASSERT (size <= PAGE_SIZE,
1031 ("'size' do not fit into PAGE_SIZE, as expected."));
1032 pmap_kenter(va, boot_address);
1033 pmap_invalidate_page (kernel_pmap, va);
1034 for (x = 0; x < size; ++x)
1038 * modify addresses in code we just moved to basemem. unfortunately we
1039 * need fairly detailed info about mpboot.s for this to work. changes
1040 * to mpboot.s might require changes here.
1043 /* boot code is located in KERNEL space */
1044 dst = (u_char *) va;
1046 /* modify the lgdt arg */
1047 dst32 = (u_int32_t *) (dst + ((u_int) & mp_gdtbase - boot_base));
1048 *dst32 = boot_address + ((u_int) & MP_GDT - boot_base);
1050 /* modify the ljmp target for MPentry() */
1051 dst32 = (u_int32_t *) (dst + ((u_int) bigJump - boot_base) + 1);
1052 *dst32 = ((u_int) MPentry - KERNBASE);
1054 /* modify the target for boot code segment */
1055 dst16 = (u_int16_t *) (dst + ((u_int) bootCodeSeg - boot_base));
1056 dst8 = (u_int8_t *) (dst16 + 1);
1057 *dst16 = (u_int) boot_address & 0xffff;
1058 *dst8 = ((u_int) boot_address >> 16) & 0xff;
1060 /* modify the target for boot data segment */
1061 dst16 = (u_int16_t *) (dst + ((u_int) bootDataSeg - boot_base));
1062 dst8 = (u_int8_t *) (dst16 + 1);
1063 *dst16 = (u_int) boot_address & 0xffff;
1064 *dst8 = ((u_int) boot_address >> 16) & 0xff;
1068 * This function starts the AP (application processor) identified
1069 * by the APIC ID 'physicalCpu'. It does quite a "song and dance"
1070 * to accomplish this. This is necessary because of the nuances
1071 * of the different hardware we might encounter. It isn't pretty,
1072 * but it seems to work.
1075 start_ap(int apic_id)
1080 /* calculate the vector */
1081 vector = (boot_address >> 12) & 0xff;
1083 /* used as a watchpoint to signal AP startup */
1086 ipi_startup(apic_id, vector);
1088 /* Wait up to 5 seconds for it to start. */
1089 for (ms = 0; ms < 5000; ms++) {
1091 return 1; /* return SUCCESS */
1094 return 0; /* return FAILURE */
1097 #ifdef COUNT_XINVLTLB_HITS
1098 u_int xhits_gbl[MAXCPU];
1099 u_int xhits_pg[MAXCPU];
1100 u_int xhits_rng[MAXCPU];
1101 static SYSCTL_NODE(_debug, OID_AUTO, xhits, CTLFLAG_RW, 0, "");
1102 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, global, CTLFLAG_RW, &xhits_gbl,
1103 sizeof(xhits_gbl), "IU", "");
1104 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, page, CTLFLAG_RW, &xhits_pg,
1105 sizeof(xhits_pg), "IU", "");
1106 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, range, CTLFLAG_RW, &xhits_rng,
1107 sizeof(xhits_rng), "IU", "");
1112 u_int ipi_range_size;
1113 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_global, CTLFLAG_RW, &ipi_global, 0, "");
1114 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_page, CTLFLAG_RW, &ipi_page, 0, "");
1115 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range, CTLFLAG_RW, &ipi_range, 0, "");
1116 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range_size, CTLFLAG_RW, &ipi_range_size,
1119 u_int ipi_masked_global;
1120 u_int ipi_masked_page;
1121 u_int ipi_masked_range;
1122 u_int ipi_masked_range_size;
1123 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_global, CTLFLAG_RW,
1124 &ipi_masked_global, 0, "");
1125 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_page, CTLFLAG_RW,
1126 &ipi_masked_page, 0, "");
1127 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_range, CTLFLAG_RW,
1128 &ipi_masked_range, 0, "");
1129 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_range_size, CTLFLAG_RW,
1130 &ipi_masked_range_size, 0, "");
1131 #endif /* COUNT_XINVLTLB_HITS */
1134 * Init and startup IPI.
1137 ipi_startup(int apic_id, int vector)
1141 * first we do an INIT IPI: this INIT IPI might be run, resetting
1142 * and running the target CPU. OR this INIT IPI might be latched (P5
1143 * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
1146 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1147 APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, apic_id);
1149 DELAY(10000); /* wait ~10mS */
1152 * next we do a STARTUP IPI: the previous INIT IPI might still be
1153 * latched, (P5 bug) this 1st STARTUP would then terminate
1154 * immediately, and the previously started INIT IPI would continue. OR
1155 * the previous INIT IPI has already run. and this STARTUP IPI will
1156 * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
1159 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1160 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1163 DELAY(200); /* wait ~200uS */
1166 * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
1167 * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
1168 * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
1169 * recognized after hardware RESET or INIT IPI.
1171 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1172 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1175 DELAY(200); /* wait ~200uS */
1179 * Send an IPI to specified CPU handling the bitmap logic.
1182 ipi_send_cpu(int cpu, u_int ipi)
1184 u_int bitmap, old_pending, new_pending;
1186 KASSERT(cpu_apic_ids[cpu] != -1, ("IPI to non-existent CPU %d", cpu));
1188 if (IPI_IS_BITMAPED(ipi)) {
1190 ipi = IPI_BITMAP_VECTOR;
1192 old_pending = cpu_ipi_pending[cpu];
1193 new_pending = old_pending | bitmap;
1194 } while (!atomic_cmpset_int(&cpu_ipi_pending[cpu],
1195 old_pending, new_pending));
1199 lapic_ipi_vectored(ipi, cpu_apic_ids[cpu]);
1203 * Flush the TLB on all other CPU's
1206 smp_tlb_shootdown(u_int vector, vm_offset_t addr1, vm_offset_t addr2)
1210 ncpu = mp_ncpus - 1; /* does not shootdown self */
1212 return; /* no other cpus */
1213 if (!(read_eflags() & PSL_I))
1214 panic("%s: interrupts disabled", __func__);
1215 mtx_lock_spin(&smp_ipi_mtx);
1216 smp_tlb_addr1 = addr1;
1217 smp_tlb_addr2 = addr2;
1218 atomic_store_rel_int(&smp_tlb_wait, 0);
1219 ipi_all_but_self(vector);
1220 while (smp_tlb_wait < ncpu)
1222 mtx_unlock_spin(&smp_ipi_mtx);
1226 smp_targeted_tlb_shootdown(cpuset_t mask, u_int vector, vm_offset_t addr1, vm_offset_t addr2)
1228 int cpu, ncpu, othercpus;
1230 othercpus = mp_ncpus - 1;
1231 if (CPU_ISFULLSET(&mask)) {
1235 CPU_CLR(PCPU_GET(cpuid), &mask);
1236 if (CPU_EMPTY(&mask))
1239 if (!(read_eflags() & PSL_I))
1240 panic("%s: interrupts disabled", __func__);
1241 mtx_lock_spin(&smp_ipi_mtx);
1242 smp_tlb_addr1 = addr1;
1243 smp_tlb_addr2 = addr2;
1244 atomic_store_rel_int(&smp_tlb_wait, 0);
1245 if (CPU_ISFULLSET(&mask)) {
1247 ipi_all_but_self(vector);
1250 while ((cpu = CPU_FFS(&mask)) != 0) {
1252 CPU_CLR(cpu, &mask);
1253 CTR3(KTR_SMP, "%s: cpu: %d ipi: %x", __func__, cpu,
1255 ipi_send_cpu(cpu, vector);
1259 while (smp_tlb_wait < ncpu)
1261 mtx_unlock_spin(&smp_ipi_mtx);
1265 smp_cache_flush(void)
1269 smp_tlb_shootdown(IPI_INVLCACHE, 0, 0);
1277 smp_tlb_shootdown(IPI_INVLTLB, 0, 0);
1278 #ifdef COUNT_XINVLTLB_HITS
1285 smp_invlpg(vm_offset_t addr)
1289 smp_tlb_shootdown(IPI_INVLPG, addr, 0);
1290 #ifdef COUNT_XINVLTLB_HITS
1297 smp_invlpg_range(vm_offset_t addr1, vm_offset_t addr2)
1301 smp_tlb_shootdown(IPI_INVLRNG, addr1, addr2);
1302 #ifdef COUNT_XINVLTLB_HITS
1304 ipi_range_size += (addr2 - addr1) / PAGE_SIZE;
1310 smp_masked_invltlb(cpuset_t mask)
1314 smp_targeted_tlb_shootdown(mask, IPI_INVLTLB, 0, 0);
1315 #ifdef COUNT_XINVLTLB_HITS
1316 ipi_masked_global++;
1322 smp_masked_invlpg(cpuset_t mask, vm_offset_t addr)
1326 smp_targeted_tlb_shootdown(mask, IPI_INVLPG, addr, 0);
1327 #ifdef COUNT_XINVLTLB_HITS
1334 smp_masked_invlpg_range(cpuset_t mask, vm_offset_t addr1, vm_offset_t addr2)
1338 smp_targeted_tlb_shootdown(mask, IPI_INVLRNG, addr1, addr2);
1339 #ifdef COUNT_XINVLTLB_HITS
1341 ipi_masked_range_size += (addr2 - addr1) / PAGE_SIZE;
1347 ipi_bitmap_handler(struct trapframe frame)
1349 struct trapframe *oldframe;
1351 int cpu = PCPU_GET(cpuid);
1356 td->td_intr_nesting_level++;
1357 oldframe = td->td_intr_frame;
1358 td->td_intr_frame = &frame;
1359 ipi_bitmap = atomic_readandclear_int(&cpu_ipi_pending[cpu]);
1360 if (ipi_bitmap & (1 << IPI_PREEMPT)) {
1362 (*ipi_preempt_counts[cpu])++;
1366 if (ipi_bitmap & (1 << IPI_AST)) {
1368 (*ipi_ast_counts[cpu])++;
1370 /* Nothing to do for AST */
1372 if (ipi_bitmap & (1 << IPI_HARDCLOCK)) {
1374 (*ipi_hardclock_counts[cpu])++;
1378 td->td_intr_frame = oldframe;
1379 td->td_intr_nesting_level--;
1384 * send an IPI to a set of cpus.
1387 ipi_selected(cpuset_t cpus, u_int ipi)
1392 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1393 * of help in order to understand what is the source.
1394 * Set the mask of receiving CPUs for this purpose.
1396 if (ipi == IPI_STOP_HARD)
1397 CPU_OR_ATOMIC(&ipi_nmi_pending, &cpus);
1399 while ((cpu = CPU_FFS(&cpus)) != 0) {
1401 CPU_CLR(cpu, &cpus);
1402 CTR3(KTR_SMP, "%s: cpu: %d ipi: %x", __func__, cpu, ipi);
1403 ipi_send_cpu(cpu, ipi);
1408 * send an IPI to a specific CPU.
1411 ipi_cpu(int cpu, u_int ipi)
1415 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1416 * of help in order to understand what is the source.
1417 * Set the mask of receiving CPUs for this purpose.
1419 if (ipi == IPI_STOP_HARD)
1420 CPU_SET_ATOMIC(cpu, &ipi_nmi_pending);
1422 CTR3(KTR_SMP, "%s: cpu: %d ipi: %x", __func__, cpu, ipi);
1423 ipi_send_cpu(cpu, ipi);
1427 * send an IPI to all CPUs EXCEPT myself
1430 ipi_all_but_self(u_int ipi)
1432 cpuset_t other_cpus;
1434 other_cpus = all_cpus;
1435 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
1436 if (IPI_IS_BITMAPED(ipi)) {
1437 ipi_selected(other_cpus, ipi);
1442 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1443 * of help in order to understand what is the source.
1444 * Set the mask of receiving CPUs for this purpose.
1446 if (ipi == IPI_STOP_HARD)
1447 CPU_OR_ATOMIC(&ipi_nmi_pending, &other_cpus);
1449 CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1450 lapic_ipi_vectored(ipi, APIC_IPI_DEST_OTHERS);
1459 * As long as there is not a simple way to know about a NMI's
1460 * source, if the bitmask for the current CPU is present in
1461 * the global pending bitword an IPI_STOP_HARD has been issued
1462 * and should be handled.
1464 cpuid = PCPU_GET(cpuid);
1465 if (!CPU_ISSET(cpuid, &ipi_nmi_pending))
1468 CPU_CLR_ATOMIC(cpuid, &ipi_nmi_pending);
1474 * Handle an IPI_STOP by saving our current context and spinning until we
1478 cpustop_handler(void)
1482 cpu = PCPU_GET(cpuid);
1484 savectx(&stoppcbs[cpu]);
1486 /* Indicate that we are stopped */
1487 CPU_SET_ATOMIC(cpu, &stopped_cpus);
1489 /* Wait for restart */
1490 while (!CPU_ISSET(cpu, &started_cpus))
1493 CPU_CLR_ATOMIC(cpu, &started_cpus);
1494 CPU_CLR_ATOMIC(cpu, &stopped_cpus);
1496 if (cpu == 0 && cpustop_restartfunc != NULL) {
1497 cpustop_restartfunc();
1498 cpustop_restartfunc = NULL;
1503 * Handle an IPI_SUSPEND by saving our current context and spinning until we
1507 cpususpend_handler(void)
1511 mtx_assert(&smp_ipi_mtx, MA_NOTOWNED);
1513 cpu = PCPU_GET(cpuid);
1514 if (savectx(&susppcbs[cpu]->sp_pcb)) {
1515 npxsuspend(&susppcbs[cpu]->sp_fpususpend);
1517 CPU_SET_ATOMIC(cpu, &suspended_cpus);
1519 npxresume(&susppcbs[cpu]->sp_fpususpend);
1522 PCPU_SET(switchtime, 0);
1523 PCPU_SET(switchticks, ticks);
1525 /* Indicate that we are resumed */
1526 CPU_CLR_ATOMIC(cpu, &suspended_cpus);
1529 /* Wait for resume */
1530 while (!CPU_ISSET(cpu, &started_cpus))
1533 if (cpu_ops.cpu_resume)
1534 cpu_ops.cpu_resume();
1536 /* Resume MCA and local APIC */
1540 /* Indicate that we are resumed */
1541 CPU_CLR_ATOMIC(cpu, &suspended_cpus);
1542 CPU_CLR_ATOMIC(cpu, &started_cpus);
1546 * Handlers for TLB related IPIs
1549 invltlb_handler(void)
1552 #ifdef COUNT_XINVLTLB_HITS
1553 xhits_gbl[PCPU_GET(cpuid)]++;
1554 #endif /* COUNT_XINVLTLB_HITS */
1556 (*ipi_invltlb_counts[PCPU_GET(cpuid)])++;
1557 #endif /* COUNT_IPIS */
1561 atomic_add_int(&smp_tlb_wait, 1);
1565 invlpg_handler(void)
1567 #ifdef COUNT_XINVLTLB_HITS
1568 xhits_pg[PCPU_GET(cpuid)]++;
1569 #endif /* COUNT_XINVLTLB_HITS */
1571 (*ipi_invlpg_counts[PCPU_GET(cpuid)])++;
1572 #endif /* COUNT_IPIS */
1574 invlpg(smp_tlb_addr1);
1576 atomic_add_int(&smp_tlb_wait, 1);
1580 invlrng_handler(void)
1583 #ifdef COUNT_XINVLTLB_HITS
1584 xhits_rng[PCPU_GET(cpuid)]++;
1585 #endif /* COUNT_XINVLTLB_HITS */
1587 (*ipi_invlrng_counts[PCPU_GET(cpuid)])++;
1588 #endif /* COUNT_IPIS */
1590 addr = smp_tlb_addr1;
1594 } while (addr < smp_tlb_addr2);
1596 atomic_add_int(&smp_tlb_wait, 1);
1600 invlcache_handler(void)
1603 (*ipi_invlcache_counts[PCPU_GET(cpuid)])++;
1604 #endif /* COUNT_IPIS */
1607 atomic_add_int(&smp_tlb_wait, 1);
1611 * This is called once the rest of the system is up and running and we're
1612 * ready to let the AP's out of the pen.
1615 release_aps(void *dummy __unused)
1620 atomic_store_rel_int(&aps_ready, 1);
1621 while (smp_started == 0)
1624 SYSINIT(start_aps, SI_SUB_SMP, SI_ORDER_FIRST, release_aps, NULL);
1628 * Setup interrupt counters for IPI handlers.
1631 mp_ipi_intrcnt(void *dummy)
1637 snprintf(buf, sizeof(buf), "cpu%d:invltlb", i);
1638 intrcnt_add(buf, &ipi_invltlb_counts[i]);
1639 snprintf(buf, sizeof(buf), "cpu%d:invlrng", i);
1640 intrcnt_add(buf, &ipi_invlrng_counts[i]);
1641 snprintf(buf, sizeof(buf), "cpu%d:invlpg", i);
1642 intrcnt_add(buf, &ipi_invlpg_counts[i]);
1643 snprintf(buf, sizeof(buf), "cpu%d:invlcache", i);
1644 intrcnt_add(buf, &ipi_invlcache_counts[i]);
1645 snprintf(buf, sizeof(buf), "cpu%d:preempt", i);
1646 intrcnt_add(buf, &ipi_preempt_counts[i]);
1647 snprintf(buf, sizeof(buf), "cpu%d:ast", i);
1648 intrcnt_add(buf, &ipi_ast_counts[i]);
1649 snprintf(buf, sizeof(buf), "cpu%d:rendezvous", i);
1650 intrcnt_add(buf, &ipi_rendezvous_counts[i]);
1651 snprintf(buf, sizeof(buf), "cpu%d:lazypmap", i);
1652 intrcnt_add(buf, &ipi_lazypmap_counts[i]);
1653 snprintf(buf, sizeof(buf), "cpu%d:hardclock", i);
1654 intrcnt_add(buf, &ipi_hardclock_counts[i]);
1657 SYSINIT(mp_ipi_intrcnt, SI_SUB_INTR, SI_ORDER_MIDDLE, mp_ipi_intrcnt, NULL);