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