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>
50 #include <sys/sysctl.h>
53 #include <vm/vm_param.h>
55 #include <vm/vm_kern.h>
56 #include <vm/vm_extern.h>
58 #include <machine/apicreg.h>
59 #include <machine/md_var.h>
60 #include <machine/mp_watchdog.h>
61 #include <machine/pcb.h>
62 #include <machine/psl.h>
63 #include <machine/smp.h>
64 #include <machine/specialreg.h>
65 #include <machine/tss.h>
67 #define WARMBOOT_TARGET 0
68 #define WARMBOOT_OFF (KERNBASE + 0x0467)
69 #define WARMBOOT_SEG (KERNBASE + 0x0469)
71 #define CMOS_REG (0x70)
72 #define CMOS_DATA (0x71)
73 #define BIOS_RESET (0x0f)
74 #define BIOS_WARM (0x0a)
76 /* lock region used by kernel profiling */
79 int mp_naps; /* # of Applications processors */
80 int boot_cpu_id = -1; /* designated BSP */
84 * CPU topology map datastructures for HTT.
86 static struct cpu_group mp_groups[MAXCPU];
87 static struct cpu_top mp_top;
89 /* AP uses this during bootstrap. Do not staticize. */
93 /* Free these after use */
94 void *bootstacks[MAXCPU];
96 /* Temporary holder for double fault stack */
97 char *doublefault_stack;
99 /* Hotwire a 0->4MB V==P mapping */
100 extern pt_entry_t *KPTphys;
102 /* SMP page table page */
103 extern pt_entry_t *SMPpt;
105 struct pcb stoppcbs[MAXCPU];
107 /* Variables needed for SMP tlb shootdown. */
108 vm_offset_t smp_tlb_addr1;
109 vm_offset_t smp_tlb_addr2;
110 volatile int smp_tlb_wait;
112 extern inthand_t IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
115 volatile cpumask_t ipi_nmi_pending;
117 static void ipi_nmi_selected(u_int32_t cpus);
121 * Local data and functions.
126 * Provide an alternate method of stopping other CPUs. If another CPU has
127 * disabled interrupts the conventional STOP IPI will be blocked. This
128 * NMI-based stop should get through in that case.
130 static int stop_cpus_with_nmi = 1;
131 SYSCTL_INT(_debug, OID_AUTO, stop_cpus_with_nmi, CTLTYPE_INT | CTLFLAG_RW,
132 &stop_cpus_with_nmi, 0, "");
133 TUNABLE_INT("debug.stop_cpus_with_nmi", &stop_cpus_with_nmi);
135 #define stop_cpus_with_nmi 0
138 static u_int logical_cpus;
140 /* used to hold the AP's until we are ready to release them */
141 static struct mtx ap_boot_mtx;
143 /* Set to 1 once we're ready to let the APs out of the pen. */
144 static volatile int aps_ready = 0;
147 * Store data from cpu_add() until later in the boot when we actually setup
154 } static cpu_info[MAXCPU];
155 static int cpu_apic_ids[MAXCPU];
157 /* Holds pending bitmap based IPIs per CPU */
158 static volatile u_int cpu_ipi_pending[MAXCPU];
160 static u_int boot_address;
162 static void set_interrupt_apic_ids(void);
163 static int start_all_aps(void);
164 static int start_ap(int apic_id);
165 static void release_aps(void *dummy);
167 static int hlt_logical_cpus;
168 static u_int hyperthreading_cpus;
169 static cpumask_t hyperthreading_cpus_mask;
170 static int hyperthreading_allowed = 1;
171 static struct sysctl_ctx_list logical_cpu_clist;
172 static u_int bootMP_size;
175 mem_range_AP_init(void)
177 if (mem_range_softc.mr_op && mem_range_softc.mr_op->initAP)
178 mem_range_softc.mr_op->initAP(&mem_range_softc);
184 struct cpu_group *group;
191 /* Build the smp_topology map. */
192 /* Nothing to do if there is no HTT support. */
193 if ((cpu_feature & CPUID_HTT) == 0)
195 logical_cpus = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
196 if (logical_cpus <= 1)
198 /* Nothing to do if reported cores are physical cores. */
199 if (strcmp(cpu_vendor, "GenuineIntel") == 0 && cpu_high >= 4) {
200 cpuid_count(4, 0, regs);
201 if ((regs[0] & 0x1f) != 0 &&
202 logical_cpus <= ((regs[0] >> 26) & 0x3f) + 1)
205 group = &mp_groups[0];
207 for (cpu = 0, apic_id = 0; apic_id < MAXCPU; apic_id++) {
208 if (!cpu_info[apic_id].cpu_present)
211 * If the current group has members and we're not a logical
212 * cpu, create a new group.
214 if (group->cg_count != 0 && (apic_id % logical_cpus) == 0) {
219 group->cg_mask |= 1 << cpu;
223 mp_top.ct_count = groups;
224 mp_top.ct_group = mp_groups;
225 smp_topology = &mp_top;
229 * Calculate usable address in base memory for AP trampoline code.
232 mp_bootaddress(u_int basemem)
235 bootMP_size = mptramp_end - mptramp_start;
236 boot_address = trunc_page(basemem * 1024); /* round down to 4k boundary */
237 if (((basemem * 1024) - boot_address) < bootMP_size)
238 boot_address -= PAGE_SIZE; /* not enough, lower by 4k */
239 /* 3 levels of page table pages */
240 mptramp_pagetables = boot_address - (PAGE_SIZE * 3);
242 return mptramp_pagetables;
246 cpu_add(u_int apic_id, char boot_cpu)
249 if (apic_id >= MAXCPU) {
250 printf("SMP: CPU %d exceeds maximum CPU %d, ignoring\n",
251 apic_id, MAXCPU - 1);
254 KASSERT(cpu_info[apic_id].cpu_present == 0, ("CPU %d added twice",
256 cpu_info[apic_id].cpu_present = 1;
258 KASSERT(boot_cpu_id == -1,
259 ("CPU %d claims to be BSP, but CPU %d already is", apic_id,
261 boot_cpu_id = apic_id;
262 cpu_info[apic_id].cpu_bsp = 1;
265 if (apic_id > mp_maxid)
268 printf("SMP: Added CPU %d (%s)\n", apic_id, boot_cpu ? "BSP" :
274 cpu_mp_setmaxid(void)
278 * mp_maxid should be already set by calls to cpu_add().
279 * Just sanity check its value here.
282 KASSERT(mp_maxid == 0,
283 ("%s: mp_ncpus is zero, but mp_maxid is not", __func__));
284 else if (mp_ncpus == 1)
287 KASSERT(mp_maxid >= mp_ncpus - 1,
288 ("%s: counters out of sync: max %d, count %d", __func__,
289 mp_maxid, mp_ncpus));
298 * Always record BSP in CPU map so that the mbuf init code works
304 * No CPUs were found, so this must be a UP system. Setup
305 * the variables to represent a system with a single CPU
312 /* At least one CPU was found. */
315 * One CPU was found, so this must be a UP system with
322 /* At least two CPUs were found. */
327 * Initialize the IPI handlers and start up the AP's.
333 u_int threads_per_cache, p[4];
335 /* Initialize the logical ID to APIC ID table. */
336 for (i = 0; i < MAXCPU; i++) {
337 cpu_apic_ids[i] = -1;
338 cpu_ipi_pending[i] = 0;
341 /* Install an inter-CPU IPI for TLB invalidation */
342 setidt(IPI_INVLTLB, IDTVEC(invltlb), SDT_SYSIGT, SEL_KPL, 0);
343 setidt(IPI_INVLPG, IDTVEC(invlpg), SDT_SYSIGT, SEL_KPL, 0);
344 setidt(IPI_INVLRNG, IDTVEC(invlrng), SDT_SYSIGT, SEL_KPL, 0);
346 /* Install an inter-CPU IPI for all-CPU rendezvous */
347 setidt(IPI_RENDEZVOUS, IDTVEC(rendezvous), SDT_SYSIGT, SEL_KPL, 0);
349 /* Install generic inter-CPU IPI handler */
350 setidt(IPI_BITMAP_VECTOR, IDTVEC(ipi_intr_bitmap_handler),
351 SDT_SYSIGT, SEL_KPL, 0);
353 /* Install an inter-CPU IPI for CPU stop/restart */
354 setidt(IPI_STOP, IDTVEC(cpustop), SDT_SYSIGT, SEL_KPL, 0);
356 /* Set boot_cpu_id if needed. */
357 if (boot_cpu_id == -1) {
358 boot_cpu_id = PCPU_GET(apic_id);
359 cpu_info[boot_cpu_id].cpu_bsp = 1;
361 KASSERT(boot_cpu_id == PCPU_GET(apic_id),
362 ("BSP's APIC ID doesn't match boot_cpu_id"));
363 cpu_apic_ids[0] = boot_cpu_id;
365 /* Start each Application Processor */
368 /* Setup the initial logical CPUs info. */
369 logical_cpus = logical_cpus_mask = 0;
370 if (cpu_feature & CPUID_HTT)
371 logical_cpus = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
374 * Work out if hyperthreading is *really* enabled. This
375 * is made really ugly by the fact that processors lie: Dual
376 * core processors claim to be hyperthreaded even when they're
377 * not, presumably because they want to be treated the same
378 * way as HTT with respect to per-cpu software licensing.
379 * At the time of writing (May 12, 2005) the only hyperthreaded
380 * cpus are from Intel, and Intel's dual-core processors can be
381 * identified via the "deterministic cache parameters" cpuid
385 * First determine if this is an Intel processor which claims
386 * to have hyperthreading support.
388 if ((cpu_feature & CPUID_HTT) &&
389 (strcmp(cpu_vendor, "GenuineIntel") == 0)) {
391 * If the "deterministic cache parameters" cpuid calls
392 * are available, use them.
395 /* Ask the processor about the L1 cache. */
396 for (i = 0; i < 1; i++) {
397 cpuid_count(4, i, p);
398 threads_per_cache = ((p[0] & 0x3ffc000) >> 14) + 1;
399 if (hyperthreading_cpus < threads_per_cache)
400 hyperthreading_cpus = threads_per_cache;
401 if ((p[0] & 0x1f) == 0)
407 * If the deterministic cache parameters are not
408 * available, or if no caches were reported to exist,
409 * just accept what the HTT flag indicated.
411 if (hyperthreading_cpus == 0)
412 hyperthreading_cpus = logical_cpus;
415 set_interrupt_apic_ids();
420 * Print various information about the SMP system hardware and setup.
423 cpu_mp_announce(void)
428 printf(" cpu0 (BSP): APIC ID: %2d\n", boot_cpu_id);
429 for (i = 1, x = 0; x < MAXCPU; x++) {
430 if (!cpu_info[x].cpu_present || cpu_info[x].cpu_bsp)
432 if (cpu_info[x].cpu_disabled)
433 printf(" cpu (AP): APIC ID: %2d (disabled)\n", x);
435 KASSERT(i < mp_ncpus,
436 ("mp_ncpus and actual cpus are out of whack"));
437 printf(" cpu%d (AP): APIC ID: %2d\n", i++, x);
443 * AP CPU's call this to initialize themselves.
452 /* Set by the startup code for us to use */
456 common_tss[cpu] = common_tss[0];
457 common_tss[cpu].tss_rsp0 = 0; /* not used until after switch */
458 common_tss[cpu].tss_iobase = sizeof(struct amd64tss);
459 common_tss[cpu].tss_ist1 = (long)&doublefault_stack[PAGE_SIZE];
461 gdt_segs[GPROC0_SEL].ssd_base = (long) &common_tss[cpu];
462 ssdtosyssd(&gdt_segs[GPROC0_SEL],
463 (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
465 lgdt(&r_gdt); /* does magic intra-segment return */
467 /* Get per-cpu data */
470 /* prime data page for it to use */
471 pcpu_init(pc, cpu, sizeof(struct pcpu));
472 pc->pc_apic_id = cpu_apic_ids[cpu];
473 pc->pc_prvspace = pc;
474 pc->pc_curthread = 0;
475 pc->pc_tssp = &common_tss[cpu];
478 wrmsr(MSR_FSBASE, 0); /* User value */
479 wrmsr(MSR_GSBASE, (u_int64_t)pc);
480 wrmsr(MSR_KGSBASE, (u_int64_t)pc); /* XXX User value while we're in the kernel */
484 gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
488 * Set to a known state:
489 * Set by mpboot.s: CR0_PG, CR0_PE
490 * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
493 cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
496 /* Set up the fast syscall stuff */
497 msr = rdmsr(MSR_EFER) | EFER_SCE;
498 wrmsr(MSR_EFER, msr);
499 wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall));
500 wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
501 msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
502 ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
503 wrmsr(MSR_STAR, msr);
504 wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D);
506 /* Disable local APIC just to be sure. */
509 /* signal our startup to the BSP. */
512 /* Spin until the BSP releases the AP's. */
516 /* Initialize the PAT MSR. */
519 /* set up CPU registers and state */
522 /* set up SSE/NX registers */
525 /* set up FPU state on the AP */
528 /* A quick check from sanity claus */
529 if (PCPU_GET(apic_id) != lapic_id()) {
530 printf("SMP: cpuid = %d\n", PCPU_GET(cpuid));
531 printf("SMP: actual apic_id = %d\n", lapic_id());
532 printf("SMP: correct apic_id = %d\n", PCPU_GET(apic_id));
533 panic("cpuid mismatch! boom!!");
536 /* Initialize curthread. */
537 KASSERT(PCPU_GET(idlethread) != NULL, ("no idle thread"));
538 PCPU_SET(curthread, PCPU_GET(idlethread));
540 mtx_lock_spin(&ap_boot_mtx);
542 /* Init local apic for irq's */
545 /* Set memory range attributes for this CPU to match the BSP */
550 CTR1(KTR_SMP, "SMP: AP CPU #%d Launched", PCPU_GET(cpuid));
551 printf("SMP: AP CPU #%d Launched!\n", PCPU_GET(cpuid));
553 /* Determine if we are a logical CPU. */
554 if (logical_cpus > 1 && PCPU_GET(apic_id) % logical_cpus != 0)
555 logical_cpus_mask |= PCPU_GET(cpumask);
557 /* Determine if we are a hyperthread. */
558 if (hyperthreading_cpus > 1 &&
559 PCPU_GET(apic_id) % hyperthreading_cpus != 0)
560 hyperthreading_cpus_mask |= PCPU_GET(cpumask);
562 /* Build our map of 'other' CPUs. */
563 PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
568 if (smp_cpus == mp_ncpus) {
569 /* enable IPI's, tlb shootdown, freezes etc */
570 atomic_store_rel_int(&smp_started, 1);
571 smp_active = 1; /* historic */
575 * Enable global pages TLB extension
576 * This also implicitly flushes the TLB
579 load_cr4(rcr4() | CR4_PGE);
581 mtx_unlock_spin(&ap_boot_mtx);
583 /* wait until all the AP's are up */
584 while (smp_started == 0)
587 /* ok, now grab sched_lock and enter the scheduler */
588 mtx_lock_spin(&sched_lock);
591 * Correct spinlock nesting. The idle thread context that we are
592 * borrowing was created so that it would start out with a single
593 * spin lock (sched_lock) held in fork_trampoline(). Since we've
594 * explicitly acquired locks in this function, the nesting count
595 * is now 2 rather than 1. Since we are nested, calling
596 * spinlock_exit() will simply adjust the counts without allowing
597 * spin lock using code to interrupt us.
600 KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
602 PCPU_SET(switchtime, cpu_ticks());
603 PCPU_SET(switchticks, ticks);
605 cpu_throw(NULL, choosethread()); /* doesn't return */
607 panic("scheduler returned us to %s", __func__);
611 /*******************************************************************
612 * local functions and data
616 * We tell the I/O APIC code about all the CPUs we want to receive
617 * interrupts. If we don't want certain CPUs to receive IRQs we
618 * can simply not tell the I/O APIC code about them in this function.
619 * We also do not tell it about the BSP since it tells itself about
620 * the BSP internally to work with UP kernels and on UP machines.
623 set_interrupt_apic_ids(void)
627 for (apic_id = 0; apic_id < MAXCPU; apic_id++) {
628 if (!cpu_info[apic_id].cpu_present)
630 if (cpu_info[apic_id].cpu_bsp)
633 /* Don't let hyperthreads service interrupts. */
634 if (hyperthreading_cpus > 1 &&
635 apic_id % hyperthreading_cpus != 0)
638 intr_add_cpu(apic_id);
643 * start each AP in our list
648 vm_offset_t va = boot_address + KERNBASE;
649 u_int64_t *pt4, *pt3, *pt2;
650 u_int32_t mpbioswarmvec;
654 mtx_init(&ap_boot_mtx, "ap boot", NULL, MTX_SPIN);
656 /* install the AP 1st level boot code */
657 pmap_kenter(va, boot_address);
658 pmap_invalidate_page(kernel_pmap, va);
659 bcopy(mptramp_start, (void *)va, bootMP_size);
661 /* Locate the page tables, they'll be below the trampoline */
662 pt4 = (u_int64_t *)(uintptr_t)(mptramp_pagetables + KERNBASE);
663 pt3 = pt4 + (PAGE_SIZE) / sizeof(u_int64_t);
664 pt2 = pt3 + (PAGE_SIZE) / sizeof(u_int64_t);
666 /* Create the initial 1GB replicated page tables */
667 for (i = 0; i < 512; i++) {
668 /* Each slot of the level 4 pages points to the same level 3 page */
669 pt4[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + PAGE_SIZE);
670 pt4[i] |= PG_V | PG_RW | PG_U;
672 /* Each slot of the level 3 pages points to the same level 2 page */
673 pt3[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + (2 * PAGE_SIZE));
674 pt3[i] |= PG_V | PG_RW | PG_U;
676 /* The level 2 page slots are mapped with 2MB pages for 1GB. */
677 pt2[i] = i * (2 * 1024 * 1024);
678 pt2[i] |= PG_V | PG_RW | PG_PS | PG_U;
681 /* save the current value of the warm-start vector */
682 mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
683 outb(CMOS_REG, BIOS_RESET);
684 mpbiosreason = inb(CMOS_DATA);
686 /* setup a vector to our boot code */
687 *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
688 *((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
689 outb(CMOS_REG, BIOS_RESET);
690 outb(CMOS_DATA, BIOS_WARM); /* 'warm-start' */
693 for (cpu = 0, apic_id = 0; apic_id < MAXCPU; apic_id++) {
695 /* Ignore non-existent CPUs and the BSP. */
696 if (!cpu_info[apic_id].cpu_present ||
697 cpu_info[apic_id].cpu_bsp)
700 /* Don't use this CPU if it has been disabled by a tunable. */
701 if (resource_disabled("lapic", apic_id)) {
702 cpu_info[apic_id].cpu_disabled = 1;
709 /* save APIC ID for this logical ID */
710 cpu_apic_ids[cpu] = apic_id;
712 /* allocate and set up an idle stack data page */
713 bootstacks[cpu] = (void *)kmem_alloc(kernel_map, KSTACK_PAGES * PAGE_SIZE);
714 doublefault_stack = (char *)kmem_alloc(kernel_map, PAGE_SIZE);
716 bootSTK = (char *)bootstacks[cpu] + KSTACK_PAGES * PAGE_SIZE - 8;
719 /* attempt to start the Application Processor */
720 if (!start_ap(apic_id)) {
721 /* restore the warmstart vector */
722 *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
723 panic("AP #%d (PHY# %d) failed!", cpu, apic_id);
726 all_cpus |= (1 << cpu); /* record AP in CPU map */
729 /* build our map of 'other' CPUs */
730 PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
732 /* restore the warmstart vector */
733 *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
735 outb(CMOS_REG, BIOS_RESET);
736 outb(CMOS_DATA, mpbiosreason);
738 /* number of APs actually started */
744 * This function starts the AP (application processor) identified
745 * by the APIC ID 'physicalCpu'. It does quite a "song and dance"
746 * to accomplish this. This is necessary because of the nuances
747 * of the different hardware we might encounter. It isn't pretty,
748 * but it seems to work.
751 start_ap(int apic_id)
756 /* calculate the vector */
757 vector = (boot_address >> 12) & 0xff;
759 /* used as a watchpoint to signal AP startup */
763 * first we do an INIT/RESET IPI this INIT IPI might be run, reseting
764 * and running the target CPU. OR this INIT IPI might be latched (P5
765 * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
769 /* do an INIT IPI: assert RESET */
770 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
771 APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, apic_id);
773 /* wait for pending status end */
776 /* do an INIT IPI: deassert RESET */
777 lapic_ipi_raw(APIC_DEST_ALLESELF | APIC_TRIGMOD_LEVEL |
778 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, 0);
780 /* wait for pending status end */
781 DELAY(10000); /* wait ~10mS */
785 * next we do a STARTUP IPI: the previous INIT IPI might still be
786 * latched, (P5 bug) this 1st STARTUP would then terminate
787 * immediately, and the previously started INIT IPI would continue. OR
788 * the previous INIT IPI has already run. and this STARTUP IPI will
789 * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
793 /* do a STARTUP IPI */
794 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
795 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
798 DELAY(200); /* wait ~200uS */
801 * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
802 * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
803 * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
804 * recognized after hardware RESET or INIT IPI.
807 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
808 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
811 DELAY(200); /* wait ~200uS */
813 /* Wait up to 5 seconds for it to start. */
814 for (ms = 0; ms < 5000; ms++) {
816 return 1; /* return SUCCESS */
819 return 0; /* return FAILURE */
823 * Flush the TLB on all other CPU's
826 smp_tlb_shootdown(u_int vector, vm_offset_t addr1, vm_offset_t addr2)
830 ncpu = mp_ncpus - 1; /* does not shootdown self */
832 return; /* no other cpus */
833 mtx_assert(&smp_ipi_mtx, MA_OWNED);
834 smp_tlb_addr1 = addr1;
835 smp_tlb_addr2 = addr2;
836 atomic_store_rel_int(&smp_tlb_wait, 0);
837 ipi_all_but_self(vector);
838 while (smp_tlb_wait < ncpu)
843 smp_targeted_tlb_shootdown(u_int mask, u_int vector, vm_offset_t addr1, vm_offset_t addr2)
847 othercpus = mp_ncpus - 1;
848 if (mask == (u_int)-1) {
853 mask &= ~PCPU_GET(cpumask);
856 ncpu = bitcount32(mask);
857 if (ncpu > othercpus) {
858 /* XXX this should be a panic offence */
859 printf("SMP: tlb shootdown to %d other cpus (only have %d)\n",
863 /* XXX should be a panic, implied by mask == 0 above */
867 mtx_assert(&smp_ipi_mtx, MA_OWNED);
868 smp_tlb_addr1 = addr1;
869 smp_tlb_addr2 = addr2;
870 atomic_store_rel_int(&smp_tlb_wait, 0);
871 if (mask == (u_int)-1)
872 ipi_all_but_self(vector);
874 ipi_selected(mask, vector);
875 while (smp_tlb_wait < ncpu)
880 smp_cache_flush(void)
884 smp_tlb_shootdown(IPI_INVLCACHE, 0, 0);
892 smp_tlb_shootdown(IPI_INVLTLB, 0, 0);
897 smp_invlpg(vm_offset_t addr)
901 smp_tlb_shootdown(IPI_INVLPG, addr, 0);
905 smp_invlpg_range(vm_offset_t addr1, vm_offset_t addr2)
909 smp_tlb_shootdown(IPI_INVLRNG, addr1, addr2);
914 smp_masked_invltlb(u_int mask)
918 smp_targeted_tlb_shootdown(mask, IPI_INVLTLB, 0, 0);
923 smp_masked_invlpg(u_int mask, vm_offset_t addr)
927 smp_targeted_tlb_shootdown(mask, IPI_INVLPG, addr, 0);
932 smp_masked_invlpg_range(u_int mask, vm_offset_t addr1, vm_offset_t addr2)
936 smp_targeted_tlb_shootdown(mask, IPI_INVLRNG, addr1, addr2);
941 ipi_bitmap_handler(struct trapframe frame)
943 int cpu = PCPU_GET(cpuid);
946 ipi_bitmap = atomic_readandclear_int(&cpu_ipi_pending[cpu]);
948 #ifdef IPI_PREEMPTION
949 if (ipi_bitmap & IPI_PREEMPT) {
950 mtx_lock_spin(&sched_lock);
951 /* Don't preempt the idle thread */
952 if (curthread->td_priority < PRI_MIN_IDLE) {
953 struct thread *running_thread = curthread;
954 if (running_thread->td_critnest > 1)
955 running_thread->td_owepreempt = 1;
957 mi_switch(SW_INVOL | SW_PREEMPT, NULL);
959 mtx_unlock_spin(&sched_lock);
963 /* Nothing to do for AST */
967 * send an IPI to a set of cpus.
970 ipi_selected(u_int32_t cpus, u_int ipi)
977 if (IPI_IS_BITMAPED(ipi)) {
979 ipi = IPI_BITMAP_VECTOR;
983 if (ipi == IPI_STOP && stop_cpus_with_nmi) {
984 ipi_nmi_selected(cpus);
988 CTR3(KTR_SMP, "%s: cpus: %x ipi: %x", __func__, cpus, ipi);
989 while ((cpu = ffs(cpus)) != 0) {
993 KASSERT(cpu_apic_ids[cpu] != -1,
994 ("IPI to non-existent CPU %d", cpu));
998 old_pending = cpu_ipi_pending[cpu];
999 new_pending = old_pending | bitmap;
1000 } while (!atomic_cmpset_int(&cpu_ipi_pending[cpu],old_pending, new_pending));
1006 lapic_ipi_vectored(ipi, cpu_apic_ids[cpu]);
1012 * send an IPI INTerrupt containing 'vector' to all CPUs, including myself
1018 if (IPI_IS_BITMAPED(ipi) || (ipi == IPI_STOP && stop_cpus_with_nmi)) {
1019 ipi_selected(all_cpus, ipi);
1022 CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1023 lapic_ipi_vectored(ipi, APIC_IPI_DEST_ALL);
1027 * send an IPI to all CPUs EXCEPT myself
1030 ipi_all_but_self(u_int ipi)
1033 if (IPI_IS_BITMAPED(ipi) || (ipi == IPI_STOP && stop_cpus_with_nmi)) {
1034 ipi_selected(PCPU_GET(other_cpus), ipi);
1037 CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1038 lapic_ipi_vectored(ipi, APIC_IPI_DEST_OTHERS);
1042 * send an IPI to myself
1048 if (IPI_IS_BITMAPED(ipi) || (ipi == IPI_STOP && stop_cpus_with_nmi)) {
1049 ipi_selected(PCPU_GET(cpumask), ipi);
1052 CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1053 lapic_ipi_vectored(ipi, APIC_IPI_DEST_SELF);
1058 * send NMI IPI to selected CPUs
1061 #define BEFORE_SPIN 1000000
1064 ipi_nmi_selected(u_int32_t cpus)
1069 icrlo = APIC_DELMODE_NMI | APIC_DESTMODE_PHY | APIC_LEVEL_ASSERT
1070 | APIC_TRIGMOD_EDGE;
1072 CTR2(KTR_SMP, "%s: cpus: %x nmi", __func__, cpus);
1074 atomic_set_int(&ipi_nmi_pending, cpus);
1076 while ((cpu = ffs(cpus)) != 0) {
1078 cpus &= ~(1 << cpu);
1080 KASSERT(cpu_apic_ids[cpu] != -1,
1081 ("IPI NMI to non-existent CPU %d", cpu));
1083 /* Wait for an earlier IPI to finish. */
1084 if (!lapic_ipi_wait(BEFORE_SPIN))
1085 panic("ipi_nmi_selected: previous IPI has not cleared");
1087 lapic_ipi_raw(icrlo, cpu_apic_ids[cpu]);
1092 ipi_nmi_handler(void)
1094 int cpumask = PCPU_GET(cpumask);
1096 if (!(ipi_nmi_pending & cpumask))
1099 atomic_clear_int(&ipi_nmi_pending, cpumask);
1104 #endif /* STOP_NMI */
1107 * Handle an IPI_STOP by saving our current context and spinning until we
1111 cpustop_handler(void)
1113 int cpu = PCPU_GET(cpuid);
1114 int cpumask = PCPU_GET(cpumask);
1116 savectx(&stoppcbs[cpu]);
1118 /* Indicate that we are stopped */
1119 atomic_set_int(&stopped_cpus, cpumask);
1121 /* Wait for restart */
1122 while (!(started_cpus & cpumask))
1125 atomic_clear_int(&started_cpus, cpumask);
1126 atomic_clear_int(&stopped_cpus, cpumask);
1128 if (cpu == 0 && cpustop_restartfunc != NULL) {
1129 cpustop_restartfunc();
1130 cpustop_restartfunc = NULL;
1135 * This is called once the rest of the system is up and running and we're
1136 * ready to let the AP's out of the pen.
1139 release_aps(void *dummy __unused)
1144 mtx_lock_spin(&sched_lock);
1145 atomic_store_rel_int(&aps_ready, 1);
1146 while (smp_started == 0)
1148 mtx_unlock_spin(&sched_lock);
1150 SYSINIT(start_aps, SI_SUB_SMP, SI_ORDER_FIRST, release_aps, NULL);
1153 sysctl_hlt_cpus(SYSCTL_HANDLER_ARGS)
1158 mask = hlt_cpus_mask;
1159 error = sysctl_handle_int(oidp, &mask, 0, req);
1160 if (error || !req->newptr)
1163 if (logical_cpus_mask != 0 &&
1164 (mask & logical_cpus_mask) == logical_cpus_mask)
1165 hlt_logical_cpus = 1;
1167 hlt_logical_cpus = 0;
1169 if (! hyperthreading_allowed)
1170 mask |= hyperthreading_cpus_mask;
1172 if ((mask & all_cpus) == all_cpus)
1174 hlt_cpus_mask = mask;
1177 SYSCTL_PROC(_machdep, OID_AUTO, hlt_cpus, CTLTYPE_INT|CTLFLAG_RW,
1178 0, 0, sysctl_hlt_cpus, "IU",
1179 "Bitmap of CPUs to halt. 101 (binary) will halt CPUs 0 and 2.");
1182 sysctl_hlt_logical_cpus(SYSCTL_HANDLER_ARGS)
1186 disable = hlt_logical_cpus;
1187 error = sysctl_handle_int(oidp, &disable, 0, req);
1188 if (error || !req->newptr)
1192 hlt_cpus_mask |= logical_cpus_mask;
1194 hlt_cpus_mask &= ~logical_cpus_mask;
1196 if (! hyperthreading_allowed)
1197 hlt_cpus_mask |= hyperthreading_cpus_mask;
1199 if ((hlt_cpus_mask & all_cpus) == all_cpus)
1200 hlt_cpus_mask &= ~(1<<0);
1202 hlt_logical_cpus = disable;
1207 sysctl_hyperthreading_allowed(SYSCTL_HANDLER_ARGS)
1211 allowed = hyperthreading_allowed;
1212 error = sysctl_handle_int(oidp, &allowed, 0, req);
1213 if (error || !req->newptr)
1217 hlt_cpus_mask &= ~hyperthreading_cpus_mask;
1219 hlt_cpus_mask |= hyperthreading_cpus_mask;
1221 if (logical_cpus_mask != 0 &&
1222 (hlt_cpus_mask & logical_cpus_mask) == logical_cpus_mask)
1223 hlt_logical_cpus = 1;
1225 hlt_logical_cpus = 0;
1227 if ((hlt_cpus_mask & all_cpus) == all_cpus)
1228 hlt_cpus_mask &= ~(1<<0);
1230 hyperthreading_allowed = allowed;
1235 cpu_hlt_setup(void *dummy __unused)
1238 if (logical_cpus_mask != 0) {
1239 TUNABLE_INT_FETCH("machdep.hlt_logical_cpus",
1241 sysctl_ctx_init(&logical_cpu_clist);
1242 SYSCTL_ADD_PROC(&logical_cpu_clist,
1243 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1244 "hlt_logical_cpus", CTLTYPE_INT|CTLFLAG_RW, 0, 0,
1245 sysctl_hlt_logical_cpus, "IU", "");
1246 SYSCTL_ADD_UINT(&logical_cpu_clist,
1247 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1248 "logical_cpus_mask", CTLTYPE_INT|CTLFLAG_RD,
1249 &logical_cpus_mask, 0, "");
1251 if (hlt_logical_cpus)
1252 hlt_cpus_mask |= logical_cpus_mask;
1255 * If necessary for security purposes, force
1256 * hyperthreading off, regardless of the value
1257 * of hlt_logical_cpus.
1259 if (hyperthreading_cpus_mask) {
1260 TUNABLE_INT_FETCH("machdep.hyperthreading_allowed",
1261 &hyperthreading_allowed);
1262 SYSCTL_ADD_PROC(&logical_cpu_clist,
1263 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1264 "hyperthreading_allowed", CTLTYPE_INT|CTLFLAG_RW,
1265 0, 0, sysctl_hyperthreading_allowed, "IU", "");
1266 if (! hyperthreading_allowed)
1267 hlt_cpus_mask |= hyperthreading_cpus_mask;
1271 SYSINIT(cpu_hlt, SI_SUB_SMP, SI_ORDER_ANY, cpu_hlt_setup, NULL);
1274 mp_grab_cpu_hlt(void)
1276 u_int mask = PCPU_GET(cpumask);
1278 u_int cpuid = PCPU_GET(cpuid);
1286 retval = mask & hlt_cpus_mask;
1287 while (mask & hlt_cpus_mask)
1288 __asm __volatile("sti; hlt" : : : "memory");