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 pcb **susppcbs = NULL;
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 = {
172 .ipi_vectored = lapic_ipi_vectored
176 * Local data and functions.
179 static volatile cpuset_t ipi_nmi_pending;
181 /* used to hold the AP's until we are ready to release them */
182 static struct mtx ap_boot_mtx;
184 /* Set to 1 once we're ready to let the APs out of the pen. */
185 static volatile int aps_ready = 0;
188 * Store data from cpu_add() until later in the boot when we actually setup
195 int cpu_hyperthread:1;
196 } static cpu_info[MAX_APIC_ID + 1];
197 int cpu_apic_ids[MAXCPU];
198 int apic_cpuids[MAX_APIC_ID + 1];
200 /* Holds pending bitmap based IPIs per CPU */
201 volatile u_int cpu_ipi_pending[MAXCPU];
203 static u_int boot_address;
204 static int cpu_logical; /* logical cpus per core */
205 static int cpu_cores; /* cores per package */
207 static void assign_cpu_ids(void);
208 static void install_ap_tramp(void);
209 static void set_interrupt_apic_ids(void);
210 static int start_all_aps(void);
211 static int start_ap(int apic_id);
212 static void release_aps(void *dummy);
214 static u_int hyperthreading_cpus; /* logical cpus sharing L1 cache */
215 static int hyperthreading_allowed = 1;
218 mem_range_AP_init(void)
220 if (mem_range_softc.mr_op && mem_range_softc.mr_op->initAP)
221 mem_range_softc.mr_op->initAP(&mem_range_softc);
230 /* AMD processors do not support HTT. */
233 if ((amd_feature2 & AMDID2_CMP) == 0) {
238 core_id_bits = (cpu_procinfo2 & AMDID_COREID_SIZE) >>
239 AMDID_COREID_SIZE_SHIFT;
240 if (core_id_bits == 0) {
241 cpu_cores = (cpu_procinfo2 & AMDID_CMP_CORES) + 1;
245 /* Fam 10h and newer should get here. */
246 for (id = 0; id <= MAX_APIC_ID; id++) {
247 /* Check logical CPU availability. */
248 if (!cpu_info[id].cpu_present || cpu_info[id].cpu_disabled)
250 /* Check if logical CPU has the same package ID. */
251 if ((id >> core_id_bits) != (boot_cpu_id >> core_id_bits))
258 * Round up to the next power of two, if necessary, and then
260 * Returns -1 if argument is zero.
266 return (fls(x << (1 - powerof2(x))) - 1);
279 /* Both zero and one here mean one logical processor per package. */
280 max_logical = (cpu_feature & CPUID_HTT) != 0 ?
281 (cpu_procinfo & CPUID_HTT_CORES) >> 16 : 1;
282 if (max_logical <= 1)
286 * Because of uniformity assumption we examine only
287 * those logical processors that belong to the same
288 * package as BSP. Further, we count number of
289 * logical processors that belong to the same core
290 * as BSP thus deducing number of threads per core.
292 if (cpu_high >= 0x4) {
293 cpuid_count(0x04, 0, p);
294 max_cores = ((p[0] >> 26) & 0x3f) + 1;
297 core_id_bits = mask_width(max_logical/max_cores);
298 if (core_id_bits < 0)
300 pkg_id_bits = core_id_bits + mask_width(max_cores);
302 for (id = 0; id <= MAX_APIC_ID; id++) {
303 /* Check logical CPU availability. */
304 if (!cpu_info[id].cpu_present || cpu_info[id].cpu_disabled)
306 /* Check if logical CPU has the same package ID. */
307 if ((id >> pkg_id_bits) != (boot_cpu_id >> pkg_id_bits))
310 /* Check if logical CPU has the same package and core IDs. */
311 if ((id >> core_id_bits) == (boot_cpu_id >> core_id_bits))
315 KASSERT(cpu_cores >= 1 && cpu_logical >= 1,
316 ("topo_probe_0x4 couldn't find BSP"));
318 cpu_cores /= cpu_logical;
319 hyperthreading_cpus = cpu_logical;
333 /* We only support three levels for now. */
334 for (i = 0; i < 3; i++) {
335 cpuid_count(0x0b, i, p);
337 /* Fall back if CPU leaf 11 doesn't really exist. */
338 if (i == 0 && p[1] == 0) {
344 logical = p[1] &= 0xffff;
345 type = (p[2] >> 8) & 0xff;
346 if (type == 0 || logical == 0)
349 * Because of uniformity assumption we examine only
350 * those logical processors that belong to the same
353 for (cnt = 0, x = 0; x <= MAX_APIC_ID; x++) {
354 if (!cpu_info[x].cpu_present ||
355 cpu_info[x].cpu_disabled)
357 if (x >> bits == boot_cpu_id >> bits)
360 if (type == CPUID_TYPE_SMT)
362 else if (type == CPUID_TYPE_CORE)
365 if (cpu_logical == 0)
367 cpu_cores /= cpu_logical;
371 * Both topology discovery code and code that consumes topology
372 * information assume top-down uniformity of the topology.
373 * That is, all physical packages must be identical and each
374 * core in a package must have the same number of threads.
375 * Topology information is queried only on BSP, on which this
376 * code runs and for which it can query CPUID information.
377 * Then topology is extrapolated on all packages using the
378 * uniformity assumption.
383 static int cpu_topo_probed = 0;
388 CPU_ZERO(&logical_cpus_mask);
390 cpu_cores = cpu_logical = 1;
391 else if (cpu_vendor_id == CPU_VENDOR_AMD)
393 else if (cpu_vendor_id == CPU_VENDOR_INTEL) {
395 * See Intel(R) 64 Architecture Processor
396 * Topology Enumeration article for details.
398 * Note that 0x1 <= cpu_high < 4 case should be
399 * compatible with topo_probe_0x4() logic when
400 * CPUID.1:EBX[23:16] > 0 (cpu_cores will be 1)
401 * or it should trigger the fallback otherwise.
405 else if (cpu_high >= 0x1)
410 * Fallback: assume each logical CPU is in separate
411 * physical package. That is, no multi-core, no SMT.
413 if (cpu_cores == 0 || cpu_logical == 0)
414 cpu_cores = cpu_logical = 1;
424 * Determine whether any threading flags are
428 if (cpu_logical > 1 && hyperthreading_cpus)
429 cg_flags = CG_FLAG_HTT;
430 else if (cpu_logical > 1)
431 cg_flags = CG_FLAG_SMT;
434 if (mp_ncpus % (cpu_cores * cpu_logical) != 0) {
435 printf("WARNING: Non-uniform processors.\n");
436 printf("WARNING: Using suboptimal topology.\n");
437 return (smp_topo_none());
440 * No multi-core or hyper-threaded.
442 if (cpu_logical * cpu_cores == 1)
443 return (smp_topo_none());
445 * Only HTT no multi-core.
447 if (cpu_logical > 1 && cpu_cores == 1)
448 return (smp_topo_1level(CG_SHARE_L1, cpu_logical, cg_flags));
450 * Only multi-core no HTT.
452 if (cpu_cores > 1 && cpu_logical == 1)
453 return (smp_topo_1level(CG_SHARE_L2, cpu_cores, cg_flags));
455 * Both HTT and multi-core.
457 return (smp_topo_2level(CG_SHARE_L2, cpu_cores,
458 CG_SHARE_L1, cpu_logical, cg_flags));
463 * Calculate usable address in base memory for AP trampoline code.
466 mp_bootaddress(u_int basemem)
469 boot_address = trunc_page(basemem); /* round down to 4k boundary */
470 if ((basemem - boot_address) < bootMP_size)
471 boot_address -= PAGE_SIZE; /* not enough, lower by 4k */
477 cpu_add(u_int apic_id, char boot_cpu)
480 if (apic_id > MAX_APIC_ID) {
481 panic("SMP: APIC ID %d too high", apic_id);
484 KASSERT(cpu_info[apic_id].cpu_present == 0, ("CPU %d added twice",
486 cpu_info[apic_id].cpu_present = 1;
488 KASSERT(boot_cpu_id == -1,
489 ("CPU %d claims to be BSP, but CPU %d already is", apic_id,
491 boot_cpu_id = apic_id;
492 cpu_info[apic_id].cpu_bsp = 1;
494 if (mp_ncpus < MAXCPU) {
496 mp_maxid = mp_ncpus - 1;
499 printf("SMP: Added CPU %d (%s)\n", apic_id, boot_cpu ? "BSP" :
504 cpu_mp_setmaxid(void)
508 * mp_maxid should be already set by calls to cpu_add().
509 * Just sanity check its value here.
512 KASSERT(mp_maxid == 0,
513 ("%s: mp_ncpus is zero, but mp_maxid is not", __func__));
514 else if (mp_ncpus == 1)
517 KASSERT(mp_maxid >= mp_ncpus - 1,
518 ("%s: counters out of sync: max %d, count %d", __func__,
519 mp_maxid, mp_ncpus));
527 * Always record BSP in CPU map so that the mbuf init code works
530 CPU_SETOF(0, &all_cpus);
533 * No CPUs were found, so this must be a UP system. Setup
534 * the variables to represent a system with a single CPU
541 /* At least one CPU was found. */
544 * One CPU was found, so this must be a UP system with
551 /* At least two CPUs were found. */
556 * Initialize the IPI handlers and start up the AP's.
563 /* Initialize the logical ID to APIC ID table. */
564 for (i = 0; i < MAXCPU; i++) {
565 cpu_apic_ids[i] = -1;
566 cpu_ipi_pending[i] = 0;
569 /* Install an inter-CPU IPI for TLB invalidation */
570 setidt(IPI_INVLTLB, IDTVEC(invltlb),
571 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
572 setidt(IPI_INVLPG, IDTVEC(invlpg),
573 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
574 setidt(IPI_INVLRNG, IDTVEC(invlrng),
575 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
577 /* Install an inter-CPU IPI for cache invalidation. */
578 setidt(IPI_INVLCACHE, IDTVEC(invlcache),
579 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
581 /* Install an inter-CPU IPI for lazy pmap release */
582 setidt(IPI_LAZYPMAP, IDTVEC(lazypmap),
583 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
585 /* Install an inter-CPU IPI for all-CPU rendezvous */
586 setidt(IPI_RENDEZVOUS, IDTVEC(rendezvous),
587 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
589 /* Install generic inter-CPU IPI handler */
590 setidt(IPI_BITMAP_VECTOR, IDTVEC(ipi_intr_bitmap_handler),
591 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
593 /* Install an inter-CPU IPI for CPU stop/restart */
594 setidt(IPI_STOP, IDTVEC(cpustop),
595 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
597 /* Install an inter-CPU IPI for CPU suspend/resume */
598 setidt(IPI_SUSPEND, IDTVEC(cpususpend),
599 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
601 /* Set boot_cpu_id if needed. */
602 if (boot_cpu_id == -1) {
603 boot_cpu_id = PCPU_GET(apic_id);
604 cpu_info[boot_cpu_id].cpu_bsp = 1;
606 KASSERT(boot_cpu_id == PCPU_GET(apic_id),
607 ("BSP's APIC ID doesn't match boot_cpu_id"));
609 /* Probe logical/physical core configuration. */
614 /* Start each Application Processor */
617 set_interrupt_apic_ids();
622 * Print various information about the SMP system hardware and setup.
625 cpu_mp_announce(void)
627 const char *hyperthread;
630 printf("FreeBSD/SMP: %d package(s) x %d core(s)",
631 mp_ncpus / (cpu_cores * cpu_logical), cpu_cores);
632 if (hyperthreading_cpus > 1)
633 printf(" x %d HTT threads", cpu_logical);
634 else if (cpu_logical > 1)
635 printf(" x %d SMT threads", cpu_logical);
638 /* List active CPUs first. */
639 printf(" cpu0 (BSP): APIC ID: %2d\n", boot_cpu_id);
640 for (i = 1; i < mp_ncpus; i++) {
641 if (cpu_info[cpu_apic_ids[i]].cpu_hyperthread)
645 printf(" cpu%d (AP%s): APIC ID: %2d\n", i, hyperthread,
649 /* List disabled CPUs last. */
650 for (i = 0; i <= MAX_APIC_ID; i++) {
651 if (!cpu_info[i].cpu_present || !cpu_info[i].cpu_disabled)
653 if (cpu_info[i].cpu_hyperthread)
657 printf(" cpu (AP%s): APIC ID: %2d (disabled)\n", hyperthread,
663 * AP CPU's call this to initialize themselves.
674 /* bootAP is set in start_ap() to our ID. */
677 /* Get per-cpu data */
680 /* prime data page for it to use */
681 pcpu_init(pc, myid, sizeof(struct pcpu));
682 dpcpu_init(dpcpu, myid);
683 pc->pc_apic_id = cpu_apic_ids[myid];
684 pc->pc_prvspace = pc;
685 pc->pc_curthread = 0;
687 gdt_segs[GPRIV_SEL].ssd_base = (int) pc;
688 gdt_segs[GPROC0_SEL].ssd_base = (int) &pc->pc_common_tss;
690 for (x = 0; x < NGDT; x++) {
691 ssdtosd(&gdt_segs[x], &gdt[myid * NGDT + x].sd);
694 r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
695 r_gdt.rd_base = (int) &gdt[myid * NGDT];
696 lgdt(&r_gdt); /* does magic intra-segment return */
701 PCPU_SET(currentldt, _default_ldt);
703 gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
704 gdt[myid * NGDT + GPROC0_SEL].sd.sd_type = SDT_SYS386TSS;
705 PCPU_SET(common_tss.tss_esp0, 0); /* not used until after switch */
706 PCPU_SET(common_tss.tss_ss0, GSEL(GDATA_SEL, SEL_KPL));
707 PCPU_SET(common_tss.tss_ioopt, (sizeof (struct i386tss)) << 16);
708 PCPU_SET(tss_gdt, &gdt[myid * NGDT + GPROC0_SEL].sd);
709 PCPU_SET(common_tssd, *PCPU_GET(tss_gdt));
712 PCPU_SET(fsgs_gdt, &gdt[myid * NGDT + GUFS_SEL].sd);
715 * Set to a known state:
716 * Set by mpboot.s: CR0_PG, CR0_PE
717 * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
720 cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
722 CHECK_WRITE(0x38, 5);
724 /* Disable local APIC just to be sure. */
727 /* signal our startup to the BSP. */
729 CHECK_WRITE(0x39, 6);
731 /* Spin until the BSP releases the AP's. */
735 /* BSP may have changed PTD while we were waiting */
737 for (addr = 0; addr < NKPT * NBPDR - 1; addr += PAGE_SIZE)
740 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
744 /* Initialize the PAT MSR if present. */
747 /* set up CPU registers and state */
750 /* set up FPU state on the AP */
753 /* set up SSE registers */
756 if (cpu_ops.cpu_init)
760 /* Enable the PTE no-execute bit. */
761 if ((amd_feature & AMDID_NX) != 0) {
764 msr = rdmsr(MSR_EFER) | EFER_NXE;
765 wrmsr(MSR_EFER, msr);
769 /* A quick check from sanity claus */
770 cpuid = PCPU_GET(cpuid);
771 if (PCPU_GET(apic_id) != lapic_id()) {
772 printf("SMP: cpuid = %d\n", cpuid);
773 printf("SMP: actual apic_id = %d\n", lapic_id());
774 printf("SMP: correct apic_id = %d\n", PCPU_GET(apic_id));
775 panic("cpuid mismatch! boom!!");
778 /* Initialize curthread. */
779 KASSERT(PCPU_GET(idlethread) != NULL, ("no idle thread"));
780 PCPU_SET(curthread, PCPU_GET(idlethread));
784 mtx_lock_spin(&ap_boot_mtx);
786 /* Init local apic for irq's */
789 /* Set memory range attributes for this CPU to match the BSP */
794 CTR1(KTR_SMP, "SMP: AP CPU #%d Launched", cpuid);
795 printf("SMP: AP CPU #%d Launched!\n", cpuid);
797 /* Determine if we are a logical CPU. */
798 /* XXX Calculation depends on cpu_logical being a power of 2, e.g. 2 */
799 if (cpu_logical > 1 && PCPU_GET(apic_id) % cpu_logical != 0)
800 CPU_SET(cpuid, &logical_cpus_mask);
805 if (smp_cpus == mp_ncpus) {
806 /* enable IPI's, tlb shootdown, freezes etc */
807 atomic_store_rel_int(&smp_started, 1);
808 smp_active = 1; /* historic */
811 mtx_unlock_spin(&ap_boot_mtx);
813 /* Wait until all the AP's are up. */
814 while (smp_started == 0)
817 /* Start per-CPU event timers. */
820 /* Enter the scheduler. */
823 panic("scheduler returned us to %s", __func__);
827 /*******************************************************************
828 * local functions and data
832 * We tell the I/O APIC code about all the CPUs we want to receive
833 * interrupts. If we don't want certain CPUs to receive IRQs we
834 * can simply not tell the I/O APIC code about them in this function.
835 * We also do not tell it about the BSP since it tells itself about
836 * the BSP internally to work with UP kernels and on UP machines.
839 set_interrupt_apic_ids(void)
843 for (i = 0; i < MAXCPU; i++) {
844 apic_id = cpu_apic_ids[i];
847 if (cpu_info[apic_id].cpu_bsp)
849 if (cpu_info[apic_id].cpu_disabled)
852 /* Don't let hyperthreads service interrupts. */
853 if (hyperthreading_cpus > 1 &&
854 apic_id % hyperthreading_cpus != 0)
862 * Assign logical CPU IDs to local APICs.
869 TUNABLE_INT_FETCH("machdep.hyperthreading_allowed",
870 &hyperthreading_allowed);
872 /* Check for explicitly disabled CPUs. */
873 for (i = 0; i <= MAX_APIC_ID; i++) {
874 if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp)
877 if (hyperthreading_cpus > 1 && i % hyperthreading_cpus != 0) {
878 cpu_info[i].cpu_hyperthread = 1;
881 * Don't use HT CPU if it has been disabled by a
884 if (hyperthreading_allowed == 0) {
885 cpu_info[i].cpu_disabled = 1;
890 /* Don't use this CPU if it has been disabled by a tunable. */
891 if (resource_disabled("lapic", i)) {
892 cpu_info[i].cpu_disabled = 1;
897 if (hyperthreading_allowed == 0 && hyperthreading_cpus > 1) {
898 hyperthreading_cpus = 0;
903 * Assign CPU IDs to local APIC IDs and disable any CPUs
904 * beyond MAXCPU. CPU 0 is always assigned to the BSP.
906 * To minimize confusion for userland, we attempt to number
907 * CPUs such that all threads and cores in a package are
908 * grouped together. For now we assume that the BSP is always
909 * the first thread in a package and just start adding APs
910 * starting with the BSP's APIC ID.
913 cpu_apic_ids[0] = boot_cpu_id;
914 apic_cpuids[boot_cpu_id] = 0;
915 for (i = boot_cpu_id + 1; i != boot_cpu_id;
916 i == MAX_APIC_ID ? i = 0 : i++) {
917 if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp ||
918 cpu_info[i].cpu_disabled)
921 if (mp_ncpus < MAXCPU) {
922 cpu_apic_ids[mp_ncpus] = i;
923 apic_cpuids[i] = mp_ncpus;
926 cpu_info[i].cpu_disabled = 1;
928 KASSERT(mp_maxid >= mp_ncpus - 1,
929 ("%s: counters out of sync: max %d, count %d", __func__, mp_maxid,
934 * start each AP in our list
936 /* Lowest 1MB is already mapped: don't touch*/
937 #define TMPMAP_START 1
944 u_int32_t mpbioswarmvec;
947 mtx_init(&ap_boot_mtx, "ap boot", NULL, MTX_SPIN);
949 /* install the AP 1st level boot code */
952 /* save the current value of the warm-start vector */
953 mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
955 outb(CMOS_REG, BIOS_RESET);
956 mpbiosreason = inb(CMOS_DATA);
959 /* set up temporary P==V mapping for AP boot */
960 /* XXX this is a hack, we should boot the AP on its own stack/PTD */
961 for (i = TMPMAP_START; i < NKPT; i++)
962 PTD[i] = PTD[KPTDI + i];
966 for (cpu = 1; cpu < mp_ncpus; cpu++) {
967 apic_id = cpu_apic_ids[cpu];
969 /* allocate and set up a boot stack data page */
971 (char *)kmem_malloc(kernel_arena, KSTACK_PAGES * PAGE_SIZE,
973 dpcpu = (void *)kmem_malloc(kernel_arena, DPCPU_SIZE,
975 /* setup a vector to our boot code */
976 *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
977 *((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
979 outb(CMOS_REG, BIOS_RESET);
980 outb(CMOS_DATA, BIOS_WARM); /* 'warm-start' */
983 bootSTK = (char *)bootstacks[cpu] + KSTACK_PAGES * PAGE_SIZE - 4;
986 /* attempt to start the Application Processor */
987 CHECK_INIT(99); /* setup checkpoints */
988 if (!start_ap(apic_id)) {
989 printf("AP #%d (PHY# %d) failed!\n", cpu, apic_id);
990 CHECK_PRINT("trace"); /* show checkpoints */
991 /* better panic as the AP may be running loose */
992 printf("panic y/n? [y] ");
996 CHECK_PRINT("trace"); /* show checkpoints */
998 CPU_SET(cpu, &all_cpus); /* record AP in CPU map */
1001 /* restore the warmstart vector */
1002 *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
1005 outb(CMOS_REG, BIOS_RESET);
1006 outb(CMOS_DATA, mpbiosreason);
1009 /* Undo V==P hack from above */
1010 for (i = TMPMAP_START; i < NKPT; i++)
1012 pmap_invalidate_range(kernel_pmap, 0, NKPT * NBPDR - 1);
1014 /* number of APs actually started */
1019 * load the 1st level AP boot code into base memory.
1022 /* targets for relocation */
1023 extern void bigJump(void);
1024 extern void bootCodeSeg(void);
1025 extern void bootDataSeg(void);
1026 extern void MPentry(void);
1027 extern u_int MP_GDT;
1028 extern u_int mp_gdtbase;
1031 install_ap_tramp(void)
1034 int size = *(int *) ((u_long) & bootMP_size);
1035 vm_offset_t va = boot_address + KERNBASE;
1036 u_char *src = (u_char *) ((u_long) bootMP);
1037 u_char *dst = (u_char *) va;
1038 u_int boot_base = (u_int) bootMP;
1043 KASSERT (size <= PAGE_SIZE,
1044 ("'size' do not fit into PAGE_SIZE, as expected."));
1045 pmap_kenter(va, boot_address);
1046 pmap_invalidate_page (kernel_pmap, va);
1047 for (x = 0; x < size; ++x)
1051 * modify addresses in code we just moved to basemem. unfortunately we
1052 * need fairly detailed info about mpboot.s for this to work. changes
1053 * to mpboot.s might require changes here.
1056 /* boot code is located in KERNEL space */
1057 dst = (u_char *) va;
1059 /* modify the lgdt arg */
1060 dst32 = (u_int32_t *) (dst + ((u_int) & mp_gdtbase - boot_base));
1061 *dst32 = boot_address + ((u_int) & MP_GDT - boot_base);
1063 /* modify the ljmp target for MPentry() */
1064 dst32 = (u_int32_t *) (dst + ((u_int) bigJump - boot_base) + 1);
1065 *dst32 = ((u_int) MPentry - KERNBASE);
1067 /* modify the target for boot code segment */
1068 dst16 = (u_int16_t *) (dst + ((u_int) bootCodeSeg - boot_base));
1069 dst8 = (u_int8_t *) (dst16 + 1);
1070 *dst16 = (u_int) boot_address & 0xffff;
1071 *dst8 = ((u_int) boot_address >> 16) & 0xff;
1073 /* modify the target for boot data segment */
1074 dst16 = (u_int16_t *) (dst + ((u_int) bootDataSeg - boot_base));
1075 dst8 = (u_int8_t *) (dst16 + 1);
1076 *dst16 = (u_int) boot_address & 0xffff;
1077 *dst8 = ((u_int) boot_address >> 16) & 0xff;
1081 * This function starts the AP (application processor) identified
1082 * by the APIC ID 'physicalCpu'. It does quite a "song and dance"
1083 * to accomplish this. This is necessary because of the nuances
1084 * of the different hardware we might encounter. It isn't pretty,
1085 * but it seems to work.
1088 start_ap(int apic_id)
1093 /* calculate the vector */
1094 vector = (boot_address >> 12) & 0xff;
1096 /* used as a watchpoint to signal AP startup */
1099 ipi_startup(apic_id, vector);
1101 /* Wait up to 5 seconds for it to start. */
1102 for (ms = 0; ms < 5000; ms++) {
1104 return 1; /* return SUCCESS */
1107 return 0; /* return FAILURE */
1110 #ifdef COUNT_XINVLTLB_HITS
1111 u_int xhits_gbl[MAXCPU];
1112 u_int xhits_pg[MAXCPU];
1113 u_int xhits_rng[MAXCPU];
1114 static SYSCTL_NODE(_debug, OID_AUTO, xhits, CTLFLAG_RW, 0, "");
1115 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, global, CTLFLAG_RW, &xhits_gbl,
1116 sizeof(xhits_gbl), "IU", "");
1117 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, page, CTLFLAG_RW, &xhits_pg,
1118 sizeof(xhits_pg), "IU", "");
1119 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, range, CTLFLAG_RW, &xhits_rng,
1120 sizeof(xhits_rng), "IU", "");
1125 u_int ipi_range_size;
1126 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_global, CTLFLAG_RW, &ipi_global, 0, "");
1127 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_page, CTLFLAG_RW, &ipi_page, 0, "");
1128 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range, CTLFLAG_RW, &ipi_range, 0, "");
1129 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range_size, CTLFLAG_RW, &ipi_range_size,
1132 u_int ipi_masked_global;
1133 u_int ipi_masked_page;
1134 u_int ipi_masked_range;
1135 u_int ipi_masked_range_size;
1136 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_global, CTLFLAG_RW,
1137 &ipi_masked_global, 0, "");
1138 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_page, CTLFLAG_RW,
1139 &ipi_masked_page, 0, "");
1140 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_range, CTLFLAG_RW,
1141 &ipi_masked_range, 0, "");
1142 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_range_size, CTLFLAG_RW,
1143 &ipi_masked_range_size, 0, "");
1144 #endif /* COUNT_XINVLTLB_HITS */
1147 * Init and startup IPI.
1150 ipi_startup(int apic_id, int vector)
1154 * first we do an INIT IPI: this INIT IPI might be run, resetting
1155 * and running the target CPU. OR this INIT IPI might be latched (P5
1156 * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
1159 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1160 APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, apic_id);
1162 DELAY(10000); /* wait ~10mS */
1165 * next we do a STARTUP IPI: the previous INIT IPI might still be
1166 * latched, (P5 bug) this 1st STARTUP would then terminate
1167 * immediately, and the previously started INIT IPI would continue. OR
1168 * the previous INIT IPI has already run. and this STARTUP IPI will
1169 * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
1172 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1173 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1176 DELAY(200); /* wait ~200uS */
1179 * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
1180 * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
1181 * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
1182 * recognized after hardware RESET or INIT IPI.
1184 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1185 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1188 DELAY(200); /* wait ~200uS */
1192 * Send an IPI to specified CPU handling the bitmap logic.
1195 ipi_send_cpu(int cpu, u_int ipi)
1197 u_int bitmap, old_pending, new_pending;
1199 KASSERT(cpu_apic_ids[cpu] != -1, ("IPI to non-existent CPU %d", cpu));
1201 if (IPI_IS_BITMAPED(ipi)) {
1203 ipi = IPI_BITMAP_VECTOR;
1205 old_pending = cpu_ipi_pending[cpu];
1206 new_pending = old_pending | bitmap;
1207 } while (!atomic_cmpset_int(&cpu_ipi_pending[cpu],
1208 old_pending, new_pending));
1212 cpu_ops.ipi_vectored(ipi, cpu_apic_ids[cpu]);
1216 * Flush the TLB on all other CPU's
1219 smp_tlb_shootdown(u_int vector, vm_offset_t addr1, vm_offset_t addr2)
1223 ncpu = mp_ncpus - 1; /* does not shootdown self */
1225 return; /* no other cpus */
1226 if (!(read_eflags() & PSL_I))
1227 panic("%s: interrupts disabled", __func__);
1228 mtx_lock_spin(&smp_ipi_mtx);
1229 smp_tlb_addr1 = addr1;
1230 smp_tlb_addr2 = addr2;
1231 atomic_store_rel_int(&smp_tlb_wait, 0);
1232 ipi_all_but_self(vector);
1233 while (smp_tlb_wait < ncpu)
1235 mtx_unlock_spin(&smp_ipi_mtx);
1239 smp_targeted_tlb_shootdown(cpuset_t mask, u_int vector, vm_offset_t addr1, vm_offset_t addr2)
1241 int cpu, ncpu, othercpus;
1243 othercpus = mp_ncpus - 1;
1244 if (CPU_ISFULLSET(&mask)) {
1248 CPU_CLR(PCPU_GET(cpuid), &mask);
1249 if (CPU_EMPTY(&mask))
1252 if (!(read_eflags() & PSL_I))
1253 panic("%s: interrupts disabled", __func__);
1254 mtx_lock_spin(&smp_ipi_mtx);
1255 smp_tlb_addr1 = addr1;
1256 smp_tlb_addr2 = addr2;
1257 atomic_store_rel_int(&smp_tlb_wait, 0);
1258 if (CPU_ISFULLSET(&mask)) {
1260 ipi_all_but_self(vector);
1263 while ((cpu = CPU_FFS(&mask)) != 0) {
1265 CPU_CLR(cpu, &mask);
1266 CTR3(KTR_SMP, "%s: cpu: %d ipi: %x", __func__, cpu,
1268 ipi_send_cpu(cpu, vector);
1272 while (smp_tlb_wait < ncpu)
1274 mtx_unlock_spin(&smp_ipi_mtx);
1278 smp_cache_flush(void)
1282 smp_tlb_shootdown(IPI_INVLCACHE, 0, 0);
1290 smp_tlb_shootdown(IPI_INVLTLB, 0, 0);
1291 #ifdef COUNT_XINVLTLB_HITS
1298 smp_invlpg(vm_offset_t addr)
1302 smp_tlb_shootdown(IPI_INVLPG, addr, 0);
1303 #ifdef COUNT_XINVLTLB_HITS
1310 smp_invlpg_range(vm_offset_t addr1, vm_offset_t addr2)
1314 smp_tlb_shootdown(IPI_INVLRNG, addr1, addr2);
1315 #ifdef COUNT_XINVLTLB_HITS
1317 ipi_range_size += (addr2 - addr1) / PAGE_SIZE;
1323 smp_masked_invltlb(cpuset_t mask)
1327 smp_targeted_tlb_shootdown(mask, IPI_INVLTLB, 0, 0);
1328 #ifdef COUNT_XINVLTLB_HITS
1329 ipi_masked_global++;
1335 smp_masked_invlpg(cpuset_t mask, vm_offset_t addr)
1339 smp_targeted_tlb_shootdown(mask, IPI_INVLPG, addr, 0);
1340 #ifdef COUNT_XINVLTLB_HITS
1347 smp_masked_invlpg_range(cpuset_t mask, vm_offset_t addr1, vm_offset_t addr2)
1351 smp_targeted_tlb_shootdown(mask, IPI_INVLRNG, addr1, addr2);
1352 #ifdef COUNT_XINVLTLB_HITS
1354 ipi_masked_range_size += (addr2 - addr1) / PAGE_SIZE;
1360 ipi_bitmap_handler(struct trapframe frame)
1362 struct trapframe *oldframe;
1364 int cpu = PCPU_GET(cpuid);
1369 td->td_intr_nesting_level++;
1370 oldframe = td->td_intr_frame;
1371 td->td_intr_frame = &frame;
1372 ipi_bitmap = atomic_readandclear_int(&cpu_ipi_pending[cpu]);
1373 if (ipi_bitmap & (1 << IPI_PREEMPT)) {
1375 (*ipi_preempt_counts[cpu])++;
1379 if (ipi_bitmap & (1 << IPI_AST)) {
1381 (*ipi_ast_counts[cpu])++;
1383 /* Nothing to do for AST */
1385 if (ipi_bitmap & (1 << IPI_HARDCLOCK)) {
1387 (*ipi_hardclock_counts[cpu])++;
1391 td->td_intr_frame = oldframe;
1392 td->td_intr_nesting_level--;
1397 * send an IPI to a set of cpus.
1400 ipi_selected(cpuset_t cpus, u_int ipi)
1405 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1406 * of help in order to understand what is the source.
1407 * Set the mask of receiving CPUs for this purpose.
1409 if (ipi == IPI_STOP_HARD)
1410 CPU_OR_ATOMIC(&ipi_nmi_pending, &cpus);
1412 while ((cpu = CPU_FFS(&cpus)) != 0) {
1414 CPU_CLR(cpu, &cpus);
1415 CTR3(KTR_SMP, "%s: cpu: %d ipi: %x", __func__, cpu, ipi);
1416 ipi_send_cpu(cpu, ipi);
1421 * send an IPI to a specific CPU.
1424 ipi_cpu(int cpu, u_int ipi)
1428 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1429 * of help in order to understand what is the source.
1430 * Set the mask of receiving CPUs for this purpose.
1432 if (ipi == IPI_STOP_HARD)
1433 CPU_SET_ATOMIC(cpu, &ipi_nmi_pending);
1435 CTR3(KTR_SMP, "%s: cpu: %d ipi: %x", __func__, cpu, ipi);
1436 ipi_send_cpu(cpu, ipi);
1440 * send an IPI to all CPUs EXCEPT myself
1443 ipi_all_but_self(u_int ipi)
1445 cpuset_t other_cpus;
1447 other_cpus = all_cpus;
1448 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
1449 if (IPI_IS_BITMAPED(ipi)) {
1450 ipi_selected(other_cpus, ipi);
1455 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1456 * of help in order to understand what is the source.
1457 * Set the mask of receiving CPUs for this purpose.
1459 if (ipi == IPI_STOP_HARD)
1460 CPU_OR_ATOMIC(&ipi_nmi_pending, &other_cpus);
1462 CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1463 cpu_ops.ipi_vectored(ipi, APIC_IPI_DEST_OTHERS);
1472 * As long as there is not a simple way to know about a NMI's
1473 * source, if the bitmask for the current CPU is present in
1474 * the global pending bitword an IPI_STOP_HARD has been issued
1475 * and should be handled.
1477 cpuid = PCPU_GET(cpuid);
1478 if (!CPU_ISSET(cpuid, &ipi_nmi_pending))
1481 CPU_CLR_ATOMIC(cpuid, &ipi_nmi_pending);
1487 * Handle an IPI_STOP by saving our current context and spinning until we
1491 cpustop_handler(void)
1495 cpu = PCPU_GET(cpuid);
1497 savectx(&stoppcbs[cpu]);
1499 /* Indicate that we are stopped */
1500 CPU_SET_ATOMIC(cpu, &stopped_cpus);
1502 /* Wait for restart */
1503 while (!CPU_ISSET(cpu, &started_cpus))
1506 CPU_CLR_ATOMIC(cpu, &started_cpus);
1507 CPU_CLR_ATOMIC(cpu, &stopped_cpus);
1509 if (cpu == 0 && cpustop_restartfunc != NULL) {
1510 cpustop_restartfunc();
1511 cpustop_restartfunc = NULL;
1516 * Handle an IPI_SUSPEND by saving our current context and spinning until we
1520 cpususpend_handler(void)
1524 mtx_assert(&smp_ipi_mtx, MA_NOTOWNED);
1526 cpu = PCPU_GET(cpuid);
1527 if (savectx(susppcbs[cpu])) {
1529 CPU_SET_ATOMIC(cpu, &suspended_cpus);
1532 PCPU_SET(switchtime, 0);
1533 PCPU_SET(switchticks, ticks);
1535 /* Indicate that we are resumed */
1536 CPU_CLR_ATOMIC(cpu, &suspended_cpus);
1539 /* Wait for resume */
1540 while (!CPU_ISSET(cpu, &started_cpus))
1543 if (cpu_ops.cpu_resume)
1544 cpu_ops.cpu_resume();
1546 /* Resume MCA and local APIC */
1550 /* Indicate that we are resumed */
1551 CPU_CLR_ATOMIC(cpu, &suspended_cpus);
1552 CPU_CLR_ATOMIC(cpu, &started_cpus);
1555 * This is called once the rest of the system is up and running and we're
1556 * ready to let the AP's out of the pen.
1559 release_aps(void *dummy __unused)
1564 atomic_store_rel_int(&aps_ready, 1);
1565 while (smp_started == 0)
1568 SYSINIT(start_aps, SI_SUB_SMP, SI_ORDER_FIRST, release_aps, NULL);
1572 * Setup interrupt counters for IPI handlers.
1575 mp_ipi_intrcnt(void *dummy)
1581 snprintf(buf, sizeof(buf), "cpu%d:invltlb", i);
1582 intrcnt_add(buf, &ipi_invltlb_counts[i]);
1583 snprintf(buf, sizeof(buf), "cpu%d:invlrng", i);
1584 intrcnt_add(buf, &ipi_invlrng_counts[i]);
1585 snprintf(buf, sizeof(buf), "cpu%d:invlpg", i);
1586 intrcnt_add(buf, &ipi_invlpg_counts[i]);
1587 snprintf(buf, sizeof(buf), "cpu%d:invlcache", i);
1588 intrcnt_add(buf, &ipi_invlcache_counts[i]);
1589 snprintf(buf, sizeof(buf), "cpu%d:preempt", i);
1590 intrcnt_add(buf, &ipi_preempt_counts[i]);
1591 snprintf(buf, sizeof(buf), "cpu%d:ast", i);
1592 intrcnt_add(buf, &ipi_ast_counts[i]);
1593 snprintf(buf, sizeof(buf), "cpu%d:rendezvous", i);
1594 intrcnt_add(buf, &ipi_rendezvous_counts[i]);
1595 snprintf(buf, sizeof(buf), "cpu%d:lazypmap", i);
1596 intrcnt_add(buf, &ipi_lazypmap_counts[i]);
1597 snprintf(buf, sizeof(buf), "cpu%d:hardclock", i);
1598 intrcnt_add(buf, &ipi_hardclock_counts[i]);
1601 SYSINIT(mp_ipi_intrcnt, SI_SUB_INTR, SI_ORDER_MIDDLE, mp_ipi_intrcnt, NULL);