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