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"
32 #include "opt_mp_watchdog.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() */
56 #include <sys/kernel.h>
59 #include <sys/malloc.h>
60 #include <sys/memrange.h>
61 #include <sys/mutex.h>
64 #include <sys/sched.h>
66 #include <sys/sysctl.h>
69 #include <vm/vm_param.h>
71 #include <vm/vm_kern.h>
72 #include <vm/vm_extern.h>
74 #include <machine/apicreg.h>
75 #include <machine/clock.h>
76 #include <machine/cputypes.h>
77 #include <machine/mca.h>
78 #include <machine/md_var.h>
79 #include <machine/mp_watchdog.h>
80 #include <machine/pcb.h>
81 #include <machine/psl.h>
82 #include <machine/smp.h>
83 #include <machine/specialreg.h>
85 #define WARMBOOT_TARGET 0
86 #define WARMBOOT_OFF (KERNBASE + 0x0467)
87 #define WARMBOOT_SEG (KERNBASE + 0x0469)
89 #define CMOS_REG (0x70)
90 #define CMOS_DATA (0x71)
91 #define BIOS_RESET (0x0f)
92 #define BIOS_WARM (0x0a)
95 * this code MUST be enabled here and in mpboot.s.
96 * it follows the very early stages of AP boot by placing values in CMOS ram.
97 * it NORMALLY will never be needed and thus the primitive method for enabling.
102 #if defined(CHECK_POINTS) && !defined(PC98)
103 #define CHECK_READ(A) (outb(CMOS_REG, (A)), inb(CMOS_DATA))
104 #define CHECK_WRITE(A,D) (outb(CMOS_REG, (A)), outb(CMOS_DATA, (D)))
106 #define CHECK_INIT(D); \
107 CHECK_WRITE(0x34, (D)); \
108 CHECK_WRITE(0x35, (D)); \
109 CHECK_WRITE(0x36, (D)); \
110 CHECK_WRITE(0x37, (D)); \
111 CHECK_WRITE(0x38, (D)); \
112 CHECK_WRITE(0x39, (D));
114 #define CHECK_PRINT(S); \
115 printf("%s: %d, %d, %d, %d, %d, %d\n", \
124 #else /* CHECK_POINTS */
126 #define CHECK_INIT(D)
127 #define CHECK_PRINT(S)
128 #define CHECK_WRITE(A, D)
130 #endif /* CHECK_POINTS */
132 /* lock region used by kernel profiling */
135 int mp_naps; /* # of Applications processors */
136 int boot_cpu_id = -1; /* designated BSP */
138 extern struct pcpu __pcpu[];
140 /* AP uses this during bootstrap. Do not staticize. */
144 /* Free these after use */
145 void *bootstacks[MAXCPU];
148 /* Hotwire a 0->4MB V==P mapping */
149 extern pt_entry_t *KPTphys;
151 struct pcb stoppcbs[MAXCPU];
153 /* Variables needed for SMP tlb shootdown. */
154 vm_offset_t smp_tlb_addr1;
155 vm_offset_t smp_tlb_addr2;
156 volatile int smp_tlb_wait;
159 /* Interrupt counts. */
160 static u_long *ipi_preempt_counts[MAXCPU];
161 static u_long *ipi_ast_counts[MAXCPU];
162 u_long *ipi_invltlb_counts[MAXCPU];
163 u_long *ipi_invlrng_counts[MAXCPU];
164 u_long *ipi_invlpg_counts[MAXCPU];
165 u_long *ipi_invlcache_counts[MAXCPU];
166 u_long *ipi_rendezvous_counts[MAXCPU];
167 u_long *ipi_lazypmap_counts[MAXCPU];
171 * Local data and functions.
174 static u_int logical_cpus;
175 static volatile cpumask_t ipi_nmi_pending;
177 /* used to hold the AP's until we are ready to release them */
178 static struct mtx ap_boot_mtx;
180 /* Set to 1 once we're ready to let the APs out of the pen. */
181 static volatile int aps_ready = 0;
184 * Store data from cpu_add() until later in the boot when we actually setup
191 int cpu_hyperthread:1;
192 } static cpu_info[MAX_APIC_ID + 1];
193 int cpu_apic_ids[MAXCPU];
194 int apic_cpuids[MAX_APIC_ID + 1];
196 /* Holds pending bitmap based IPIs per CPU */
197 static volatile u_int cpu_ipi_pending[MAXCPU];
199 static u_int boot_address;
200 static int cpu_logical;
201 static int cpu_cores;
203 static void assign_cpu_ids(void);
204 static void install_ap_tramp(void);
205 static void set_interrupt_apic_ids(void);
206 static int start_all_aps(void);
207 static int start_ap(int apic_id);
208 static void release_aps(void *dummy);
210 static int hlt_logical_cpus;
211 static u_int hyperthreading_cpus;
212 static cpumask_t hyperthreading_cpus_mask;
213 static int hyperthreading_allowed = 1;
214 static struct sysctl_ctx_list logical_cpu_clist;
217 mem_range_AP_init(void)
219 if (mem_range_softc.mr_op && mem_range_softc.mr_op->initAP)
220 mem_range_softc.mr_op->initAP(&mem_range_softc);
234 /* We only support two levels for now. */
235 for (i = 0; i < 3; i++) {
236 cpuid_count(0x0B, i, p);
238 logical = p[1] &= 0xffff;
239 type = (p[2] >> 8) & 0xff;
240 if (type == 0 || logical == 0)
242 for (cnt = 0, x = 0; x <= MAX_APIC_ID; x++) {
243 if (!cpu_info[x].cpu_present ||
244 cpu_info[x].cpu_disabled)
246 if (x >> bits == boot_cpu_id >> bits)
249 if (type == CPUID_TYPE_SMT)
251 else if (type == CPUID_TYPE_CORE)
254 if (cpu_logical == 0)
256 cpu_cores /= cpu_logical;
262 u_int threads_per_cache, p[4];
268 * If this CPU supports HTT or CMP then mention the
269 * number of physical/logical cores it contains.
271 if (cpu_feature & CPUID_HTT)
272 htt = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
273 if (cpu_vendor_id == CPU_VENDOR_AMD && (amd_feature2 & AMDID2_CMP))
274 cmp = (cpu_procinfo2 & AMDID_CMP_CORES) + 1;
275 else if (cpu_vendor_id == CPU_VENDOR_INTEL && (cpu_high >= 4)) {
276 cpuid_count(4, 0, p);
277 if ((p[0] & 0x1f) != 0)
278 cmp = ((p[0] >> 26) & 0x3f) + 1;
281 cpu_logical = htt / cmp;
283 /* Setup the initial logical CPUs info. */
284 if (cpu_feature & CPUID_HTT)
285 logical_cpus = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
288 * Work out if hyperthreading is *really* enabled. This
289 * is made really ugly by the fact that processors lie: Dual
290 * core processors claim to be hyperthreaded even when they're
291 * not, presumably because they want to be treated the same
292 * way as HTT with respect to per-cpu software licensing.
293 * At the time of writing (May 12, 2005) the only hyperthreaded
294 * cpus are from Intel, and Intel's dual-core processors can be
295 * identified via the "deterministic cache parameters" cpuid
299 * First determine if this is an Intel processor which claims
300 * to have hyperthreading support.
302 if ((cpu_feature & CPUID_HTT) && cpu_vendor_id == CPU_VENDOR_INTEL) {
304 * If the "deterministic cache parameters" cpuid calls
305 * are available, use them.
308 /* Ask the processor about the L1 cache. */
309 for (i = 0; i < 1; i++) {
310 cpuid_count(4, i, p);
311 threads_per_cache = ((p[0] & 0x3ffc000) >> 14) + 1;
312 if (hyperthreading_cpus < threads_per_cache)
313 hyperthreading_cpus = threads_per_cache;
314 if ((p[0] & 0x1f) == 0)
320 * If the deterministic cache parameters are not
321 * available, or if no caches were reported to exist,
322 * just accept what the HTT flag indicated.
324 if (hyperthreading_cpus == 0)
325 hyperthreading_cpus = logical_cpus;
332 static int cpu_topo_probed = 0;
337 logical_cpus = logical_cpus_mask = 0;
343 cpu_cores = mp_ncpus > 0 ? mp_ncpus : 1;
344 if (cpu_logical == 0)
355 * Determine whether any threading flags are
359 if (cpu_logical > 1 && hyperthreading_cpus)
360 cg_flags = CG_FLAG_HTT;
361 else if (cpu_logical > 1)
362 cg_flags = CG_FLAG_SMT;
365 if (mp_ncpus % (cpu_cores * cpu_logical) != 0) {
366 printf("WARNING: Non-uniform processors.\n");
367 printf("WARNING: Using suboptimal topology.\n");
368 return (smp_topo_none());
371 * No multi-core or hyper-threaded.
373 if (cpu_logical * cpu_cores == 1)
374 return (smp_topo_none());
376 * Only HTT no multi-core.
378 if (cpu_logical > 1 && cpu_cores == 1)
379 return (smp_topo_1level(CG_SHARE_L1, cpu_logical, cg_flags));
381 * Only multi-core no HTT.
383 if (cpu_cores > 1 && cpu_logical == 1)
384 return (smp_topo_1level(CG_SHARE_L2, cpu_cores, cg_flags));
386 * Both HTT and multi-core.
388 return (smp_topo_2level(CG_SHARE_L2, cpu_cores,
389 CG_SHARE_L1, cpu_logical, cg_flags));
394 * Calculate usable address in base memory for AP trampoline code.
397 mp_bootaddress(u_int basemem)
400 boot_address = trunc_page(basemem); /* round down to 4k boundary */
401 if ((basemem - boot_address) < bootMP_size)
402 boot_address -= PAGE_SIZE; /* not enough, lower by 4k */
408 cpu_add(u_int apic_id, char boot_cpu)
411 if (apic_id > MAX_APIC_ID) {
412 panic("SMP: APIC ID %d too high", apic_id);
415 KASSERT(cpu_info[apic_id].cpu_present == 0, ("CPU %d added twice",
417 cpu_info[apic_id].cpu_present = 1;
419 KASSERT(boot_cpu_id == -1,
420 ("CPU %d claims to be BSP, but CPU %d already is", apic_id,
422 boot_cpu_id = apic_id;
423 cpu_info[apic_id].cpu_bsp = 1;
425 if (mp_ncpus < MAXCPU)
428 printf("SMP: Added CPU %d (%s)\n", apic_id, boot_cpu ? "BSP" :
433 cpu_mp_setmaxid(void)
436 mp_maxid = MAXCPU - 1;
444 * Always record BSP in CPU map so that the mbuf init code works
450 * No CPUs were found, so this must be a UP system. Setup
451 * the variables to represent a system with a single CPU
458 /* At least one CPU was found. */
461 * One CPU was found, so this must be a UP system with
467 /* At least two CPUs were found. */
472 * Initialize the IPI handlers and start up the AP's.
479 /* Initialize the logical ID to APIC ID table. */
480 for (i = 0; i < MAXCPU; i++) {
481 cpu_apic_ids[i] = -1;
482 cpu_ipi_pending[i] = 0;
485 /* Install an inter-CPU IPI for TLB invalidation */
486 setidt(IPI_INVLTLB, IDTVEC(invltlb),
487 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
488 setidt(IPI_INVLPG, IDTVEC(invlpg),
489 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
490 setidt(IPI_INVLRNG, IDTVEC(invlrng),
491 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
493 /* Install an inter-CPU IPI for cache invalidation. */
494 setidt(IPI_INVLCACHE, IDTVEC(invlcache),
495 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
497 /* Install an inter-CPU IPI for lazy pmap release */
498 setidt(IPI_LAZYPMAP, IDTVEC(lazypmap),
499 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
501 /* Install an inter-CPU IPI for all-CPU rendezvous */
502 setidt(IPI_RENDEZVOUS, IDTVEC(rendezvous),
503 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
505 /* Install generic inter-CPU IPI handler */
506 setidt(IPI_BITMAP_VECTOR, IDTVEC(ipi_intr_bitmap_handler),
507 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
509 /* Install an inter-CPU IPI for CPU stop/restart */
510 setidt(IPI_STOP, IDTVEC(cpustop),
511 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
514 /* Set boot_cpu_id if needed. */
515 if (boot_cpu_id == -1) {
516 boot_cpu_id = PCPU_GET(apic_id);
517 cpu_info[boot_cpu_id].cpu_bsp = 1;
519 KASSERT(boot_cpu_id == PCPU_GET(apic_id),
520 ("BSP's APIC ID doesn't match boot_cpu_id"));
522 /* Probe logical/physical core configuration. */
527 /* Start each Application Processor */
530 set_interrupt_apic_ids();
535 * Print various information about the SMP system hardware and setup.
538 cpu_mp_announce(void)
540 const char *hyperthread;
543 printf("FreeBSD/SMP: %d package(s) x %d core(s)",
544 mp_ncpus / (cpu_cores * cpu_logical), cpu_cores);
545 if (hyperthreading_cpus > 1)
546 printf(" x %d HTT threads", cpu_logical);
547 else if (cpu_logical > 1)
548 printf(" x %d SMT threads", cpu_logical);
551 /* List active CPUs first. */
552 printf(" cpu0 (BSP): APIC ID: %2d\n", boot_cpu_id);
553 for (i = 1; i < mp_ncpus; i++) {
554 if (cpu_info[cpu_apic_ids[i]].cpu_hyperthread)
558 printf(" cpu%d (AP%s): APIC ID: %2d\n", i, hyperthread,
562 /* List disabled CPUs last. */
563 for (i = 0; i <= MAX_APIC_ID; i++) {
564 if (!cpu_info[i].cpu_present || !cpu_info[i].cpu_disabled)
566 if (cpu_info[i].cpu_hyperthread)
570 printf(" cpu (AP%s): APIC ID: %2d (disabled)\n", hyperthread,
576 * AP CPU's call this to initialize themselves.
587 /* bootAP is set in start_ap() to our ID. */
590 /* Get per-cpu data */
593 /* prime data page for it to use */
594 pcpu_init(pc, myid, sizeof(struct pcpu));
595 dpcpu_init(dpcpu, myid);
596 pc->pc_apic_id = cpu_apic_ids[myid];
597 pc->pc_prvspace = pc;
598 pc->pc_curthread = 0;
600 gdt_segs[GPRIV_SEL].ssd_base = (int) pc;
601 gdt_segs[GPROC0_SEL].ssd_base = (int) &pc->pc_common_tss;
603 for (x = 0; x < NGDT; x++) {
604 ssdtosd(&gdt_segs[x], &gdt[myid * NGDT + x].sd);
607 r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
608 r_gdt.rd_base = (int) &gdt[myid * NGDT];
609 lgdt(&r_gdt); /* does magic intra-segment return */
614 PCPU_SET(currentldt, _default_ldt);
616 gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
617 gdt[myid * NGDT + GPROC0_SEL].sd.sd_type = SDT_SYS386TSS;
618 PCPU_SET(common_tss.tss_esp0, 0); /* not used until after switch */
619 PCPU_SET(common_tss.tss_ss0, GSEL(GDATA_SEL, SEL_KPL));
620 PCPU_SET(common_tss.tss_ioopt, (sizeof (struct i386tss)) << 16);
621 PCPU_SET(tss_gdt, &gdt[myid * NGDT + GPROC0_SEL].sd);
622 PCPU_SET(common_tssd, *PCPU_GET(tss_gdt));
625 PCPU_SET(fsgs_gdt, &gdt[myid * NGDT + GUFS_SEL].sd);
628 * Set to a known state:
629 * Set by mpboot.s: CR0_PG, CR0_PE
630 * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
633 cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
635 CHECK_WRITE(0x38, 5);
637 /* Disable local APIC just to be sure. */
640 /* signal our startup to the BSP. */
642 CHECK_WRITE(0x39, 6);
644 /* Spin until the BSP releases the AP's. */
648 /* BSP may have changed PTD while we were waiting */
650 for (addr = 0; addr < NKPT * NBPDR - 1; addr += PAGE_SIZE)
653 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
657 /* Initialize the PAT MSR if present. */
660 /* set up CPU registers and state */
663 /* set up FPU state on the AP */
666 /* set up SSE registers */
670 /* Enable the PTE no-execute bit. */
671 if ((amd_feature & AMDID_NX) != 0) {
674 msr = rdmsr(MSR_EFER) | EFER_NXE;
675 wrmsr(MSR_EFER, msr);
679 /* A quick check from sanity claus */
680 if (PCPU_GET(apic_id) != lapic_id()) {
681 printf("SMP: cpuid = %d\n", PCPU_GET(cpuid));
682 printf("SMP: actual apic_id = %d\n", lapic_id());
683 printf("SMP: correct apic_id = %d\n", PCPU_GET(apic_id));
684 panic("cpuid mismatch! boom!!");
687 /* Initialize curthread. */
688 KASSERT(PCPU_GET(idlethread) != NULL, ("no idle thread"));
689 PCPU_SET(curthread, PCPU_GET(idlethread));
693 mtx_lock_spin(&ap_boot_mtx);
695 /* Init local apic for irq's */
698 /* Set memory range attributes for this CPU to match the BSP */
703 CTR1(KTR_SMP, "SMP: AP CPU #%d Launched", PCPU_GET(cpuid));
704 printf("SMP: AP CPU #%d Launched!\n", PCPU_GET(cpuid));
706 /* Determine if we are a logical CPU. */
707 if (logical_cpus > 1 && PCPU_GET(apic_id) % logical_cpus != 0)
708 logical_cpus_mask |= PCPU_GET(cpumask);
710 /* Determine if we are a hyperthread. */
711 if (hyperthreading_cpus > 1 &&
712 PCPU_GET(apic_id) % hyperthreading_cpus != 0)
713 hyperthreading_cpus_mask |= PCPU_GET(cpumask);
715 /* Build our map of 'other' CPUs. */
716 PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
721 if (smp_cpus == mp_ncpus) {
722 /* enable IPI's, tlb shootdown, freezes etc */
723 atomic_store_rel_int(&smp_started, 1);
724 smp_active = 1; /* historic */
727 mtx_unlock_spin(&ap_boot_mtx);
729 /* wait until all the AP's are up */
730 while (smp_started == 0)
733 /* enter the scheduler */
736 panic("scheduler returned us to %s", __func__);
740 /*******************************************************************
741 * local functions and data
745 * We tell the I/O APIC code about all the CPUs we want to receive
746 * interrupts. If we don't want certain CPUs to receive IRQs we
747 * can simply not tell the I/O APIC code about them in this function.
748 * We also do not tell it about the BSP since it tells itself about
749 * the BSP internally to work with UP kernels and on UP machines.
752 set_interrupt_apic_ids(void)
756 for (i = 0; i < MAXCPU; i++) {
757 apic_id = cpu_apic_ids[i];
760 if (cpu_info[apic_id].cpu_bsp)
762 if (cpu_info[apic_id].cpu_disabled)
765 /* Don't let hyperthreads service interrupts. */
766 if (hyperthreading_cpus > 1 &&
767 apic_id % hyperthreading_cpus != 0)
775 * Assign logical CPU IDs to local APICs.
782 TUNABLE_INT_FETCH("machdep.hyperthreading_allowed",
783 &hyperthreading_allowed);
785 /* Check for explicitly disabled CPUs. */
786 for (i = 0; i <= MAX_APIC_ID; i++) {
787 if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp)
790 if (hyperthreading_cpus > 1 && i % hyperthreading_cpus != 0) {
791 cpu_info[i].cpu_hyperthread = 1;
792 #if defined(SCHED_ULE)
794 * Don't use HT CPU if it has been disabled by a
797 if (hyperthreading_allowed == 0) {
798 cpu_info[i].cpu_disabled = 1;
804 /* Don't use this CPU if it has been disabled by a tunable. */
805 if (resource_disabled("lapic", i)) {
806 cpu_info[i].cpu_disabled = 1;
812 * Assign CPU IDs to local APIC IDs and disable any CPUs
813 * beyond MAXCPU. CPU 0 is always assigned to the BSP.
815 * To minimize confusion for userland, we attempt to number
816 * CPUs such that all threads and cores in a package are
817 * grouped together. For now we assume that the BSP is always
818 * the first thread in a package and just start adding APs
819 * starting with the BSP's APIC ID.
822 cpu_apic_ids[0] = boot_cpu_id;
823 apic_cpuids[boot_cpu_id] = 0;
824 for (i = boot_cpu_id + 1; i != boot_cpu_id;
825 i == MAX_APIC_ID ? i = 0 : i++) {
826 if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp ||
827 cpu_info[i].cpu_disabled)
830 if (mp_ncpus < MAXCPU) {
831 cpu_apic_ids[mp_ncpus] = i;
832 apic_cpuids[i] = mp_ncpus;
835 cpu_info[i].cpu_disabled = 1;
837 KASSERT(mp_maxid >= mp_ncpus - 1,
838 ("%s: counters out of sync: max %d, count %d", __func__, mp_maxid,
843 * start each AP in our list
845 /* Lowest 1MB is already mapped: don't touch*/
846 #define TMPMAP_START 1
854 u_int32_t mpbioswarmvec;
857 mtx_init(&ap_boot_mtx, "ap boot", NULL, MTX_SPIN);
859 /* install the AP 1st level boot code */
862 /* save the current value of the warm-start vector */
863 mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
865 outb(CMOS_REG, BIOS_RESET);
866 mpbiosreason = inb(CMOS_DATA);
869 /* set up temporary P==V mapping for AP boot */
870 /* XXX this is a hack, we should boot the AP on its own stack/PTD */
872 kptbase = (uintptr_t)(void *)KPTphys;
873 for (i = TMPMAP_START; i < NKPT; i++)
874 PTD[i] = (pd_entry_t)(PG_V | PG_RW |
875 ((kptbase + i * PAGE_SIZE) & PG_FRAME));
879 for (cpu = 1; cpu < mp_ncpus; cpu++) {
880 apic_id = cpu_apic_ids[cpu];
882 /* allocate and set up a boot stack data page */
884 (char *)kmem_alloc(kernel_map, KSTACK_PAGES * PAGE_SIZE);
885 dpcpu = (void *)kmem_alloc(kernel_map, DPCPU_SIZE);
886 /* setup a vector to our boot code */
887 *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
888 *((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
890 outb(CMOS_REG, BIOS_RESET);
891 outb(CMOS_DATA, BIOS_WARM); /* 'warm-start' */
894 bootSTK = (char *)bootstacks[cpu] + KSTACK_PAGES * PAGE_SIZE - 4;
897 /* attempt to start the Application Processor */
898 CHECK_INIT(99); /* setup checkpoints */
899 if (!start_ap(apic_id)) {
900 printf("AP #%d (PHY# %d) failed!\n", cpu, apic_id);
901 CHECK_PRINT("trace"); /* show checkpoints */
902 /* better panic as the AP may be running loose */
903 printf("panic y/n? [y] ");
907 CHECK_PRINT("trace"); /* show checkpoints */
909 all_cpus |= (1 << cpu); /* record AP in CPU map */
912 /* build our map of 'other' CPUs */
913 PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
915 /* restore the warmstart vector */
916 *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
919 outb(CMOS_REG, BIOS_RESET);
920 outb(CMOS_DATA, mpbiosreason);
923 /* Undo V==P hack from above */
924 for (i = TMPMAP_START; i < NKPT; i++)
926 pmap_invalidate_range(kernel_pmap, 0, NKPT * NBPDR - 1);
928 /* number of APs actually started */
933 * load the 1st level AP boot code into base memory.
936 /* targets for relocation */
937 extern void bigJump(void);
938 extern void bootCodeSeg(void);
939 extern void bootDataSeg(void);
940 extern void MPentry(void);
942 extern u_int mp_gdtbase;
945 install_ap_tramp(void)
948 int size = *(int *) ((u_long) & bootMP_size);
949 vm_offset_t va = boot_address + KERNBASE;
950 u_char *src = (u_char *) ((u_long) bootMP);
951 u_char *dst = (u_char *) va;
952 u_int boot_base = (u_int) bootMP;
957 KASSERT (size <= PAGE_SIZE,
958 ("'size' do not fit into PAGE_SIZE, as expected."));
959 pmap_kenter(va, boot_address);
960 pmap_invalidate_page (kernel_pmap, va);
961 for (x = 0; x < size; ++x)
965 * modify addresses in code we just moved to basemem. unfortunately we
966 * need fairly detailed info about mpboot.s for this to work. changes
967 * to mpboot.s might require changes here.
970 /* boot code is located in KERNEL space */
973 /* modify the lgdt arg */
974 dst32 = (u_int32_t *) (dst + ((u_int) & mp_gdtbase - boot_base));
975 *dst32 = boot_address + ((u_int) & MP_GDT - boot_base);
977 /* modify the ljmp target for MPentry() */
978 dst32 = (u_int32_t *) (dst + ((u_int) bigJump - boot_base) + 1);
979 *dst32 = ((u_int) MPentry - KERNBASE);
981 /* modify the target for boot code segment */
982 dst16 = (u_int16_t *) (dst + ((u_int) bootCodeSeg - boot_base));
983 dst8 = (u_int8_t *) (dst16 + 1);
984 *dst16 = (u_int) boot_address & 0xffff;
985 *dst8 = ((u_int) boot_address >> 16) & 0xff;
987 /* modify the target for boot data segment */
988 dst16 = (u_int16_t *) (dst + ((u_int) bootDataSeg - boot_base));
989 dst8 = (u_int8_t *) (dst16 + 1);
990 *dst16 = (u_int) boot_address & 0xffff;
991 *dst8 = ((u_int) boot_address >> 16) & 0xff;
995 * This function starts the AP (application processor) identified
996 * by the APIC ID 'physicalCpu'. It does quite a "song and dance"
997 * to accomplish this. This is necessary because of the nuances
998 * of the different hardware we might encounter. It isn't pretty,
999 * but it seems to work.
1002 start_ap(int apic_id)
1007 /* calculate the vector */
1008 vector = (boot_address >> 12) & 0xff;
1010 /* used as a watchpoint to signal AP startup */
1014 * first we do an INIT/RESET IPI this INIT IPI might be run, reseting
1015 * and running the target CPU. OR this INIT IPI might be latched (P5
1016 * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
1020 /* do an INIT IPI: assert RESET */
1021 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1022 APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, apic_id);
1024 /* wait for pending status end */
1027 /* do an INIT IPI: deassert RESET */
1028 lapic_ipi_raw(APIC_DEST_ALLESELF | APIC_TRIGMOD_LEVEL |
1029 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, 0);
1031 /* wait for pending status end */
1032 DELAY(10000); /* wait ~10mS */
1036 * next we do a STARTUP IPI: the previous INIT IPI might still be
1037 * latched, (P5 bug) this 1st STARTUP would then terminate
1038 * immediately, and the previously started INIT IPI would continue. OR
1039 * the previous INIT IPI has already run. and this STARTUP IPI will
1040 * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
1044 /* do a STARTUP IPI */
1045 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1046 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1049 DELAY(200); /* wait ~200uS */
1052 * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
1053 * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
1054 * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
1055 * recognized after hardware RESET or INIT IPI.
1058 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1059 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1062 DELAY(200); /* wait ~200uS */
1064 /* Wait up to 5 seconds for it to start. */
1065 for (ms = 0; ms < 5000; ms++) {
1067 return 1; /* return SUCCESS */
1070 return 0; /* return FAILURE */
1073 #ifdef COUNT_XINVLTLB_HITS
1074 u_int xhits_gbl[MAXCPU];
1075 u_int xhits_pg[MAXCPU];
1076 u_int xhits_rng[MAXCPU];
1077 SYSCTL_NODE(_debug, OID_AUTO, xhits, CTLFLAG_RW, 0, "");
1078 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, global, CTLFLAG_RW, &xhits_gbl,
1079 sizeof(xhits_gbl), "IU", "");
1080 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, page, CTLFLAG_RW, &xhits_pg,
1081 sizeof(xhits_pg), "IU", "");
1082 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, range, CTLFLAG_RW, &xhits_rng,
1083 sizeof(xhits_rng), "IU", "");
1088 u_int ipi_range_size;
1089 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_global, CTLFLAG_RW, &ipi_global, 0, "");
1090 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_page, CTLFLAG_RW, &ipi_page, 0, "");
1091 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range, CTLFLAG_RW, &ipi_range, 0, "");
1092 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range_size, CTLFLAG_RW, &ipi_range_size,
1095 u_int ipi_masked_global;
1096 u_int ipi_masked_page;
1097 u_int ipi_masked_range;
1098 u_int ipi_masked_range_size;
1099 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_global, CTLFLAG_RW,
1100 &ipi_masked_global, 0, "");
1101 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_page, CTLFLAG_RW,
1102 &ipi_masked_page, 0, "");
1103 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_range, CTLFLAG_RW,
1104 &ipi_masked_range, 0, "");
1105 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_range_size, CTLFLAG_RW,
1106 &ipi_masked_range_size, 0, "");
1107 #endif /* COUNT_XINVLTLB_HITS */
1110 * Flush the TLB on all other CPU's
1113 smp_tlb_shootdown(u_int vector, vm_offset_t addr1, vm_offset_t addr2)
1117 ncpu = mp_ncpus - 1; /* does not shootdown self */
1119 return; /* no other cpus */
1120 if (!(read_eflags() & PSL_I))
1121 panic("%s: interrupts disabled", __func__);
1122 mtx_lock_spin(&smp_ipi_mtx);
1123 smp_tlb_addr1 = addr1;
1124 smp_tlb_addr2 = addr2;
1125 atomic_store_rel_int(&smp_tlb_wait, 0);
1126 ipi_all_but_self(vector);
1127 while (smp_tlb_wait < ncpu)
1129 mtx_unlock_spin(&smp_ipi_mtx);
1133 smp_targeted_tlb_shootdown(cpumask_t mask, u_int vector, vm_offset_t addr1, vm_offset_t addr2)
1135 int ncpu, othercpus;
1137 othercpus = mp_ncpus - 1;
1138 if (mask == (u_int)-1) {
1143 mask &= ~PCPU_GET(cpumask);
1146 ncpu = bitcount32(mask);
1147 if (ncpu > othercpus) {
1148 /* XXX this should be a panic offence */
1149 printf("SMP: tlb shootdown to %d other cpus (only have %d)\n",
1153 /* XXX should be a panic, implied by mask == 0 above */
1157 if (!(read_eflags() & PSL_I))
1158 panic("%s: interrupts disabled", __func__);
1159 mtx_lock_spin(&smp_ipi_mtx);
1160 smp_tlb_addr1 = addr1;
1161 smp_tlb_addr2 = addr2;
1162 atomic_store_rel_int(&smp_tlb_wait, 0);
1163 if (mask == (u_int)-1)
1164 ipi_all_but_self(vector);
1166 ipi_selected(mask, vector);
1167 while (smp_tlb_wait < ncpu)
1169 mtx_unlock_spin(&smp_ipi_mtx);
1173 smp_cache_flush(void)
1177 smp_tlb_shootdown(IPI_INVLCACHE, 0, 0);
1185 smp_tlb_shootdown(IPI_INVLTLB, 0, 0);
1186 #ifdef COUNT_XINVLTLB_HITS
1193 smp_invlpg(vm_offset_t addr)
1197 smp_tlb_shootdown(IPI_INVLPG, addr, 0);
1198 #ifdef COUNT_XINVLTLB_HITS
1205 smp_invlpg_range(vm_offset_t addr1, vm_offset_t addr2)
1209 smp_tlb_shootdown(IPI_INVLRNG, addr1, addr2);
1210 #ifdef COUNT_XINVLTLB_HITS
1212 ipi_range_size += (addr2 - addr1) / PAGE_SIZE;
1218 smp_masked_invltlb(cpumask_t mask)
1222 smp_targeted_tlb_shootdown(mask, IPI_INVLTLB, 0, 0);
1223 #ifdef COUNT_XINVLTLB_HITS
1224 ipi_masked_global++;
1230 smp_masked_invlpg(cpumask_t mask, vm_offset_t addr)
1234 smp_targeted_tlb_shootdown(mask, IPI_INVLPG, addr, 0);
1235 #ifdef COUNT_XINVLTLB_HITS
1242 smp_masked_invlpg_range(cpumask_t mask, vm_offset_t addr1, vm_offset_t addr2)
1246 smp_targeted_tlb_shootdown(mask, IPI_INVLRNG, addr1, addr2);
1247 #ifdef COUNT_XINVLTLB_HITS
1249 ipi_masked_range_size += (addr2 - addr1) / PAGE_SIZE;
1255 ipi_bitmap_handler(struct trapframe frame)
1257 int cpu = PCPU_GET(cpuid);
1260 ipi_bitmap = atomic_readandclear_int(&cpu_ipi_pending[cpu]);
1262 if (ipi_bitmap & (1 << IPI_PREEMPT)) {
1264 (*ipi_preempt_counts[cpu])++;
1266 sched_preempt(curthread);
1269 if (ipi_bitmap & (1 << IPI_AST)) {
1271 (*ipi_ast_counts[cpu])++;
1273 /* Nothing to do for AST */
1276 if (ipi_bitmap & (1 << IPI_HARDCLOCK))
1277 hardclockintr(&frame);
1279 if (ipi_bitmap & (1 << IPI_STATCLOCK))
1280 statclockintr(&frame);
1282 if (ipi_bitmap & (1 << IPI_PROFCLOCK))
1283 profclockintr(&frame);
1287 * send an IPI to a set of cpus.
1290 ipi_selected(cpumask_t cpus, u_int ipi)
1297 if (IPI_IS_BITMAPED(ipi)) {
1299 ipi = IPI_BITMAP_VECTOR;
1303 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1304 * of help in order to understand what is the source.
1305 * Set the mask of receiving CPUs for this purpose.
1307 if (ipi == IPI_STOP_HARD)
1308 atomic_set_int(&ipi_nmi_pending, cpus);
1310 CTR3(KTR_SMP, "%s: cpus: %x ipi: %x", __func__, cpus, ipi);
1311 while ((cpu = ffs(cpus)) != 0) {
1313 cpus &= ~(1 << cpu);
1315 KASSERT(cpu_apic_ids[cpu] != -1,
1316 ("IPI to non-existent CPU %d", cpu));
1320 old_pending = cpu_ipi_pending[cpu];
1321 new_pending = old_pending | bitmap;
1322 } while (!atomic_cmpset_int(&cpu_ipi_pending[cpu],old_pending, new_pending));
1328 lapic_ipi_vectored(ipi, cpu_apic_ids[cpu]);
1334 * send an IPI to all CPUs EXCEPT myself
1337 ipi_all_but_self(u_int ipi)
1340 if (IPI_IS_BITMAPED(ipi)) {
1341 ipi_selected(PCPU_GET(other_cpus), ipi);
1346 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1347 * of help in order to understand what is the source.
1348 * Set the mask of receiving CPUs for this purpose.
1350 if (ipi == IPI_STOP_HARD)
1351 atomic_set_int(&ipi_nmi_pending, PCPU_GET(other_cpus));
1352 CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1353 lapic_ipi_vectored(ipi, APIC_IPI_DEST_OTHERS);
1362 * As long as there is not a simple way to know about a NMI's
1363 * source, if the bitmask for the current CPU is present in
1364 * the global pending bitword an IPI_STOP_HARD has been issued
1365 * and should be handled.
1367 cpumask = PCPU_GET(cpumask);
1368 if ((ipi_nmi_pending & cpumask) == 0)
1371 atomic_clear_int(&ipi_nmi_pending, cpumask);
1377 * Handle an IPI_STOP by saving our current context and spinning until we
1381 cpustop_handler(void)
1383 int cpu = PCPU_GET(cpuid);
1384 int cpumask = PCPU_GET(cpumask);
1386 savectx(&stoppcbs[cpu]);
1388 /* Indicate that we are stopped */
1389 atomic_set_int(&stopped_cpus, cpumask);
1391 /* Wait for restart */
1392 while (!(started_cpus & cpumask))
1395 atomic_clear_int(&started_cpus, cpumask);
1396 atomic_clear_int(&stopped_cpus, cpumask);
1398 if (cpu == 0 && cpustop_restartfunc != NULL) {
1399 cpustop_restartfunc();
1400 cpustop_restartfunc = NULL;
1405 * This is called once the rest of the system is up and running and we're
1406 * ready to let the AP's out of the pen.
1409 release_aps(void *dummy __unused)
1414 atomic_store_rel_int(&aps_ready, 1);
1415 while (smp_started == 0)
1418 SYSINIT(start_aps, SI_SUB_SMP, SI_ORDER_FIRST, release_aps, NULL);
1421 sysctl_hlt_cpus(SYSCTL_HANDLER_ARGS)
1426 mask = hlt_cpus_mask;
1427 error = sysctl_handle_int(oidp, &mask, 0, req);
1428 if (error || !req->newptr)
1431 if (logical_cpus_mask != 0 &&
1432 (mask & logical_cpus_mask) == logical_cpus_mask)
1433 hlt_logical_cpus = 1;
1435 hlt_logical_cpus = 0;
1437 if (! hyperthreading_allowed)
1438 mask |= hyperthreading_cpus_mask;
1440 if ((mask & all_cpus) == all_cpus)
1442 hlt_cpus_mask = mask;
1445 SYSCTL_PROC(_machdep, OID_AUTO, hlt_cpus, CTLTYPE_INT|CTLFLAG_RW,
1446 0, 0, sysctl_hlt_cpus, "IU",
1447 "Bitmap of CPUs to halt. 101 (binary) will halt CPUs 0 and 2.");
1450 sysctl_hlt_logical_cpus(SYSCTL_HANDLER_ARGS)
1454 disable = hlt_logical_cpus;
1455 error = sysctl_handle_int(oidp, &disable, 0, req);
1456 if (error || !req->newptr)
1460 hlt_cpus_mask |= logical_cpus_mask;
1462 hlt_cpus_mask &= ~logical_cpus_mask;
1464 if (! hyperthreading_allowed)
1465 hlt_cpus_mask |= hyperthreading_cpus_mask;
1467 if ((hlt_cpus_mask & all_cpus) == all_cpus)
1468 hlt_cpus_mask &= ~(1<<0);
1470 hlt_logical_cpus = disable;
1475 sysctl_hyperthreading_allowed(SYSCTL_HANDLER_ARGS)
1479 allowed = hyperthreading_allowed;
1480 error = sysctl_handle_int(oidp, &allowed, 0, req);
1481 if (error || !req->newptr)
1486 * SCHED_ULE doesn't allow enabling/disabling HT cores at
1489 if (allowed != hyperthreading_allowed)
1495 hlt_cpus_mask &= ~hyperthreading_cpus_mask;
1497 hlt_cpus_mask |= hyperthreading_cpus_mask;
1499 if (logical_cpus_mask != 0 &&
1500 (hlt_cpus_mask & logical_cpus_mask) == logical_cpus_mask)
1501 hlt_logical_cpus = 1;
1503 hlt_logical_cpus = 0;
1505 if ((hlt_cpus_mask & all_cpus) == all_cpus)
1506 hlt_cpus_mask &= ~(1<<0);
1508 hyperthreading_allowed = allowed;
1513 cpu_hlt_setup(void *dummy __unused)
1516 if (logical_cpus_mask != 0) {
1517 TUNABLE_INT_FETCH("machdep.hlt_logical_cpus",
1519 sysctl_ctx_init(&logical_cpu_clist);
1520 SYSCTL_ADD_PROC(&logical_cpu_clist,
1521 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1522 "hlt_logical_cpus", CTLTYPE_INT|CTLFLAG_RW, 0, 0,
1523 sysctl_hlt_logical_cpus, "IU", "");
1524 SYSCTL_ADD_UINT(&logical_cpu_clist,
1525 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1526 "logical_cpus_mask", CTLTYPE_INT|CTLFLAG_RD,
1527 &logical_cpus_mask, 0, "");
1529 if (hlt_logical_cpus)
1530 hlt_cpus_mask |= logical_cpus_mask;
1533 * If necessary for security purposes, force
1534 * hyperthreading off, regardless of the value
1535 * of hlt_logical_cpus.
1537 if (hyperthreading_cpus_mask) {
1538 SYSCTL_ADD_PROC(&logical_cpu_clist,
1539 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1540 "hyperthreading_allowed", CTLTYPE_INT|CTLFLAG_RW,
1541 0, 0, sysctl_hyperthreading_allowed, "IU", "");
1542 if (! hyperthreading_allowed)
1543 hlt_cpus_mask |= hyperthreading_cpus_mask;
1547 SYSINIT(cpu_hlt, SI_SUB_SMP, SI_ORDER_ANY, cpu_hlt_setup, NULL);
1550 mp_grab_cpu_hlt(void)
1552 u_int mask = PCPU_GET(cpumask);
1554 u_int cpuid = PCPU_GET(cpuid);
1562 retval = mask & hlt_cpus_mask;
1563 while (mask & hlt_cpus_mask)
1564 __asm __volatile("sti; hlt" : : : "memory");
1570 * Setup interrupt counters for IPI handlers.
1573 mp_ipi_intrcnt(void *dummy)
1578 for (i = 0; i < mp_maxid; i++) {
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: preempt", i);
1588 intrcnt_add(buf, &ipi_preempt_counts[i]);
1589 snprintf(buf, sizeof(buf), "cpu%d: ast", i);
1590 intrcnt_add(buf, &ipi_ast_counts[i]);
1591 snprintf(buf, sizeof(buf), "cpu%d: rendezvous", i);
1592 intrcnt_add(buf, &ipi_rendezvous_counts[i]);
1593 snprintf(buf, sizeof(buf), "cpu%d: lazypmap", i);
1594 intrcnt_add(buf, &ipi_lazypmap_counts[i]);
1597 SYSINIT(mp_ipi_intrcnt, SI_SUB_INTR, SI_ORDER_MIDDLE, mp_ipi_intrcnt, NULL);