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