mp_x86.c revision 162232
1/*-
2 * Copyright (c) 1996, by Steve Passe
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. The name of the developer may NOT be used to endorse or promote products
11 *    derived from this software without specific prior written permission.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23 * SUCH DAMAGE.
24 */
25
26#include <sys/cdefs.h>
27__FBSDID("$FreeBSD: head/sys/i386/i386/mp_machdep.c 162232 2006-09-11 20:10:42Z jhb $");
28
29#include "opt_apic.h"
30#include "opt_cpu.h"
31#include "opt_kstack_pages.h"
32#include "opt_mp_watchdog.h"
33#include "opt_sched.h"
34#include "opt_smp.h"
35
36#if !defined(lint)
37#if !defined(SMP)
38#error How did you get here?
39#endif
40
41#ifndef DEV_APIC
42#error The apic device is required for SMP, add "device apic" to your config file.
43#endif
44#if defined(CPU_DISABLE_CMPXCHG) && !defined(COMPILING_LINT)
45#error SMP not supported with CPU_DISABLE_CMPXCHG
46#endif
47#endif /* not lint */
48
49#include <sys/param.h>
50#include <sys/systm.h>
51#include <sys/bus.h>
52#include <sys/cons.h>	/* cngetc() */
53#ifdef GPROF
54#include <sys/gmon.h>
55#endif
56#include <sys/kernel.h>
57#include <sys/ktr.h>
58#include <sys/lock.h>
59#include <sys/malloc.h>
60#include <sys/memrange.h>
61#include <sys/mutex.h>
62#include <sys/pcpu.h>
63#include <sys/proc.h>
64#include <sys/smp.h>
65#include <sys/sysctl.h>
66
67#include <vm/vm.h>
68#include <vm/vm_param.h>
69#include <vm/pmap.h>
70#include <vm/vm_kern.h>
71#include <vm/vm_extern.h>
72
73#include <machine/apicreg.h>
74#include <machine/md_var.h>
75#include <machine/mp_watchdog.h>
76#include <machine/pcb.h>
77#include <machine/smp.h>
78#include <machine/specialreg.h>
79#include <machine/privatespace.h>
80
81#define WARMBOOT_TARGET		0
82#define WARMBOOT_OFF		(KERNBASE + 0x0467)
83#define WARMBOOT_SEG		(KERNBASE + 0x0469)
84
85#define CMOS_REG		(0x70)
86#define CMOS_DATA		(0x71)
87#define BIOS_RESET		(0x0f)
88#define BIOS_WARM		(0x0a)
89
90/*
91 * this code MUST be enabled here and in mpboot.s.
92 * it follows the very early stages of AP boot by placing values in CMOS ram.
93 * it NORMALLY will never be needed and thus the primitive method for enabling.
94 *
95#define CHECK_POINTS
96 */
97
98#if defined(CHECK_POINTS) && !defined(PC98)
99#define CHECK_READ(A)	 (outb(CMOS_REG, (A)), inb(CMOS_DATA))
100#define CHECK_WRITE(A,D) (outb(CMOS_REG, (A)), outb(CMOS_DATA, (D)))
101
102#define CHECK_INIT(D);				\
103	CHECK_WRITE(0x34, (D));			\
104	CHECK_WRITE(0x35, (D));			\
105	CHECK_WRITE(0x36, (D));			\
106	CHECK_WRITE(0x37, (D));			\
107	CHECK_WRITE(0x38, (D));			\
108	CHECK_WRITE(0x39, (D));
109
110#define CHECK_PRINT(S);				\
111	printf("%s: %d, %d, %d, %d, %d, %d\n",	\
112	   (S),					\
113	   CHECK_READ(0x34),			\
114	   CHECK_READ(0x35),			\
115	   CHECK_READ(0x36),			\
116	   CHECK_READ(0x37),			\
117	   CHECK_READ(0x38),			\
118	   CHECK_READ(0x39));
119
120#else				/* CHECK_POINTS */
121
122#define CHECK_INIT(D)
123#define CHECK_PRINT(S)
124#define CHECK_WRITE(A, D)
125
126#endif				/* CHECK_POINTS */
127
128/* lock region used by kernel profiling */
129int	mcount_lock;
130
131int	mp_naps;		/* # of Applications processors */
132int	boot_cpu_id = -1;	/* designated BSP */
133extern	int nkpt;
134
135/*
136 * CPU topology map datastructures for HTT.
137 */
138static struct cpu_group mp_groups[MAXCPU];
139static struct cpu_top mp_top;
140
141/* AP uses this during bootstrap.  Do not staticize.  */
142char *bootSTK;
143static int bootAP;
144
145/* Hotwire a 0->4MB V==P mapping */
146extern pt_entry_t *KPTphys;
147
148/* SMP page table page */
149extern pt_entry_t *SMPpt;
150
151struct pcb stoppcbs[MAXCPU];
152
153/* Variables needed for SMP tlb shootdown. */
154vm_offset_t smp_tlb_addr1;
155vm_offset_t smp_tlb_addr2;
156volatile int smp_tlb_wait;
157
158#ifdef STOP_NMI
159volatile cpumask_t ipi_nmi_pending;
160
161static void	ipi_nmi_selected(u_int32_t cpus);
162#endif
163
164#ifdef COUNT_IPIS
165/* Interrupt counts. */
166#ifdef IPI_PREEMPTION
167static u_long *ipi_preempt_counts[MAXCPU];
168#endif
169static u_long *ipi_ast_counts[MAXCPU];
170u_long *ipi_invltlb_counts[MAXCPU];
171u_long *ipi_invlrng_counts[MAXCPU];
172u_long *ipi_invlpg_counts[MAXCPU];
173u_long *ipi_invlcache_counts[MAXCPU];
174u_long *ipi_rendezvous_counts[MAXCPU];
175u_long *ipi_lazypmap_counts[MAXCPU];
176#endif
177
178/*
179 * Local data and functions.
180 */
181
182#ifdef STOP_NMI
183/*
184 * Provide an alternate method of stopping other CPUs. If another CPU has
185 * disabled interrupts the conventional STOP IPI will be blocked. This
186 * NMI-based stop should get through in that case.
187 */
188static int stop_cpus_with_nmi = 1;
189SYSCTL_INT(_debug, OID_AUTO, stop_cpus_with_nmi, CTLTYPE_INT | CTLFLAG_RW,
190    &stop_cpus_with_nmi, 0, "");
191TUNABLE_INT("debug.stop_cpus_with_nmi", &stop_cpus_with_nmi);
192#else
193#define	stop_cpus_with_nmi	0
194#endif
195
196static u_int logical_cpus;
197
198/* used to hold the AP's until we are ready to release them */
199static struct mtx ap_boot_mtx;
200
201/* Set to 1 once we're ready to let the APs out of the pen. */
202static volatile int aps_ready = 0;
203
204/*
205 * Store data from cpu_add() until later in the boot when we actually setup
206 * the APs.
207 */
208struct cpu_info {
209	int	cpu_present:1;
210	int	cpu_bsp:1;
211	int	cpu_disabled:1;
212} static cpu_info[MAXCPU];
213static int cpu_apic_ids[MAXCPU];
214
215/* Holds pending bitmap based IPIs per CPU */
216static volatile u_int cpu_ipi_pending[MAXCPU];
217
218static u_int boot_address;
219
220static void	set_interrupt_apic_ids(void);
221static int	start_all_aps(void);
222static void	install_ap_tramp(void);
223static int	start_ap(int apic_id);
224static void	release_aps(void *dummy);
225
226static int	hlt_logical_cpus;
227static u_int	hyperthreading_cpus;
228static cpumask_t	hyperthreading_cpus_mask;
229static int	hyperthreading_allowed = 1;
230static struct	sysctl_ctx_list logical_cpu_clist;
231
232static void
233mem_range_AP_init(void)
234{
235	if (mem_range_softc.mr_op && mem_range_softc.mr_op->initAP)
236		mem_range_softc.mr_op->initAP(&mem_range_softc);
237}
238
239void
240mp_topology(void)
241{
242	struct cpu_group *group;
243	u_int regs[4];
244	int logical_cpus;
245	int apic_id;
246	int groups;
247	int cpu;
248
249	/* Build the smp_topology map. */
250	/* Nothing to do if there is no HTT support. */
251	if ((cpu_feature & CPUID_HTT) == 0)
252		return;
253	logical_cpus = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
254	if (logical_cpus <= 1)
255		return;
256	/* Nothing to do if reported cores are physical cores. */
257	if (strcmp(cpu_vendor, "GenuineIntel") == 0 && cpu_high >= 4) {
258		cpuid_count(4, 0, regs);
259		if ((regs[0] & 0x1f) != 0 &&
260		    logical_cpus <= ((regs[0] >> 26) & 0x3f) + 1)
261			return;
262	}
263	group = &mp_groups[0];
264	groups = 1;
265	for (cpu = 0, apic_id = 0; apic_id < MAXCPU; apic_id++) {
266		if (!cpu_info[apic_id].cpu_present)
267			continue;
268		/*
269		 * If the current group has members and we're not a logical
270		 * cpu, create a new group.
271		 */
272		if (group->cg_count != 0 && (apic_id % logical_cpus) == 0) {
273			group++;
274			groups++;
275		}
276		group->cg_count++;
277		group->cg_mask |= 1 << cpu;
278		cpu++;
279	}
280
281	mp_top.ct_count = groups;
282	mp_top.ct_group = mp_groups;
283	smp_topology = &mp_top;
284}
285
286
287/*
288 * Calculate usable address in base memory for AP trampoline code.
289 */
290u_int
291mp_bootaddress(u_int basemem)
292{
293
294	boot_address = trunc_page(basemem);	/* round down to 4k boundary */
295	if ((basemem - boot_address) < bootMP_size)
296		boot_address -= PAGE_SIZE;	/* not enough, lower by 4k */
297
298	return boot_address;
299}
300
301void
302cpu_add(u_int apic_id, char boot_cpu)
303{
304
305	if (apic_id >= MAXCPU) {
306		printf("SMP: CPU %d exceeds maximum CPU %d, ignoring\n",
307		    apic_id, MAXCPU - 1);
308		return;
309	}
310	KASSERT(cpu_info[apic_id].cpu_present == 0, ("CPU %d added twice",
311	    apic_id));
312	cpu_info[apic_id].cpu_present = 1;
313	if (boot_cpu) {
314		KASSERT(boot_cpu_id == -1,
315		    ("CPU %d claims to be BSP, but CPU %d already is", apic_id,
316		    boot_cpu_id));
317		boot_cpu_id = apic_id;
318		cpu_info[apic_id].cpu_bsp = 1;
319	}
320	mp_ncpus++;
321	if (bootverbose)
322		printf("SMP: Added CPU %d (%s)\n", apic_id, boot_cpu ? "BSP" :
323		    "AP");
324
325}
326
327void
328cpu_mp_setmaxid(void)
329{
330
331	mp_maxid = MAXCPU - 1;
332}
333
334int
335cpu_mp_probe(void)
336{
337
338	/*
339	 * Always record BSP in CPU map so that the mbuf init code works
340	 * correctly.
341	 */
342	all_cpus = 1;
343	if (mp_ncpus == 0) {
344		/*
345		 * No CPUs were found, so this must be a UP system.  Setup
346		 * the variables to represent a system with a single CPU
347		 * with an id of 0.
348		 */
349		mp_ncpus = 1;
350		return (0);
351	}
352
353	/* At least one CPU was found. */
354	if (mp_ncpus == 1) {
355		/*
356		 * One CPU was found, so this must be a UP system with
357		 * an I/O APIC.
358		 */
359		return (0);
360	}
361
362	/* At least two CPUs were found. */
363	return (1);
364}
365
366/*
367 * Initialize the IPI handlers and start up the AP's.
368 */
369void
370cpu_mp_start(void)
371{
372	int i;
373	u_int threads_per_cache, p[4];
374
375	/* Initialize the logical ID to APIC ID table. */
376	for (i = 0; i < MAXCPU; i++) {
377		cpu_apic_ids[i] = -1;
378		cpu_ipi_pending[i] = 0;
379	}
380
381	/* Install an inter-CPU IPI for TLB invalidation */
382	setidt(IPI_INVLTLB, IDTVEC(invltlb),
383	       SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
384	setidt(IPI_INVLPG, IDTVEC(invlpg),
385	       SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
386	setidt(IPI_INVLRNG, IDTVEC(invlrng),
387	       SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
388
389	/* Install an inter-CPU IPI for cache invalidation. */
390	setidt(IPI_INVLCACHE, IDTVEC(invlcache),
391	       SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
392
393	/* Install an inter-CPU IPI for lazy pmap release */
394	setidt(IPI_LAZYPMAP, IDTVEC(lazypmap),
395	       SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
396
397	/* Install an inter-CPU IPI for all-CPU rendezvous */
398	setidt(IPI_RENDEZVOUS, IDTVEC(rendezvous),
399	       SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
400
401	/* Install generic inter-CPU IPI handler */
402	setidt(IPI_BITMAP_VECTOR, IDTVEC(ipi_intr_bitmap_handler),
403	       SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
404
405	/* Install an inter-CPU IPI for CPU stop/restart */
406	setidt(IPI_STOP, IDTVEC(cpustop),
407	       SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
408
409
410	/* Set boot_cpu_id if needed. */
411	if (boot_cpu_id == -1) {
412		boot_cpu_id = PCPU_GET(apic_id);
413		cpu_info[boot_cpu_id].cpu_bsp = 1;
414	} else
415		KASSERT(boot_cpu_id == PCPU_GET(apic_id),
416		    ("BSP's APIC ID doesn't match boot_cpu_id"));
417	cpu_apic_ids[0] = boot_cpu_id;
418
419	/* Start each Application Processor */
420	start_all_aps();
421
422	/* Setup the initial logical CPUs info. */
423	logical_cpus = logical_cpus_mask = 0;
424	if (cpu_feature & CPUID_HTT)
425		logical_cpus = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
426
427	/*
428	 * Work out if hyperthreading is *really* enabled.  This
429	 * is made really ugly by the fact that processors lie: Dual
430	 * core processors claim to be hyperthreaded even when they're
431	 * not, presumably because they want to be treated the same
432	 * way as HTT with respect to per-cpu software licensing.
433	 * At the time of writing (May 12, 2005) the only hyperthreaded
434	 * cpus are from Intel, and Intel's dual-core processors can be
435	 * identified via the "deterministic cache parameters" cpuid
436	 * calls.
437	 */
438	/*
439	 * First determine if this is an Intel processor which claims
440	 * to have hyperthreading support.
441	 */
442	if ((cpu_feature & CPUID_HTT) &&
443	    (strcmp(cpu_vendor, "GenuineIntel") == 0)) {
444		/*
445		 * If the "deterministic cache parameters" cpuid calls
446		 * are available, use them.
447		 */
448		if (cpu_high >= 4) {
449			/* Ask the processor about the L1 cache. */
450			for (i = 0; i < 1; i++) {
451				cpuid_count(4, i, p);
452				threads_per_cache = ((p[0] & 0x3ffc000) >> 14) + 1;
453				if (hyperthreading_cpus < threads_per_cache)
454					hyperthreading_cpus = threads_per_cache;
455				if ((p[0] & 0x1f) == 0)
456					break;
457			}
458		}
459
460		/*
461		 * If the deterministic cache parameters are not
462		 * available, or if no caches were reported to exist,
463		 * just accept what the HTT flag indicated.
464		 */
465		if (hyperthreading_cpus == 0)
466			hyperthreading_cpus = logical_cpus;
467	}
468
469	set_interrupt_apic_ids();
470}
471
472
473/*
474 * Print various information about the SMP system hardware and setup.
475 */
476void
477cpu_mp_announce(void)
478{
479	int i, x;
480
481	/* List CPUs */
482	printf(" cpu0 (BSP): APIC ID: %2d\n", boot_cpu_id);
483	for (i = 1, x = 0; x < MAXCPU; x++) {
484		if (!cpu_info[x].cpu_present || cpu_info[x].cpu_bsp)
485			continue;
486		if (cpu_info[x].cpu_disabled)
487			printf("  cpu (AP): APIC ID: %2d (disabled)\n", x);
488		else {
489			KASSERT(i < mp_ncpus,
490			    ("mp_ncpus and actual cpus are out of whack"));
491			printf(" cpu%d (AP): APIC ID: %2d\n", i++, x);
492		}
493	}
494}
495
496/*
497 * AP CPU's call this to initialize themselves.
498 */
499void
500init_secondary(void)
501{
502	vm_offset_t addr;
503	int	gsel_tss;
504	int	x, myid;
505	u_int	cr0;
506
507	/* bootAP is set in start_ap() to our ID. */
508	myid = bootAP;
509	gdt_segs[GPRIV_SEL].ssd_base = (int) &SMP_prvspace[myid];
510	gdt_segs[GPROC0_SEL].ssd_base =
511		(int) &SMP_prvspace[myid].pcpu.pc_common_tss;
512	SMP_prvspace[myid].pcpu.pc_prvspace =
513		&SMP_prvspace[myid].pcpu;
514
515	for (x = 0; x < NGDT; x++) {
516		ssdtosd(&gdt_segs[x], &gdt[myid * NGDT + x].sd);
517	}
518
519	r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
520	r_gdt.rd_base = (int) &gdt[myid * NGDT];
521	lgdt(&r_gdt);			/* does magic intra-segment return */
522
523	lidt(&r_idt);
524
525	lldt(_default_ldt);
526	PCPU_SET(currentldt, _default_ldt);
527
528	gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
529	gdt[myid * NGDT + GPROC0_SEL].sd.sd_type = SDT_SYS386TSS;
530	PCPU_SET(common_tss.tss_esp0, 0); /* not used until after switch */
531	PCPU_SET(common_tss.tss_ss0, GSEL(GDATA_SEL, SEL_KPL));
532	PCPU_SET(common_tss.tss_ioopt, (sizeof (struct i386tss)) << 16);
533	PCPU_SET(tss_gdt, &gdt[myid * NGDT + GPROC0_SEL].sd);
534	PCPU_SET(common_tssd, *PCPU_GET(tss_gdt));
535	ltr(gsel_tss);
536
537	PCPU_SET(fsgs_gdt, &gdt[myid * NGDT + GUFS_SEL].sd);
538
539	/*
540	 * Set to a known state:
541	 * Set by mpboot.s: CR0_PG, CR0_PE
542	 * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
543	 */
544	cr0 = rcr0();
545	cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
546	load_cr0(cr0);
547	CHECK_WRITE(0x38, 5);
548
549	/* Disable local APIC just to be sure. */
550	lapic_disable();
551
552	/* signal our startup to the BSP. */
553	mp_naps++;
554	CHECK_WRITE(0x39, 6);
555
556	/* Spin until the BSP releases the AP's. */
557	while (!aps_ready)
558		ia32_pause();
559
560	/* BSP may have changed PTD while we were waiting */
561	invltlb();
562	for (addr = 0; addr < NKPT * NBPDR - 1; addr += PAGE_SIZE)
563		invlpg(addr);
564
565#if defined(I586_CPU) && !defined(NO_F00F_HACK)
566	lidt(&r_idt);
567#endif
568
569	/* Initialize the PAT MSR if present. */
570	pmap_init_pat();
571
572	/* set up CPU registers and state */
573	cpu_setregs();
574
575	/* set up FPU state on the AP */
576	npxinit(__INITIAL_NPXCW__);
577
578	/* set up SSE registers */
579	enable_sse();
580
581	/* A quick check from sanity claus */
582	if (PCPU_GET(apic_id) != lapic_id()) {
583		printf("SMP: cpuid = %d\n", PCPU_GET(cpuid));
584		printf("SMP: actual apic_id = %d\n", lapic_id());
585		printf("SMP: correct apic_id = %d\n", PCPU_GET(apic_id));
586		printf("PTD[MPPTDI] = %#jx\n", (uintmax_t)PTD[MPPTDI]);
587		panic("cpuid mismatch! boom!!");
588	}
589
590	/* Initialize curthread. */
591	KASSERT(PCPU_GET(idlethread) != NULL, ("no idle thread"));
592	PCPU_SET(curthread, PCPU_GET(idlethread));
593
594	mtx_lock_spin(&ap_boot_mtx);
595
596	/* Init local apic for irq's */
597	lapic_setup();
598
599	/* Set memory range attributes for this CPU to match the BSP */
600	mem_range_AP_init();
601
602	smp_cpus++;
603
604	CTR1(KTR_SMP, "SMP: AP CPU #%d Launched", PCPU_GET(cpuid));
605	printf("SMP: AP CPU #%d Launched!\n", PCPU_GET(cpuid));
606
607	/* Determine if we are a logical CPU. */
608	if (logical_cpus > 1 && PCPU_GET(apic_id) % logical_cpus != 0)
609		logical_cpus_mask |= PCPU_GET(cpumask);
610
611	/* Determine if we are a hyperthread. */
612	if (hyperthreading_cpus > 1 &&
613	    PCPU_GET(apic_id) % hyperthreading_cpus != 0)
614		hyperthreading_cpus_mask |= PCPU_GET(cpumask);
615
616	/* Build our map of 'other' CPUs. */
617	PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
618
619	if (bootverbose)
620		lapic_dump("AP");
621
622	if (smp_cpus == mp_ncpus) {
623		/* enable IPI's, tlb shootdown, freezes etc */
624		atomic_store_rel_int(&smp_started, 1);
625		smp_active = 1;	 /* historic */
626	}
627
628	mtx_unlock_spin(&ap_boot_mtx);
629
630	/* wait until all the AP's are up */
631	while (smp_started == 0)
632		ia32_pause();
633
634	/* ok, now grab sched_lock and enter the scheduler */
635	mtx_lock_spin(&sched_lock);
636
637	/*
638	 * Correct spinlock nesting.  The idle thread context that we are
639	 * borrowing was created so that it would start out with a single
640	 * spin lock (sched_lock) held in fork_trampoline().  Since we've
641	 * explicitly acquired locks in this function, the nesting count
642	 * is now 2 rather than 1.  Since we are nested, calling
643	 * spinlock_exit() will simply adjust the counts without allowing
644	 * spin lock using code to interrupt us.
645	 */
646	spinlock_exit();
647	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
648
649	PCPU_SET(switchtime, cpu_ticks());
650	PCPU_SET(switchticks, ticks);
651
652	cpu_throw(NULL, choosethread());	/* doesn't return */
653
654	panic("scheduler returned us to %s", __func__);
655	/* NOTREACHED */
656}
657
658/*******************************************************************
659 * local functions and data
660 */
661
662/*
663 * We tell the I/O APIC code about all the CPUs we want to receive
664 * interrupts.  If we don't want certain CPUs to receive IRQs we
665 * can simply not tell the I/O APIC code about them in this function.
666 * We also do not tell it about the BSP since it tells itself about
667 * the BSP internally to work with UP kernels and on UP machines.
668 */
669static void
670set_interrupt_apic_ids(void)
671{
672	u_int apic_id;
673
674	for (apic_id = 0; apic_id < MAXCPU; apic_id++) {
675		if (!cpu_info[apic_id].cpu_present)
676			continue;
677		if (cpu_info[apic_id].cpu_bsp)
678			continue;
679
680		/* Don't let hyperthreads service interrupts. */
681		if (hyperthreading_cpus > 1 &&
682		    apic_id % hyperthreading_cpus != 0)
683			continue;
684
685		intr_add_cpu(apic_id);
686	}
687}
688
689/*
690 * start each AP in our list
691 */
692static int
693start_all_aps(void)
694{
695#ifndef PC98
696	u_char mpbiosreason;
697#endif
698	struct pcpu *pc;
699	char *stack;
700	uintptr_t kptbase;
701	u_int32_t mpbioswarmvec;
702	int apic_id, cpu, i, pg;
703
704	mtx_init(&ap_boot_mtx, "ap boot", NULL, MTX_SPIN);
705
706	/* install the AP 1st level boot code */
707	install_ap_tramp();
708
709	/* save the current value of the warm-start vector */
710	mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
711#ifndef PC98
712	outb(CMOS_REG, BIOS_RESET);
713	mpbiosreason = inb(CMOS_DATA);
714#endif
715
716	/* set up temporary P==V mapping for AP boot */
717	/* XXX this is a hack, we should boot the AP on its own stack/PTD */
718	kptbase = (uintptr_t)(void *)KPTphys;
719	for (i = 0; i < NKPT; i++)
720		PTD[i] = (pd_entry_t)(PG_V | PG_RW |
721		    ((kptbase + i * PAGE_SIZE) & PG_FRAME));
722	invltlb();
723
724	/* start each AP */
725	for (cpu = 0, apic_id = 0; apic_id < MAXCPU; apic_id++) {
726
727		/* Ignore non-existent CPUs and the BSP. */
728		if (!cpu_info[apic_id].cpu_present ||
729		    cpu_info[apic_id].cpu_bsp)
730			continue;
731
732		/* Don't use this CPU if it has been disabled by a tunable. */
733		if (resource_disabled("lapic", apic_id)) {
734			cpu_info[apic_id].cpu_disabled = 1;
735			mp_ncpus--;
736			continue;
737		}
738
739		cpu++;
740
741		/* save APIC ID for this logical ID */
742		cpu_apic_ids[cpu] = apic_id;
743
744		/* first page of AP's private space */
745		pg = cpu * i386_btop(sizeof(struct privatespace));
746
747		/* allocate a new private data page */
748		pc = (struct pcpu *)kmem_alloc(kernel_map, PAGE_SIZE);
749
750		/* wire it into the private page table page */
751		SMPpt[pg] = (pt_entry_t)(PG_V | PG_RW | vtophys(pc));
752
753		/* allocate and set up an idle stack data page */
754		stack = (char *)kmem_alloc(kernel_map, KSTACK_PAGES * PAGE_SIZE); /* XXXKSE */
755		for (i = 0; i < KSTACK_PAGES; i++)
756			SMPpt[pg + 1 + i] = (pt_entry_t)
757			    (PG_V | PG_RW | vtophys(PAGE_SIZE * i + stack));
758
759		/* prime data page for it to use */
760		pcpu_init(pc, cpu, sizeof(struct pcpu));
761		pc->pc_apic_id = apic_id;
762
763		/* setup a vector to our boot code */
764		*((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
765		*((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
766#ifndef PC98
767		outb(CMOS_REG, BIOS_RESET);
768		outb(CMOS_DATA, BIOS_WARM);	/* 'warm-start' */
769#endif
770
771		bootSTK = &SMP_prvspace[cpu].idlekstack[KSTACK_PAGES *
772		    PAGE_SIZE];
773		bootAP = cpu;
774
775		/* attempt to start the Application Processor */
776		CHECK_INIT(99);	/* setup checkpoints */
777		if (!start_ap(apic_id)) {
778			printf("AP #%d (PHY# %d) failed!\n", cpu, apic_id);
779			CHECK_PRINT("trace");	/* show checkpoints */
780			/* better panic as the AP may be running loose */
781			printf("panic y/n? [y] ");
782			if (cngetc() != 'n')
783				panic("bye-bye");
784		}
785		CHECK_PRINT("trace");		/* show checkpoints */
786
787		all_cpus |= (1 << cpu);		/* record AP in CPU map */
788	}
789
790	/* build our map of 'other' CPUs */
791	PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
792
793	/* restore the warmstart vector */
794	*(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
795
796#ifndef PC98
797	outb(CMOS_REG, BIOS_RESET);
798	outb(CMOS_DATA, mpbiosreason);
799#endif
800
801	/*
802	 * Set up the idle context for the BSP.  Similar to above except
803	 * that some was done by locore, some by pmap.c and some is implicit
804	 * because the BSP is cpu#0 and the page is initially zero and also
805	 * because we can refer to variables by name on the BSP..
806	 */
807
808	/* Allocate and setup BSP idle stack */
809	stack = (char *)kmem_alloc(kernel_map, KSTACK_PAGES * PAGE_SIZE);
810	for (i = 0; i < KSTACK_PAGES; i++)
811		SMPpt[1 + i] = (pt_entry_t)
812		    (PG_V | PG_RW | vtophys(PAGE_SIZE * i + stack));
813
814	for (i = 0; i < NKPT; i++)
815		PTD[i] = 0;
816	pmap_invalidate_range(kernel_pmap, 0, NKPT * NBPDR - 1);
817
818	/* number of APs actually started */
819	return mp_naps;
820}
821
822/*
823 * load the 1st level AP boot code into base memory.
824 */
825
826/* targets for relocation */
827extern void bigJump(void);
828extern void bootCodeSeg(void);
829extern void bootDataSeg(void);
830extern void MPentry(void);
831extern u_int MP_GDT;
832extern u_int mp_gdtbase;
833
834static void
835install_ap_tramp(void)
836{
837	int     x;
838	int     size = *(int *) ((u_long) & bootMP_size);
839	vm_offset_t va = boot_address + KERNBASE;
840	u_char *src = (u_char *) ((u_long) bootMP);
841	u_char *dst = (u_char *) va;
842	u_int   boot_base = (u_int) bootMP;
843	u_int8_t *dst8;
844	u_int16_t *dst16;
845	u_int32_t *dst32;
846
847	KASSERT (size <= PAGE_SIZE,
848	    ("'size' do not fit into PAGE_SIZE, as expected."));
849	pmap_kenter(va, boot_address);
850	pmap_invalidate_page (kernel_pmap, va);
851	for (x = 0; x < size; ++x)
852		*dst++ = *src++;
853
854	/*
855	 * modify addresses in code we just moved to basemem. unfortunately we
856	 * need fairly detailed info about mpboot.s for this to work.  changes
857	 * to mpboot.s might require changes here.
858	 */
859
860	/* boot code is located in KERNEL space */
861	dst = (u_char *) va;
862
863	/* modify the lgdt arg */
864	dst32 = (u_int32_t *) (dst + ((u_int) & mp_gdtbase - boot_base));
865	*dst32 = boot_address + ((u_int) & MP_GDT - boot_base);
866
867	/* modify the ljmp target for MPentry() */
868	dst32 = (u_int32_t *) (dst + ((u_int) bigJump - boot_base) + 1);
869	*dst32 = ((u_int) MPentry - KERNBASE);
870
871	/* modify the target for boot code segment */
872	dst16 = (u_int16_t *) (dst + ((u_int) bootCodeSeg - boot_base));
873	dst8 = (u_int8_t *) (dst16 + 1);
874	*dst16 = (u_int) boot_address & 0xffff;
875	*dst8 = ((u_int) boot_address >> 16) & 0xff;
876
877	/* modify the target for boot data segment */
878	dst16 = (u_int16_t *) (dst + ((u_int) bootDataSeg - boot_base));
879	dst8 = (u_int8_t *) (dst16 + 1);
880	*dst16 = (u_int) boot_address & 0xffff;
881	*dst8 = ((u_int) boot_address >> 16) & 0xff;
882}
883
884/*
885 * This function starts the AP (application processor) identified
886 * by the APIC ID 'physicalCpu'.  It does quite a "song and dance"
887 * to accomplish this.  This is necessary because of the nuances
888 * of the different hardware we might encounter.  It isn't pretty,
889 * but it seems to work.
890 */
891static int
892start_ap(int apic_id)
893{
894	int vector, ms;
895	int cpus;
896
897	/* calculate the vector */
898	vector = (boot_address >> 12) & 0xff;
899
900	/* used as a watchpoint to signal AP startup */
901	cpus = mp_naps;
902
903	/*
904	 * first we do an INIT/RESET IPI this INIT IPI might be run, reseting
905	 * and running the target CPU. OR this INIT IPI might be latched (P5
906	 * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
907	 * ignored.
908	 */
909
910	/* do an INIT IPI: assert RESET */
911	lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
912	    APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, apic_id);
913
914	/* wait for pending status end */
915	lapic_ipi_wait(-1);
916
917	/* do an INIT IPI: deassert RESET */
918	lapic_ipi_raw(APIC_DEST_ALLESELF | APIC_TRIGMOD_LEVEL |
919	    APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, 0);
920
921	/* wait for pending status end */
922	DELAY(10000);		/* wait ~10mS */
923	lapic_ipi_wait(-1);
924
925	/*
926	 * next we do a STARTUP IPI: the previous INIT IPI might still be
927	 * latched, (P5 bug) this 1st STARTUP would then terminate
928	 * immediately, and the previously started INIT IPI would continue. OR
929	 * the previous INIT IPI has already run. and this STARTUP IPI will
930	 * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
931	 * will run.
932	 */
933
934	/* do a STARTUP IPI */
935	lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
936	    APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
937	    vector, apic_id);
938	lapic_ipi_wait(-1);
939	DELAY(200);		/* wait ~200uS */
940
941	/*
942	 * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
943	 * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
944	 * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
945	 * recognized after hardware RESET or INIT IPI.
946	 */
947
948	lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
949	    APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
950	    vector, apic_id);
951	lapic_ipi_wait(-1);
952	DELAY(200);		/* wait ~200uS */
953
954	/* Wait up to 5 seconds for it to start. */
955	for (ms = 0; ms < 5000; ms++) {
956		if (mp_naps > cpus)
957			return 1;	/* return SUCCESS */
958		DELAY(1000);
959	}
960	return 0;		/* return FAILURE */
961}
962
963#ifdef COUNT_XINVLTLB_HITS
964u_int xhits_gbl[MAXCPU];
965u_int xhits_pg[MAXCPU];
966u_int xhits_rng[MAXCPU];
967SYSCTL_NODE(_debug, OID_AUTO, xhits, CTLFLAG_RW, 0, "");
968SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, global, CTLFLAG_RW, &xhits_gbl,
969    sizeof(xhits_gbl), "IU", "");
970SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, page, CTLFLAG_RW, &xhits_pg,
971    sizeof(xhits_pg), "IU", "");
972SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, range, CTLFLAG_RW, &xhits_rng,
973    sizeof(xhits_rng), "IU", "");
974
975u_int ipi_global;
976u_int ipi_page;
977u_int ipi_range;
978u_int ipi_range_size;
979SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_global, CTLFLAG_RW, &ipi_global, 0, "");
980SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_page, CTLFLAG_RW, &ipi_page, 0, "");
981SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range, CTLFLAG_RW, &ipi_range, 0, "");
982SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range_size, CTLFLAG_RW, &ipi_range_size,
983    0, "");
984
985u_int ipi_masked_global;
986u_int ipi_masked_page;
987u_int ipi_masked_range;
988u_int ipi_masked_range_size;
989SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_global, CTLFLAG_RW,
990    &ipi_masked_global, 0, "");
991SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_page, CTLFLAG_RW,
992    &ipi_masked_page, 0, "");
993SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_range, CTLFLAG_RW,
994    &ipi_masked_range, 0, "");
995SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_range_size, CTLFLAG_RW,
996    &ipi_masked_range_size, 0, "");
997#endif /* COUNT_XINVLTLB_HITS */
998
999/*
1000 * Flush the TLB on all other CPU's
1001 */
1002static void
1003smp_tlb_shootdown(u_int vector, vm_offset_t addr1, vm_offset_t addr2)
1004{
1005	u_int ncpu;
1006
1007	ncpu = mp_ncpus - 1;	/* does not shootdown self */
1008	if (ncpu < 1)
1009		return;		/* no other cpus */
1010	mtx_assert(&smp_ipi_mtx, MA_OWNED);
1011	smp_tlb_addr1 = addr1;
1012	smp_tlb_addr2 = addr2;
1013	atomic_store_rel_int(&smp_tlb_wait, 0);
1014	ipi_all_but_self(vector);
1015	while (smp_tlb_wait < ncpu)
1016		ia32_pause();
1017}
1018
1019static void
1020smp_targeted_tlb_shootdown(u_int mask, u_int vector, vm_offset_t addr1, vm_offset_t addr2)
1021{
1022	int ncpu, othercpus;
1023
1024	othercpus = mp_ncpus - 1;
1025	if (mask == (u_int)-1) {
1026		ncpu = othercpus;
1027		if (ncpu < 1)
1028			return;
1029	} else {
1030		mask &= ~PCPU_GET(cpumask);
1031		if (mask == 0)
1032			return;
1033		ncpu = bitcount32(mask);
1034		if (ncpu > othercpus) {
1035			/* XXX this should be a panic offence */
1036			printf("SMP: tlb shootdown to %d other cpus (only have %d)\n",
1037			    ncpu, othercpus);
1038			ncpu = othercpus;
1039		}
1040		/* XXX should be a panic, implied by mask == 0 above */
1041		if (ncpu < 1)
1042			return;
1043	}
1044	mtx_assert(&smp_ipi_mtx, MA_OWNED);
1045	smp_tlb_addr1 = addr1;
1046	smp_tlb_addr2 = addr2;
1047	atomic_store_rel_int(&smp_tlb_wait, 0);
1048	if (mask == (u_int)-1)
1049		ipi_all_but_self(vector);
1050	else
1051		ipi_selected(mask, vector);
1052	while (smp_tlb_wait < ncpu)
1053		ia32_pause();
1054}
1055
1056void
1057smp_cache_flush(void)
1058{
1059
1060	if (smp_started)
1061		smp_tlb_shootdown(IPI_INVLCACHE, 0, 0);
1062}
1063
1064void
1065smp_invltlb(void)
1066{
1067
1068	if (smp_started) {
1069		smp_tlb_shootdown(IPI_INVLTLB, 0, 0);
1070#ifdef COUNT_XINVLTLB_HITS
1071		ipi_global++;
1072#endif
1073	}
1074}
1075
1076void
1077smp_invlpg(vm_offset_t addr)
1078{
1079
1080	if (smp_started) {
1081		smp_tlb_shootdown(IPI_INVLPG, addr, 0);
1082#ifdef COUNT_XINVLTLB_HITS
1083		ipi_page++;
1084#endif
1085	}
1086}
1087
1088void
1089smp_invlpg_range(vm_offset_t addr1, vm_offset_t addr2)
1090{
1091
1092	if (smp_started) {
1093		smp_tlb_shootdown(IPI_INVLRNG, addr1, addr2);
1094#ifdef COUNT_XINVLTLB_HITS
1095		ipi_range++;
1096		ipi_range_size += (addr2 - addr1) / PAGE_SIZE;
1097#endif
1098	}
1099}
1100
1101void
1102smp_masked_invltlb(u_int mask)
1103{
1104
1105	if (smp_started) {
1106		smp_targeted_tlb_shootdown(mask, IPI_INVLTLB, 0, 0);
1107#ifdef COUNT_XINVLTLB_HITS
1108		ipi_masked_global++;
1109#endif
1110	}
1111}
1112
1113void
1114smp_masked_invlpg(u_int mask, vm_offset_t addr)
1115{
1116
1117	if (smp_started) {
1118		smp_targeted_tlb_shootdown(mask, IPI_INVLPG, addr, 0);
1119#ifdef COUNT_XINVLTLB_HITS
1120		ipi_masked_page++;
1121#endif
1122	}
1123}
1124
1125void
1126smp_masked_invlpg_range(u_int mask, vm_offset_t addr1, vm_offset_t addr2)
1127{
1128
1129	if (smp_started) {
1130		smp_targeted_tlb_shootdown(mask, IPI_INVLRNG, addr1, addr2);
1131#ifdef COUNT_XINVLTLB_HITS
1132		ipi_masked_range++;
1133		ipi_masked_range_size += (addr2 - addr1) / PAGE_SIZE;
1134#endif
1135	}
1136}
1137
1138void
1139ipi_bitmap_handler(struct trapframe frame)
1140{
1141	int cpu = PCPU_GET(cpuid);
1142	u_int ipi_bitmap;
1143
1144	ipi_bitmap = atomic_readandclear_int(&cpu_ipi_pending[cpu]);
1145
1146#ifdef IPI_PREEMPTION
1147	if (ipi_bitmap & IPI_PREEMPT) {
1148#ifdef COUNT_IPIS
1149		*ipi_preempt_counts[cpu]++;
1150#endif
1151		mtx_lock_spin(&sched_lock);
1152		/* Don't preempt the idle thread */
1153		if (curthread->td_priority <  PRI_MIN_IDLE) {
1154			struct thread *running_thread = curthread;
1155			if (running_thread->td_critnest > 1)
1156				running_thread->td_owepreempt = 1;
1157			else
1158				mi_switch(SW_INVOL | SW_PREEMPT, NULL);
1159		}
1160		mtx_unlock_spin(&sched_lock);
1161	}
1162#endif
1163
1164	if (ipi_bitmap & IPI_AST) {
1165#ifdef COUNT_IPIS
1166		*ipi_ast_counts[cpu]++;
1167#endif
1168		/* Nothing to do for AST */
1169	}
1170}
1171
1172/*
1173 * send an IPI to a set of cpus.
1174 */
1175void
1176ipi_selected(u_int32_t cpus, u_int ipi)
1177{
1178	int cpu;
1179	u_int bitmap = 0;
1180	u_int old_pending;
1181	u_int new_pending;
1182
1183	if (IPI_IS_BITMAPED(ipi)) {
1184		bitmap = 1 << ipi;
1185		ipi = IPI_BITMAP_VECTOR;
1186	}
1187
1188#ifdef STOP_NMI
1189	if (ipi == IPI_STOP && stop_cpus_with_nmi) {
1190		ipi_nmi_selected(cpus);
1191		return;
1192	}
1193#endif
1194	CTR3(KTR_SMP, "%s: cpus: %x ipi: %x", __func__, cpus, ipi);
1195	while ((cpu = ffs(cpus)) != 0) {
1196		cpu--;
1197		cpus &= ~(1 << cpu);
1198
1199		KASSERT(cpu_apic_ids[cpu] != -1,
1200		    ("IPI to non-existent CPU %d", cpu));
1201
1202		if (bitmap) {
1203			do {
1204				old_pending = cpu_ipi_pending[cpu];
1205				new_pending = old_pending | bitmap;
1206			} while  (!atomic_cmpset_int(&cpu_ipi_pending[cpu],old_pending, new_pending));
1207
1208			if (old_pending)
1209				continue;
1210		}
1211
1212		lapic_ipi_vectored(ipi, cpu_apic_ids[cpu]);
1213	}
1214
1215}
1216
1217/*
1218 * send an IPI INTerrupt containing 'vector' to all CPUs, including myself
1219 */
1220void
1221ipi_all(u_int ipi)
1222{
1223
1224	if (IPI_IS_BITMAPED(ipi) || (ipi == IPI_STOP && stop_cpus_with_nmi)) {
1225		ipi_selected(all_cpus, ipi);
1226		return;
1227	}
1228	CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1229	lapic_ipi_vectored(ipi, APIC_IPI_DEST_ALL);
1230}
1231
1232/*
1233 * send an IPI to all CPUs EXCEPT myself
1234 */
1235void
1236ipi_all_but_self(u_int ipi)
1237{
1238
1239	if (IPI_IS_BITMAPED(ipi) || (ipi == IPI_STOP && stop_cpus_with_nmi)) {
1240		ipi_selected(PCPU_GET(other_cpus), ipi);
1241		return;
1242	}
1243	CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1244	lapic_ipi_vectored(ipi, APIC_IPI_DEST_OTHERS);
1245}
1246
1247/*
1248 * send an IPI to myself
1249 */
1250void
1251ipi_self(u_int ipi)
1252{
1253
1254	if (IPI_IS_BITMAPED(ipi) || (ipi == IPI_STOP && stop_cpus_with_nmi)) {
1255		ipi_selected(PCPU_GET(cpumask), ipi);
1256		return;
1257	}
1258	CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1259	lapic_ipi_vectored(ipi, APIC_IPI_DEST_SELF);
1260}
1261
1262#ifdef STOP_NMI
1263/*
1264 * send NMI IPI to selected CPUs
1265 */
1266
1267#define	BEFORE_SPIN	1000000
1268
1269void
1270ipi_nmi_selected(u_int32_t cpus)
1271{
1272	int cpu;
1273	register_t icrlo;
1274
1275	icrlo = APIC_DELMODE_NMI | APIC_DESTMODE_PHY | APIC_LEVEL_ASSERT
1276		| APIC_TRIGMOD_EDGE;
1277
1278	CTR2(KTR_SMP, "%s: cpus: %x nmi", __func__, cpus);
1279
1280	atomic_set_int(&ipi_nmi_pending, cpus);
1281
1282	while ((cpu = ffs(cpus)) != 0) {
1283		cpu--;
1284		cpus &= ~(1 << cpu);
1285
1286		KASSERT(cpu_apic_ids[cpu] != -1,
1287		    ("IPI NMI to non-existent CPU %d", cpu));
1288
1289		/* Wait for an earlier IPI to finish. */
1290		if (!lapic_ipi_wait(BEFORE_SPIN))
1291			panic("ipi_nmi_selected: previous IPI has not cleared");
1292
1293		lapic_ipi_raw(icrlo, cpu_apic_ids[cpu]);
1294	}
1295}
1296
1297int
1298ipi_nmi_handler(void)
1299{
1300	int cpumask = PCPU_GET(cpumask);
1301
1302	if (!(ipi_nmi_pending & cpumask))
1303		return 1;
1304
1305	atomic_clear_int(&ipi_nmi_pending, cpumask);
1306	cpustop_handler();
1307	return 0;
1308}
1309
1310#endif /* STOP_NMI */
1311
1312/*
1313 * Handle an IPI_STOP by saving our current context and spinning until we
1314 * are resumed.
1315 */
1316void
1317cpustop_handler(void)
1318{
1319	int cpu = PCPU_GET(cpuid);
1320	int cpumask = PCPU_GET(cpumask);
1321
1322	savectx(&stoppcbs[cpu]);
1323
1324	/* Indicate that we are stopped */
1325	atomic_set_int(&stopped_cpus, cpumask);
1326
1327	/* Wait for restart */
1328	while (!(started_cpus & cpumask))
1329	    ia32_pause();
1330
1331	atomic_clear_int(&started_cpus, cpumask);
1332	atomic_clear_int(&stopped_cpus, cpumask);
1333
1334	if (cpu == 0 && cpustop_restartfunc != NULL) {
1335		cpustop_restartfunc();
1336		cpustop_restartfunc = NULL;
1337	}
1338}
1339
1340/*
1341 * This is called once the rest of the system is up and running and we're
1342 * ready to let the AP's out of the pen.
1343 */
1344static void
1345release_aps(void *dummy __unused)
1346{
1347
1348	if (mp_ncpus == 1)
1349		return;
1350	mtx_lock_spin(&sched_lock);
1351	atomic_store_rel_int(&aps_ready, 1);
1352	while (smp_started == 0)
1353		ia32_pause();
1354	mtx_unlock_spin(&sched_lock);
1355}
1356SYSINIT(start_aps, SI_SUB_SMP, SI_ORDER_FIRST, release_aps, NULL);
1357
1358static int
1359sysctl_hlt_cpus(SYSCTL_HANDLER_ARGS)
1360{
1361	u_int mask;
1362	int error;
1363
1364	mask = hlt_cpus_mask;
1365	error = sysctl_handle_int(oidp, &mask, 0, req);
1366	if (error || !req->newptr)
1367		return (error);
1368
1369	if (logical_cpus_mask != 0 &&
1370	    (mask & logical_cpus_mask) == logical_cpus_mask)
1371		hlt_logical_cpus = 1;
1372	else
1373		hlt_logical_cpus = 0;
1374
1375	if (! hyperthreading_allowed)
1376		mask |= hyperthreading_cpus_mask;
1377
1378	if ((mask & all_cpus) == all_cpus)
1379		mask &= ~(1<<0);
1380	hlt_cpus_mask = mask;
1381	return (error);
1382}
1383SYSCTL_PROC(_machdep, OID_AUTO, hlt_cpus, CTLTYPE_INT|CTLFLAG_RW,
1384    0, 0, sysctl_hlt_cpus, "IU",
1385    "Bitmap of CPUs to halt.  101 (binary) will halt CPUs 0 and 2.");
1386
1387static int
1388sysctl_hlt_logical_cpus(SYSCTL_HANDLER_ARGS)
1389{
1390	int disable, error;
1391
1392	disable = hlt_logical_cpus;
1393	error = sysctl_handle_int(oidp, &disable, 0, req);
1394	if (error || !req->newptr)
1395		return (error);
1396
1397	if (disable)
1398		hlt_cpus_mask |= logical_cpus_mask;
1399	else
1400		hlt_cpus_mask &= ~logical_cpus_mask;
1401
1402	if (! hyperthreading_allowed)
1403		hlt_cpus_mask |= hyperthreading_cpus_mask;
1404
1405	if ((hlt_cpus_mask & all_cpus) == all_cpus)
1406		hlt_cpus_mask &= ~(1<<0);
1407
1408	hlt_logical_cpus = disable;
1409	return (error);
1410}
1411
1412static int
1413sysctl_hyperthreading_allowed(SYSCTL_HANDLER_ARGS)
1414{
1415	int allowed, error;
1416
1417	allowed = hyperthreading_allowed;
1418	error = sysctl_handle_int(oidp, &allowed, 0, req);
1419	if (error || !req->newptr)
1420		return (error);
1421
1422	if (allowed)
1423		hlt_cpus_mask &= ~hyperthreading_cpus_mask;
1424	else
1425		hlt_cpus_mask |= hyperthreading_cpus_mask;
1426
1427	if (logical_cpus_mask != 0 &&
1428	    (hlt_cpus_mask & logical_cpus_mask) == logical_cpus_mask)
1429		hlt_logical_cpus = 1;
1430	else
1431		hlt_logical_cpus = 0;
1432
1433	if ((hlt_cpus_mask & all_cpus) == all_cpus)
1434		hlt_cpus_mask &= ~(1<<0);
1435
1436	hyperthreading_allowed = allowed;
1437	return (error);
1438}
1439
1440static void
1441cpu_hlt_setup(void *dummy __unused)
1442{
1443
1444	if (logical_cpus_mask != 0) {
1445		TUNABLE_INT_FETCH("machdep.hlt_logical_cpus",
1446		    &hlt_logical_cpus);
1447		sysctl_ctx_init(&logical_cpu_clist);
1448		SYSCTL_ADD_PROC(&logical_cpu_clist,
1449		    SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1450		    "hlt_logical_cpus", CTLTYPE_INT|CTLFLAG_RW, 0, 0,
1451		    sysctl_hlt_logical_cpus, "IU", "");
1452		SYSCTL_ADD_UINT(&logical_cpu_clist,
1453		    SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1454		    "logical_cpus_mask", CTLTYPE_INT|CTLFLAG_RD,
1455		    &logical_cpus_mask, 0, "");
1456
1457		if (hlt_logical_cpus)
1458			hlt_cpus_mask |= logical_cpus_mask;
1459
1460		/*
1461		 * If necessary for security purposes, force
1462		 * hyperthreading off, regardless of the value
1463		 * of hlt_logical_cpus.
1464		 */
1465		if (hyperthreading_cpus_mask) {
1466			TUNABLE_INT_FETCH("machdep.hyperthreading_allowed",
1467			    &hyperthreading_allowed);
1468			SYSCTL_ADD_PROC(&logical_cpu_clist,
1469			    SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1470			    "hyperthreading_allowed", CTLTYPE_INT|CTLFLAG_RW,
1471			    0, 0, sysctl_hyperthreading_allowed, "IU", "");
1472			if (! hyperthreading_allowed)
1473				hlt_cpus_mask |= hyperthreading_cpus_mask;
1474		}
1475	}
1476}
1477SYSINIT(cpu_hlt, SI_SUB_SMP, SI_ORDER_ANY, cpu_hlt_setup, NULL);
1478
1479int
1480mp_grab_cpu_hlt(void)
1481{
1482	u_int mask = PCPU_GET(cpumask);
1483#ifdef MP_WATCHDOG
1484	u_int cpuid = PCPU_GET(cpuid);
1485#endif
1486	int retval;
1487
1488#ifdef MP_WATCHDOG
1489	ap_watchdog(cpuid);
1490#endif
1491
1492	retval = mask & hlt_cpus_mask;
1493	while (mask & hlt_cpus_mask)
1494		__asm __volatile("sti; hlt" : : : "memory");
1495	return (retval);
1496}
1497
1498#ifdef COUNT_IPIS
1499/*
1500 * Setup interrupt counters for IPI handlers.
1501 */
1502static void
1503mp_ipi_intrcnt(void *dummy)
1504{
1505	char buf[64];
1506	int i;
1507
1508	for (i = 0; i < mp_maxid; i++) {
1509		if (CPU_ABSENT(i))
1510			continue;
1511		snprintf(buf, sizeof(buf), "cpu%d: invltlb", i);
1512		intrcnt_add(buf, &ipi_invltlb_counts[i]);
1513		snprintf(buf, sizeof(buf), "cpu%d: invlrng", i);
1514		intrcnt_add(buf, &ipi_invlrng_counts[i]);
1515		snprintf(buf, sizeof(buf), "cpu%d: invlpg", i);
1516		intrcnt_add(buf, &ipi_invlpg_counts[i]);
1517#ifdef IPI_PREEMPTION
1518		snprintf(buf, sizeof(buf), "cpu%d: preempt", i);
1519		intrcnt_add(buf, &ipi_preempt_counts[i]);
1520#endif
1521		snprintf(buf, sizeof(buf), "cpu%d: ast", i);
1522		intrcnt_add(buf, &ipi_ast_counts[i]);
1523		snprintf(buf, sizeof(buf), "cpu%d: rendezvous", i);
1524		intrcnt_add(buf, &ipi_rendezvous_counts[i]);
1525		snprintf(buf, sizeof(buf), "cpu%d: lazypmap", i);
1526		intrcnt_add(buf, &ipi_lazypmap_counts[i]);
1527	}
1528}
1529SYSINIT(mp_ipi_intrcnt, SI_SUB_INTR, SI_ORDER_MIDDLE, mp_ipi_intrcnt, NULL)
1530#endif
1531