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