2 * Copyright (c) 1996, by Steve Passe
3 * Copyright (c) 2003, by Peter Wemm
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. The name of the developer may NOT be used to endorse or promote products
12 * derived from this software without specific prior written permission.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
31 #include "opt_kstack_pages.h"
32 #include "opt_mp_watchdog.h"
33 #include "opt_sched.h"
35 #include <sys/param.h>
36 #include <sys/systm.h>
41 #include <sys/kernel.h>
44 #include <sys/malloc.h>
45 #include <sys/memrange.h>
46 #include <sys/mutex.h>
49 #include <sys/sched.h>
51 #include <sys/sysctl.h>
54 #include <vm/vm_param.h>
56 #include <vm/vm_kern.h>
57 #include <vm/vm_extern.h>
59 #include <machine/apicreg.h>
60 #include <machine/clock.h>
61 #include <machine/cputypes.h>
62 #include <machine/cpufunc.h>
63 #include <machine/mca.h>
64 #include <machine/md_var.h>
65 #include <machine/mp_watchdog.h>
66 #include <machine/pcb.h>
67 #include <machine/psl.h>
68 #include <machine/smp.h>
69 #include <machine/specialreg.h>
70 #include <machine/tss.h>
72 #define WARMBOOT_TARGET 0
73 #define WARMBOOT_OFF (KERNBASE + 0x0467)
74 #define WARMBOOT_SEG (KERNBASE + 0x0469)
76 #define CMOS_REG (0x70)
77 #define CMOS_DATA (0x71)
78 #define BIOS_RESET (0x0f)
79 #define BIOS_WARM (0x0a)
81 /* lock region used by kernel profiling */
84 int mp_naps; /* # of Applications processors */
85 int boot_cpu_id = -1; /* designated BSP */
87 extern struct pcpu __pcpu[];
89 /* AP uses this during bootstrap. Do not staticize. */
93 /* Free these after use */
94 void *bootstacks[MAXCPU];
96 /* Temporary variables for init_secondary() */
97 char *doublefault_stack;
101 /* Hotwire a 0->4MB V==P mapping */
102 extern pt_entry_t *KPTphys;
104 /* SMP page table page */
105 extern pt_entry_t *SMPpt;
107 struct pcb stoppcbs[MAXCPU];
108 struct pcb **susppcbs;
111 /* Variables needed for SMP tlb shootdown. */
112 vm_offset_t smp_tlb_addr1;
113 vm_offset_t smp_tlb_addr2;
114 volatile int smp_tlb_wait;
116 extern inthand_t IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
119 * Local data and functions.
122 static volatile cpumask_t ipi_nmi_pending;
124 /* used to hold the AP's until we are ready to release them */
125 static struct mtx ap_boot_mtx;
127 /* Set to 1 once we're ready to let the APs out of the pen. */
128 static volatile int aps_ready = 0;
131 * Store data from cpu_add() until later in the boot when we actually setup
138 int cpu_hyperthread:1;
139 } static cpu_info[MAX_APIC_ID + 1];
140 int cpu_apic_ids[MAXCPU];
141 int apic_cpuids[MAX_APIC_ID + 1];
143 /* Holds pending bitmap based IPIs per CPU */
144 static volatile u_int cpu_ipi_pending[MAXCPU];
146 static u_int boot_address;
147 static int cpu_logical; /* logical cpus per core */
148 static int cpu_cores; /* cores per package */
150 static void assign_cpu_ids(void);
151 static void set_interrupt_apic_ids(void);
152 static int start_all_aps(void);
153 static int start_ap(int apic_id);
154 static void release_aps(void *dummy);
156 static int hlt_logical_cpus;
157 static u_int hyperthreading_cpus; /* logical cpus sharing L1 cache */
158 static cpumask_t hyperthreading_cpus_mask;
159 static int hyperthreading_allowed = 1;
160 static struct sysctl_ctx_list logical_cpu_clist;
161 static u_int bootMP_size;
164 mem_range_AP_init(void)
166 if (mem_range_softc.mr_op && mem_range_softc.mr_op->initAP)
167 mem_range_softc.mr_op->initAP(&mem_range_softc);
176 /* AMD processors do not support HTT. */
179 if ((amd_feature2 & AMDID2_CMP) == 0) {
184 core_id_bits = (cpu_procinfo2 & AMDID_COREID_SIZE) >>
185 AMDID_COREID_SIZE_SHIFT;
186 if (core_id_bits == 0) {
187 cpu_cores = (cpu_procinfo2 & AMDID_CMP_CORES) + 1;
191 /* Fam 10h and newer should get here. */
192 for (id = 0; id <= MAX_APIC_ID; id++) {
193 /* Check logical CPU availability. */
194 if (!cpu_info[id].cpu_present || cpu_info[id].cpu_disabled)
196 /* Check if logical CPU has the same package ID. */
197 if ((id >> core_id_bits) != (boot_cpu_id >> core_id_bits))
204 * Round up to the next power of two, if necessary, and then
206 * Returns -1 if argument is zero.
212 return (fls(x << (1 - powerof2(x))) - 1);
225 /* Both zero and one here mean one logical processor per package. */
226 max_logical = (cpu_feature & CPUID_HTT) != 0 ?
227 (cpu_procinfo & CPUID_HTT_CORES) >> 16 : 1;
228 if (max_logical <= 1)
232 * Because of uniformity assumption we examine only
233 * those logical processors that belong to the same
234 * package as BSP. Further, we count number of
235 * logical processors that belong to the same core
236 * as BSP thus deducing number of threads per core.
238 if (cpu_high >= 0x4) {
239 cpuid_count(0x04, 0, p);
240 max_cores = ((p[0] >> 26) & 0x3f) + 1;
243 core_id_bits = mask_width(max_logical/max_cores);
244 if (core_id_bits < 0)
246 pkg_id_bits = core_id_bits + mask_width(max_cores);
248 for (id = 0; id <= MAX_APIC_ID; id++) {
249 /* Check logical CPU availability. */
250 if (!cpu_info[id].cpu_present || cpu_info[id].cpu_disabled)
252 /* Check if logical CPU has the same package ID. */
253 if ((id >> pkg_id_bits) != (boot_cpu_id >> pkg_id_bits))
256 /* Check if logical CPU has the same package and core IDs. */
257 if ((id >> core_id_bits) == (boot_cpu_id >> core_id_bits))
261 KASSERT(cpu_cores >= 1 && cpu_logical >= 1,
262 ("topo_probe_0x4 couldn't find BSP"));
264 cpu_cores /= cpu_logical;
265 hyperthreading_cpus = cpu_logical;
279 /* We only support three levels for now. */
280 for (i = 0; i < 3; i++) {
281 cpuid_count(0x0b, i, p);
283 /* Fall back if CPU leaf 11 doesn't really exist. */
284 if (i == 0 && p[1] == 0) {
290 logical = p[1] &= 0xffff;
291 type = (p[2] >> 8) & 0xff;
292 if (type == 0 || logical == 0)
295 * Because of uniformity assumption we examine only
296 * those logical processors that belong to the same
299 for (cnt = 0, x = 0; x <= MAX_APIC_ID; x++) {
300 if (!cpu_info[x].cpu_present ||
301 cpu_info[x].cpu_disabled)
303 if (x >> bits == boot_cpu_id >> bits)
306 if (type == CPUID_TYPE_SMT)
308 else if (type == CPUID_TYPE_CORE)
311 if (cpu_logical == 0)
313 cpu_cores /= cpu_logical;
317 * Both topology discovery code and code that consumes topology
318 * information assume top-down uniformity of the topology.
319 * That is, all physical packages must be identical and each
320 * core in a package must have the same number of threads.
321 * Topology information is queried only on BSP, on which this
322 * code runs and for which it can query CPUID information.
323 * Then topology is extrapolated on all packages using the
324 * uniformity assumption.
329 static int cpu_topo_probed = 0;
334 logical_cpus_mask = 0;
336 cpu_cores = cpu_logical = 1;
337 else if (cpu_vendor_id == CPU_VENDOR_AMD)
339 else if (cpu_vendor_id == CPU_VENDOR_INTEL) {
341 * See Intel(R) 64 Architecture Processor
342 * Topology Enumeration article for details.
344 * Note that 0x1 <= cpu_high < 4 case should be
345 * compatible with topo_probe_0x4() logic when
346 * CPUID.1:EBX[23:16] > 0 (cpu_cores will be 1)
347 * or it should trigger the fallback otherwise.
351 else if (cpu_high >= 0x1)
356 * Fallback: assume each logical CPU is in separate
357 * physical package. That is, no multi-core, no SMT.
359 if (cpu_cores == 0 || cpu_logical == 0)
360 cpu_cores = cpu_logical = 1;
370 * Determine whether any threading flags are
374 if (cpu_logical > 1 && hyperthreading_cpus)
375 cg_flags = CG_FLAG_HTT;
376 else if (cpu_logical > 1)
377 cg_flags = CG_FLAG_SMT;
380 if (mp_ncpus % (cpu_cores * cpu_logical) != 0) {
381 printf("WARNING: Non-uniform processors.\n");
382 printf("WARNING: Using suboptimal topology.\n");
383 return (smp_topo_none());
386 * No multi-core or hyper-threaded.
388 if (cpu_logical * cpu_cores == 1)
389 return (smp_topo_none());
391 * Only HTT no multi-core.
393 if (cpu_logical > 1 && cpu_cores == 1)
394 return (smp_topo_1level(CG_SHARE_L1, cpu_logical, cg_flags));
396 * Only multi-core no HTT.
398 if (cpu_cores > 1 && cpu_logical == 1)
399 return (smp_topo_1level(CG_SHARE_L2, cpu_cores, cg_flags));
401 * Both HTT and multi-core.
403 return (smp_topo_2level(CG_SHARE_L2, cpu_cores,
404 CG_SHARE_L1, cpu_logical, cg_flags));
408 * Calculate usable address in base memory for AP trampoline code.
411 mp_bootaddress(u_int basemem)
414 bootMP_size = mptramp_end - mptramp_start;
415 boot_address = trunc_page(basemem * 1024); /* round down to 4k boundary */
416 if (((basemem * 1024) - boot_address) < bootMP_size)
417 boot_address -= PAGE_SIZE; /* not enough, lower by 4k */
418 /* 3 levels of page table pages */
419 mptramp_pagetables = boot_address - (PAGE_SIZE * 3);
421 return mptramp_pagetables;
425 cpu_add(u_int apic_id, char boot_cpu)
428 if (apic_id > MAX_APIC_ID) {
429 panic("SMP: APIC ID %d too high", apic_id);
432 KASSERT(cpu_info[apic_id].cpu_present == 0, ("CPU %d added twice",
434 cpu_info[apic_id].cpu_present = 1;
436 KASSERT(boot_cpu_id == -1,
437 ("CPU %d claims to be BSP, but CPU %d already is", apic_id,
439 boot_cpu_id = apic_id;
440 cpu_info[apic_id].cpu_bsp = 1;
442 if (mp_ncpus < MAXCPU) {
444 mp_maxid = mp_ncpus -1;
447 printf("SMP: Added CPU %d (%s)\n", apic_id, boot_cpu ? "BSP" :
452 cpu_mp_setmaxid(void)
456 * mp_maxid should be already set by calls to cpu_add().
457 * Just sanity check its value here.
460 KASSERT(mp_maxid == 0,
461 ("%s: mp_ncpus is zero, but mp_maxid is not", __func__));
462 else if (mp_ncpus == 1)
465 KASSERT(mp_maxid >= mp_ncpus - 1,
466 ("%s: counters out of sync: max %d, count %d", __func__,
467 mp_maxid, mp_ncpus));
475 * Always record BSP in CPU map so that the mbuf init code works
481 * No CPUs were found, so this must be a UP system. Setup
482 * the variables to represent a system with a single CPU
489 /* At least one CPU was found. */
492 * One CPU was found, so this must be a UP system with
499 /* At least two CPUs were found. */
504 * Initialize the IPI handlers and start up the AP's.
511 /* Initialize the logical ID to APIC ID table. */
512 for (i = 0; i < MAXCPU; i++) {
513 cpu_apic_ids[i] = -1;
514 cpu_ipi_pending[i] = 0;
517 /* Install an inter-CPU IPI for TLB invalidation */
518 setidt(IPI_INVLTLB, IDTVEC(invltlb), SDT_SYSIGT, SEL_KPL, 0);
519 setidt(IPI_INVLPG, IDTVEC(invlpg), SDT_SYSIGT, SEL_KPL, 0);
520 setidt(IPI_INVLRNG, IDTVEC(invlrng), SDT_SYSIGT, SEL_KPL, 0);
522 /* Install an inter-CPU IPI for cache invalidation. */
523 setidt(IPI_INVLCACHE, IDTVEC(invlcache), SDT_SYSIGT, SEL_KPL, 0);
525 /* Install an inter-CPU IPI for all-CPU rendezvous */
526 setidt(IPI_RENDEZVOUS, IDTVEC(rendezvous), SDT_SYSIGT, SEL_KPL, 0);
528 /* Install generic inter-CPU IPI handler */
529 setidt(IPI_BITMAP_VECTOR, IDTVEC(ipi_intr_bitmap_handler),
530 SDT_SYSIGT, SEL_KPL, 0);
532 /* Install an inter-CPU IPI for CPU stop/restart */
533 setidt(IPI_STOP, IDTVEC(cpustop), SDT_SYSIGT, SEL_KPL, 0);
535 /* Install an inter-CPU IPI for CPU suspend/resume */
536 setidt(IPI_SUSPEND, IDTVEC(cpususpend), SDT_SYSIGT, SEL_KPL, 0);
538 /* Set boot_cpu_id if needed. */
539 if (boot_cpu_id == -1) {
540 boot_cpu_id = PCPU_GET(apic_id);
541 cpu_info[boot_cpu_id].cpu_bsp = 1;
543 KASSERT(boot_cpu_id == PCPU_GET(apic_id),
544 ("BSP's APIC ID doesn't match boot_cpu_id"));
546 /* Probe logical/physical core configuration. */
551 /* Start each Application Processor */
554 set_interrupt_apic_ids();
559 * Print various information about the SMP system hardware and setup.
562 cpu_mp_announce(void)
564 const char *hyperthread;
567 printf("FreeBSD/SMP: %d package(s) x %d core(s)",
568 mp_ncpus / (cpu_cores * cpu_logical), cpu_cores);
569 if (hyperthreading_cpus > 1)
570 printf(" x %d HTT threads", cpu_logical);
571 else if (cpu_logical > 1)
572 printf(" x %d SMT threads", cpu_logical);
575 /* List active CPUs first. */
576 printf(" cpu0 (BSP): APIC ID: %2d\n", boot_cpu_id);
577 for (i = 1; i < mp_ncpus; i++) {
578 if (cpu_info[cpu_apic_ids[i]].cpu_hyperthread)
582 printf(" cpu%d (AP%s): APIC ID: %2d\n", i, hyperthread,
586 /* List disabled CPUs last. */
587 for (i = 0; i <= MAX_APIC_ID; i++) {
588 if (!cpu_info[i].cpu_present || !cpu_info[i].cpu_disabled)
590 if (cpu_info[i].cpu_hyperthread)
594 printf(" cpu (AP%s): APIC ID: %2d (disabled)\n", hyperthread,
600 * AP CPU's call this to initialize themselves.
608 int cpu, gsel_tss, x;
609 struct region_descriptor ap_gdt;
611 /* Set by the startup code for us to use */
615 common_tss[cpu] = common_tss[0];
616 common_tss[cpu].tss_rsp0 = 0; /* not used until after switch */
617 common_tss[cpu].tss_iobase = sizeof(struct amd64tss) +
619 common_tss[cpu].tss_ist1 = (long)&doublefault_stack[PAGE_SIZE];
621 /* The NMI stack runs on IST2. */
622 np = ((struct nmi_pcpu *) &nmi_stack[PAGE_SIZE]) - 1;
623 common_tss[cpu].tss_ist2 = (long) np;
625 /* Prepare private GDT */
626 gdt_segs[GPROC0_SEL].ssd_base = (long) &common_tss[cpu];
627 for (x = 0; x < NGDT; x++) {
628 if (x != GPROC0_SEL && x != (GPROC0_SEL + 1) &&
629 x != GUSERLDT_SEL && x != (GUSERLDT_SEL + 1))
630 ssdtosd(&gdt_segs[x], &gdt[NGDT * cpu + x]);
632 ssdtosyssd(&gdt_segs[GPROC0_SEL],
633 (struct system_segment_descriptor *)&gdt[NGDT * cpu + GPROC0_SEL]);
634 ap_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
635 ap_gdt.rd_base = (long) &gdt[NGDT * cpu];
636 lgdt(&ap_gdt); /* does magic intra-segment return */
638 /* Get per-cpu data */
641 /* prime data page for it to use */
642 pcpu_init(pc, cpu, sizeof(struct pcpu));
643 dpcpu_init(dpcpu, cpu);
644 pc->pc_apic_id = cpu_apic_ids[cpu];
645 pc->pc_prvspace = pc;
646 pc->pc_curthread = 0;
647 pc->pc_tssp = &common_tss[cpu];
648 pc->pc_commontssp = &common_tss[cpu];
650 pc->pc_tss = (struct system_segment_descriptor *)&gdt[NGDT * cpu +
652 pc->pc_fs32p = &gdt[NGDT * cpu + GUFS32_SEL];
653 pc->pc_gs32p = &gdt[NGDT * cpu + GUGS32_SEL];
654 pc->pc_ldt = (struct system_segment_descriptor *)&gdt[NGDT * cpu +
657 /* Save the per-cpu pointer for use by the NMI handler. */
658 np->np_pcpu = (register_t) pc;
660 wrmsr(MSR_FSBASE, 0); /* User value */
661 wrmsr(MSR_GSBASE, (u_int64_t)pc);
662 wrmsr(MSR_KGSBASE, (u_int64_t)pc); /* XXX User value while we're in the kernel */
666 gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
670 * Set to a known state:
671 * Set by mpboot.s: CR0_PG, CR0_PE
672 * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
675 cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
678 /* Set up the fast syscall stuff */
679 msr = rdmsr(MSR_EFER) | EFER_SCE;
680 wrmsr(MSR_EFER, msr);
681 wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall));
682 wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
683 msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
684 ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
685 wrmsr(MSR_STAR, msr);
686 wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D);
688 /* Disable local APIC just to be sure. */
691 /* signal our startup to the BSP. */
694 /* Spin until the BSP releases the AP's. */
698 /* Initialize the PAT MSR. */
701 /* set up CPU registers and state */
704 /* set up SSE/NX registers */
707 /* set up FPU state on the AP */
710 /* A quick check from sanity claus */
711 if (PCPU_GET(apic_id) != lapic_id()) {
712 printf("SMP: cpuid = %d\n", PCPU_GET(cpuid));
713 printf("SMP: actual apic_id = %d\n", lapic_id());
714 printf("SMP: correct apic_id = %d\n", PCPU_GET(apic_id));
715 panic("cpuid mismatch! boom!!");
718 /* Initialize curthread. */
719 KASSERT(PCPU_GET(idlethread) != NULL, ("no idle thread"));
720 PCPU_SET(curthread, PCPU_GET(idlethread));
724 mtx_lock_spin(&ap_boot_mtx);
726 /* Init local apic for irq's */
729 /* Set memory range attributes for this CPU to match the BSP */
734 CTR1(KTR_SMP, "SMP: AP CPU #%d Launched", PCPU_GET(cpuid));
735 printf("SMP: AP CPU #%d Launched!\n", PCPU_GET(cpuid));
737 /* Determine if we are a logical CPU. */
738 /* XXX Calculation depends on cpu_logical being a power of 2, e.g. 2 */
739 if (cpu_logical > 1 && PCPU_GET(apic_id) % cpu_logical != 0)
740 logical_cpus_mask |= PCPU_GET(cpumask);
742 /* Determine if we are a hyperthread. */
743 if (hyperthreading_cpus > 1 &&
744 PCPU_GET(apic_id) % hyperthreading_cpus != 0)
745 hyperthreading_cpus_mask |= PCPU_GET(cpumask);
747 /* Build our map of 'other' CPUs. */
748 PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
753 if (smp_cpus == mp_ncpus) {
754 /* enable IPI's, tlb shootdown, freezes etc */
755 atomic_store_rel_int(&smp_started, 1);
756 smp_active = 1; /* historic */
760 * Enable global pages TLB extension
761 * This also implicitly flushes the TLB
764 load_cr4(rcr4() | CR4_PGE);
768 mtx_unlock_spin(&ap_boot_mtx);
770 /* wait until all the AP's are up */
771 while (smp_started == 0)
776 panic("scheduler returned us to %s", __func__);
780 /*******************************************************************
781 * local functions and data
785 * We tell the I/O APIC code about all the CPUs we want to receive
786 * interrupts. If we don't want certain CPUs to receive IRQs we
787 * can simply not tell the I/O APIC code about them in this function.
788 * We also do not tell it about the BSP since it tells itself about
789 * the BSP internally to work with UP kernels and on UP machines.
792 set_interrupt_apic_ids(void)
796 for (i = 0; i < MAXCPU; i++) {
797 apic_id = cpu_apic_ids[i];
800 if (cpu_info[apic_id].cpu_bsp)
802 if (cpu_info[apic_id].cpu_disabled)
805 /* Don't let hyperthreads service interrupts. */
806 if (hyperthreading_cpus > 1 &&
807 apic_id % hyperthreading_cpus != 0)
815 * Assign logical CPU IDs to local APICs.
822 TUNABLE_INT_FETCH("machdep.hyperthreading_allowed",
823 &hyperthreading_allowed);
825 /* Check for explicitly disabled CPUs. */
826 for (i = 0; i <= MAX_APIC_ID; i++) {
827 if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp)
830 if (hyperthreading_cpus > 1 && i % hyperthreading_cpus != 0) {
831 cpu_info[i].cpu_hyperthread = 1;
832 #if defined(SCHED_ULE)
834 * Don't use HT CPU if it has been disabled by a
837 if (hyperthreading_allowed == 0) {
838 cpu_info[i].cpu_disabled = 1;
844 /* Don't use this CPU if it has been disabled by a tunable. */
845 if (resource_disabled("lapic", i)) {
846 cpu_info[i].cpu_disabled = 1;
852 * Assign CPU IDs to local APIC IDs and disable any CPUs
853 * beyond MAXCPU. CPU 0 is always assigned to the BSP.
855 * To minimize confusion for userland, we attempt to number
856 * CPUs such that all threads and cores in a package are
857 * grouped together. For now we assume that the BSP is always
858 * the first thread in a package and just start adding APs
859 * starting with the BSP's APIC ID.
862 cpu_apic_ids[0] = boot_cpu_id;
863 apic_cpuids[boot_cpu_id] = 0;
864 for (i = boot_cpu_id + 1; i != boot_cpu_id;
865 i == MAX_APIC_ID ? i = 0 : i++) {
866 if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp ||
867 cpu_info[i].cpu_disabled)
870 if (mp_ncpus < MAXCPU) {
871 cpu_apic_ids[mp_ncpus] = i;
872 apic_cpuids[i] = mp_ncpus;
875 cpu_info[i].cpu_disabled = 1;
877 KASSERT(mp_maxid >= mp_ncpus - 1,
878 ("%s: counters out of sync: max %d, count %d", __func__, mp_maxid,
883 * start each AP in our list
888 vm_offset_t va = boot_address + KERNBASE;
889 u_int64_t *pt4, *pt3, *pt2;
890 u_int32_t mpbioswarmvec;
894 mtx_init(&ap_boot_mtx, "ap boot", NULL, MTX_SPIN);
896 /* install the AP 1st level boot code */
897 pmap_kenter(va, boot_address);
898 pmap_invalidate_page(kernel_pmap, va);
899 bcopy(mptramp_start, (void *)va, bootMP_size);
901 /* Locate the page tables, they'll be below the trampoline */
902 pt4 = (u_int64_t *)(uintptr_t)(mptramp_pagetables + KERNBASE);
903 pt3 = pt4 + (PAGE_SIZE) / sizeof(u_int64_t);
904 pt2 = pt3 + (PAGE_SIZE) / sizeof(u_int64_t);
906 /* Create the initial 1GB replicated page tables */
907 for (i = 0; i < 512; i++) {
908 /* Each slot of the level 4 pages points to the same level 3 page */
909 pt4[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + PAGE_SIZE);
910 pt4[i] |= PG_V | PG_RW | PG_U;
912 /* Each slot of the level 3 pages points to the same level 2 page */
913 pt3[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + (2 * PAGE_SIZE));
914 pt3[i] |= PG_V | PG_RW | PG_U;
916 /* The level 2 page slots are mapped with 2MB pages for 1GB. */
917 pt2[i] = i * (2 * 1024 * 1024);
918 pt2[i] |= PG_V | PG_RW | PG_PS | PG_U;
921 /* save the current value of the warm-start vector */
922 mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
923 outb(CMOS_REG, BIOS_RESET);
924 mpbiosreason = inb(CMOS_DATA);
926 /* setup a vector to our boot code */
927 *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
928 *((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
929 outb(CMOS_REG, BIOS_RESET);
930 outb(CMOS_DATA, BIOS_WARM); /* 'warm-start' */
933 for (cpu = 1; cpu < mp_ncpus; cpu++) {
934 apic_id = cpu_apic_ids[cpu];
936 /* allocate and set up an idle stack data page */
937 bootstacks[cpu] = (void *)kmem_alloc(kernel_map, KSTACK_PAGES * PAGE_SIZE);
938 doublefault_stack = (char *)kmem_alloc(kernel_map, PAGE_SIZE);
939 nmi_stack = (char *)kmem_alloc(kernel_map, PAGE_SIZE);
940 dpcpu = (void *)kmem_alloc(kernel_map, DPCPU_SIZE);
942 bootSTK = (char *)bootstacks[cpu] + KSTACK_PAGES * PAGE_SIZE - 8;
945 /* attempt to start the Application Processor */
946 if (!start_ap(apic_id)) {
947 /* restore the warmstart vector */
948 *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
949 panic("AP #%d (PHY# %d) failed!", cpu, apic_id);
952 all_cpus |= (1 << cpu); /* record AP in CPU map */
955 /* build our map of 'other' CPUs */
956 PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
958 /* restore the warmstart vector */
959 *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
961 outb(CMOS_REG, BIOS_RESET);
962 outb(CMOS_DATA, mpbiosreason);
964 /* number of APs actually started */
970 * This function starts the AP (application processor) identified
971 * by the APIC ID 'physicalCpu'. It does quite a "song and dance"
972 * to accomplish this. This is necessary because of the nuances
973 * of the different hardware we might encounter. It isn't pretty,
974 * but it seems to work.
977 start_ap(int apic_id)
982 /* calculate the vector */
983 vector = (boot_address >> 12) & 0xff;
985 /* used as a watchpoint to signal AP startup */
989 * first we do an INIT/RESET IPI this INIT IPI might be run, reseting
990 * and running the target CPU. OR this INIT IPI might be latched (P5
991 * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
995 /* do an INIT IPI: assert RESET */
996 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
997 APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, apic_id);
999 /* wait for pending status end */
1002 /* do an INIT IPI: deassert RESET */
1003 lapic_ipi_raw(APIC_DEST_ALLESELF | APIC_TRIGMOD_LEVEL |
1004 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, 0);
1006 /* wait for pending status end */
1007 DELAY(10000); /* wait ~10mS */
1011 * next we do a STARTUP IPI: the previous INIT IPI might still be
1012 * latched, (P5 bug) this 1st STARTUP would then terminate
1013 * immediately, and the previously started INIT IPI would continue. OR
1014 * the previous INIT IPI has already run. and this STARTUP IPI will
1015 * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
1019 /* do a STARTUP IPI */
1020 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1021 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1024 DELAY(200); /* wait ~200uS */
1027 * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
1028 * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
1029 * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
1030 * recognized after hardware RESET or INIT IPI.
1033 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1034 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1037 DELAY(200); /* wait ~200uS */
1039 /* Wait up to 5 seconds for it to start. */
1040 for (ms = 0; ms < 5000; ms++) {
1042 return 1; /* return SUCCESS */
1045 return 0; /* return FAILURE */
1049 * Flush the TLB on all other CPU's
1052 smp_tlb_shootdown(u_int vector, vm_offset_t addr1, vm_offset_t addr2)
1056 ncpu = mp_ncpus - 1; /* does not shootdown self */
1058 return; /* no other cpus */
1059 if (!(read_rflags() & PSL_I))
1060 panic("%s: interrupts disabled", __func__);
1061 mtx_lock_spin(&smp_ipi_mtx);
1062 smp_tlb_addr1 = addr1;
1063 smp_tlb_addr2 = addr2;
1064 atomic_store_rel_int(&smp_tlb_wait, 0);
1065 ipi_all_but_self(vector);
1066 while (smp_tlb_wait < ncpu)
1068 mtx_unlock_spin(&smp_ipi_mtx);
1072 smp_targeted_tlb_shootdown(cpumask_t mask, u_int vector, vm_offset_t addr1, vm_offset_t addr2)
1074 int ncpu, othercpus;
1076 othercpus = mp_ncpus - 1;
1077 if (mask == (cpumask_t)-1) {
1082 mask &= ~PCPU_GET(cpumask);
1085 ncpu = bitcount32(mask);
1086 if (ncpu > othercpus) {
1087 /* XXX this should be a panic offence */
1088 printf("SMP: tlb shootdown to %d other cpus (only have %d)\n",
1092 /* XXX should be a panic, implied by mask == 0 above */
1096 if (!(read_rflags() & PSL_I))
1097 panic("%s: interrupts disabled", __func__);
1098 mtx_lock_spin(&smp_ipi_mtx);
1099 smp_tlb_addr1 = addr1;
1100 smp_tlb_addr2 = addr2;
1101 atomic_store_rel_int(&smp_tlb_wait, 0);
1102 if (mask == (cpumask_t)-1)
1103 ipi_all_but_self(vector);
1105 ipi_selected(mask, vector);
1106 while (smp_tlb_wait < ncpu)
1108 mtx_unlock_spin(&smp_ipi_mtx);
1112 * Send an IPI to specified CPU handling the bitmap logic.
1115 ipi_send_cpu(int cpu, u_int ipi)
1117 u_int bitmap, old_pending, new_pending;
1119 KASSERT(cpu_apic_ids[cpu] != -1, ("IPI to non-existent CPU %d", cpu));
1121 if (IPI_IS_BITMAPED(ipi)) {
1123 ipi = IPI_BITMAP_VECTOR;
1125 old_pending = cpu_ipi_pending[cpu];
1126 new_pending = old_pending | bitmap;
1127 } while (!atomic_cmpset_int(&cpu_ipi_pending[cpu],
1128 old_pending, new_pending));
1132 lapic_ipi_vectored(ipi, cpu_apic_ids[cpu]);
1136 smp_cache_flush(void)
1140 smp_tlb_shootdown(IPI_INVLCACHE, 0, 0);
1148 smp_tlb_shootdown(IPI_INVLTLB, 0, 0);
1153 smp_invlpg(vm_offset_t addr)
1157 smp_tlb_shootdown(IPI_INVLPG, addr, 0);
1161 smp_invlpg_range(vm_offset_t addr1, vm_offset_t addr2)
1165 smp_tlb_shootdown(IPI_INVLRNG, addr1, addr2);
1170 smp_masked_invltlb(cpumask_t mask)
1174 smp_targeted_tlb_shootdown(mask, IPI_INVLTLB, 0, 0);
1179 smp_masked_invlpg(cpumask_t mask, vm_offset_t addr)
1183 smp_targeted_tlb_shootdown(mask, IPI_INVLPG, addr, 0);
1188 smp_masked_invlpg_range(cpumask_t mask, vm_offset_t addr1, vm_offset_t addr2)
1192 smp_targeted_tlb_shootdown(mask, IPI_INVLRNG, addr1, addr2);
1197 ipi_bitmap_handler(struct trapframe frame)
1199 int cpu = PCPU_GET(cpuid);
1202 ipi_bitmap = atomic_readandclear_int(&cpu_ipi_pending[cpu]);
1204 if (ipi_bitmap & (1 << IPI_PREEMPT))
1205 sched_preempt(curthread);
1207 /* Nothing to do for AST */
1209 if (ipi_bitmap & (1 << IPI_HARDCLOCK))
1210 hardclockintr(&frame);
1212 if (ipi_bitmap & (1 << IPI_STATCLOCK))
1213 statclockintr(&frame);
1215 if (ipi_bitmap & (1 << IPI_PROFCLOCK))
1216 profclockintr(&frame);
1220 * send an IPI to a set of cpus.
1223 ipi_selected(cpumask_t cpus, u_int ipi)
1228 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1229 * of help in order to understand what is the source.
1230 * Set the mask of receiving CPUs for this purpose.
1232 if (ipi == IPI_STOP_HARD)
1233 atomic_set_int(&ipi_nmi_pending, cpus);
1235 CTR3(KTR_SMP, "%s: cpus: %x ipi: %x", __func__, cpus, ipi);
1236 while ((cpu = ffs(cpus)) != 0) {
1238 cpus &= ~(1 << cpu);
1239 ipi_send_cpu(cpu, ipi);
1244 * send an IPI to a specific CPU.
1247 ipi_cpu(int cpu, u_int ipi)
1251 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1252 * of help in order to understand what is the source.
1253 * Set the mask of receiving CPUs for this purpose.
1255 if (ipi == IPI_STOP_HARD)
1256 atomic_set_int(&ipi_nmi_pending, 1 << cpu);
1258 CTR3(KTR_SMP, "%s: cpu: %d ipi: %x", __func__, cpu, ipi);
1259 ipi_send_cpu(cpu, ipi);
1263 * send an IPI to all CPUs EXCEPT myself
1266 ipi_all_but_self(u_int ipi)
1269 if (IPI_IS_BITMAPED(ipi)) {
1270 ipi_selected(PCPU_GET(other_cpus), ipi);
1275 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1276 * of help in order to understand what is the source.
1277 * Set the mask of receiving CPUs for this purpose.
1279 if (ipi == IPI_STOP_HARD)
1280 atomic_set_int(&ipi_nmi_pending, PCPU_GET(other_cpus));
1282 CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1283 lapic_ipi_vectored(ipi, APIC_IPI_DEST_OTHERS);
1292 * As long as there is not a simple way to know about a NMI's
1293 * source, if the bitmask for the current CPU is present in
1294 * the global pending bitword an IPI_STOP_HARD has been issued
1295 * and should be handled.
1297 cpumask = PCPU_GET(cpumask);
1298 if ((ipi_nmi_pending & cpumask) == 0)
1301 atomic_clear_int(&ipi_nmi_pending, cpumask);
1307 * Handle an IPI_STOP by saving our current context and spinning until we
1311 cpustop_handler(void)
1316 cpu = PCPU_GET(cpuid);
1317 cpumask = PCPU_GET(cpumask);
1319 savectx(&stoppcbs[cpu]);
1321 /* Indicate that we are stopped */
1322 atomic_set_int(&stopped_cpus, cpumask);
1324 /* Wait for restart */
1325 while (!(started_cpus & cpumask))
1328 atomic_clear_int(&started_cpus, cpumask);
1329 atomic_clear_int(&stopped_cpus, cpumask);
1331 if (cpu == 0 && cpustop_restartfunc != NULL) {
1332 cpustop_restartfunc();
1333 cpustop_restartfunc = NULL;
1338 * Handle an IPI_SUSPEND by saving our current context and spinning until we
1342 cpususpend_handler(void)
1348 cpu = PCPU_GET(cpuid);
1349 cpumask = PCPU_GET(cpumask);
1351 rf = intr_disable();
1354 if (savectx(susppcbs[cpu])) {
1355 fpususpend(suspfpusave[cpu]);
1357 atomic_set_int(&stopped_cpus, cpumask);
1360 PCPU_SET(switchtime, 0);
1361 PCPU_SET(switchticks, ticks);
1364 /* Wait for resume */
1365 while (!(started_cpus & cpumask))
1368 /* Restore CR3 and enable interrupts */
1373 atomic_clear_int(&started_cpus, cpumask);
1374 atomic_clear_int(&stopped_cpus, cpumask);
1380 * This is called once the rest of the system is up and running and we're
1381 * ready to let the AP's out of the pen.
1384 release_aps(void *dummy __unused)
1389 atomic_store_rel_int(&aps_ready, 1);
1390 while (smp_started == 0)
1393 SYSINIT(start_aps, SI_SUB_SMP, SI_ORDER_FIRST, release_aps, NULL);
1396 sysctl_hlt_cpus(SYSCTL_HANDLER_ARGS)
1401 mask = hlt_cpus_mask;
1402 error = sysctl_handle_int(oidp, &mask, 0, req);
1403 if (error || !req->newptr)
1406 if (logical_cpus_mask != 0 &&
1407 (mask & logical_cpus_mask) == logical_cpus_mask)
1408 hlt_logical_cpus = 1;
1410 hlt_logical_cpus = 0;
1412 if (! hyperthreading_allowed)
1413 mask |= hyperthreading_cpus_mask;
1415 if ((mask & all_cpus) == all_cpus)
1417 hlt_cpus_mask = mask;
1420 SYSCTL_PROC(_machdep, OID_AUTO, hlt_cpus, CTLTYPE_INT|CTLFLAG_RW,
1421 0, 0, sysctl_hlt_cpus, "IU",
1422 "Bitmap of CPUs to halt. 101 (binary) will halt CPUs 0 and 2.");
1425 sysctl_hlt_logical_cpus(SYSCTL_HANDLER_ARGS)
1429 disable = hlt_logical_cpus;
1430 error = sysctl_handle_int(oidp, &disable, 0, req);
1431 if (error || !req->newptr)
1435 hlt_cpus_mask |= logical_cpus_mask;
1437 hlt_cpus_mask &= ~logical_cpus_mask;
1439 if (! hyperthreading_allowed)
1440 hlt_cpus_mask |= hyperthreading_cpus_mask;
1442 if ((hlt_cpus_mask & all_cpus) == all_cpus)
1443 hlt_cpus_mask &= ~(1<<0);
1445 hlt_logical_cpus = disable;
1450 sysctl_hyperthreading_allowed(SYSCTL_HANDLER_ARGS)
1454 allowed = hyperthreading_allowed;
1455 error = sysctl_handle_int(oidp, &allowed, 0, req);
1456 if (error || !req->newptr)
1461 * SCHED_ULE doesn't allow enabling/disabling HT cores at
1464 if (allowed != hyperthreading_allowed)
1470 hlt_cpus_mask &= ~hyperthreading_cpus_mask;
1472 hlt_cpus_mask |= hyperthreading_cpus_mask;
1474 if (logical_cpus_mask != 0 &&
1475 (hlt_cpus_mask & logical_cpus_mask) == logical_cpus_mask)
1476 hlt_logical_cpus = 1;
1478 hlt_logical_cpus = 0;
1480 if ((hlt_cpus_mask & all_cpus) == all_cpus)
1481 hlt_cpus_mask &= ~(1<<0);
1483 hyperthreading_allowed = allowed;
1488 cpu_hlt_setup(void *dummy __unused)
1491 if (logical_cpus_mask != 0) {
1492 TUNABLE_INT_FETCH("machdep.hlt_logical_cpus",
1494 sysctl_ctx_init(&logical_cpu_clist);
1495 SYSCTL_ADD_PROC(&logical_cpu_clist,
1496 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1497 "hlt_logical_cpus", CTLTYPE_INT|CTLFLAG_RW, 0, 0,
1498 sysctl_hlt_logical_cpus, "IU", "");
1499 SYSCTL_ADD_UINT(&logical_cpu_clist,
1500 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1501 "logical_cpus_mask", CTLTYPE_INT|CTLFLAG_RD,
1502 &logical_cpus_mask, 0, "");
1504 if (hlt_logical_cpus)
1505 hlt_cpus_mask |= logical_cpus_mask;
1508 * If necessary for security purposes, force
1509 * hyperthreading off, regardless of the value
1510 * of hlt_logical_cpus.
1512 if (hyperthreading_cpus_mask) {
1513 SYSCTL_ADD_PROC(&logical_cpu_clist,
1514 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1515 "hyperthreading_allowed", CTLTYPE_INT|CTLFLAG_RW,
1516 0, 0, sysctl_hyperthreading_allowed, "IU", "");
1517 if (! hyperthreading_allowed)
1518 hlt_cpus_mask |= hyperthreading_cpus_mask;
1522 SYSINIT(cpu_hlt, SI_SUB_SMP, SI_ORDER_ANY, cpu_hlt_setup, NULL);
1525 mp_grab_cpu_hlt(void)
1533 mask = PCPU_GET(cpumask);
1535 cpuid = PCPU_GET(cpuid);
1540 while (mask & hlt_cpus_mask) {
1542 __asm __volatile("sti; hlt" : : : "memory");