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/clock.h>
60 #include <machine/md_var.h>
61 #include <machine/mp_watchdog.h>
62 #include <machine/pcb.h>
63 #include <machine/psl.h>
64 #include <machine/smp.h>
65 #include <machine/specialreg.h>
66 #include <machine/tss.h>
68 #define WARMBOOT_TARGET 0
69 #define WARMBOOT_OFF (KERNBASE + 0x0467)
70 #define WARMBOOT_SEG (KERNBASE + 0x0469)
72 #define CMOS_REG (0x70)
73 #define CMOS_DATA (0x71)
74 #define BIOS_RESET (0x0f)
75 #define BIOS_WARM (0x0a)
77 /* lock region used by kernel profiling */
80 int mp_naps; /* # of Applications processors */
81 int boot_cpu_id = -1; /* designated BSP */
85 * CPU topology map datastructures for HTT.
87 static struct cpu_group mp_groups[MAXCPU];
88 static struct cpu_top mp_top;
90 /* AP uses this during bootstrap. Do not staticize. */
94 /* Free these after use */
95 void *bootstacks[MAXCPU];
97 /* Hotwire a 0->4MB V==P mapping */
98 extern pt_entry_t *KPTphys;
100 /* SMP page table page */
101 extern pt_entry_t *SMPpt;
103 struct pcb stoppcbs[MAXCPU];
105 /* Variables needed for SMP tlb shootdown. */
106 vm_offset_t smp_tlb_addr1;
107 vm_offset_t smp_tlb_addr2;
108 volatile int smp_tlb_wait;
110 extern inthand_t IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
113 * Local data and functions.
116 static u_int logical_cpus;
118 /* used to hold the AP's until we are ready to release them */
119 static struct mtx ap_boot_mtx;
121 /* Set to 1 once we're ready to let the APs out of the pen. */
122 static volatile int aps_ready = 0;
125 * Store data from cpu_add() until later in the boot when we actually setup
132 } static cpu_info[MAXCPU];
133 static int cpu_apic_ids[MAXCPU];
135 /* Holds pending bitmap based IPIs per CPU */
136 static volatile u_int cpu_ipi_pending[MAXCPU];
138 static u_int boot_address;
140 static void set_logical_apic_ids(void);
141 static int start_all_aps(void);
142 static int start_ap(int apic_id);
143 static void release_aps(void *dummy);
145 static int hlt_logical_cpus;
146 static u_int hyperthreading_cpus;
147 static cpumask_t hyperthreading_cpus_mask;
148 static int hyperthreading_allowed = 1;
149 static struct sysctl_ctx_list logical_cpu_clist;
150 static u_int bootMP_size;
153 mem_range_AP_init(void)
155 if (mem_range_softc.mr_op && mem_range_softc.mr_op->initAP)
156 mem_range_softc.mr_op->initAP(&mem_range_softc);
162 struct cpu_group *group;
168 /* Build the smp_topology map. */
169 /* Nothing to do if there is no HTT support. */
170 if ((cpu_feature & CPUID_HTT) == 0)
172 logical_cpus = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
173 if (logical_cpus <= 1)
175 group = &mp_groups[0];
177 for (cpu = 0, apic_id = 0; apic_id < MAXCPU; apic_id++) {
178 if (!cpu_info[apic_id].cpu_present)
181 * If the current group has members and we're not a logical
182 * cpu, create a new group.
184 if (group->cg_count != 0 && (apic_id % logical_cpus) == 0) {
189 group->cg_mask |= 1 << cpu;
193 mp_top.ct_count = groups;
194 mp_top.ct_group = mp_groups;
195 smp_topology = &mp_top;
200 volatile cpumask_t ipi_nmi_pending;
204 * Calculate usable address in base memory for AP trampoline code.
207 mp_bootaddress(u_int basemem)
210 bootMP_size = mptramp_end - mptramp_start;
211 boot_address = trunc_page(basemem * 1024); /* round down to 4k boundary */
212 if (((basemem * 1024) - boot_address) < bootMP_size)
213 boot_address -= PAGE_SIZE; /* not enough, lower by 4k */
214 /* 3 levels of page table pages */
215 mptramp_pagetables = boot_address - (PAGE_SIZE * 3);
217 return mptramp_pagetables;
221 cpu_add(u_int apic_id, char boot_cpu)
224 if (apic_id >= MAXCPU) {
225 printf("SMP: CPU %d exceeds maximum CPU %d, ignoring\n",
226 apic_id, MAXCPU - 1);
229 KASSERT(cpu_info[apic_id].cpu_present == 0, ("CPU %d added twice",
231 cpu_info[apic_id].cpu_present = 1;
233 KASSERT(boot_cpu_id == -1,
234 ("CPU %d claims to be BSP, but CPU %d already is", apic_id,
236 boot_cpu_id = apic_id;
237 cpu_info[apic_id].cpu_bsp = 1;
240 if (apic_id > mp_maxid)
243 printf("SMP: Added CPU %d (%s)\n", apic_id, boot_cpu ? "BSP" :
249 cpu_mp_setmaxid(void)
253 * mp_maxid should be already set by calls to cpu_add().
254 * Just sanity check its value here.
257 KASSERT(mp_maxid == 0,
258 ("%s: mp_ncpus is zero, but mp_maxid is not", __func__));
259 else if (mp_ncpus == 1)
262 KASSERT(mp_maxid >= mp_ncpus - 1,
263 ("%s: counters out of sync: max %d, count %d", __func__,
264 mp_maxid, mp_ncpus));
273 * Always record BSP in CPU map so that the mbuf init code works
279 * No CPUs were found, so this must be a UP system. Setup
280 * the variables to represent a system with a single CPU
287 /* At least one CPU was found. */
290 * One CPU was found, so this must be a UP system with
297 /* At least two CPUs were found. */
302 * Initialize the IPI handlers and start up the AP's.
308 u_int threads_per_cache, p[4];
310 /* Initialize the logical ID to APIC ID table. */
311 for (i = 0; i < MAXCPU; i++) {
312 cpu_apic_ids[i] = -1;
313 cpu_ipi_pending[i] = 0;
316 /* Install an inter-CPU IPI for TLB invalidation */
317 setidt(IPI_INVLTLB, IDTVEC(invltlb), SDT_SYSIGT, SEL_KPL, 0);
318 setidt(IPI_INVLPG, IDTVEC(invlpg), SDT_SYSIGT, SEL_KPL, 0);
319 setidt(IPI_INVLRNG, IDTVEC(invlrng), SDT_SYSIGT, SEL_KPL, 0);
321 /* Install an inter-CPU IPI for all-CPU rendezvous */
322 setidt(IPI_RENDEZVOUS, IDTVEC(rendezvous), SDT_SYSIGT, SEL_KPL, 0);
324 /* Install generic inter-CPU IPI handler */
325 setidt(IPI_BITMAP_VECTOR, IDTVEC(ipi_intr_bitmap_handler),
326 SDT_SYSIGT, SEL_KPL, 0);
328 /* Install an inter-CPU IPI for CPU stop/restart */
329 setidt(IPI_STOP, IDTVEC(cpustop), SDT_SYSIGT, SEL_KPL, 0);
331 /* Set boot_cpu_id if needed. */
332 if (boot_cpu_id == -1) {
333 boot_cpu_id = PCPU_GET(apic_id);
334 cpu_info[boot_cpu_id].cpu_bsp = 1;
336 KASSERT(boot_cpu_id == PCPU_GET(apic_id),
337 ("BSP's APIC ID doesn't match boot_cpu_id"));
338 cpu_apic_ids[0] = boot_cpu_id;
340 /* Start each Application Processor */
343 /* Setup the initial logical CPUs info. */
344 logical_cpus = logical_cpus_mask = 0;
345 if (cpu_feature & CPUID_HTT)
346 logical_cpus = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
349 * Work out if hyperthreading is *really* enabled. This
350 * is made really ugly by the fact that processors lie: Dual
351 * core processors claim to be hyperthreaded even when they're
352 * not, presumably because they want to be treated the same
353 * way as HTT with respect to per-cpu software licensing.
354 * At the time of writing (May 12, 2005) the only hyperthreaded
355 * cpus are from Intel, and Intel's dual-core processors can be
356 * identified via the "deterministic cache parameters" cpuid
360 * First determine if this is an Intel processor which claims
361 * to have hyperthreading support.
363 if ((cpu_feature & CPUID_HTT) &&
364 (strcmp(cpu_vendor, "GenuineIntel") == 0)) {
366 * If the "deterministic cache parameters" cpuid calls
367 * are available, use them.
370 /* Ask the processor about up to 32 caches. */
371 for (i = 0; i < 32; i++) {
372 cpuid_count(4, i, p);
373 threads_per_cache = ((p[0] & 0x3ffc000) >> 14) + 1;
374 if (hyperthreading_cpus < threads_per_cache)
375 hyperthreading_cpus = threads_per_cache;
376 if ((p[0] & 0x1f) == 0)
382 * If the deterministic cache parameters are not
383 * available, or if no caches were reported to exist,
384 * just accept what the HTT flag indicated.
386 if (hyperthreading_cpus == 0)
387 hyperthreading_cpus = logical_cpus;
390 set_logical_apic_ids();
395 * Print various information about the SMP system hardware and setup.
398 cpu_mp_announce(void)
403 printf(" cpu0 (BSP): APIC ID: %2d\n", boot_cpu_id);
404 for (i = 1, x = 0; x < MAXCPU; x++) {
405 if (!cpu_info[x].cpu_present || cpu_info[x].cpu_bsp)
407 if (cpu_info[x].cpu_disabled)
408 printf(" cpu (AP): APIC ID: %2d (disabled)\n", x);
410 KASSERT(i < mp_ncpus,
411 ("mp_ncpus and actual cpus are out of whack"));
412 printf(" cpu%d (AP): APIC ID: %2d\n", i++, x);
418 * AP CPU's call this to initialize themselves.
427 /* Set by the startup code for us to use */
431 common_tss[cpu] = common_tss[0];
432 common_tss[cpu].tss_rsp0 = 0; /* not used until after switch */
433 common_tss[cpu].tss_iobase = sizeof(struct amd64tss);
435 gdt_segs[GPROC0_SEL].ssd_base = (long) &common_tss[cpu];
436 ssdtosyssd(&gdt_segs[GPROC0_SEL],
437 (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
439 lgdt(&r_gdt); /* does magic intra-segment return */
441 /* Get per-cpu data */
444 /* prime data page for it to use */
445 pcpu_init(pc, cpu, sizeof(struct pcpu));
446 pc->pc_apic_id = cpu_apic_ids[cpu];
447 pc->pc_prvspace = pc;
448 pc->pc_curthread = 0;
449 pc->pc_tssp = &common_tss[cpu];
452 wrmsr(MSR_FSBASE, 0); /* User value */
453 wrmsr(MSR_GSBASE, (u_int64_t)pc);
454 wrmsr(MSR_KGSBASE, (u_int64_t)pc); /* XXX User value while we're in the kernel */
458 gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
462 * Set to a known state:
463 * Set by mpboot.s: CR0_PG, CR0_PE
464 * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
467 cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
470 /* Set up the fast syscall stuff */
471 msr = rdmsr(MSR_EFER) | EFER_SCE;
472 wrmsr(MSR_EFER, msr);
473 wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall));
474 wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
475 msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
476 ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
477 wrmsr(MSR_STAR, msr);
478 wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D);
480 /* Disable local APIC just to be sure. */
483 /* signal our startup to the BSP. */
486 /* Spin until the BSP releases the AP's. */
490 /* set up CPU registers and state */
493 /* set up SSE/NX registers */
496 /* set up FPU state on the AP */
499 /* A quick check from sanity claus */
500 if (PCPU_GET(apic_id) != lapic_id()) {
501 printf("SMP: cpuid = %d\n", PCPU_GET(cpuid));
502 printf("SMP: actual apic_id = %d\n", lapic_id());
503 printf("SMP: correct apic_id = %d\n", PCPU_GET(apic_id));
504 panic("cpuid mismatch! boom!!");
507 /* Initialize curthread. */
508 KASSERT(PCPU_GET(idlethread) != NULL, ("no idle thread"));
509 PCPU_SET(curthread, PCPU_GET(idlethread));
511 mtx_lock_spin(&ap_boot_mtx);
513 /* Init local apic for irq's */
516 /* Set memory range attributes for this CPU to match the BSP */
521 CTR1(KTR_SMP, "SMP: AP CPU #%d Launched", PCPU_GET(cpuid));
522 printf("SMP: AP CPU #%d Launched!\n", PCPU_GET(cpuid));
524 /* Determine if we are a logical CPU. */
525 if (logical_cpus > 1 && PCPU_GET(apic_id) % logical_cpus != 0)
526 logical_cpus_mask |= PCPU_GET(cpumask);
528 /* Determine if we are a hyperthread. */
529 if (hyperthreading_cpus > 1 &&
530 PCPU_GET(apic_id) % hyperthreading_cpus != 0)
531 hyperthreading_cpus_mask |= PCPU_GET(cpumask);
533 /* Build our map of 'other' CPUs. */
534 PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
539 if (smp_cpus == mp_ncpus) {
540 /* enable IPI's, tlb shootdown, freezes etc */
541 atomic_store_rel_int(&smp_started, 1);
542 smp_active = 1; /* historic */
545 mtx_unlock_spin(&ap_boot_mtx);
547 /* wait until all the AP's are up */
548 while (smp_started == 0)
551 /* ok, now grab sched_lock and enter the scheduler */
552 mtx_lock_spin(&sched_lock);
555 * Correct spinlock nesting. The idle thread context that we are
556 * borrowing was created so that it would start out with a single
557 * spin lock (sched_lock) held in fork_trampoline(). Since we've
558 * explicitly acquired locks in this function, the nesting count
559 * is now 2 rather than 1. Since we are nested, calling
560 * spinlock_exit() will simply adjust the counts without allowing
561 * spin lock using code to interrupt us.
564 KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
566 binuptime(PCPU_PTR(switchtime));
567 PCPU_SET(switchticks, ticks);
569 cpu_throw(NULL, choosethread()); /* doesn't return */
571 panic("scheduler returned us to %s", __func__);
575 /*******************************************************************
576 * local functions and data
580 * Set the APIC logical IDs.
582 * We want to cluster logical CPU's within the same APIC ID cluster.
583 * Since logical CPU's are aligned simply filling in the clusters in
584 * APIC ID order works fine. Note that this does not try to balance
585 * the number of CPU's in each cluster. (XXX?)
588 set_logical_apic_ids(void)
590 u_int apic_id, cluster, cluster_id;
592 /* Force us to allocate cluster 0 at the start. */
594 cluster_id = APIC_MAX_INTRACLUSTER_ID;
595 for (apic_id = 0; apic_id < MAXCPU; apic_id++) {
596 if (!cpu_info[apic_id].cpu_present)
598 if (cluster_id == APIC_MAX_INTRACLUSTER_ID) {
599 cluster = ioapic_next_logical_cluster();
604 printf("APIC ID: physical %u, logical %u:%u\n",
605 apic_id, cluster, cluster_id);
606 lapic_set_logical_id(apic_id, cluster, cluster_id);
611 * start each AP in our list
616 vm_offset_t va = boot_address + KERNBASE;
617 u_int64_t *pt4, *pt3, *pt2;
618 u_int32_t mpbioswarmvec;
622 mtx_init(&ap_boot_mtx, "ap boot", NULL, MTX_SPIN);
624 /* install the AP 1st level boot code */
625 pmap_kenter(va, boot_address);
626 pmap_invalidate_page(kernel_pmap, va);
627 bcopy(mptramp_start, (void *)va, bootMP_size);
629 /* Locate the page tables, they'll be below the trampoline */
630 pt4 = (u_int64_t *)(uintptr_t)(mptramp_pagetables + KERNBASE);
631 pt3 = pt4 + (PAGE_SIZE) / sizeof(u_int64_t);
632 pt2 = pt3 + (PAGE_SIZE) / sizeof(u_int64_t);
634 /* Create the initial 1GB replicated page tables */
635 for (i = 0; i < 512; i++) {
636 /* Each slot of the level 4 pages points to the same level 3 page */
637 pt4[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + PAGE_SIZE);
638 pt4[i] |= PG_V | PG_RW | PG_U;
640 /* Each slot of the level 3 pages points to the same level 2 page */
641 pt3[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + (2 * PAGE_SIZE));
642 pt3[i] |= PG_V | PG_RW | PG_U;
644 /* The level 2 page slots are mapped with 2MB pages for 1GB. */
645 pt2[i] = i * (2 * 1024 * 1024);
646 pt2[i] |= PG_V | PG_RW | PG_PS | PG_U;
649 /* save the current value of the warm-start vector */
650 mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
651 outb(CMOS_REG, BIOS_RESET);
652 mpbiosreason = inb(CMOS_DATA);
654 /* setup a vector to our boot code */
655 *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
656 *((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
657 outb(CMOS_REG, BIOS_RESET);
658 outb(CMOS_DATA, BIOS_WARM); /* 'warm-start' */
661 for (cpu = 0, apic_id = 0; apic_id < MAXCPU; apic_id++) {
663 /* Ignore non-existent CPUs and the BSP. */
664 if (!cpu_info[apic_id].cpu_present ||
665 cpu_info[apic_id].cpu_bsp)
668 /* Don't use this CPU if it has been disabled by a tunable. */
669 if (resource_disabled("lapic", apic_id)) {
670 cpu_info[apic_id].cpu_disabled = 1;
677 /* save APIC ID for this logical ID */
678 cpu_apic_ids[cpu] = apic_id;
680 /* allocate and set up an idle stack data page */
681 bootstacks[cpu] = (char *)kmem_alloc(kernel_map, KSTACK_PAGES * PAGE_SIZE);
683 bootSTK = (char *)bootstacks[cpu] + KSTACK_PAGES * PAGE_SIZE - 8;
686 /* attempt to start the Application Processor */
687 if (!start_ap(apic_id)) {
688 /* restore the warmstart vector */
689 *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
690 panic("AP #%d (PHY# %d) failed!", cpu, apic_id);
693 all_cpus |= (1 << cpu); /* record AP in CPU map */
696 /* build our map of 'other' CPUs */
697 PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
699 /* restore the warmstart vector */
700 *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
702 outb(CMOS_REG, BIOS_RESET);
703 outb(CMOS_DATA, mpbiosreason);
705 /* number of APs actually started */
711 * This function starts the AP (application processor) identified
712 * by the APIC ID 'physicalCpu'. It does quite a "song and dance"
713 * to accomplish this. This is necessary because of the nuances
714 * of the different hardware we might encounter. It isn't pretty,
715 * but it seems to work.
718 start_ap(int apic_id)
723 /* calculate the vector */
724 vector = (boot_address >> 12) & 0xff;
726 /* used as a watchpoint to signal AP startup */
730 * first we do an INIT/RESET IPI this INIT IPI might be run, reseting
731 * and running the target CPU. OR this INIT IPI might be latched (P5
732 * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
736 /* do an INIT IPI: assert RESET */
737 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
738 APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, apic_id);
740 /* wait for pending status end */
743 /* do an INIT IPI: deassert RESET */
744 lapic_ipi_raw(APIC_DEST_ALLESELF | APIC_TRIGMOD_LEVEL |
745 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, 0);
747 /* wait for pending status end */
748 DELAY(10000); /* wait ~10mS */
752 * next we do a STARTUP IPI: the previous INIT IPI might still be
753 * latched, (P5 bug) this 1st STARTUP would then terminate
754 * immediately, and the previously started INIT IPI would continue. OR
755 * the previous INIT IPI has already run. and this STARTUP IPI will
756 * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
760 /* do a STARTUP IPI */
761 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
762 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
765 DELAY(200); /* wait ~200uS */
768 * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
769 * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
770 * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
771 * recognized after hardware RESET or INIT IPI.
774 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
775 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
778 DELAY(200); /* wait ~200uS */
780 /* Wait up to 5 seconds for it to start. */
781 for (ms = 0; ms < 5000; ms++) {
783 return 1; /* return SUCCESS */
786 return 0; /* return FAILURE */
790 * Flush the TLB on all other CPU's
793 smp_tlb_shootdown(u_int vector, vm_offset_t addr1, vm_offset_t addr2)
797 ncpu = mp_ncpus - 1; /* does not shootdown self */
799 return; /* no other cpus */
800 mtx_assert(&smp_ipi_mtx, MA_OWNED);
801 smp_tlb_addr1 = addr1;
802 smp_tlb_addr2 = addr2;
803 atomic_store_rel_int(&smp_tlb_wait, 0);
804 ipi_all_but_self(vector);
805 while (smp_tlb_wait < ncpu)
810 * This is about as magic as it gets. fortune(1) has got similar code
811 * for reversing bits in a word. Who thinks up this stuff??
813 * Yes, it does appear to be consistently faster than:
814 * while (i = ffs(m)) {
819 * while (lsb = (m & -m)) { // This is magic too
820 * m &= ~lsb; // or: m ^= lsb
823 * Both of these latter forms do some very strange things on gcc-3.1 with
824 * -mcpu=pentiumpro and/or -march=pentiumpro and/or -O or -O2.
825 * There is probably an SSE or MMX popcnt instruction.
827 * I wonder if this should be in libkern?
829 * XXX Stop the presses! Another one:
830 * static __inline u_int32_t
831 * popcnt1(u_int32_t v)
833 * v -= ((v >> 1) & 0x55555555);
834 * v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
835 * v = (v + (v >> 4)) & 0x0F0F0F0F;
836 * return (v * 0x01010101) >> 24;
838 * The downside is that it has a multiply. With a pentium3 with
839 * -mcpu=pentiumpro and -march=pentiumpro then gcc-3.1 will use
840 * an imull, and in that case it is faster. In most other cases
841 * it appears slightly slower.
843 * Another variant (also from fortune):
844 * #define BITCOUNT(x) (((BX_(x)+(BX_(x)>>4)) & 0x0F0F0F0F) % 255)
845 * #define BX_(x) ((x) - (((x)>>1)&0x77777777) \
846 * - (((x)>>2)&0x33333333) \
847 * - (((x)>>3)&0x11111111))
849 static __inline u_int32_t
853 m = (m & 0x55555555) + ((m & 0xaaaaaaaa) >> 1);
854 m = (m & 0x33333333) + ((m & 0xcccccccc) >> 2);
855 m = (m & 0x0f0f0f0f) + ((m & 0xf0f0f0f0) >> 4);
856 m = (m & 0x00ff00ff) + ((m & 0xff00ff00) >> 8);
857 m = (m & 0x0000ffff) + ((m & 0xffff0000) >> 16);
862 smp_targeted_tlb_shootdown(u_int mask, u_int vector, vm_offset_t addr1, vm_offset_t addr2)
866 othercpus = mp_ncpus - 1;
867 if (mask == (u_int)-1) {
872 mask &= ~PCPU_GET(cpumask);
876 if (ncpu > othercpus) {
877 /* XXX this should be a panic offence */
878 printf("SMP: tlb shootdown to %d other cpus (only have %d)\n",
882 /* XXX should be a panic, implied by mask == 0 above */
886 mtx_assert(&smp_ipi_mtx, MA_OWNED);
887 smp_tlb_addr1 = addr1;
888 smp_tlb_addr2 = addr2;
889 atomic_store_rel_int(&smp_tlb_wait, 0);
890 if (mask == (u_int)-1)
891 ipi_all_but_self(vector);
893 ipi_selected(mask, vector);
894 while (smp_tlb_wait < ncpu)
903 smp_tlb_shootdown(IPI_INVLTLB, 0, 0);
908 smp_invlpg(vm_offset_t addr)
912 smp_tlb_shootdown(IPI_INVLPG, addr, 0);
916 smp_invlpg_range(vm_offset_t addr1, vm_offset_t addr2)
920 smp_tlb_shootdown(IPI_INVLRNG, addr1, addr2);
925 smp_masked_invltlb(u_int mask)
929 smp_targeted_tlb_shootdown(mask, IPI_INVLTLB, 0, 0);
934 smp_masked_invlpg(u_int mask, vm_offset_t addr)
938 smp_targeted_tlb_shootdown(mask, IPI_INVLPG, addr, 0);
943 smp_masked_invlpg_range(u_int mask, vm_offset_t addr1, vm_offset_t addr2)
947 smp_targeted_tlb_shootdown(mask, IPI_INVLRNG, addr1, addr2);
953 ipi_bitmap_handler(struct clockframe frame)
955 int cpu = PCPU_GET(cpuid);
958 ipi_bitmap = atomic_readandclear_int(&cpu_ipi_pending[cpu]);
960 #ifdef IPI_PREEMPTION
961 if (ipi_bitmap & IPI_PREEMPT) {
962 mtx_lock_spin(&sched_lock);
963 /* Don't preempt the idle thread */
964 if (curthread->td_priority < PRI_MIN_IDLE) {
965 struct thread *running_thread = curthread;
966 if (running_thread->td_critnest > 1)
967 running_thread->td_owepreempt = 1;
969 mi_switch(SW_INVOL | SW_PREEMPT, NULL);
971 mtx_unlock_spin(&sched_lock);
975 /* Nothing to do for AST */
979 * send an IPI to a set of cpus.
982 ipi_selected(u_int32_t cpus, u_int ipi)
989 if (IPI_IS_BITMAPED(ipi)) {
991 ipi = IPI_BITMAP_VECTOR;
994 CTR3(KTR_SMP, "%s: cpus: %x ipi: %x", __func__, cpus, ipi);
995 while ((cpu = ffs(cpus)) != 0) {
999 KASSERT(cpu_apic_ids[cpu] != -1,
1000 ("IPI to non-existent CPU %d", cpu));
1004 old_pending = cpu_ipi_pending[cpu];
1005 new_pending = old_pending | bitmap;
1006 } while (!atomic_cmpset_int(&cpu_ipi_pending[cpu],old_pending, new_pending));
1012 lapic_ipi_vectored(ipi, cpu_apic_ids[cpu]);
1018 * send an IPI INTerrupt containing 'vector' to all CPUs, including myself
1024 CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1025 lapic_ipi_vectored(ipi, APIC_IPI_DEST_ALL);
1029 * send an IPI to all CPUs EXCEPT myself
1032 ipi_all_but_self(u_int ipi)
1035 CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1036 lapic_ipi_vectored(ipi, APIC_IPI_DEST_OTHERS);
1040 * send an IPI to myself
1046 CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1047 lapic_ipi_vectored(ipi, APIC_IPI_DEST_SELF);
1052 * send NMI IPI to selected CPUs
1055 #define BEFORE_SPIN 1000000
1058 ipi_nmi_selected(u_int32_t cpus)
1064 icrlo = APIC_DELMODE_NMI | APIC_DESTMODE_PHY | APIC_LEVEL_ASSERT
1065 | APIC_TRIGMOD_EDGE;
1067 CTR2(KTR_SMP, "%s: cpus: %x nmi", __func__, cpus);
1070 atomic_set_int(&ipi_nmi_pending, cpus);
1073 while ((cpu = ffs(cpus)) != 0) {
1075 cpus &= ~(1 << cpu);
1077 KASSERT(cpu_apic_ids[cpu] != -1,
1078 ("IPI NMI to non-existent CPU %d", cpu));
1080 /* Wait for an earlier IPI to finish. */
1081 if (!lapic_ipi_wait(BEFORE_SPIN))
1082 panic("ipi_nmi_selected: previous IPI has not cleared");
1084 lapic_ipi_raw(icrlo,cpu_apic_ids[cpu]);
1092 int cpu = PCPU_GET(cpuid);
1094 if(!(atomic_load_acq_int(&ipi_nmi_pending) & (1 << cpu)))
1097 atomic_clear_int(&ipi_nmi_pending,1 << cpu);
1099 savectx(&stoppcbs[cpu]);
1101 /* Indicate that we are stopped */
1102 atomic_set_int(&stopped_cpus,1 << cpu);
1105 /* Wait for restart */
1106 while(!(atomic_load_acq_int(&started_cpus) & (1 << cpu)))
1109 atomic_clear_int(&started_cpus,1 << cpu);
1110 atomic_clear_int(&stopped_cpus,1 << cpu);
1112 if(cpu == 0 && cpustop_restartfunc != NULL)
1113 cpustop_restartfunc();
1118 #endif /* KDB_STOP_NMI */
1121 * This is called once the rest of the system is up and running and we're
1122 * ready to let the AP's out of the pen.
1125 release_aps(void *dummy __unused)
1130 mtx_lock_spin(&sched_lock);
1131 atomic_store_rel_int(&aps_ready, 1);
1132 while (smp_started == 0)
1134 mtx_unlock_spin(&sched_lock);
1136 SYSINIT(start_aps, SI_SUB_SMP, SI_ORDER_FIRST, release_aps, NULL);
1139 sysctl_hlt_cpus(SYSCTL_HANDLER_ARGS)
1144 mask = hlt_cpus_mask;
1145 error = sysctl_handle_int(oidp, &mask, 0, req);
1146 if (error || !req->newptr)
1149 if (logical_cpus_mask != 0 &&
1150 (mask & logical_cpus_mask) == logical_cpus_mask)
1151 hlt_logical_cpus = 1;
1153 hlt_logical_cpus = 0;
1155 if (! hyperthreading_allowed)
1156 mask |= hyperthreading_cpus_mask;
1158 if ((mask & all_cpus) == all_cpus)
1160 hlt_cpus_mask = mask;
1163 SYSCTL_PROC(_machdep, OID_AUTO, hlt_cpus, CTLTYPE_INT|CTLFLAG_RW,
1164 0, 0, sysctl_hlt_cpus, "IU",
1165 "Bitmap of CPUs to halt. 101 (binary) will halt CPUs 0 and 2.");
1168 sysctl_hlt_logical_cpus(SYSCTL_HANDLER_ARGS)
1172 disable = hlt_logical_cpus;
1173 error = sysctl_handle_int(oidp, &disable, 0, req);
1174 if (error || !req->newptr)
1178 hlt_cpus_mask |= logical_cpus_mask;
1180 hlt_cpus_mask &= ~logical_cpus_mask;
1182 if (! hyperthreading_allowed)
1183 hlt_cpus_mask |= hyperthreading_cpus_mask;
1185 if ((hlt_cpus_mask & all_cpus) == all_cpus)
1186 hlt_cpus_mask &= ~(1<<0);
1188 hlt_logical_cpus = disable;
1193 sysctl_hyperthreading_allowed(SYSCTL_HANDLER_ARGS)
1197 allowed = hyperthreading_allowed;
1198 error = sysctl_handle_int(oidp, &allowed, 0, req);
1199 if (error || !req->newptr)
1203 hlt_cpus_mask &= ~hyperthreading_cpus_mask;
1205 hlt_cpus_mask |= hyperthreading_cpus_mask;
1207 if (logical_cpus_mask != 0 &&
1208 (hlt_cpus_mask & logical_cpus_mask) == logical_cpus_mask)
1209 hlt_logical_cpus = 1;
1211 hlt_logical_cpus = 0;
1213 if ((hlt_cpus_mask & all_cpus) == all_cpus)
1214 hlt_cpus_mask &= ~(1<<0);
1216 hyperthreading_allowed = allowed;
1221 cpu_hlt_setup(void *dummy __unused)
1224 if (logical_cpus_mask != 0) {
1225 TUNABLE_INT_FETCH("machdep.hlt_logical_cpus",
1227 sysctl_ctx_init(&logical_cpu_clist);
1228 SYSCTL_ADD_PROC(&logical_cpu_clist,
1229 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1230 "hlt_logical_cpus", CTLTYPE_INT|CTLFLAG_RW, 0, 0,
1231 sysctl_hlt_logical_cpus, "IU", "");
1232 SYSCTL_ADD_UINT(&logical_cpu_clist,
1233 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1234 "logical_cpus_mask", CTLTYPE_INT|CTLFLAG_RD,
1235 &logical_cpus_mask, 0, "");
1237 if (hlt_logical_cpus)
1238 hlt_cpus_mask |= logical_cpus_mask;
1241 * If necessary for security purposes, force
1242 * hyperthreading off, regardless of the value
1243 * of hlt_logical_cpus.
1245 if (hyperthreading_cpus_mask) {
1246 TUNABLE_INT_FETCH("machdep.hyperthreading_allowed",
1247 &hyperthreading_allowed);
1248 SYSCTL_ADD_PROC(&logical_cpu_clist,
1249 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1250 "hyperthreading_allowed", CTLTYPE_INT|CTLFLAG_RW,
1251 0, 0, sysctl_hyperthreading_allowed, "IU", "");
1252 if (! hyperthreading_allowed)
1253 hlt_cpus_mask |= hyperthreading_cpus_mask;
1257 SYSINIT(cpu_hlt, SI_SUB_SMP, SI_ORDER_ANY, cpu_hlt_setup, NULL);
1260 mp_grab_cpu_hlt(void)
1262 u_int mask = PCPU_GET(cpumask);
1264 u_int cpuid = PCPU_GET(cpuid);
1272 retval = mask & hlt_cpus_mask;
1273 while (mask & hlt_cpus_mask)
1274 __asm __volatile("sti; hlt" : : : "memory");