mp_machdep.c revision 188065
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 188065 2009-02-03 09:01:45Z jkoshy $");
29
30#include "opt_cpu.h"
31#include "opt_kstack_pages.h"
32#include "opt_mp_watchdog.h"
33#include "opt_sched.h"
34
35#include <sys/param.h>
36#include <sys/systm.h>
37#include <sys/bus.h>
38#ifdef GPROF
39#include <sys/gmon.h>
40#endif
41#include <sys/kernel.h>
42#include <sys/ktr.h>
43#include <sys/lock.h>
44#include <sys/malloc.h>
45#include <sys/memrange.h>
46#include <sys/mutex.h>
47#include <sys/pcpu.h>
48#include <sys/proc.h>
49#include <sys/sched.h>
50#include <sys/smp.h>
51#include <sys/sysctl.h>
52
53#include <vm/vm.h>
54#include <vm/vm_param.h>
55#include <vm/pmap.h>
56#include <vm/vm_kern.h>
57#include <vm/vm_extern.h>
58
59#include <machine/apicreg.h>
60#include <machine/cputypes.h>
61#include <machine/md_var.h>
62#include <machine/mp_watchdog.h>
63#include <machine/pcb.h>
64#include <machine/psl.h>
65#include <machine/smp.h>
66#include <machine/specialreg.h>
67#include <machine/tss.h>
68
69#define WARMBOOT_TARGET		0
70#define WARMBOOT_OFF		(KERNBASE + 0x0467)
71#define WARMBOOT_SEG		(KERNBASE + 0x0469)
72
73#define CMOS_REG		(0x70)
74#define CMOS_DATA		(0x71)
75#define BIOS_RESET		(0x0f)
76#define BIOS_WARM		(0x0a)
77
78/* lock region used by kernel profiling */
79int	mcount_lock;
80
81int	mp_naps;		/* # of Applications processors */
82int	boot_cpu_id = -1;	/* designated BSP */
83
84extern  struct pcpu __pcpu[];
85
86/* AP uses this during bootstrap.  Do not staticize.  */
87char *bootSTK;
88static int bootAP;
89
90/* Free these after use */
91void *bootstacks[MAXCPU];
92
93/* Temporary holder for double fault stack */
94char *doublefault_stack;
95char *nmi_stack;
96
97/* Hotwire a 0->4MB V==P mapping */
98extern pt_entry_t *KPTphys;
99
100/* SMP page table page */
101extern pt_entry_t *SMPpt;
102
103extern int  _udatasel;
104
105struct pcb stoppcbs[MAXCPU];
106
107/* Variables needed for SMP tlb shootdown. */
108vm_offset_t smp_tlb_addr1;
109vm_offset_t smp_tlb_addr2;
110volatile int smp_tlb_wait;
111
112extern inthand_t IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
113
114#ifdef STOP_NMI
115volatile cpumask_t ipi_nmi_pending;
116
117static void	ipi_nmi_selected(u_int32_t cpus);
118#endif
119
120/*
121 * Local data and functions.
122 */
123
124#ifdef STOP_NMI
125/*
126 * Provide an alternate method of stopping other CPUs. If another CPU has
127 * disabled interrupts the conventional STOP IPI will be blocked. This
128 * NMI-based stop should get through in that case.
129 */
130static int stop_cpus_with_nmi = 1;
131SYSCTL_INT(_debug, OID_AUTO, stop_cpus_with_nmi, CTLTYPE_INT | CTLFLAG_RW,
132    &stop_cpus_with_nmi, 0, "");
133TUNABLE_INT("debug.stop_cpus_with_nmi", &stop_cpus_with_nmi);
134#else
135#define	stop_cpus_with_nmi	0
136#endif
137
138static u_int logical_cpus;
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} static cpu_info[MAX_APIC_ID + 1];
155int cpu_apic_ids[MAXCPU];
156int apic_cpuids[MAX_APIC_ID + 1];
157
158/* Holds pending bitmap based IPIs per CPU */
159static volatile u_int cpu_ipi_pending[MAXCPU];
160
161static u_int boot_address;
162
163static void	assign_cpu_ids(void);
164static void	set_interrupt_apic_ids(void);
165static int	start_all_aps(void);
166static int	start_ap(int apic_id);
167static void	release_aps(void *dummy);
168
169static int	hlt_logical_cpus;
170static u_int	hyperthreading_cpus;
171static cpumask_t	hyperthreading_cpus_mask;
172static int	hyperthreading_allowed = 1;
173static struct	sysctl_ctx_list logical_cpu_clist;
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
183struct cpu_group *
184cpu_topo(void)
185{
186	if (cpu_cores == 0)
187		cpu_cores = 1;
188	if (cpu_logical == 0)
189		cpu_logical = 1;
190	if (mp_ncpus % (cpu_cores * cpu_logical) != 0) {
191		printf("WARNING: Non-uniform processors.\n");
192		printf("WARNING: Using suboptimal topology.\n");
193		return (smp_topo_none());
194	}
195	/*
196	 * No multi-core or hyper-threaded.
197	 */
198	if (cpu_logical * cpu_cores == 1)
199		return (smp_topo_none());
200	/*
201	 * Only HTT no multi-core.
202	 */
203	if (cpu_logical > 1 && cpu_cores == 1)
204		return (smp_topo_1level(CG_SHARE_L1, cpu_logical, CG_FLAG_HTT));
205	/*
206	 * Only multi-core no HTT.
207	 */
208	if (cpu_cores > 1 && cpu_logical == 1)
209		return (smp_topo_1level(CG_SHARE_NONE, cpu_cores, 0));
210	/*
211	 * Both HTT and multi-core.
212	 */
213	return (smp_topo_2level(CG_SHARE_NONE, cpu_cores,
214	    CG_SHARE_L1, cpu_logical, CG_FLAG_HTT));
215}
216
217/*
218 * Calculate usable address in base memory for AP trampoline code.
219 */
220u_int
221mp_bootaddress(u_int basemem)
222{
223
224	bootMP_size = mptramp_end - mptramp_start;
225	boot_address = trunc_page(basemem * 1024); /* round down to 4k boundary */
226	if (((basemem * 1024) - boot_address) < bootMP_size)
227		boot_address -= PAGE_SIZE;	/* not enough, lower by 4k */
228	/* 3 levels of page table pages */
229	mptramp_pagetables = boot_address - (PAGE_SIZE * 3);
230
231	return mptramp_pagetables;
232}
233
234void
235cpu_add(u_int apic_id, char boot_cpu)
236{
237
238	if (apic_id > MAX_APIC_ID) {
239		panic("SMP: APIC ID %d too high", apic_id);
240		return;
241	}
242	KASSERT(cpu_info[apic_id].cpu_present == 0, ("CPU %d added twice",
243	    apic_id));
244	cpu_info[apic_id].cpu_present = 1;
245	if (boot_cpu) {
246		KASSERT(boot_cpu_id == -1,
247		    ("CPU %d claims to be BSP, but CPU %d already is", apic_id,
248		    boot_cpu_id));
249		boot_cpu_id = apic_id;
250		cpu_info[apic_id].cpu_bsp = 1;
251	}
252	if (mp_ncpus < MAXCPU) {
253		mp_ncpus++;
254		mp_maxid = mp_ncpus -1;
255	}
256	if (bootverbose)
257		printf("SMP: Added CPU %d (%s)\n", apic_id, boot_cpu ? "BSP" :
258		    "AP");
259}
260
261void
262cpu_mp_setmaxid(void)
263{
264
265	/*
266	 * mp_maxid should be already set by calls to cpu_add().
267	 * Just sanity check its value here.
268	 */
269	if (mp_ncpus == 0)
270		KASSERT(mp_maxid == 0,
271		    ("%s: mp_ncpus is zero, but mp_maxid is not", __func__));
272	else if (mp_ncpus == 1)
273		mp_maxid = 0;
274	else
275		KASSERT(mp_maxid >= mp_ncpus - 1,
276		    ("%s: counters out of sync: max %d, count %d", __func__,
277			mp_maxid, mp_ncpus));
278}
279
280int
281cpu_mp_probe(void)
282{
283
284	/*
285	 * Always record BSP in CPU map so that the mbuf init code works
286	 * correctly.
287	 */
288	all_cpus = 1;
289	if (mp_ncpus == 0) {
290		/*
291		 * No CPUs were found, so this must be a UP system.  Setup
292		 * the variables to represent a system with a single CPU
293		 * with an id of 0.
294		 */
295		mp_ncpus = 1;
296		return (0);
297	}
298
299	/* At least one CPU was found. */
300	if (mp_ncpus == 1) {
301		/*
302		 * One CPU was found, so this must be a UP system with
303		 * an I/O APIC.
304		 */
305		mp_maxid = 0;
306		return (0);
307	}
308
309	/* At least two CPUs were found. */
310	return (1);
311}
312
313/*
314 * Initialize the IPI handlers and start up the AP's.
315 */
316void
317cpu_mp_start(void)
318{
319	int i;
320	u_int threads_per_cache, p[4];
321
322	/* Initialize the logical ID to APIC ID table. */
323	for (i = 0; i < MAXCPU; i++) {
324		cpu_apic_ids[i] = -1;
325		cpu_ipi_pending[i] = 0;
326	}
327
328	/* Install an inter-CPU IPI for TLB invalidation */
329	setidt(IPI_INVLTLB, IDTVEC(invltlb), SDT_SYSIGT, SEL_KPL, 0);
330	setidt(IPI_INVLPG, IDTVEC(invlpg), SDT_SYSIGT, SEL_KPL, 0);
331	setidt(IPI_INVLRNG, IDTVEC(invlrng), SDT_SYSIGT, SEL_KPL, 0);
332
333	/* Install an inter-CPU IPI for cache invalidation. */
334	setidt(IPI_INVLCACHE, IDTVEC(invlcache), SDT_SYSIGT, SEL_KPL, 0);
335
336	/* Install an inter-CPU IPI for all-CPU rendezvous */
337	setidt(IPI_RENDEZVOUS, IDTVEC(rendezvous), SDT_SYSIGT, SEL_KPL, 0);
338
339	/* Install generic inter-CPU IPI handler */
340	setidt(IPI_BITMAP_VECTOR, IDTVEC(ipi_intr_bitmap_handler),
341	       SDT_SYSIGT, SEL_KPL, 0);
342
343	/* Install an inter-CPU IPI for CPU stop/restart */
344	setidt(IPI_STOP, IDTVEC(cpustop), SDT_SYSIGT, SEL_KPL, 0);
345
346	/* Set boot_cpu_id if needed. */
347	if (boot_cpu_id == -1) {
348		boot_cpu_id = PCPU_GET(apic_id);
349		cpu_info[boot_cpu_id].cpu_bsp = 1;
350	} else
351		KASSERT(boot_cpu_id == PCPU_GET(apic_id),
352		    ("BSP's APIC ID doesn't match boot_cpu_id"));
353	cpu_apic_ids[0] = boot_cpu_id;
354	apic_cpuids[boot_cpu_id] = 0;
355
356	assign_cpu_ids();
357
358	/* Start each Application Processor */
359	start_all_aps();
360
361	/* Setup the initial logical CPUs info. */
362	logical_cpus = logical_cpus_mask = 0;
363	if (cpu_feature & CPUID_HTT)
364		logical_cpus = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
365
366	/*
367	 * Work out if hyperthreading is *really* enabled.  This
368	 * is made really ugly by the fact that processors lie: Dual
369	 * core processors claim to be hyperthreaded even when they're
370	 * not, presumably because they want to be treated the same
371	 * way as HTT with respect to per-cpu software licensing.
372	 * At the time of writing (May 12, 2005) the only hyperthreaded
373	 * cpus are from Intel, and Intel's dual-core processors can be
374	 * identified via the "deterministic cache parameters" cpuid
375	 * calls.
376	 */
377	/*
378	 * First determine if this is an Intel processor which claims
379	 * to have hyperthreading support.
380	 */
381	if ((cpu_feature & CPUID_HTT) && cpu_vendor_id == CPU_VENDOR_INTEL) {
382		/*
383		 * If the "deterministic cache parameters" cpuid calls
384		 * are available, use them.
385		 */
386		if (cpu_high >= 4) {
387			/* Ask the processor about the L1 cache. */
388			for (i = 0; i < 1; i++) {
389				cpuid_count(4, i, p);
390				threads_per_cache = ((p[0] & 0x3ffc000) >> 14) + 1;
391				if (hyperthreading_cpus < threads_per_cache)
392					hyperthreading_cpus = threads_per_cache;
393				if ((p[0] & 0x1f) == 0)
394					break;
395			}
396		}
397
398		/*
399		 * If the deterministic cache parameters are not
400		 * available, or if no caches were reported to exist,
401		 * just accept what the HTT flag indicated.
402		 */
403		if (hyperthreading_cpus == 0)
404			hyperthreading_cpus = logical_cpus;
405	}
406
407	set_interrupt_apic_ids();
408}
409
410
411/*
412 * Print various information about the SMP system hardware and setup.
413 */
414void
415cpu_mp_announce(void)
416{
417	int i, x;
418
419	/* List CPUs */
420	printf(" cpu0 (BSP): APIC ID: %2d\n", boot_cpu_id);
421	for (i = 1, x = 0; x <= MAX_APIC_ID; x++) {
422		if (!cpu_info[x].cpu_present || cpu_info[x].cpu_bsp)
423			continue;
424		if (cpu_info[x].cpu_disabled)
425			printf("  cpu (AP): APIC ID: %2d (disabled)\n", x);
426		else {
427			KASSERT(i < mp_ncpus,
428			    ("mp_ncpus and actual cpus are out of whack"));
429			printf(" cpu%d (AP): APIC ID: %2d\n", i++, x);
430		}
431	}
432}
433
434/*
435 * AP CPU's call this to initialize themselves.
436 */
437void
438init_secondary(void)
439{
440	struct pcpu *pc;
441	struct nmi_pcpu *np;
442	u_int64_t msr, cr0;
443	int cpu, gsel_tss, x;
444	struct region_descriptor ap_gdt;
445
446	/* Set by the startup code for us to use */
447	cpu = bootAP;
448
449	/* Init tss */
450	common_tss[cpu] = common_tss[0];
451	common_tss[cpu].tss_rsp0 = 0;   /* not used until after switch */
452	common_tss[cpu].tss_iobase = sizeof(struct amd64tss);
453	common_tss[cpu].tss_ist1 = (long)&doublefault_stack[PAGE_SIZE];
454
455	/* The NMI stack runs on IST2. */
456	np = ((struct nmi_pcpu *) &nmi_stack[PAGE_SIZE]) - 1;
457	common_tss[cpu].tss_ist2 = (long) np;
458
459	/* Prepare private GDT */
460	gdt_segs[GPROC0_SEL].ssd_base = (long) &common_tss[cpu];
461	ssdtosyssd(&gdt_segs[GPROC0_SEL],
462	   (struct system_segment_descriptor *)&gdt[NGDT * cpu + GPROC0_SEL]);
463	for (x = 0; x < NGDT; x++) {
464		if (x != GPROC0_SEL && x != (GPROC0_SEL + 1))
465			ssdtosd(&gdt_segs[x], &gdt[NGDT * cpu + x]);
466	}
467	ap_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
468	ap_gdt.rd_base =  (long) &gdt[NGDT * cpu];
469	lgdt(&ap_gdt);			/* does magic intra-segment return */
470
471	/* Get per-cpu data */
472	pc = &__pcpu[cpu];
473
474	/* prime data page for it to use */
475	pcpu_init(pc, cpu, sizeof(struct pcpu));
476	pc->pc_apic_id = cpu_apic_ids[cpu];
477	pc->pc_prvspace = pc;
478	pc->pc_curthread = 0;
479	pc->pc_tssp = &common_tss[cpu];
480	pc->pc_rsp0 = 0;
481	pc->pc_gs32p = &gdt[NGDT * cpu + GUGS32_SEL];
482
483	/* Save the per-cpu pointer for use by the NMI handler. */
484	np->np_pcpu = (register_t) pc;
485
486	wrmsr(MSR_FSBASE, 0);		/* User value */
487	wrmsr(MSR_GSBASE, (u_int64_t)pc);
488	wrmsr(MSR_KGSBASE, (u_int64_t)pc);	/* XXX User value while we're in the kernel */
489
490	lidt(&r_idt);
491
492	gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
493	ltr(gsel_tss);
494
495	/*
496	 * Set to a known state:
497	 * Set by mpboot.s: CR0_PG, CR0_PE
498	 * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
499	 */
500	cr0 = rcr0();
501	cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
502	load_cr0(cr0);
503
504	/* Set up the fast syscall stuff */
505	msr = rdmsr(MSR_EFER) | EFER_SCE;
506	wrmsr(MSR_EFER, msr);
507	wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall));
508	wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
509	msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
510	      ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
511	wrmsr(MSR_STAR, msr);
512	wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D);
513
514	/* Disable local APIC just to be sure. */
515	lapic_disable();
516
517	/* signal our startup to the BSP. */
518	mp_naps++;
519
520	/* Spin until the BSP releases the AP's. */
521	while (!aps_ready)
522		ia32_pause();
523
524	/* Initialize the PAT MSR. */
525	pmap_init_pat();
526
527	/* set up CPU registers and state */
528	cpu_setregs();
529
530	/* set up SSE/NX registers */
531	initializecpu();
532
533	/* set up FPU state on the AP */
534	fpuinit();
535
536	/* A quick check from sanity claus */
537	if (PCPU_GET(apic_id) != lapic_id()) {
538		printf("SMP: cpuid = %d\n", PCPU_GET(cpuid));
539		printf("SMP: actual apic_id = %d\n", lapic_id());
540		printf("SMP: correct apic_id = %d\n", PCPU_GET(apic_id));
541		panic("cpuid mismatch! boom!!");
542	}
543
544	/* Initialize curthread. */
545	KASSERT(PCPU_GET(idlethread) != NULL, ("no idle thread"));
546	PCPU_SET(curthread, PCPU_GET(idlethread));
547
548	mtx_lock_spin(&ap_boot_mtx);
549
550	/* Init local apic for irq's */
551	lapic_setup(1);
552
553	/* Set memory range attributes for this CPU to match the BSP */
554	mem_range_AP_init();
555
556	smp_cpus++;
557
558	CTR1(KTR_SMP, "SMP: AP CPU #%d Launched", PCPU_GET(cpuid));
559	printf("SMP: AP CPU #%d Launched!\n", PCPU_GET(cpuid));
560
561	/* Determine if we are a logical CPU. */
562	if (logical_cpus > 1 && PCPU_GET(apic_id) % logical_cpus != 0)
563		logical_cpus_mask |= PCPU_GET(cpumask);
564
565	/* Determine if we are a hyperthread. */
566	if (hyperthreading_cpus > 1 &&
567	    PCPU_GET(apic_id) % hyperthreading_cpus != 0)
568		hyperthreading_cpus_mask |= PCPU_GET(cpumask);
569
570	/* Build our map of 'other' CPUs. */
571	PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
572
573	if (bootverbose)
574		lapic_dump("AP");
575
576	if (smp_cpus == mp_ncpus) {
577		/* enable IPI's, tlb shootdown, freezes etc */
578		atomic_store_rel_int(&smp_started, 1);
579		smp_active = 1;	 /* historic */
580	}
581
582	/*
583	 * Enable global pages TLB extension
584	 * This also implicitly flushes the TLB
585	 */
586
587	load_cr4(rcr4() | CR4_PGE);
588	load_ds(_udatasel);
589	load_es(_udatasel);
590	load_fs(_udatasel);
591	mtx_unlock_spin(&ap_boot_mtx);
592
593	/* wait until all the AP's are up */
594	while (smp_started == 0)
595		ia32_pause();
596
597	sched_throw(NULL);
598
599	panic("scheduler returned us to %s", __func__);
600	/* NOTREACHED */
601}
602
603/*******************************************************************
604 * local functions and data
605 */
606
607/*
608 * We tell the I/O APIC code about all the CPUs we want to receive
609 * interrupts.  If we don't want certain CPUs to receive IRQs we
610 * can simply not tell the I/O APIC code about them in this function.
611 * We also do not tell it about the BSP since it tells itself about
612 * the BSP internally to work with UP kernels and on UP machines.
613 */
614static void
615set_interrupt_apic_ids(void)
616{
617	u_int i, apic_id;
618
619	for (i = 0; i < MAXCPU; i++) {
620		apic_id = cpu_apic_ids[i];
621		if (apic_id == -1)
622			continue;
623		if (cpu_info[apic_id].cpu_bsp)
624			continue;
625		if (cpu_info[apic_id].cpu_disabled)
626			continue;
627
628		/* Don't let hyperthreads service interrupts. */
629		if (hyperthreading_cpus > 1 &&
630		    apic_id % hyperthreading_cpus != 0)
631			continue;
632
633		intr_add_cpu(i);
634	}
635}
636
637/*
638 * Assign logical CPU IDs to local APICs.
639 */
640static void
641assign_cpu_ids(void)
642{
643	u_int i;
644
645	/* Check for explicitly disabled CPUs. */
646	for (i = 0; i <= MAX_APIC_ID; i++) {
647		if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp)
648			continue;
649
650		/* Don't use this CPU if it has been disabled by a tunable. */
651		if (resource_disabled("lapic", i)) {
652			cpu_info[i].cpu_disabled = 1;
653			continue;
654		}
655	}
656
657	/*
658	 * Assign CPU IDs to local APIC IDs and disable any CPUs
659	 * beyond MAXCPU.  CPU 0 has already been assigned to the BSP,
660	 * so we only have to assign IDs for APs.
661	 */
662	mp_ncpus = 1;
663	for (i = 0; i <= MAX_APIC_ID; i++) {
664		if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp ||
665		    cpu_info[i].cpu_disabled)
666			continue;
667
668		if (mp_ncpus < MAXCPU) {
669			cpu_apic_ids[mp_ncpus] = i;
670			apic_cpuids[i] = mp_ncpus;
671			mp_ncpus++;
672		} else
673			cpu_info[i].cpu_disabled = 1;
674	}
675	KASSERT(mp_maxid >= mp_ncpus - 1,
676	    ("%s: counters out of sync: max %d, count %d", __func__, mp_maxid,
677	    mp_ncpus));
678}
679
680/*
681 * start each AP in our list
682 */
683static int
684start_all_aps(void)
685{
686	vm_offset_t va = boot_address + KERNBASE;
687	u_int64_t *pt4, *pt3, *pt2;
688	u_int32_t mpbioswarmvec;
689	int apic_id, cpu, i;
690	u_char mpbiosreason;
691
692	mtx_init(&ap_boot_mtx, "ap boot", NULL, MTX_SPIN);
693
694	/* install the AP 1st level boot code */
695	pmap_kenter(va, boot_address);
696	pmap_invalidate_page(kernel_pmap, va);
697	bcopy(mptramp_start, (void *)va, bootMP_size);
698
699	/* Locate the page tables, they'll be below the trampoline */
700	pt4 = (u_int64_t *)(uintptr_t)(mptramp_pagetables + KERNBASE);
701	pt3 = pt4 + (PAGE_SIZE) / sizeof(u_int64_t);
702	pt2 = pt3 + (PAGE_SIZE) / sizeof(u_int64_t);
703
704	/* Create the initial 1GB replicated page tables */
705	for (i = 0; i < 512; i++) {
706		/* Each slot of the level 4 pages points to the same level 3 page */
707		pt4[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + PAGE_SIZE);
708		pt4[i] |= PG_V | PG_RW | PG_U;
709
710		/* Each slot of the level 3 pages points to the same level 2 page */
711		pt3[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + (2 * PAGE_SIZE));
712		pt3[i] |= PG_V | PG_RW | PG_U;
713
714		/* The level 2 page slots are mapped with 2MB pages for 1GB. */
715		pt2[i] = i * (2 * 1024 * 1024);
716		pt2[i] |= PG_V | PG_RW | PG_PS | PG_U;
717	}
718
719	/* save the current value of the warm-start vector */
720	mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
721	outb(CMOS_REG, BIOS_RESET);
722	mpbiosreason = inb(CMOS_DATA);
723
724	/* setup a vector to our boot code */
725	*((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
726	*((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
727	outb(CMOS_REG, BIOS_RESET);
728	outb(CMOS_DATA, BIOS_WARM);	/* 'warm-start' */
729
730	/* start each AP */
731	for (cpu = 1; cpu < mp_ncpus; cpu++) {
732		apic_id = cpu_apic_ids[cpu];
733
734		/* allocate and set up an idle stack data page */
735		bootstacks[cpu] = (void *)kmem_alloc(kernel_map, KSTACK_PAGES * PAGE_SIZE);
736		doublefault_stack = (char *)kmem_alloc(kernel_map, PAGE_SIZE);
737		nmi_stack = (char *)kmem_alloc(kernel_map, PAGE_SIZE);
738
739		bootSTK = (char *)bootstacks[cpu] + KSTACK_PAGES * PAGE_SIZE - 8;
740		bootAP = cpu;
741
742		/* attempt to start the Application Processor */
743		if (!start_ap(apic_id)) {
744			/* restore the warmstart vector */
745			*(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
746			panic("AP #%d (PHY# %d) failed!", cpu, apic_id);
747		}
748
749		all_cpus |= (1 << cpu);		/* record AP in CPU map */
750	}
751
752	/* build our map of 'other' CPUs */
753	PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
754
755	/* restore the warmstart vector */
756	*(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
757
758	outb(CMOS_REG, BIOS_RESET);
759	outb(CMOS_DATA, mpbiosreason);
760
761	/* number of APs actually started */
762	return mp_naps;
763}
764
765
766/*
767 * This function starts the AP (application processor) identified
768 * by the APIC ID 'physicalCpu'.  It does quite a "song and dance"
769 * to accomplish this.  This is necessary because of the nuances
770 * of the different hardware we might encounter.  It isn't pretty,
771 * but it seems to work.
772 */
773static int
774start_ap(int apic_id)
775{
776	int vector, ms;
777	int cpus;
778
779	/* calculate the vector */
780	vector = (boot_address >> 12) & 0xff;
781
782	/* used as a watchpoint to signal AP startup */
783	cpus = mp_naps;
784
785	/*
786	 * first we do an INIT/RESET IPI this INIT IPI might be run, reseting
787	 * and running the target CPU. OR this INIT IPI might be latched (P5
788	 * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
789	 * ignored.
790	 */
791
792	/* do an INIT IPI: assert RESET */
793	lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
794	    APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, apic_id);
795
796	/* wait for pending status end */
797	lapic_ipi_wait(-1);
798
799	/* do an INIT IPI: deassert RESET */
800	lapic_ipi_raw(APIC_DEST_ALLESELF | APIC_TRIGMOD_LEVEL |
801	    APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, 0);
802
803	/* wait for pending status end */
804	DELAY(10000);		/* wait ~10mS */
805	lapic_ipi_wait(-1);
806
807	/*
808	 * next we do a STARTUP IPI: the previous INIT IPI might still be
809	 * latched, (P5 bug) this 1st STARTUP would then terminate
810	 * immediately, and the previously started INIT IPI would continue. OR
811	 * the previous INIT IPI has already run. and this STARTUP IPI will
812	 * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
813	 * will run.
814	 */
815
816	/* do a STARTUP IPI */
817	lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
818	    APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
819	    vector, apic_id);
820	lapic_ipi_wait(-1);
821	DELAY(200);		/* wait ~200uS */
822
823	/*
824	 * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
825	 * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
826	 * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
827	 * recognized after hardware RESET or INIT IPI.
828	 */
829
830	lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
831	    APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
832	    vector, apic_id);
833	lapic_ipi_wait(-1);
834	DELAY(200);		/* wait ~200uS */
835
836	/* Wait up to 5 seconds for it to start. */
837	for (ms = 0; ms < 5000; ms++) {
838		if (mp_naps > cpus)
839			return 1;	/* return SUCCESS */
840		DELAY(1000);
841	}
842	return 0;		/* return FAILURE */
843}
844
845/*
846 * Flush the TLB on all other CPU's
847 */
848static void
849smp_tlb_shootdown(u_int vector, vm_offset_t addr1, vm_offset_t addr2)
850{
851	u_int ncpu;
852
853	ncpu = mp_ncpus - 1;	/* does not shootdown self */
854	if (ncpu < 1)
855		return;		/* no other cpus */
856	if (!(read_rflags() & PSL_I))
857		panic("%s: interrupts disabled", __func__);
858	mtx_lock_spin(&smp_ipi_mtx);
859	smp_tlb_addr1 = addr1;
860	smp_tlb_addr2 = addr2;
861	atomic_store_rel_int(&smp_tlb_wait, 0);
862	ipi_all_but_self(vector);
863	while (smp_tlb_wait < ncpu)
864		ia32_pause();
865	mtx_unlock_spin(&smp_ipi_mtx);
866}
867
868static void
869smp_targeted_tlb_shootdown(u_int mask, u_int vector, vm_offset_t addr1, vm_offset_t addr2)
870{
871	int ncpu, othercpus;
872
873	othercpus = mp_ncpus - 1;
874	if (mask == (u_int)-1) {
875		ncpu = othercpus;
876		if (ncpu < 1)
877			return;
878	} else {
879		mask &= ~PCPU_GET(cpumask);
880		if (mask == 0)
881			return;
882		ncpu = bitcount32(mask);
883		if (ncpu > othercpus) {
884			/* XXX this should be a panic offence */
885			printf("SMP: tlb shootdown to %d other cpus (only have %d)\n",
886			    ncpu, othercpus);
887			ncpu = othercpus;
888		}
889		/* XXX should be a panic, implied by mask == 0 above */
890		if (ncpu < 1)
891			return;
892	}
893	if (!(read_rflags() & PSL_I))
894		panic("%s: interrupts disabled", __func__);
895	mtx_lock_spin(&smp_ipi_mtx);
896	smp_tlb_addr1 = addr1;
897	smp_tlb_addr2 = addr2;
898	atomic_store_rel_int(&smp_tlb_wait, 0);
899	if (mask == (u_int)-1)
900		ipi_all_but_self(vector);
901	else
902		ipi_selected(mask, vector);
903	while (smp_tlb_wait < ncpu)
904		ia32_pause();
905	mtx_unlock_spin(&smp_ipi_mtx);
906}
907
908void
909smp_cache_flush(void)
910{
911
912	if (smp_started)
913		smp_tlb_shootdown(IPI_INVLCACHE, 0, 0);
914}
915
916void
917smp_invltlb(void)
918{
919
920	if (smp_started) {
921		smp_tlb_shootdown(IPI_INVLTLB, 0, 0);
922	}
923}
924
925void
926smp_invlpg(vm_offset_t addr)
927{
928
929	if (smp_started)
930		smp_tlb_shootdown(IPI_INVLPG, addr, 0);
931}
932
933void
934smp_invlpg_range(vm_offset_t addr1, vm_offset_t addr2)
935{
936
937	if (smp_started) {
938		smp_tlb_shootdown(IPI_INVLRNG, addr1, addr2);
939	}
940}
941
942void
943smp_masked_invltlb(u_int mask)
944{
945
946	if (smp_started) {
947		smp_targeted_tlb_shootdown(mask, IPI_INVLTLB, 0, 0);
948	}
949}
950
951void
952smp_masked_invlpg(u_int mask, vm_offset_t addr)
953{
954
955	if (smp_started) {
956		smp_targeted_tlb_shootdown(mask, IPI_INVLPG, addr, 0);
957	}
958}
959
960void
961smp_masked_invlpg_range(u_int mask, vm_offset_t addr1, vm_offset_t addr2)
962{
963
964	if (smp_started) {
965		smp_targeted_tlb_shootdown(mask, IPI_INVLRNG, addr1, addr2);
966	}
967}
968
969void
970ipi_bitmap_handler(struct trapframe frame)
971{
972	int cpu = PCPU_GET(cpuid);
973	u_int ipi_bitmap;
974
975	ipi_bitmap = atomic_readandclear_int(&cpu_ipi_pending[cpu]);
976
977	if (ipi_bitmap & (1 << IPI_PREEMPT))
978		sched_preempt(curthread);
979
980	/* Nothing to do for AST */
981}
982
983/*
984 * send an IPI to a set of cpus.
985 */
986void
987ipi_selected(u_int32_t cpus, u_int ipi)
988{
989	int cpu;
990	u_int bitmap = 0;
991	u_int old_pending;
992	u_int new_pending;
993
994	if (IPI_IS_BITMAPED(ipi)) {
995		bitmap = 1 << ipi;
996		ipi = IPI_BITMAP_VECTOR;
997	}
998
999#ifdef STOP_NMI
1000	if (ipi == IPI_STOP && stop_cpus_with_nmi) {
1001		ipi_nmi_selected(cpus);
1002		return;
1003	}
1004#endif
1005	CTR3(KTR_SMP, "%s: cpus: %x ipi: %x", __func__, cpus, ipi);
1006	while ((cpu = ffs(cpus)) != 0) {
1007		cpu--;
1008		cpus &= ~(1 << cpu);
1009
1010		KASSERT(cpu_apic_ids[cpu] != -1,
1011		    ("IPI to non-existent CPU %d", cpu));
1012
1013		if (bitmap) {
1014			do {
1015				old_pending = cpu_ipi_pending[cpu];
1016				new_pending = old_pending | bitmap;
1017			} while  (!atomic_cmpset_int(&cpu_ipi_pending[cpu],old_pending, new_pending));
1018
1019			if (old_pending)
1020				continue;
1021		}
1022
1023		lapic_ipi_vectored(ipi, cpu_apic_ids[cpu]);
1024	}
1025
1026}
1027
1028/*
1029 * send an IPI to all CPUs EXCEPT myself
1030 */
1031void
1032ipi_all_but_self(u_int ipi)
1033{
1034
1035	if (IPI_IS_BITMAPED(ipi) || (ipi == IPI_STOP && stop_cpus_with_nmi)) {
1036		ipi_selected(PCPU_GET(other_cpus), ipi);
1037		return;
1038	}
1039	CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1040	lapic_ipi_vectored(ipi, APIC_IPI_DEST_OTHERS);
1041}
1042
1043#ifdef STOP_NMI
1044/*
1045 * send NMI IPI to selected CPUs
1046 */
1047
1048#define	BEFORE_SPIN	1000000
1049
1050void
1051ipi_nmi_selected(u_int32_t cpus)
1052{
1053	int cpu;
1054	register_t icrlo;
1055
1056	icrlo = APIC_DELMODE_NMI | APIC_DESTMODE_PHY | APIC_LEVEL_ASSERT
1057		| APIC_TRIGMOD_EDGE;
1058
1059	CTR2(KTR_SMP, "%s: cpus: %x nmi", __func__, cpus);
1060
1061	atomic_set_int(&ipi_nmi_pending, cpus);
1062
1063	while ((cpu = ffs(cpus)) != 0) {
1064		cpu--;
1065		cpus &= ~(1 << cpu);
1066
1067		KASSERT(cpu_apic_ids[cpu] != -1,
1068		    ("IPI NMI to non-existent CPU %d", cpu));
1069
1070		/* Wait for an earlier IPI to finish. */
1071		if (!lapic_ipi_wait(BEFORE_SPIN))
1072			panic("ipi_nmi_selected: previous IPI has not cleared");
1073
1074		lapic_ipi_raw(icrlo, cpu_apic_ids[cpu]);
1075	}
1076}
1077
1078int
1079ipi_nmi_handler(void)
1080{
1081	int cpumask = PCPU_GET(cpumask);
1082
1083	if (!(ipi_nmi_pending & cpumask))
1084		return 1;
1085
1086	atomic_clear_int(&ipi_nmi_pending, cpumask);
1087	cpustop_handler();
1088	return 0;
1089}
1090
1091#endif /* STOP_NMI */
1092
1093/*
1094 * Handle an IPI_STOP by saving our current context and spinning until we
1095 * are resumed.
1096 */
1097void
1098cpustop_handler(void)
1099{
1100	int cpu = PCPU_GET(cpuid);
1101	int cpumask = PCPU_GET(cpumask);
1102
1103	savectx(&stoppcbs[cpu]);
1104
1105	/* Indicate that we are stopped */
1106	atomic_set_int(&stopped_cpus, cpumask);
1107
1108	/* Wait for restart */
1109	while (!(started_cpus & cpumask))
1110	    ia32_pause();
1111
1112	atomic_clear_int(&started_cpus, cpumask);
1113	atomic_clear_int(&stopped_cpus, cpumask);
1114
1115	if (cpu == 0 && cpustop_restartfunc != NULL) {
1116		cpustop_restartfunc();
1117		cpustop_restartfunc = NULL;
1118	}
1119}
1120
1121/*
1122 * This is called once the rest of the system is up and running and we're
1123 * ready to let the AP's out of the pen.
1124 */
1125static void
1126release_aps(void *dummy __unused)
1127{
1128
1129	if (mp_ncpus == 1)
1130		return;
1131	atomic_store_rel_int(&aps_ready, 1);
1132	while (smp_started == 0)
1133		ia32_pause();
1134}
1135SYSINIT(start_aps, SI_SUB_SMP, SI_ORDER_FIRST, release_aps, NULL);
1136
1137static int
1138sysctl_hlt_cpus(SYSCTL_HANDLER_ARGS)
1139{
1140	u_int mask;
1141	int error;
1142
1143	mask = hlt_cpus_mask;
1144	error = sysctl_handle_int(oidp, &mask, 0, req);
1145	if (error || !req->newptr)
1146		return (error);
1147
1148	if (logical_cpus_mask != 0 &&
1149	    (mask & logical_cpus_mask) == logical_cpus_mask)
1150		hlt_logical_cpus = 1;
1151	else
1152		hlt_logical_cpus = 0;
1153
1154	if (! hyperthreading_allowed)
1155		mask |= hyperthreading_cpus_mask;
1156
1157	if ((mask & all_cpus) == all_cpus)
1158		mask &= ~(1<<0);
1159	hlt_cpus_mask = mask;
1160	return (error);
1161}
1162SYSCTL_PROC(_machdep, OID_AUTO, hlt_cpus, CTLTYPE_INT|CTLFLAG_RW,
1163    0, 0, sysctl_hlt_cpus, "IU",
1164    "Bitmap of CPUs to halt.  101 (binary) will halt CPUs 0 and 2.");
1165
1166static int
1167sysctl_hlt_logical_cpus(SYSCTL_HANDLER_ARGS)
1168{
1169	int disable, error;
1170
1171	disable = hlt_logical_cpus;
1172	error = sysctl_handle_int(oidp, &disable, 0, req);
1173	if (error || !req->newptr)
1174		return (error);
1175
1176	if (disable)
1177		hlt_cpus_mask |= logical_cpus_mask;
1178	else
1179		hlt_cpus_mask &= ~logical_cpus_mask;
1180
1181	if (! hyperthreading_allowed)
1182		hlt_cpus_mask |= hyperthreading_cpus_mask;
1183
1184	if ((hlt_cpus_mask & all_cpus) == all_cpus)
1185		hlt_cpus_mask &= ~(1<<0);
1186
1187	hlt_logical_cpus = disable;
1188	return (error);
1189}
1190
1191static int
1192sysctl_hyperthreading_allowed(SYSCTL_HANDLER_ARGS)
1193{
1194	int allowed, error;
1195
1196	allowed = hyperthreading_allowed;
1197	error = sysctl_handle_int(oidp, &allowed, 0, req);
1198	if (error || !req->newptr)
1199		return (error);
1200
1201	if (allowed)
1202		hlt_cpus_mask &= ~hyperthreading_cpus_mask;
1203	else
1204		hlt_cpus_mask |= hyperthreading_cpus_mask;
1205
1206	if (logical_cpus_mask != 0 &&
1207	    (hlt_cpus_mask & logical_cpus_mask) == logical_cpus_mask)
1208		hlt_logical_cpus = 1;
1209	else
1210		hlt_logical_cpus = 0;
1211
1212	if ((hlt_cpus_mask & all_cpus) == all_cpus)
1213		hlt_cpus_mask &= ~(1<<0);
1214
1215	hyperthreading_allowed = allowed;
1216	return (error);
1217}
1218
1219static void
1220cpu_hlt_setup(void *dummy __unused)
1221{
1222
1223	if (logical_cpus_mask != 0) {
1224		TUNABLE_INT_FETCH("machdep.hlt_logical_cpus",
1225		    &hlt_logical_cpus);
1226		sysctl_ctx_init(&logical_cpu_clist);
1227		SYSCTL_ADD_PROC(&logical_cpu_clist,
1228		    SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1229		    "hlt_logical_cpus", CTLTYPE_INT|CTLFLAG_RW, 0, 0,
1230		    sysctl_hlt_logical_cpus, "IU", "");
1231		SYSCTL_ADD_UINT(&logical_cpu_clist,
1232		    SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1233		    "logical_cpus_mask", CTLTYPE_INT|CTLFLAG_RD,
1234		    &logical_cpus_mask, 0, "");
1235
1236		if (hlt_logical_cpus)
1237			hlt_cpus_mask |= logical_cpus_mask;
1238
1239		/*
1240		 * If necessary for security purposes, force
1241		 * hyperthreading off, regardless of the value
1242		 * of hlt_logical_cpus.
1243		 */
1244		if (hyperthreading_cpus_mask) {
1245			TUNABLE_INT_FETCH("machdep.hyperthreading_allowed",
1246			    &hyperthreading_allowed);
1247			SYSCTL_ADD_PROC(&logical_cpu_clist,
1248			    SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1249			    "hyperthreading_allowed", CTLTYPE_INT|CTLFLAG_RW,
1250			    0, 0, sysctl_hyperthreading_allowed, "IU", "");
1251			if (! hyperthreading_allowed)
1252				hlt_cpus_mask |= hyperthreading_cpus_mask;
1253		}
1254	}
1255}
1256SYSINIT(cpu_hlt, SI_SUB_SMP, SI_ORDER_ANY, cpu_hlt_setup, NULL);
1257
1258int
1259mp_grab_cpu_hlt(void)
1260{
1261	u_int mask = PCPU_GET(cpumask);
1262#ifdef MP_WATCHDOG
1263	u_int cpuid = PCPU_GET(cpuid);
1264#endif
1265	int retval;
1266
1267#ifdef MP_WATCHDOG
1268	ap_watchdog(cpuid);
1269#endif
1270
1271	retval = mask & hlt_cpus_mask;
1272	while (mask & hlt_cpus_mask)
1273		__asm __volatile("sti; hlt" : : : "memory");
1274	return (retval);
1275}
1276