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