mp_machdep.c revision 208494
1/*-
2 * Copyright (c) 1996, by Steve Passe
3 * Copyright (c) 2003, by Peter Wemm
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
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.
13 *
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
24 * SUCH DAMAGE.
25 */
26
27#include <sys/cdefs.h>
28__FBSDID("$FreeBSD: head/sys/amd64/amd64/mp_machdep.c 208494 2010-05-24 11:40:49Z mav $");
29
30#include "opt_cpu.h"
31#include "opt_kstack_pages.h"
32#include "opt_mp_watchdog.h"
33#include "opt_sched.h"
34
35#include <sys/param.h>
36#include <sys/systm.h>
37#include <sys/bus.h>
38#ifdef GPROF
39#include <sys/gmon.h>
40#endif
41#include <sys/kernel.h>
42#include <sys/ktr.h>
43#include <sys/lock.h>
44#include <sys/malloc.h>
45#include <sys/memrange.h>
46#include <sys/mutex.h>
47#include <sys/pcpu.h>
48#include <sys/proc.h>
49#include <sys/sched.h>
50#include <sys/smp.h>
51#include <sys/sysctl.h>
52
53#include <vm/vm.h>
54#include <vm/vm_param.h>
55#include <vm/pmap.h>
56#include <vm/vm_kern.h>
57#include <vm/vm_extern.h>
58
59#include <machine/apicreg.h>
60#include <machine/clock.h>
61#include <machine/cputypes.h>
62#include <machine/cpufunc.h>
63#include <machine/mca.h>
64#include <machine/md_var.h>
65#include <machine/mp_watchdog.h>
66#include <machine/pcb.h>
67#include <machine/psl.h>
68#include <machine/smp.h>
69#include <machine/specialreg.h>
70#include <machine/tss.h>
71
72#define WARMBOOT_TARGET		0
73#define WARMBOOT_OFF		(KERNBASE + 0x0467)
74#define WARMBOOT_SEG		(KERNBASE + 0x0469)
75
76#define CMOS_REG		(0x70)
77#define CMOS_DATA		(0x71)
78#define BIOS_RESET		(0x0f)
79#define BIOS_WARM		(0x0a)
80
81/* lock region used by kernel profiling */
82int	mcount_lock;
83
84int	mp_naps;		/* # of Applications processors */
85int	boot_cpu_id = -1;	/* designated BSP */
86
87extern  struct pcpu __pcpu[];
88
89/* AP uses this during bootstrap.  Do not staticize.  */
90char *bootSTK;
91static int bootAP;
92
93/* Free these after use */
94void *bootstacks[MAXCPU];
95
96/* Temporary variables for init_secondary()  */
97char *doublefault_stack;
98char *nmi_stack;
99void *dpcpu;
100
101struct pcb stoppcbs[MAXCPU];
102struct xpcb **stopxpcbs = NULL;
103
104/* Variables needed for SMP tlb shootdown. */
105vm_offset_t smp_tlb_addr1;
106vm_offset_t smp_tlb_addr2;
107volatile int smp_tlb_wait;
108
109extern inthand_t IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
110
111/*
112 * Local data and functions.
113 */
114
115static u_int logical_cpus;
116static volatile cpumask_t ipi_nmi_pending;
117
118/* used to hold the AP's until we are ready to release them */
119static struct mtx ap_boot_mtx;
120
121/* Set to 1 once we're ready to let the APs out of the pen. */
122static volatile int aps_ready = 0;
123
124/*
125 * Store data from cpu_add() until later in the boot when we actually setup
126 * the APs.
127 */
128struct cpu_info {
129	int	cpu_present:1;
130	int	cpu_bsp:1;
131	int	cpu_disabled:1;
132	int	cpu_hyperthread:1;
133} static cpu_info[MAX_APIC_ID + 1];
134int cpu_apic_ids[MAXCPU];
135int apic_cpuids[MAX_APIC_ID + 1];
136
137/* Holds pending bitmap based IPIs per CPU */
138static volatile u_int cpu_ipi_pending[MAXCPU];
139
140static u_int boot_address;
141static int cpu_logical;
142static int cpu_cores;
143
144static void	assign_cpu_ids(void);
145static void	set_interrupt_apic_ids(void);
146static int	start_all_aps(void);
147static int	start_ap(int apic_id);
148static void	release_aps(void *dummy);
149
150static int	hlt_logical_cpus;
151static u_int	hyperthreading_cpus;
152static cpumask_t	hyperthreading_cpus_mask;
153static int	hyperthreading_allowed = 1;
154static struct	sysctl_ctx_list logical_cpu_clist;
155static u_int	bootMP_size;
156
157static void
158mem_range_AP_init(void)
159{
160	if (mem_range_softc.mr_op && mem_range_softc.mr_op->initAP)
161		mem_range_softc.mr_op->initAP(&mem_range_softc);
162}
163
164static void
165topo_probe_0xb(void)
166{
167	int logical;
168	int p[4];
169	int bits;
170	int type;
171	int cnt;
172	int i;
173	int x;
174
175	/* We only support two levels for now. */
176	for (i = 0; i < 3; i++) {
177		cpuid_count(0x0B, i, p);
178		bits = p[0] & 0x1f;
179		logical = p[1] &= 0xffff;
180		type = (p[2] >> 8) & 0xff;
181		if (type == 0 || logical == 0)
182			break;
183		for (cnt = 0, x = 0; x <= MAX_APIC_ID; x++) {
184			if (!cpu_info[x].cpu_present ||
185			    cpu_info[x].cpu_disabled)
186				continue;
187			if (x >> bits == boot_cpu_id >> bits)
188				cnt++;
189		}
190		if (type == CPUID_TYPE_SMT)
191			cpu_logical = cnt;
192		else if (type == CPUID_TYPE_CORE)
193			cpu_cores = cnt;
194	}
195	if (cpu_logical == 0)
196		cpu_logical = 1;
197	cpu_cores /= cpu_logical;
198}
199
200static void
201topo_probe_0x4(void)
202{
203	u_int threads_per_cache, p[4];
204	u_int htt, cmp;
205	int i;
206
207	htt = cmp = 1;
208	/*
209	 * If this CPU supports HTT or CMP then mention the
210	 * number of physical/logical cores it contains.
211	 */
212	if (cpu_feature & CPUID_HTT)
213		htt = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
214	if (cpu_vendor_id == CPU_VENDOR_AMD && (amd_feature2 & AMDID2_CMP))
215		cmp = (cpu_procinfo2 & AMDID_CMP_CORES) + 1;
216	else if (cpu_vendor_id == CPU_VENDOR_INTEL && (cpu_high >= 4)) {
217		cpuid_count(4, 0, p);
218		if ((p[0] & 0x1f) != 0)
219			cmp = ((p[0] >> 26) & 0x3f) + 1;
220	}
221	cpu_cores = cmp;
222	cpu_logical = htt / cmp;
223
224	/* Setup the initial logical CPUs info. */
225	if (cpu_feature & CPUID_HTT)
226		logical_cpus = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
227
228	/*
229	 * Work out if hyperthreading is *really* enabled.  This
230	 * is made really ugly by the fact that processors lie: Dual
231	 * core processors claim to be hyperthreaded even when they're
232	 * not, presumably because they want to be treated the same
233	 * way as HTT with respect to per-cpu software licensing.
234	 * At the time of writing (May 12, 2005) the only hyperthreaded
235	 * cpus are from Intel, and Intel's dual-core processors can be
236	 * identified via the "deterministic cache parameters" cpuid
237	 * calls.
238	 */
239	/*
240	 * First determine if this is an Intel processor which claims
241	 * to have hyperthreading support.
242	 */
243	if ((cpu_feature & CPUID_HTT) && cpu_vendor_id == CPU_VENDOR_INTEL) {
244		/*
245		 * If the "deterministic cache parameters" cpuid calls
246		 * are available, use them.
247		 */
248		if (cpu_high >= 4) {
249			/* Ask the processor about the L1 cache. */
250			for (i = 0; i < 1; i++) {
251				cpuid_count(4, i, p);
252				threads_per_cache = ((p[0] & 0x3ffc000) >> 14) + 1;
253				if (hyperthreading_cpus < threads_per_cache)
254					hyperthreading_cpus = threads_per_cache;
255				if ((p[0] & 0x1f) == 0)
256					break;
257			}
258		}
259
260		/*
261		 * If the deterministic cache parameters are not
262		 * available, or if no caches were reported to exist,
263		 * just accept what the HTT flag indicated.
264		 */
265		if (hyperthreading_cpus == 0)
266			hyperthreading_cpus = logical_cpus;
267	}
268}
269
270static void
271topo_probe(void)
272{
273	static int cpu_topo_probed = 0;
274
275	if (cpu_topo_probed)
276		return;
277
278	logical_cpus = logical_cpus_mask = 0;
279	if (cpu_high >= 0xb)
280		topo_probe_0xb();
281	else if (cpu_high)
282		topo_probe_0x4();
283	if (cpu_cores == 0)
284		cpu_cores = mp_ncpus > 0 ? mp_ncpus : 1;
285	if (cpu_logical == 0)
286		cpu_logical = 1;
287	cpu_topo_probed = 1;
288}
289
290struct cpu_group *
291cpu_topo(void)
292{
293	int cg_flags;
294
295	/*
296	 * Determine whether any threading flags are
297	 * necessry.
298	 */
299	topo_probe();
300	if (cpu_logical > 1 && hyperthreading_cpus)
301		cg_flags = CG_FLAG_HTT;
302	else if (cpu_logical > 1)
303		cg_flags = CG_FLAG_SMT;
304	else
305		cg_flags = 0;
306	if (mp_ncpus % (cpu_cores * cpu_logical) != 0) {
307		printf("WARNING: Non-uniform processors.\n");
308		printf("WARNING: Using suboptimal topology.\n");
309		return (smp_topo_none());
310	}
311	/*
312	 * No multi-core or hyper-threaded.
313	 */
314	if (cpu_logical * cpu_cores == 1)
315		return (smp_topo_none());
316	/*
317	 * Only HTT no multi-core.
318	 */
319	if (cpu_logical > 1 && cpu_cores == 1)
320		return (smp_topo_1level(CG_SHARE_L1, cpu_logical, cg_flags));
321	/*
322	 * Only multi-core no HTT.
323	 */
324	if (cpu_cores > 1 && cpu_logical == 1)
325		return (smp_topo_1level(CG_SHARE_L2, cpu_cores, cg_flags));
326	/*
327	 * Both HTT and multi-core.
328	 */
329	return (smp_topo_2level(CG_SHARE_L2, cpu_cores,
330	    CG_SHARE_L1, cpu_logical, cg_flags));
331}
332
333/*
334 * Calculate usable address in base memory for AP trampoline code.
335 */
336u_int
337mp_bootaddress(u_int basemem)
338{
339
340	bootMP_size = mptramp_end - mptramp_start;
341	boot_address = trunc_page(basemem * 1024); /* round down to 4k boundary */
342	if (((basemem * 1024) - boot_address) < bootMP_size)
343		boot_address -= PAGE_SIZE;	/* not enough, lower by 4k */
344	/* 3 levels of page table pages */
345	mptramp_pagetables = boot_address - (PAGE_SIZE * 3);
346
347	return mptramp_pagetables;
348}
349
350void
351cpu_add(u_int apic_id, char boot_cpu)
352{
353
354	if (apic_id > MAX_APIC_ID) {
355		panic("SMP: APIC ID %d too high", apic_id);
356		return;
357	}
358	KASSERT(cpu_info[apic_id].cpu_present == 0, ("CPU %d added twice",
359	    apic_id));
360	cpu_info[apic_id].cpu_present = 1;
361	if (boot_cpu) {
362		KASSERT(boot_cpu_id == -1,
363		    ("CPU %d claims to be BSP, but CPU %d already is", apic_id,
364		    boot_cpu_id));
365		boot_cpu_id = apic_id;
366		cpu_info[apic_id].cpu_bsp = 1;
367	}
368	if (mp_ncpus < MAXCPU) {
369		mp_ncpus++;
370		mp_maxid = mp_ncpus -1;
371	}
372	if (bootverbose)
373		printf("SMP: Added CPU %d (%s)\n", apic_id, boot_cpu ? "BSP" :
374		    "AP");
375}
376
377void
378cpu_mp_setmaxid(void)
379{
380
381	/*
382	 * mp_maxid should be already set by calls to cpu_add().
383	 * Just sanity check its value here.
384	 */
385	if (mp_ncpus == 0)
386		KASSERT(mp_maxid == 0,
387		    ("%s: mp_ncpus is zero, but mp_maxid is not", __func__));
388	else if (mp_ncpus == 1)
389		mp_maxid = 0;
390	else
391		KASSERT(mp_maxid >= mp_ncpus - 1,
392		    ("%s: counters out of sync: max %d, count %d", __func__,
393			mp_maxid, mp_ncpus));
394}
395
396int
397cpu_mp_probe(void)
398{
399
400	/*
401	 * Always record BSP in CPU map so that the mbuf init code works
402	 * correctly.
403	 */
404	all_cpus = 1;
405	if (mp_ncpus == 0) {
406		/*
407		 * No CPUs were found, so this must be a UP system.  Setup
408		 * the variables to represent a system with a single CPU
409		 * with an id of 0.
410		 */
411		mp_ncpus = 1;
412		return (0);
413	}
414
415	/* At least one CPU was found. */
416	if (mp_ncpus == 1) {
417		/*
418		 * One CPU was found, so this must be a UP system with
419		 * an I/O APIC.
420		 */
421		mp_maxid = 0;
422		return (0);
423	}
424
425	/* At least two CPUs were found. */
426	return (1);
427}
428
429/*
430 * Initialize the IPI handlers and start up the AP's.
431 */
432void
433cpu_mp_start(void)
434{
435	int i;
436
437	/* Initialize the logical ID to APIC ID table. */
438	for (i = 0; i < MAXCPU; i++) {
439		cpu_apic_ids[i] = -1;
440		cpu_ipi_pending[i] = 0;
441	}
442
443	/* Install an inter-CPU IPI for TLB invalidation */
444	setidt(IPI_INVLTLB, IDTVEC(invltlb), SDT_SYSIGT, SEL_KPL, 0);
445	setidt(IPI_INVLPG, IDTVEC(invlpg), SDT_SYSIGT, SEL_KPL, 0);
446	setidt(IPI_INVLRNG, IDTVEC(invlrng), SDT_SYSIGT, SEL_KPL, 0);
447
448	/* Install an inter-CPU IPI for cache invalidation. */
449	setidt(IPI_INVLCACHE, IDTVEC(invlcache), SDT_SYSIGT, SEL_KPL, 0);
450
451	/* Install an inter-CPU IPI for all-CPU rendezvous */
452	setidt(IPI_RENDEZVOUS, IDTVEC(rendezvous), SDT_SYSIGT, SEL_KPL, 0);
453
454	/* Install generic inter-CPU IPI handler */
455	setidt(IPI_BITMAP_VECTOR, IDTVEC(ipi_intr_bitmap_handler),
456	       SDT_SYSIGT, SEL_KPL, 0);
457
458	/* Install an inter-CPU IPI for CPU stop/restart */
459	setidt(IPI_STOP, IDTVEC(cpustop), SDT_SYSIGT, SEL_KPL, 0);
460
461	/* Install an inter-CPU IPI for CPU suspend/resume */
462	setidt(IPI_SUSPEND, IDTVEC(cpususpend), SDT_SYSIGT, SEL_KPL, 0);
463
464	/* Set boot_cpu_id if needed. */
465	if (boot_cpu_id == -1) {
466		boot_cpu_id = PCPU_GET(apic_id);
467		cpu_info[boot_cpu_id].cpu_bsp = 1;
468	} else
469		KASSERT(boot_cpu_id == PCPU_GET(apic_id),
470		    ("BSP's APIC ID doesn't match boot_cpu_id"));
471
472	/* Probe logical/physical core configuration. */
473	topo_probe();
474
475	assign_cpu_ids();
476
477	/* Start each Application Processor */
478	start_all_aps();
479
480	set_interrupt_apic_ids();
481}
482
483
484/*
485 * Print various information about the SMP system hardware and setup.
486 */
487void
488cpu_mp_announce(void)
489{
490	const char *hyperthread;
491	int i;
492
493	printf("FreeBSD/SMP: %d package(s) x %d core(s)",
494	    mp_ncpus / (cpu_cores * cpu_logical), cpu_cores);
495	if (hyperthreading_cpus > 1)
496	    printf(" x %d HTT threads", cpu_logical);
497	else if (cpu_logical > 1)
498	    printf(" x %d SMT threads", cpu_logical);
499	printf("\n");
500
501	/* List active CPUs first. */
502	printf(" cpu0 (BSP): APIC ID: %2d\n", boot_cpu_id);
503	for (i = 1; i < mp_ncpus; i++) {
504		if (cpu_info[cpu_apic_ids[i]].cpu_hyperthread)
505			hyperthread = "/HT";
506		else
507			hyperthread = "";
508		printf(" cpu%d (AP%s): APIC ID: %2d\n", i, hyperthread,
509		    cpu_apic_ids[i]);
510	}
511
512	/* List disabled CPUs last. */
513	for (i = 0; i <= MAX_APIC_ID; i++) {
514		if (!cpu_info[i].cpu_present || !cpu_info[i].cpu_disabled)
515			continue;
516		if (cpu_info[i].cpu_hyperthread)
517			hyperthread = "/HT";
518		else
519			hyperthread = "";
520		printf("  cpu (AP%s): APIC ID: %2d (disabled)\n", hyperthread,
521		    i);
522	}
523}
524
525/*
526 * AP CPU's call this to initialize themselves.
527 */
528void
529init_secondary(void)
530{
531	struct pcpu *pc;
532	struct nmi_pcpu *np;
533	u_int64_t msr, cr0;
534	int cpu, gsel_tss, x;
535	struct region_descriptor ap_gdt;
536
537	/* Set by the startup code for us to use */
538	cpu = bootAP;
539
540	/* Init tss */
541	common_tss[cpu] = common_tss[0];
542	common_tss[cpu].tss_rsp0 = 0;   /* not used until after switch */
543	common_tss[cpu].tss_iobase = sizeof(struct amd64tss) +
544	    IOPAGES * PAGE_SIZE;
545	common_tss[cpu].tss_ist1 = (long)&doublefault_stack[PAGE_SIZE];
546
547	/* The NMI stack runs on IST2. */
548	np = ((struct nmi_pcpu *) &nmi_stack[PAGE_SIZE]) - 1;
549	common_tss[cpu].tss_ist2 = (long) np;
550
551	/* Prepare private GDT */
552	gdt_segs[GPROC0_SEL].ssd_base = (long) &common_tss[cpu];
553	for (x = 0; x < NGDT; x++) {
554		if (x != GPROC0_SEL && x != (GPROC0_SEL + 1) &&
555		    x != GUSERLDT_SEL && x != (GUSERLDT_SEL + 1))
556			ssdtosd(&gdt_segs[x], &gdt[NGDT * cpu + x]);
557	}
558	ssdtosyssd(&gdt_segs[GPROC0_SEL],
559	    (struct system_segment_descriptor *)&gdt[NGDT * cpu + GPROC0_SEL]);
560	ap_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
561	ap_gdt.rd_base =  (long) &gdt[NGDT * cpu];
562	lgdt(&ap_gdt);			/* does magic intra-segment return */
563
564	/* Get per-cpu data */
565	pc = &__pcpu[cpu];
566
567	/* prime data page for it to use */
568	pcpu_init(pc, cpu, sizeof(struct pcpu));
569	dpcpu_init(dpcpu, cpu);
570	pc->pc_apic_id = cpu_apic_ids[cpu];
571	pc->pc_prvspace = pc;
572	pc->pc_curthread = 0;
573	pc->pc_tssp = &common_tss[cpu];
574	pc->pc_commontssp = &common_tss[cpu];
575	pc->pc_rsp0 = 0;
576	pc->pc_tss = (struct system_segment_descriptor *)&gdt[NGDT * cpu +
577	    GPROC0_SEL];
578	pc->pc_fs32p = &gdt[NGDT * cpu + GUFS32_SEL];
579	pc->pc_gs32p = &gdt[NGDT * cpu + GUGS32_SEL];
580	pc->pc_ldt = (struct system_segment_descriptor *)&gdt[NGDT * cpu +
581	    GUSERLDT_SEL];
582
583	/* Save the per-cpu pointer for use by the NMI handler. */
584	np->np_pcpu = (register_t) pc;
585
586	wrmsr(MSR_FSBASE, 0);		/* User value */
587	wrmsr(MSR_GSBASE, (u_int64_t)pc);
588	wrmsr(MSR_KGSBASE, (u_int64_t)pc);	/* XXX User value while we're in the kernel */
589
590	lidt(&r_idt);
591
592	gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
593	ltr(gsel_tss);
594
595	/*
596	 * Set to a known state:
597	 * Set by mpboot.s: CR0_PG, CR0_PE
598	 * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
599	 */
600	cr0 = rcr0();
601	cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
602	load_cr0(cr0);
603
604	/* Set up the fast syscall stuff */
605	msr = rdmsr(MSR_EFER) | EFER_SCE;
606	wrmsr(MSR_EFER, msr);
607	wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall));
608	wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
609	msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
610	      ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
611	wrmsr(MSR_STAR, msr);
612	wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D);
613
614	/* Disable local APIC just to be sure. */
615	lapic_disable();
616
617	/* signal our startup to the BSP. */
618	mp_naps++;
619
620	/* Spin until the BSP releases the AP's. */
621	while (!aps_ready)
622		ia32_pause();
623
624	/* Initialize the PAT MSR. */
625	pmap_init_pat();
626
627	/* set up CPU registers and state */
628	cpu_setregs();
629
630	/* set up SSE/NX registers */
631	initializecpu();
632
633	/* set up FPU state on the AP */
634	fpuinit();
635
636	/* A quick check from sanity claus */
637	if (PCPU_GET(apic_id) != lapic_id()) {
638		printf("SMP: cpuid = %d\n", PCPU_GET(cpuid));
639		printf("SMP: actual apic_id = %d\n", lapic_id());
640		printf("SMP: correct apic_id = %d\n", PCPU_GET(apic_id));
641		panic("cpuid mismatch! boom!!");
642	}
643
644	/* Initialize curthread. */
645	KASSERT(PCPU_GET(idlethread) != NULL, ("no idle thread"));
646	PCPU_SET(curthread, PCPU_GET(idlethread));
647
648	mca_init();
649
650	mtx_lock_spin(&ap_boot_mtx);
651
652	/* Init local apic for irq's */
653	lapic_setup(1);
654
655	/* Set memory range attributes for this CPU to match the BSP */
656	mem_range_AP_init();
657
658	smp_cpus++;
659
660	CTR1(KTR_SMP, "SMP: AP CPU #%d Launched", PCPU_GET(cpuid));
661	printf("SMP: AP CPU #%d Launched!\n", PCPU_GET(cpuid));
662
663	/* Determine if we are a logical CPU. */
664	if (logical_cpus > 1 && PCPU_GET(apic_id) % logical_cpus != 0)
665		logical_cpus_mask |= PCPU_GET(cpumask);
666
667	/* Determine if we are a hyperthread. */
668	if (hyperthreading_cpus > 1 &&
669	    PCPU_GET(apic_id) % hyperthreading_cpus != 0)
670		hyperthreading_cpus_mask |= PCPU_GET(cpumask);
671
672	/* Build our map of 'other' CPUs. */
673	PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
674
675	if (bootverbose)
676		lapic_dump("AP");
677
678	if (smp_cpus == mp_ncpus) {
679		/* enable IPI's, tlb shootdown, freezes etc */
680		atomic_store_rel_int(&smp_started, 1);
681		smp_active = 1;	 /* historic */
682	}
683
684	/*
685	 * Enable global pages TLB extension
686	 * This also implicitly flushes the TLB
687	 */
688
689	load_cr4(rcr4() | CR4_PGE);
690	load_ds(_udatasel);
691	load_es(_udatasel);
692	load_fs(_ufssel);
693	mtx_unlock_spin(&ap_boot_mtx);
694
695	/* wait until all the AP's are up */
696	while (smp_started == 0)
697		ia32_pause();
698
699	sched_throw(NULL);
700
701	panic("scheduler returned us to %s", __func__);
702	/* NOTREACHED */
703}
704
705/*******************************************************************
706 * local functions and data
707 */
708
709/*
710 * We tell the I/O APIC code about all the CPUs we want to receive
711 * interrupts.  If we don't want certain CPUs to receive IRQs we
712 * can simply not tell the I/O APIC code about them in this function.
713 * We also do not tell it about the BSP since it tells itself about
714 * the BSP internally to work with UP kernels and on UP machines.
715 */
716static void
717set_interrupt_apic_ids(void)
718{
719	u_int i, apic_id;
720
721	for (i = 0; i < MAXCPU; i++) {
722		apic_id = cpu_apic_ids[i];
723		if (apic_id == -1)
724			continue;
725		if (cpu_info[apic_id].cpu_bsp)
726			continue;
727		if (cpu_info[apic_id].cpu_disabled)
728			continue;
729
730		/* Don't let hyperthreads service interrupts. */
731		if (hyperthreading_cpus > 1 &&
732		    apic_id % hyperthreading_cpus != 0)
733			continue;
734
735		intr_add_cpu(i);
736	}
737}
738
739/*
740 * Assign logical CPU IDs to local APICs.
741 */
742static void
743assign_cpu_ids(void)
744{
745	u_int i;
746
747	TUNABLE_INT_FETCH("machdep.hyperthreading_allowed",
748	    &hyperthreading_allowed);
749
750	/* Check for explicitly disabled CPUs. */
751	for (i = 0; i <= MAX_APIC_ID; i++) {
752		if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp)
753			continue;
754
755		if (hyperthreading_cpus > 1 && i % hyperthreading_cpus != 0) {
756			cpu_info[i].cpu_hyperthread = 1;
757#if defined(SCHED_ULE)
758			/*
759			 * Don't use HT CPU if it has been disabled by a
760			 * tunable.
761			 */
762			if (hyperthreading_allowed == 0) {
763				cpu_info[i].cpu_disabled = 1;
764				continue;
765			}
766#endif
767		}
768
769		/* Don't use this CPU if it has been disabled by a tunable. */
770		if (resource_disabled("lapic", i)) {
771			cpu_info[i].cpu_disabled = 1;
772			continue;
773		}
774	}
775
776	/*
777	 * Assign CPU IDs to local APIC IDs and disable any CPUs
778	 * beyond MAXCPU.  CPU 0 is always assigned to the BSP.
779	 *
780	 * To minimize confusion for userland, we attempt to number
781	 * CPUs such that all threads and cores in a package are
782	 * grouped together.  For now we assume that the BSP is always
783	 * the first thread in a package and just start adding APs
784	 * starting with the BSP's APIC ID.
785	 */
786	mp_ncpus = 1;
787	cpu_apic_ids[0] = boot_cpu_id;
788	apic_cpuids[boot_cpu_id] = 0;
789	for (i = boot_cpu_id + 1; i != boot_cpu_id;
790	     i == MAX_APIC_ID ? i = 0 : i++) {
791		if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp ||
792		    cpu_info[i].cpu_disabled)
793			continue;
794
795		if (mp_ncpus < MAXCPU) {
796			cpu_apic_ids[mp_ncpus] = i;
797			apic_cpuids[i] = mp_ncpus;
798			mp_ncpus++;
799		} else
800			cpu_info[i].cpu_disabled = 1;
801	}
802	KASSERT(mp_maxid >= mp_ncpus - 1,
803	    ("%s: counters out of sync: max %d, count %d", __func__, mp_maxid,
804	    mp_ncpus));
805}
806
807/*
808 * start each AP in our list
809 */
810static int
811start_all_aps(void)
812{
813	vm_offset_t va = boot_address + KERNBASE;
814	u_int64_t *pt4, *pt3, *pt2;
815	u_int32_t mpbioswarmvec;
816	int apic_id, cpu, i;
817	u_char mpbiosreason;
818
819	mtx_init(&ap_boot_mtx, "ap boot", NULL, MTX_SPIN);
820
821	/* install the AP 1st level boot code */
822	pmap_kenter(va, boot_address);
823	pmap_invalidate_page(kernel_pmap, va);
824	bcopy(mptramp_start, (void *)va, bootMP_size);
825
826	/* Locate the page tables, they'll be below the trampoline */
827	pt4 = (u_int64_t *)(uintptr_t)(mptramp_pagetables + KERNBASE);
828	pt3 = pt4 + (PAGE_SIZE) / sizeof(u_int64_t);
829	pt2 = pt3 + (PAGE_SIZE) / sizeof(u_int64_t);
830
831	/* Create the initial 1GB replicated page tables */
832	for (i = 0; i < 512; i++) {
833		/* Each slot of the level 4 pages points to the same level 3 page */
834		pt4[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + PAGE_SIZE);
835		pt4[i] |= PG_V | PG_RW | PG_U;
836
837		/* Each slot of the level 3 pages points to the same level 2 page */
838		pt3[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + (2 * PAGE_SIZE));
839		pt3[i] |= PG_V | PG_RW | PG_U;
840
841		/* The level 2 page slots are mapped with 2MB pages for 1GB. */
842		pt2[i] = i * (2 * 1024 * 1024);
843		pt2[i] |= PG_V | PG_RW | PG_PS | PG_U;
844	}
845
846	/* save the current value of the warm-start vector */
847	mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
848	outb(CMOS_REG, BIOS_RESET);
849	mpbiosreason = inb(CMOS_DATA);
850
851	/* setup a vector to our boot code */
852	*((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
853	*((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
854	outb(CMOS_REG, BIOS_RESET);
855	outb(CMOS_DATA, BIOS_WARM);	/* 'warm-start' */
856
857	/* start each AP */
858	for (cpu = 1; cpu < mp_ncpus; cpu++) {
859		apic_id = cpu_apic_ids[cpu];
860
861		/* allocate and set up an idle stack data page */
862		bootstacks[cpu] = (void *)kmem_alloc(kernel_map, KSTACK_PAGES * PAGE_SIZE);
863		doublefault_stack = (char *)kmem_alloc(kernel_map, PAGE_SIZE);
864		nmi_stack = (char *)kmem_alloc(kernel_map, PAGE_SIZE);
865		dpcpu = (void *)kmem_alloc(kernel_map, DPCPU_SIZE);
866
867		bootSTK = (char *)bootstacks[cpu] + KSTACK_PAGES * PAGE_SIZE - 8;
868		bootAP = cpu;
869
870		/* attempt to start the Application Processor */
871		if (!start_ap(apic_id)) {
872			/* restore the warmstart vector */
873			*(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
874			panic("AP #%d (PHY# %d) failed!", cpu, apic_id);
875		}
876
877		all_cpus |= (1 << cpu);		/* record AP in CPU map */
878	}
879
880	/* build our map of 'other' CPUs */
881	PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
882
883	/* restore the warmstart vector */
884	*(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
885
886	outb(CMOS_REG, BIOS_RESET);
887	outb(CMOS_DATA, mpbiosreason);
888
889	/* number of APs actually started */
890	return mp_naps;
891}
892
893
894/*
895 * This function starts the AP (application processor) identified
896 * by the APIC ID 'physicalCpu'.  It does quite a "song and dance"
897 * to accomplish this.  This is necessary because of the nuances
898 * of the different hardware we might encounter.  It isn't pretty,
899 * but it seems to work.
900 */
901static int
902start_ap(int apic_id)
903{
904	int vector, ms;
905	int cpus;
906
907	/* calculate the vector */
908	vector = (boot_address >> 12) & 0xff;
909
910	/* used as a watchpoint to signal AP startup */
911	cpus = mp_naps;
912
913	/*
914	 * first we do an INIT/RESET IPI this INIT IPI might be run, reseting
915	 * and running the target CPU. OR this INIT IPI might be latched (P5
916	 * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
917	 * ignored.
918	 */
919
920	/* do an INIT IPI: assert RESET */
921	lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
922	    APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, apic_id);
923
924	/* wait for pending status end */
925	lapic_ipi_wait(-1);
926
927	/* do an INIT IPI: deassert RESET */
928	lapic_ipi_raw(APIC_DEST_ALLESELF | APIC_TRIGMOD_LEVEL |
929	    APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, 0);
930
931	/* wait for pending status end */
932	DELAY(10000);		/* wait ~10mS */
933	lapic_ipi_wait(-1);
934
935	/*
936	 * next we do a STARTUP IPI: the previous INIT IPI might still be
937	 * latched, (P5 bug) this 1st STARTUP would then terminate
938	 * immediately, and the previously started INIT IPI would continue. OR
939	 * the previous INIT IPI has already run. and this STARTUP IPI will
940	 * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
941	 * will run.
942	 */
943
944	/* do a STARTUP IPI */
945	lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
946	    APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
947	    vector, apic_id);
948	lapic_ipi_wait(-1);
949	DELAY(200);		/* wait ~200uS */
950
951	/*
952	 * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
953	 * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
954	 * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
955	 * recognized after hardware RESET or INIT IPI.
956	 */
957
958	lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
959	    APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
960	    vector, apic_id);
961	lapic_ipi_wait(-1);
962	DELAY(200);		/* wait ~200uS */
963
964	/* Wait up to 5 seconds for it to start. */
965	for (ms = 0; ms < 5000; ms++) {
966		if (mp_naps > cpus)
967			return 1;	/* return SUCCESS */
968		DELAY(1000);
969	}
970	return 0;		/* return FAILURE */
971}
972
973/*
974 * Flush the TLB on all other CPU's
975 */
976static void
977smp_tlb_shootdown(u_int vector, vm_offset_t addr1, vm_offset_t addr2)
978{
979	u_int ncpu;
980
981	ncpu = mp_ncpus - 1;	/* does not shootdown self */
982	if (ncpu < 1)
983		return;		/* no other cpus */
984	if (!(read_rflags() & PSL_I))
985		panic("%s: interrupts disabled", __func__);
986	mtx_lock_spin(&smp_ipi_mtx);
987	smp_tlb_addr1 = addr1;
988	smp_tlb_addr2 = addr2;
989	atomic_store_rel_int(&smp_tlb_wait, 0);
990	ipi_all_but_self(vector);
991	while (smp_tlb_wait < ncpu)
992		ia32_pause();
993	mtx_unlock_spin(&smp_ipi_mtx);
994}
995
996static void
997smp_targeted_tlb_shootdown(cpumask_t mask, u_int vector, vm_offset_t addr1, vm_offset_t addr2)
998{
999	int ncpu, othercpus;
1000
1001	othercpus = mp_ncpus - 1;
1002	if (mask == (u_int)-1) {
1003		ncpu = othercpus;
1004		if (ncpu < 1)
1005			return;
1006	} else {
1007		mask &= ~PCPU_GET(cpumask);
1008		if (mask == 0)
1009			return;
1010		ncpu = bitcount32(mask);
1011		if (ncpu > othercpus) {
1012			/* XXX this should be a panic offence */
1013			printf("SMP: tlb shootdown to %d other cpus (only have %d)\n",
1014			    ncpu, othercpus);
1015			ncpu = othercpus;
1016		}
1017		/* XXX should be a panic, implied by mask == 0 above */
1018		if (ncpu < 1)
1019			return;
1020	}
1021	if (!(read_rflags() & PSL_I))
1022		panic("%s: interrupts disabled", __func__);
1023	mtx_lock_spin(&smp_ipi_mtx);
1024	smp_tlb_addr1 = addr1;
1025	smp_tlb_addr2 = addr2;
1026	atomic_store_rel_int(&smp_tlb_wait, 0);
1027	if (mask == (u_int)-1)
1028		ipi_all_but_self(vector);
1029	else
1030		ipi_selected(mask, vector);
1031	while (smp_tlb_wait < ncpu)
1032		ia32_pause();
1033	mtx_unlock_spin(&smp_ipi_mtx);
1034}
1035
1036void
1037smp_cache_flush(void)
1038{
1039
1040	if (smp_started)
1041		smp_tlb_shootdown(IPI_INVLCACHE, 0, 0);
1042}
1043
1044void
1045smp_invltlb(void)
1046{
1047
1048	if (smp_started) {
1049		smp_tlb_shootdown(IPI_INVLTLB, 0, 0);
1050	}
1051}
1052
1053void
1054smp_invlpg(vm_offset_t addr)
1055{
1056
1057	if (smp_started)
1058		smp_tlb_shootdown(IPI_INVLPG, addr, 0);
1059}
1060
1061void
1062smp_invlpg_range(vm_offset_t addr1, vm_offset_t addr2)
1063{
1064
1065	if (smp_started) {
1066		smp_tlb_shootdown(IPI_INVLRNG, addr1, addr2);
1067	}
1068}
1069
1070void
1071smp_masked_invltlb(cpumask_t mask)
1072{
1073
1074	if (smp_started) {
1075		smp_targeted_tlb_shootdown(mask, IPI_INVLTLB, 0, 0);
1076	}
1077}
1078
1079void
1080smp_masked_invlpg(cpumask_t mask, vm_offset_t addr)
1081{
1082
1083	if (smp_started) {
1084		smp_targeted_tlb_shootdown(mask, IPI_INVLPG, addr, 0);
1085	}
1086}
1087
1088void
1089smp_masked_invlpg_range(cpumask_t mask, vm_offset_t addr1, vm_offset_t addr2)
1090{
1091
1092	if (smp_started) {
1093		smp_targeted_tlb_shootdown(mask, IPI_INVLRNG, addr1, addr2);
1094	}
1095}
1096
1097void
1098ipi_bitmap_handler(struct trapframe frame)
1099{
1100	int cpu = PCPU_GET(cpuid);
1101	u_int ipi_bitmap;
1102
1103	ipi_bitmap = atomic_readandclear_int(&cpu_ipi_pending[cpu]);
1104
1105	if (ipi_bitmap & (1 << IPI_PREEMPT))
1106		sched_preempt(curthread);
1107
1108	/* Nothing to do for AST */
1109
1110	if (ipi_bitmap & (1 << IPI_HARDCLOCK))
1111		hardclockintr(&frame);
1112
1113	if (ipi_bitmap & (1 << IPI_STATCLOCK))
1114		statclockintr(&frame);
1115}
1116
1117/*
1118 * send an IPI to a set of cpus.
1119 */
1120void
1121ipi_selected(cpumask_t cpus, u_int ipi)
1122{
1123	int cpu;
1124	u_int bitmap = 0;
1125	u_int old_pending;
1126	u_int new_pending;
1127
1128	if (IPI_IS_BITMAPED(ipi)) {
1129		bitmap = 1 << ipi;
1130		ipi = IPI_BITMAP_VECTOR;
1131	}
1132
1133	/*
1134	 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1135	 * of help in order to understand what is the source.
1136	 * Set the mask of receiving CPUs for this purpose.
1137	 */
1138	if (ipi == IPI_STOP_HARD)
1139		atomic_set_int(&ipi_nmi_pending, cpus);
1140
1141	CTR3(KTR_SMP, "%s: cpus: %x ipi: %x", __func__, cpus, ipi);
1142	while ((cpu = ffs(cpus)) != 0) {
1143		cpu--;
1144		cpus &= ~(1 << cpu);
1145
1146		KASSERT(cpu_apic_ids[cpu] != -1,
1147		    ("IPI to non-existent CPU %d", cpu));
1148
1149		if (bitmap) {
1150			do {
1151				old_pending = cpu_ipi_pending[cpu];
1152				new_pending = old_pending | bitmap;
1153			} while  (!atomic_cmpset_int(&cpu_ipi_pending[cpu],old_pending, new_pending));
1154
1155			if (old_pending)
1156				continue;
1157		}
1158
1159		lapic_ipi_vectored(ipi, cpu_apic_ids[cpu]);
1160	}
1161
1162}
1163
1164/*
1165 * send an IPI to all CPUs EXCEPT myself
1166 */
1167void
1168ipi_all_but_self(u_int ipi)
1169{
1170
1171	if (IPI_IS_BITMAPED(ipi)) {
1172		ipi_selected(PCPU_GET(other_cpus), ipi);
1173		return;
1174	}
1175
1176	/*
1177	 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1178	 * of help in order to understand what is the source.
1179	 * Set the mask of receiving CPUs for this purpose.
1180	 */
1181	if (ipi == IPI_STOP_HARD)
1182		atomic_set_int(&ipi_nmi_pending, PCPU_GET(other_cpus));
1183
1184	CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1185	lapic_ipi_vectored(ipi, APIC_IPI_DEST_OTHERS);
1186}
1187
1188int
1189ipi_nmi_handler()
1190{
1191	cpumask_t cpumask;
1192
1193	/*
1194	 * As long as there is not a simple way to know about a NMI's
1195	 * source, if the bitmask for the current CPU is present in
1196	 * the global pending bitword an IPI_STOP_HARD has been issued
1197	 * and should be handled.
1198	 */
1199	cpumask = PCPU_GET(cpumask);
1200	if ((ipi_nmi_pending & cpumask) == 0)
1201		return (1);
1202
1203	atomic_clear_int(&ipi_nmi_pending, cpumask);
1204	cpustop_handler();
1205	return (0);
1206}
1207
1208/*
1209 * Handle an IPI_STOP by saving our current context and spinning until we
1210 * are resumed.
1211 */
1212void
1213cpustop_handler(void)
1214{
1215	int cpu = PCPU_GET(cpuid);
1216	int cpumask = PCPU_GET(cpumask);
1217
1218	savectx(&stoppcbs[cpu]);
1219
1220	/* Indicate that we are stopped */
1221	atomic_set_int(&stopped_cpus, cpumask);
1222
1223	/* Wait for restart */
1224	while (!(started_cpus & cpumask))
1225	    ia32_pause();
1226
1227	atomic_clear_int(&started_cpus, cpumask);
1228	atomic_clear_int(&stopped_cpus, cpumask);
1229
1230	if (cpu == 0 && cpustop_restartfunc != NULL) {
1231		cpustop_restartfunc();
1232		cpustop_restartfunc = NULL;
1233	}
1234}
1235
1236/*
1237 * Handle an IPI_SUSPEND by saving our current context and spinning until we
1238 * are resumed.
1239 */
1240void
1241cpususpend_handler(void)
1242{
1243	struct savefpu *stopfpu;
1244	register_t cr3, rf;
1245	int cpu = PCPU_GET(cpuid);
1246	int cpumask = PCPU_GET(cpumask);
1247
1248	rf = intr_disable();
1249	cr3 = rcr3();
1250	stopfpu = &stopxpcbs[cpu]->xpcb_pcb.pcb_save;
1251	if (savectx2(stopxpcbs[cpu])) {
1252		fpugetregs(curthread, stopfpu);
1253		wbinvd();
1254		atomic_set_int(&stopped_cpus, cpumask);
1255	} else
1256		fpusetregs(curthread, stopfpu);
1257
1258	/* Wait for resume */
1259	while (!(started_cpus & cpumask))
1260		ia32_pause();
1261
1262	atomic_clear_int(&started_cpus, cpumask);
1263	atomic_clear_int(&stopped_cpus, cpumask);
1264
1265	/* Restore CR3 and enable interrupts */
1266	load_cr3(cr3);
1267	lapic_setup(0);
1268	intr_restore(rf);
1269}
1270
1271/*
1272 * This is called once the rest of the system is up and running and we're
1273 * ready to let the AP's out of the pen.
1274 */
1275static void
1276release_aps(void *dummy __unused)
1277{
1278
1279	if (mp_ncpus == 1)
1280		return;
1281	atomic_store_rel_int(&aps_ready, 1);
1282	while (smp_started == 0)
1283		ia32_pause();
1284}
1285SYSINIT(start_aps, SI_SUB_SMP, SI_ORDER_FIRST, release_aps, NULL);
1286
1287static int
1288sysctl_hlt_cpus(SYSCTL_HANDLER_ARGS)
1289{
1290	cpumask_t mask;
1291	int error;
1292
1293	mask = hlt_cpus_mask;
1294	error = sysctl_handle_int(oidp, &mask, 0, req);
1295	if (error || !req->newptr)
1296		return (error);
1297
1298	if (logical_cpus_mask != 0 &&
1299	    (mask & logical_cpus_mask) == logical_cpus_mask)
1300		hlt_logical_cpus = 1;
1301	else
1302		hlt_logical_cpus = 0;
1303
1304	if (! hyperthreading_allowed)
1305		mask |= hyperthreading_cpus_mask;
1306
1307	if ((mask & all_cpus) == all_cpus)
1308		mask &= ~(1<<0);
1309	hlt_cpus_mask = mask;
1310	return (error);
1311}
1312SYSCTL_PROC(_machdep, OID_AUTO, hlt_cpus, CTLTYPE_INT|CTLFLAG_RW,
1313    0, 0, sysctl_hlt_cpus, "IU",
1314    "Bitmap of CPUs to halt.  101 (binary) will halt CPUs 0 and 2.");
1315
1316static int
1317sysctl_hlt_logical_cpus(SYSCTL_HANDLER_ARGS)
1318{
1319	int disable, error;
1320
1321	disable = hlt_logical_cpus;
1322	error = sysctl_handle_int(oidp, &disable, 0, req);
1323	if (error || !req->newptr)
1324		return (error);
1325
1326	if (disable)
1327		hlt_cpus_mask |= logical_cpus_mask;
1328	else
1329		hlt_cpus_mask &= ~logical_cpus_mask;
1330
1331	if (! hyperthreading_allowed)
1332		hlt_cpus_mask |= hyperthreading_cpus_mask;
1333
1334	if ((hlt_cpus_mask & all_cpus) == all_cpus)
1335		hlt_cpus_mask &= ~(1<<0);
1336
1337	hlt_logical_cpus = disable;
1338	return (error);
1339}
1340
1341static int
1342sysctl_hyperthreading_allowed(SYSCTL_HANDLER_ARGS)
1343{
1344	int allowed, error;
1345
1346	allowed = hyperthreading_allowed;
1347	error = sysctl_handle_int(oidp, &allowed, 0, req);
1348	if (error || !req->newptr)
1349		return (error);
1350
1351#ifdef SCHED_ULE
1352	/*
1353	 * SCHED_ULE doesn't allow enabling/disabling HT cores at
1354	 * run-time.
1355	 */
1356	if (allowed != hyperthreading_allowed)
1357		return (ENOTSUP);
1358	return (error);
1359#endif
1360
1361	if (allowed)
1362		hlt_cpus_mask &= ~hyperthreading_cpus_mask;
1363	else
1364		hlt_cpus_mask |= hyperthreading_cpus_mask;
1365
1366	if (logical_cpus_mask != 0 &&
1367	    (hlt_cpus_mask & logical_cpus_mask) == logical_cpus_mask)
1368		hlt_logical_cpus = 1;
1369	else
1370		hlt_logical_cpus = 0;
1371
1372	if ((hlt_cpus_mask & all_cpus) == all_cpus)
1373		hlt_cpus_mask &= ~(1<<0);
1374
1375	hyperthreading_allowed = allowed;
1376	return (error);
1377}
1378
1379static void
1380cpu_hlt_setup(void *dummy __unused)
1381{
1382
1383	if (logical_cpus_mask != 0) {
1384		TUNABLE_INT_FETCH("machdep.hlt_logical_cpus",
1385		    &hlt_logical_cpus);
1386		sysctl_ctx_init(&logical_cpu_clist);
1387		SYSCTL_ADD_PROC(&logical_cpu_clist,
1388		    SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1389		    "hlt_logical_cpus", CTLTYPE_INT|CTLFLAG_RW, 0, 0,
1390		    sysctl_hlt_logical_cpus, "IU", "");
1391		SYSCTL_ADD_UINT(&logical_cpu_clist,
1392		    SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1393		    "logical_cpus_mask", CTLTYPE_INT|CTLFLAG_RD,
1394		    &logical_cpus_mask, 0, "");
1395
1396		if (hlt_logical_cpus)
1397			hlt_cpus_mask |= logical_cpus_mask;
1398
1399		/*
1400		 * If necessary for security purposes, force
1401		 * hyperthreading off, regardless of the value
1402		 * of hlt_logical_cpus.
1403		 */
1404		if (hyperthreading_cpus_mask) {
1405			SYSCTL_ADD_PROC(&logical_cpu_clist,
1406			    SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1407			    "hyperthreading_allowed", CTLTYPE_INT|CTLFLAG_RW,
1408			    0, 0, sysctl_hyperthreading_allowed, "IU", "");
1409			if (! hyperthreading_allowed)
1410				hlt_cpus_mask |= hyperthreading_cpus_mask;
1411		}
1412	}
1413}
1414SYSINIT(cpu_hlt, SI_SUB_SMP, SI_ORDER_ANY, cpu_hlt_setup, NULL);
1415
1416int
1417mp_grab_cpu_hlt(void)
1418{
1419	u_int mask = PCPU_GET(cpumask);
1420#ifdef MP_WATCHDOG
1421	u_int cpuid = PCPU_GET(cpuid);
1422#endif
1423	int retval;
1424
1425#ifdef MP_WATCHDOG
1426	ap_watchdog(cpuid);
1427#endif
1428
1429	retval = mask & hlt_cpus_mask;
1430	while (mask & hlt_cpus_mask)
1431		__asm __volatile("sti; hlt" : : : "memory");
1432	return (retval);
1433}
1434