local_apic.c revision 156920
1/*-
2 * Copyright (c) 2003 John Baldwin <jhb@FreeBSD.org>
3 * Copyright (c) 1996, by Steve Passe
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 * 3. Neither the name of the author nor the names of any co-contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30/*
31 * Local APIC support on Pentium and later processors.
32 */
33
34#include <sys/cdefs.h>
35__FBSDID("$FreeBSD: head/sys/i386/i386/local_apic.c 156920 2006-03-20 19:39:08Z jhb $");
36
37#include "opt_hwpmc_hooks.h"
38
39#include "opt_ddb.h"
40
41#include <sys/param.h>
42#include <sys/systm.h>
43#include <sys/bus.h>
44#include <sys/kernel.h>
45#include <sys/lock.h>
46#include <sys/mutex.h>
47#include <sys/pcpu.h>
48#include <sys/smp.h>
49
50#include <vm/vm.h>
51#include <vm/pmap.h>
52
53#include <machine/apicreg.h>
54#include <machine/cpu.h>
55#include <machine/cputypes.h>
56#include <machine/frame.h>
57#include <machine/intr_machdep.h>
58#include <machine/apicvar.h>
59#include <machine/md_var.h>
60#include <machine/smp.h>
61#include <machine/specialreg.h>
62
63#ifdef DDB
64#include <sys/interrupt.h>
65#include <ddb/ddb.h>
66#endif
67
68/*
69 * We can handle up to 60 APICs via our logical cluster IDs, but currently
70 * the physical IDs on Intel processors up to the Pentium 4 are limited to
71 * 16.
72 */
73#define	MAX_APICID	16
74
75/* Sanity checks on IDT vectors. */
76CTASSERT(APIC_IO_INTS + APIC_NUM_IOINTS == APIC_TIMER_INT);
77CTASSERT(APIC_TIMER_INT < APIC_LOCAL_INTS);
78CTASSERT(APIC_LOCAL_INTS == 240);
79CTASSERT(IPI_STOP < APIC_SPURIOUS_INT);
80
81#define	LAPIC_TIMER_HZ_DIVIDER		2
82#define	LAPIC_TIMER_STATHZ_DIVIDER	15
83#define	LAPIC_TIMER_PROFHZ_DIVIDER	3
84
85/* Magic IRQ values for the timer and syscalls. */
86#define	IRQ_TIMER	(NUM_IO_INTS + 1)
87#define	IRQ_SYSCALL	(NUM_IO_INTS + 2)
88
89/*
90 * Support for local APICs.  Local APICs manage interrupts on each
91 * individual processor as opposed to I/O APICs which receive interrupts
92 * from I/O devices and then forward them on to the local APICs.
93 *
94 * Local APICs can also send interrupts to each other thus providing the
95 * mechanism for IPIs.
96 */
97
98struct lvt {
99	u_int lvt_edgetrigger:1;
100	u_int lvt_activehi:1;
101	u_int lvt_masked:1;
102	u_int lvt_active:1;
103	u_int lvt_mode:16;
104	u_int lvt_vector:8;
105};
106
107struct lapic {
108	struct lvt la_lvts[LVT_MAX + 1];
109	u_int la_id:8;
110	u_int la_cluster:4;
111	u_int la_cluster_id:2;
112	u_int la_present:1;
113	u_long *la_timer_count;
114	u_long la_hard_ticks;
115	u_long la_stat_ticks;
116	u_long la_prof_ticks;
117} static lapics[MAX_APICID];
118
119/* XXX: should thermal be an NMI? */
120
121/* Global defaults for local APIC LVT entries. */
122static struct lvt lvts[LVT_MAX + 1] = {
123	{ 1, 1, 1, 1, APIC_LVT_DM_EXTINT, 0 },	/* LINT0: masked ExtINT */
124	{ 1, 1, 0, 1, APIC_LVT_DM_NMI, 0 },	/* LINT1: NMI */
125	{ 1, 1, 1, 1, APIC_LVT_DM_FIXED, APIC_TIMER_INT },	/* Timer */
126	{ 1, 1, 1, 1, APIC_LVT_DM_FIXED, APIC_ERROR_INT },	/* Error */
127	{ 1, 1, 0, 1, APIC_LVT_DM_NMI, 0 },	/* PMC */
128	{ 1, 1, 1, 1, APIC_LVT_DM_FIXED, APIC_THERMAL_INT },	/* Thermal */
129};
130
131static inthand_t *ioint_handlers[] = {
132	NULL,			/* 0 - 31 */
133	IDTVEC(apic_isr1),	/* 32 - 63 */
134	IDTVEC(apic_isr2),	/* 64 - 95 */
135	IDTVEC(apic_isr3),	/* 96 - 127 */
136	IDTVEC(apic_isr4),	/* 128 - 159 */
137	IDTVEC(apic_isr5),	/* 160 - 191 */
138	IDTVEC(apic_isr6),	/* 192 - 223 */
139	IDTVEC(apic_isr7),	/* 224 - 255 */
140};
141
142/* Include IDT_SYSCALL to make indexing easier. */
143static u_int ioint_irqs[APIC_NUM_IOINTS + 1];
144
145static u_int32_t lapic_timer_divisors[] = {
146	APIC_TDCR_1, APIC_TDCR_2, APIC_TDCR_4, APIC_TDCR_8, APIC_TDCR_16,
147	APIC_TDCR_32, APIC_TDCR_64, APIC_TDCR_128
148};
149
150volatile lapic_t *lapic;
151static u_long lapic_timer_divisor, lapic_timer_period, lapic_timer_hz;
152
153static void	lapic_enable(void);
154static void	lapic_timer_enable_intr(void);
155static void	lapic_timer_oneshot(u_int count);
156static void	lapic_timer_periodic(u_int count);
157static void	lapic_timer_set_divisor(u_int divisor);
158static uint32_t	lvt_mode(struct lapic *la, u_int pin, uint32_t value);
159
160static uint32_t
161lvt_mode(struct lapic *la, u_int pin, uint32_t value)
162{
163	struct lvt *lvt;
164
165	KASSERT(pin <= LVT_MAX, ("%s: pin %u out of range", __func__, pin));
166	if (la->la_lvts[pin].lvt_active)
167		lvt = &la->la_lvts[pin];
168	else
169		lvt = &lvts[pin];
170
171	value &= ~(APIC_LVT_M | APIC_LVT_TM | APIC_LVT_IIPP | APIC_LVT_DM |
172	    APIC_LVT_VECTOR);
173	if (lvt->lvt_edgetrigger == 0)
174		value |= APIC_LVT_TM;
175	if (lvt->lvt_activehi == 0)
176		value |= APIC_LVT_IIPP_INTALO;
177	if (lvt->lvt_masked)
178		value |= APIC_LVT_M;
179	value |= lvt->lvt_mode;
180	switch (lvt->lvt_mode) {
181	case APIC_LVT_DM_NMI:
182	case APIC_LVT_DM_SMI:
183	case APIC_LVT_DM_INIT:
184	case APIC_LVT_DM_EXTINT:
185		if (!lvt->lvt_edgetrigger) {
186			printf("lapic%u: Forcing LINT%u to edge trigger\n",
187			    la->la_id, pin);
188			value |= APIC_LVT_TM;
189		}
190		/* Use a vector of 0. */
191		break;
192	case APIC_LVT_DM_FIXED:
193		value |= lvt->lvt_vector;
194		break;
195	default:
196		panic("bad APIC LVT delivery mode: %#x\n", value);
197	}
198	return (value);
199}
200
201/*
202 * Map the local APIC and setup necessary interrupt vectors.
203 */
204void
205lapic_init(uintptr_t addr)
206{
207
208	/* Map the local APIC and setup the spurious interrupt handler. */
209	KASSERT(trunc_page(addr) == addr,
210	    ("local APIC not aligned on a page boundary"));
211	lapic = pmap_mapdev(addr, sizeof(lapic_t));
212	setidt(APIC_SPURIOUS_INT, IDTVEC(spuriousint), SDT_SYS386IGT, SEL_KPL,
213	    GSEL(GCODE_SEL, SEL_KPL));
214
215	/* Perform basic initialization of the BSP's local APIC. */
216	lapic_enable();
217	ioint_irqs[IDT_SYSCALL - APIC_IO_INTS] = IRQ_SYSCALL;
218
219	/* Set BSP's per-CPU local APIC ID. */
220	PCPU_SET(apic_id, lapic_id());
221	intr_add_cpu(PCPU_GET(apic_id));
222
223	/* Local APIC timer interrupt. */
224	setidt(APIC_TIMER_INT, IDTVEC(timerint), SDT_SYS386IGT, SEL_KPL,
225	    GSEL(GCODE_SEL, SEL_KPL));
226	ioint_irqs[APIC_TIMER_INT - APIC_IO_INTS] = IRQ_TIMER;
227
228	/* XXX: error/thermal interrupts */
229}
230
231/*
232 * Create a local APIC instance.
233 */
234void
235lapic_create(u_int apic_id, int boot_cpu)
236{
237	int i;
238
239	if (apic_id >= MAX_APICID) {
240		printf("APIC: Ignoring local APIC with ID %d\n", apic_id);
241		if (boot_cpu)
242			panic("Can't ignore BSP");
243		return;
244	}
245	KASSERT(!lapics[apic_id].la_present, ("duplicate local APIC %u",
246	    apic_id));
247
248	/*
249	 * Assume no local LVT overrides and a cluster of 0 and
250	 * intra-cluster ID of 0.
251	 */
252	lapics[apic_id].la_present = 1;
253	lapics[apic_id].la_id = apic_id;
254	for (i = 0; i < LVT_MAX; i++) {
255		lapics[apic_id].la_lvts[i] = lvts[i];
256		lapics[apic_id].la_lvts[i].lvt_active = 0;
257	}
258
259#ifdef SMP
260	cpu_add(apic_id, boot_cpu);
261#endif
262}
263
264/*
265 * Dump contents of local APIC registers
266 */
267void
268lapic_dump(const char* str)
269{
270
271	printf("cpu%d %s:\n", PCPU_GET(cpuid), str);
272	printf("     ID: 0x%08x   VER: 0x%08x LDR: 0x%08x DFR: 0x%08x\n",
273	    lapic->id, lapic->version, lapic->ldr, lapic->dfr);
274	printf("  lint0: 0x%08x lint1: 0x%08x TPR: 0x%08x SVR: 0x%08x\n",
275	    lapic->lvt_lint0, lapic->lvt_lint1, lapic->tpr, lapic->svr);
276	printf("  timer: 0x%08x therm: 0x%08x err: 0x%08x pcm: 0x%08x\n",
277	    lapic->lvt_timer, lapic->lvt_thermal, lapic->lvt_error,
278	    lapic->lvt_pcint);
279}
280
281void
282lapic_setup(void)
283{
284	struct lapic *la;
285	u_int32_t maxlvt;
286	register_t eflags;
287	char buf[MAXCOMLEN + 1];
288
289	la = &lapics[lapic_id()];
290	KASSERT(la->la_present, ("missing APIC structure"));
291	eflags = intr_disable();
292	maxlvt = (lapic->version & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
293
294	/* Initialize the TPR to allow all interrupts. */
295	lapic_set_tpr(0);
296
297	/* Setup spurious vector and enable the local APIC. */
298	lapic_enable();
299
300	/* Program LINT[01] LVT entries. */
301	lapic->lvt_lint0 = lvt_mode(la, LVT_LINT0, lapic->lvt_lint0);
302	lapic->lvt_lint1 = lvt_mode(la, LVT_LINT1, lapic->lvt_lint1);
303#ifdef	HWPMC_HOOKS
304	/* Program the PMC LVT entry if present. */
305	if (maxlvt >= LVT_PMC)
306		lapic->lvt_pcint = lvt_mode(la, LVT_PMC, lapic->lvt_pcint);
307#endif
308
309	/* Program timer LVT and setup handler. */
310	lapic->lvt_timer = lvt_mode(la, LVT_TIMER, lapic->lvt_timer);
311	snprintf(buf, sizeof(buf), "cpu%d: timer", PCPU_GET(cpuid));
312	intrcnt_add(buf, &la->la_timer_count);
313	if (PCPU_GET(cpuid) != 0) {
314		KASSERT(lapic_timer_period != 0, ("lapic%u: zero divisor",
315		    lapic_id()));
316		lapic_timer_set_divisor(lapic_timer_divisor);
317		lapic_timer_periodic(lapic_timer_period);
318		lapic_timer_enable_intr();
319	}
320
321	/* XXX: Error and thermal LVTs */
322
323	intr_restore(eflags);
324}
325
326/*
327 * Called by cpu_initclocks() on the BSP to setup the local APIC timer so
328 * that it can drive hardclock, statclock, and profclock.  This function
329 * returns true if it is able to use the local APIC timer to drive the
330 * clocks and false if it is not able.
331 */
332int
333lapic_setup_clock(void)
334{
335	u_long value;
336
337	/* Can't drive the timer without a local APIC. */
338	if (lapic == NULL)
339		return (0);
340
341	/* Start off with a divisor of 2 (power on reset default). */
342	lapic_timer_divisor = 2;
343
344	/* Try to calibrate the local APIC timer. */
345	do {
346		lapic_timer_set_divisor(lapic_timer_divisor);
347		lapic_timer_oneshot(APIC_TIMER_MAX_COUNT);
348		DELAY(2000000);
349		value = APIC_TIMER_MAX_COUNT - lapic->ccr_timer;
350		if (value != APIC_TIMER_MAX_COUNT)
351			break;
352		lapic_timer_divisor <<= 1;
353	} while (lapic_timer_divisor <= 128);
354	if (lapic_timer_divisor > 128)
355		panic("lapic: Divisor too big");
356	value /= 2;
357	if (bootverbose)
358		printf("lapic: Divisor %lu, Frequency %lu hz\n",
359		    lapic_timer_divisor, value);
360
361	/*
362	 * We will drive the timer at a small multiple of hz and drive
363	 * both of the other timers with similarly small but relatively
364	 * prime divisors.
365	 */
366	lapic_timer_hz = hz * LAPIC_TIMER_HZ_DIVIDER;
367	stathz = lapic_timer_hz / LAPIC_TIMER_STATHZ_DIVIDER;
368	profhz = lapic_timer_hz / LAPIC_TIMER_PROFHZ_DIVIDER;
369	lapic_timer_period = value / lapic_timer_hz;
370
371	/*
372	 * Start up the timer on the BSP.  The APs will kick off their
373	 * timer during lapic_setup().
374	 */
375	lapic_timer_periodic(lapic_timer_period);
376	lapic_timer_enable_intr();
377	return (1);
378}
379
380void
381lapic_disable(void)
382{
383	uint32_t value;
384
385	/* Software disable the local APIC. */
386	value = lapic->svr;
387	value &= ~APIC_SVR_SWEN;
388	lapic->svr = value;
389}
390
391static void
392lapic_enable(void)
393{
394	u_int32_t value;
395
396	/* Program the spurious vector to enable the local APIC. */
397	value = lapic->svr;
398	value &= ~(APIC_SVR_VECTOR | APIC_SVR_FOCUS);
399	value |= (APIC_SVR_FEN | APIC_SVR_SWEN | APIC_SPURIOUS_INT);
400	lapic->svr = value;
401}
402
403int
404lapic_id(void)
405{
406
407	KASSERT(lapic != NULL, ("local APIC is not mapped"));
408	return (lapic->id >> APIC_ID_SHIFT);
409}
410
411int
412lapic_intr_pending(u_int vector)
413{
414	volatile u_int32_t *irr;
415
416	/*
417	 * The IRR registers are an array of 128-bit registers each of
418	 * which only describes 32 interrupts in the low 32 bits..  Thus,
419	 * we divide the vector by 32 to get the 128-bit index.  We then
420	 * multiply that index by 4 to get the equivalent index from
421	 * treating the IRR as an array of 32-bit registers.  Finally, we
422	 * modulus the vector by 32 to determine the individual bit to
423	 * test.
424	 */
425	irr = &lapic->irr0;
426	return (irr[(vector / 32) * 4] & 1 << (vector % 32));
427}
428
429void
430lapic_set_logical_id(u_int apic_id, u_int cluster, u_int cluster_id)
431{
432	struct lapic *la;
433
434	KASSERT(lapics[apic_id].la_present, ("%s: APIC %u doesn't exist",
435	    __func__, apic_id));
436	KASSERT(cluster <= APIC_MAX_CLUSTER, ("%s: cluster %u too big",
437	    __func__, cluster));
438	KASSERT(cluster_id <= APIC_MAX_INTRACLUSTER_ID,
439	    ("%s: intra cluster id %u too big", __func__, cluster_id));
440	la = &lapics[apic_id];
441	la->la_cluster = cluster;
442	la->la_cluster_id = cluster_id;
443}
444
445int
446lapic_set_lvt_mask(u_int apic_id, u_int pin, u_char masked)
447{
448
449	if (pin > LVT_MAX)
450		return (EINVAL);
451	if (apic_id == APIC_ID_ALL) {
452		lvts[pin].lvt_masked = masked;
453		if (bootverbose)
454			printf("lapic:");
455	} else {
456		KASSERT(lapics[apic_id].la_present,
457		    ("%s: missing APIC %u", __func__, apic_id));
458		lapics[apic_id].la_lvts[pin].lvt_masked = masked;
459		lapics[apic_id].la_lvts[pin].lvt_active = 1;
460		if (bootverbose)
461			printf("lapic%u:", apic_id);
462	}
463	if (bootverbose)
464		printf(" LINT%u %s\n", pin, masked ? "masked" : "unmasked");
465	return (0);
466}
467
468int
469lapic_set_lvt_mode(u_int apic_id, u_int pin, u_int32_t mode)
470{
471	struct lvt *lvt;
472
473	if (pin > LVT_MAX)
474		return (EINVAL);
475	if (apic_id == APIC_ID_ALL) {
476		lvt = &lvts[pin];
477		if (bootverbose)
478			printf("lapic:");
479	} else {
480		KASSERT(lapics[apic_id].la_present,
481		    ("%s: missing APIC %u", __func__, apic_id));
482		lvt = &lapics[apic_id].la_lvts[pin];
483		lvt->lvt_active = 1;
484		if (bootverbose)
485			printf("lapic%u:", apic_id);
486	}
487	lvt->lvt_mode = mode;
488	switch (mode) {
489	case APIC_LVT_DM_NMI:
490	case APIC_LVT_DM_SMI:
491	case APIC_LVT_DM_INIT:
492	case APIC_LVT_DM_EXTINT:
493		lvt->lvt_edgetrigger = 1;
494		lvt->lvt_activehi = 1;
495		if (mode == APIC_LVT_DM_EXTINT)
496			lvt->lvt_masked = 1;
497		else
498			lvt->lvt_masked = 0;
499		break;
500	default:
501		panic("Unsupported delivery mode: 0x%x\n", mode);
502	}
503	if (bootverbose) {
504		printf(" Routing ");
505		switch (mode) {
506		case APIC_LVT_DM_NMI:
507			printf("NMI");
508			break;
509		case APIC_LVT_DM_SMI:
510			printf("SMI");
511			break;
512		case APIC_LVT_DM_INIT:
513			printf("INIT");
514			break;
515		case APIC_LVT_DM_EXTINT:
516			printf("ExtINT");
517			break;
518		}
519		printf(" -> LINT%u\n", pin);
520	}
521	return (0);
522}
523
524int
525lapic_set_lvt_polarity(u_int apic_id, u_int pin, enum intr_polarity pol)
526{
527
528	if (pin > LVT_MAX || pol == INTR_POLARITY_CONFORM)
529		return (EINVAL);
530	if (apic_id == APIC_ID_ALL) {
531		lvts[pin].lvt_activehi = (pol == INTR_POLARITY_HIGH);
532		if (bootverbose)
533			printf("lapic:");
534	} else {
535		KASSERT(lapics[apic_id].la_present,
536		    ("%s: missing APIC %u", __func__, apic_id));
537		lapics[apic_id].la_lvts[pin].lvt_active = 1;
538		lapics[apic_id].la_lvts[pin].lvt_activehi =
539		    (pol == INTR_POLARITY_HIGH);
540		if (bootverbose)
541			printf("lapic%u:", apic_id);
542	}
543	if (bootverbose)
544		printf(" LINT%u polarity: %s\n", pin,
545		    pol == INTR_POLARITY_HIGH ? "high" : "low");
546	return (0);
547}
548
549int
550lapic_set_lvt_triggermode(u_int apic_id, u_int pin, enum intr_trigger trigger)
551{
552
553	if (pin > LVT_MAX || trigger == INTR_TRIGGER_CONFORM)
554		return (EINVAL);
555	if (apic_id == APIC_ID_ALL) {
556		lvts[pin].lvt_edgetrigger = (trigger == INTR_TRIGGER_EDGE);
557		if (bootverbose)
558			printf("lapic:");
559	} else {
560		KASSERT(lapics[apic_id].la_present,
561		    ("%s: missing APIC %u", __func__, apic_id));
562		lapics[apic_id].la_lvts[pin].lvt_edgetrigger =
563		    (trigger == INTR_TRIGGER_EDGE);
564		lapics[apic_id].la_lvts[pin].lvt_active = 1;
565		if (bootverbose)
566			printf("lapic%u:", apic_id);
567	}
568	if (bootverbose)
569		printf(" LINT%u trigger: %s\n", pin,
570		    trigger == INTR_TRIGGER_EDGE ? "edge" : "level");
571	return (0);
572}
573
574/*
575 * Adjust the TPR of the current CPU so that it blocks all interrupts below
576 * the passed in vector.
577 */
578void
579lapic_set_tpr(u_int vector)
580{
581#ifdef CHEAP_TPR
582	lapic->tpr = vector;
583#else
584	u_int32_t tpr;
585
586	tpr = lapic->tpr & ~APIC_TPR_PRIO;
587	tpr |= vector;
588	lapic->tpr = tpr;
589#endif
590}
591
592void
593lapic_eoi(void)
594{
595
596	lapic->eoi = 0;
597}
598
599void
600lapic_handle_intr(int vector, struct trapframe frame)
601{
602	struct intsrc *isrc;
603
604	if (vector == -1)
605		panic("Couldn't get vector from ISR!");
606	isrc = intr_lookup_source(apic_idt_to_irq(vector));
607	intr_execute_handlers(isrc, &frame);
608}
609
610void
611lapic_handle_timer(struct trapframe frame)
612{
613	struct lapic *la;
614
615	/* Send EOI first thing. */
616	lapic_eoi();
617
618	/* Look up our local APIC structure for the tick counters. */
619	la = &lapics[PCPU_GET(apic_id)];
620	(*la->la_timer_count)++;
621	critical_enter();
622
623	/* Fire hardclock at hz. */
624	la->la_hard_ticks += hz;
625	if (la->la_hard_ticks >= lapic_timer_hz) {
626		la->la_hard_ticks -= lapic_timer_hz;
627		if (PCPU_GET(cpuid) == 0)
628			hardclock(TRAPF_USERMODE(&frame), TRAPF_PC(&frame));
629		else
630			hardclock_cpu(TRAPF_USERMODE(&frame));
631	}
632
633	/* Fire statclock at stathz. */
634	la->la_stat_ticks += stathz;
635	if (la->la_stat_ticks >= lapic_timer_hz) {
636		la->la_stat_ticks -= lapic_timer_hz;
637		statclock(TRAPF_USERMODE(&frame));
638	}
639
640	/* Fire profclock at profhz, but only when needed. */
641	la->la_prof_ticks += profhz;
642	if (la->la_prof_ticks >= lapic_timer_hz) {
643		la->la_prof_ticks -= lapic_timer_hz;
644		if (profprocs != 0)
645			profclock(TRAPF_USERMODE(&frame), TRAPF_PC(&frame));
646	}
647	critical_exit();
648}
649
650static void
651lapic_timer_set_divisor(u_int divisor)
652{
653
654	KASSERT(powerof2(divisor), ("lapic: invalid divisor %u", divisor));
655	KASSERT(ffs(divisor) <= sizeof(lapic_timer_divisors) /
656	    sizeof(u_int32_t), ("lapic: invalid divisor %u", divisor));
657	lapic->dcr_timer = lapic_timer_divisors[ffs(divisor) - 1];
658}
659
660static void
661lapic_timer_oneshot(u_int count)
662{
663	u_int32_t value;
664
665	value = lapic->lvt_timer;
666	value &= ~APIC_LVTT_TM;
667	value |= APIC_LVTT_TM_ONE_SHOT;
668	lapic->lvt_timer = value;
669	lapic->icr_timer = count;
670}
671
672static void
673lapic_timer_periodic(u_int count)
674{
675	u_int32_t value;
676
677	value = lapic->lvt_timer;
678	value &= ~APIC_LVTT_TM;
679	value |= APIC_LVTT_TM_PERIODIC;
680	lapic->lvt_timer = value;
681	lapic->icr_timer = count;
682}
683
684static void
685lapic_timer_enable_intr(void)
686{
687	u_int32_t value;
688
689	value = lapic->lvt_timer;
690	value &= ~APIC_LVT_M;
691	lapic->lvt_timer = value;
692}
693
694/* Request a free IDT vector to be used by the specified IRQ. */
695u_int
696apic_alloc_vector(u_int irq)
697{
698	u_int vector;
699
700	KASSERT(irq < NUM_IO_INTS, ("Invalid IRQ %u", irq));
701
702	/*
703	 * Search for a free vector.  Currently we just use a very simple
704	 * algorithm to find the first free vector.
705	 */
706	mtx_lock_spin(&icu_lock);
707	for (vector = 0; vector < APIC_NUM_IOINTS; vector++) {
708		if (ioint_irqs[vector] != 0)
709			continue;
710		ioint_irqs[vector] = irq;
711		mtx_unlock_spin(&icu_lock);
712		return (vector + APIC_IO_INTS);
713	}
714	mtx_unlock_spin(&icu_lock);
715	panic("Couldn't find an APIC vector for IRQ %u", irq);
716}
717
718void
719apic_enable_vector(u_int vector)
720{
721
722	KASSERT(vector != IDT_SYSCALL, ("Attempt to overwrite syscall entry"));
723	KASSERT(ioint_handlers[vector / 32] != NULL,
724	    ("No ISR handler for vector %u", vector));
725	setidt(vector, ioint_handlers[vector / 32], SDT_SYS386IGT, SEL_KPL,
726	    GSEL(GCODE_SEL, SEL_KPL));
727}
728
729/* Release an APIC vector when it's no longer in use. */
730void
731apic_free_vector(u_int vector, u_int irq)
732{
733	KASSERT(vector >= APIC_IO_INTS && vector != IDT_SYSCALL &&
734	    vector <= APIC_IO_INTS + APIC_NUM_IOINTS,
735	    ("Vector %u does not map to an IRQ line", vector));
736	KASSERT(irq < NUM_IO_INTS, ("Invalid IRQ %u", irq));
737	KASSERT(ioint_irqs[vector - APIC_IO_INTS] == irq, ("IRQ mismatch"));
738	mtx_lock_spin(&icu_lock);
739	ioint_irqs[vector - APIC_IO_INTS] = 0;
740	mtx_unlock_spin(&icu_lock);
741}
742
743/* Map an IDT vector (APIC) to an IRQ (interrupt source). */
744u_int
745apic_idt_to_irq(u_int vector)
746{
747
748	KASSERT(vector >= APIC_IO_INTS && vector != IDT_SYSCALL &&
749	    vector <= APIC_IO_INTS + APIC_NUM_IOINTS,
750	    ("Vector %u does not map to an IRQ line", vector));
751	return (ioint_irqs[vector - APIC_IO_INTS]);
752}
753
754#ifdef DDB
755/*
756 * Dump data about APIC IDT vector mappings.
757 */
758DB_SHOW_COMMAND(apic, db_show_apic)
759{
760	struct intsrc *isrc;
761	int quit, i, verbose;
762	u_int irq;
763
764	quit = 0;
765	if (strcmp(modif, "vv") == 0)
766		verbose = 2;
767	else if (strcmp(modif, "v") == 0)
768		verbose = 1;
769	else
770		verbose = 0;
771	db_setup_paging(db_simple_pager, &quit, db_lines_per_page);
772	for (i = 0; i < APIC_NUM_IOINTS + 1 && !quit; i++) {
773		irq = ioint_irqs[i];
774		if (irq != 0 && irq != IRQ_SYSCALL) {
775			db_printf("vec 0x%2x -> ", i + APIC_IO_INTS);
776			if (irq == IRQ_TIMER)
777				db_printf("lapic timer\n");
778			else if (irq < NUM_IO_INTS) {
779				isrc = intr_lookup_source(irq);
780				if (isrc == NULL || verbose == 0)
781					db_printf("IRQ %u\n", irq);
782				else
783					db_dump_intr_event(isrc->is_event,
784					    verbose == 2);
785			} else
786				db_printf("IRQ %u ???\n", irq);
787		}
788	}
789}
790#endif
791
792/*
793 * APIC probing support code.  This includes code to manage enumerators.
794 */
795
796static SLIST_HEAD(, apic_enumerator) enumerators =
797	SLIST_HEAD_INITIALIZER(enumerators);
798static struct apic_enumerator *best_enum;
799
800void
801apic_register_enumerator(struct apic_enumerator *enumerator)
802{
803#ifdef INVARIANTS
804	struct apic_enumerator *apic_enum;
805
806	SLIST_FOREACH(apic_enum, &enumerators, apic_next) {
807		if (apic_enum == enumerator)
808			panic("%s: Duplicate register of %s", __func__,
809			    enumerator->apic_name);
810	}
811#endif
812	SLIST_INSERT_HEAD(&enumerators, enumerator, apic_next);
813}
814
815/*
816 * Probe the APIC enumerators, enumerate CPUs, and initialize the
817 * local APIC.
818 */
819static void
820apic_init(void *dummy __unused)
821{
822	struct apic_enumerator *enumerator;
823	uint64_t apic_base;
824	int retval, best;
825
826	/* We only support built in local APICs. */
827	if (!(cpu_feature & CPUID_APIC))
828		return;
829
830	/* Don't probe if APIC mode is disabled. */
831	if (resource_disabled("apic", 0))
832		return;
833
834	/* First, probe all the enumerators to find the best match. */
835	best_enum = NULL;
836	best = 0;
837	SLIST_FOREACH(enumerator, &enumerators, apic_next) {
838		retval = enumerator->apic_probe();
839		if (retval > 0)
840			continue;
841		if (best_enum == NULL || best < retval) {
842			best_enum = enumerator;
843			best = retval;
844		}
845	}
846	if (best_enum == NULL) {
847		if (bootverbose)
848			printf("APIC: Could not find any APICs.\n");
849		return;
850	}
851
852	if (bootverbose)
853		printf("APIC: Using the %s enumerator.\n",
854		    best_enum->apic_name);
855
856	/*
857	 * To work around an errata, we disable the local APIC on some
858	 * CPUs during early startup.  We need to turn the local APIC back
859	 * on on such CPUs now.
860	 */
861	if (cpu == CPU_686 && strcmp(cpu_vendor, "GenuineIntel") == 0 &&
862	    (cpu_id & 0xff0) == 0x610) {
863		apic_base = rdmsr(MSR_APICBASE);
864		apic_base |= APICBASE_ENABLED;
865		wrmsr(MSR_APICBASE, apic_base);
866	}
867
868	/* Second, probe the CPU's in the system. */
869	retval = best_enum->apic_probe_cpus();
870	if (retval != 0)
871		printf("%s: Failed to probe CPUs: returned %d\n",
872		    best_enum->apic_name, retval);
873
874	/* Third, initialize the local APIC. */
875	retval = best_enum->apic_setup_local();
876	if (retval != 0)
877		printf("%s: Failed to setup the local APIC: returned %d\n",
878		    best_enum->apic_name, retval);
879#ifdef SMP
880	/* Last, setup the cpu topology now that we have probed CPUs */
881	mp_topology();
882#endif
883}
884SYSINIT(apic_init, SI_SUB_CPU, SI_ORDER_FIRST, apic_init, NULL)
885
886/*
887 * Setup the I/O APICs.
888 */
889static void
890apic_setup_io(void *dummy __unused)
891{
892	int retval;
893
894	if (best_enum == NULL)
895		return;
896	retval = best_enum->apic_setup_io();
897	if (retval != 0)
898		printf("%s: Failed to setup I/O APICs: returned %d\n",
899		    best_enum->apic_name, retval);
900
901	/*
902	 * Finish setting up the local APIC on the BSP once we know how to
903	 * properly program the LINT pins.
904	 */
905	lapic_setup();
906	if (bootverbose)
907		lapic_dump("BSP");
908}
909SYSINIT(apic_setup_io, SI_SUB_INTR, SI_ORDER_SECOND, apic_setup_io, NULL)
910
911#ifdef SMP
912/*
913 * Inter Processor Interrupt functions.  The lapic_ipi_*() functions are
914 * private to the sys/i386 code.  The public interface for the rest of the
915 * kernel is defined in mp_machdep.c.
916 */
917int
918lapic_ipi_wait(int delay)
919{
920	int x, incr;
921
922	/*
923	 * Wait delay loops for IPI to be sent.  This is highly bogus
924	 * since this is sensitive to CPU clock speed.  If delay is
925	 * -1, we wait forever.
926	 */
927	if (delay == -1) {
928		incr = 0;
929		delay = 1;
930	} else
931		incr = 1;
932	for (x = 0; x < delay; x += incr) {
933		if ((lapic->icr_lo & APIC_DELSTAT_MASK) == APIC_DELSTAT_IDLE)
934			return (1);
935		ia32_pause();
936	}
937	return (0);
938}
939
940void
941lapic_ipi_raw(register_t icrlo, u_int dest)
942{
943	register_t value, eflags;
944
945	/* XXX: Need more sanity checking of icrlo? */
946	KASSERT(lapic != NULL, ("%s called too early", __func__));
947	KASSERT((dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
948	    ("%s: invalid dest field", __func__));
949	KASSERT((icrlo & APIC_ICRLO_RESV_MASK) == 0,
950	    ("%s: reserved bits set in ICR LO register", __func__));
951
952	/* Set destination in ICR HI register if it is being used. */
953	eflags = intr_disable();
954	if ((icrlo & APIC_DEST_MASK) == APIC_DEST_DESTFLD) {
955		value = lapic->icr_hi;
956		value &= ~APIC_ID_MASK;
957		value |= dest << APIC_ID_SHIFT;
958		lapic->icr_hi = value;
959	}
960
961	/* Program the contents of the IPI and dispatch it. */
962	value = lapic->icr_lo;
963	value &= APIC_ICRLO_RESV_MASK;
964	value |= icrlo;
965	lapic->icr_lo = value;
966	intr_restore(eflags);
967}
968
969#define	BEFORE_SPIN	1000000
970#ifdef DETECT_DEADLOCK
971#define	AFTER_SPIN	1000
972#endif
973
974void
975lapic_ipi_vectored(u_int vector, int dest)
976{
977	register_t icrlo, destfield;
978
979	KASSERT((vector & ~APIC_VECTOR_MASK) == 0,
980	    ("%s: invalid vector %d", __func__, vector));
981
982	icrlo = vector | APIC_DELMODE_FIXED | APIC_DESTMODE_PHY |
983	    APIC_LEVEL_DEASSERT | APIC_TRIGMOD_EDGE;
984	destfield = 0;
985	switch (dest) {
986	case APIC_IPI_DEST_SELF:
987		icrlo |= APIC_DEST_SELF;
988		break;
989	case APIC_IPI_DEST_ALL:
990		icrlo |= APIC_DEST_ALLISELF;
991		break;
992	case APIC_IPI_DEST_OTHERS:
993		icrlo |= APIC_DEST_ALLESELF;
994		break;
995	default:
996		KASSERT((dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
997		    ("%s: invalid destination 0x%x", __func__, dest));
998		destfield = dest;
999	}
1000
1001	/* Wait for an earlier IPI to finish. */
1002	if (!lapic_ipi_wait(BEFORE_SPIN)) {
1003		if (panicstr != NULL)
1004			return;
1005		else
1006			panic("APIC: Previous IPI is stuck");
1007	}
1008
1009	lapic_ipi_raw(icrlo, destfield);
1010
1011#ifdef DETECT_DEADLOCK
1012	/* Wait for IPI to be delivered. */
1013	if (!lapic_ipi_wait(AFTER_SPIN)) {
1014#ifdef needsattention
1015		/*
1016		 * XXX FIXME:
1017		 *
1018		 * The above function waits for the message to actually be
1019		 * delivered.  It breaks out after an arbitrary timeout
1020		 * since the message should eventually be delivered (at
1021		 * least in theory) and that if it wasn't we would catch
1022		 * the failure with the check above when the next IPI is
1023		 * sent.
1024		 *
1025		 * We could skip this wait entirely, EXCEPT it probably
1026		 * protects us from other routines that assume that the
1027		 * message was delivered and acted upon when this function
1028		 * returns.
1029		 */
1030		printf("APIC: IPI might be stuck\n");
1031#else /* !needsattention */
1032		/* Wait until mesage is sent without a timeout. */
1033		while (lapic->icr_lo & APIC_DELSTAT_PEND)
1034			ia32_pause();
1035#endif /* needsattention */
1036	}
1037#endif /* DETECT_DEADLOCK */
1038}
1039#endif /* SMP */
1040