xref: /dragonfly/sys/platform/pc64/apic/lapic.c (revision 07a2f99c)
1 /*
2  * Copyright (c) 1996, by Steve Passe
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. The name of the developer may NOT be used to endorse or promote products
11  *    derived from this software without specific prior written permission.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  * $FreeBSD: src/sys/i386/i386/mpapic.c,v 1.37.2.7 2003/01/25 02:31:47 peter Exp $
26  */
27 
28 #include <sys/param.h>
29 #include <sys/systm.h>
30 #include <sys/kernel.h>
31 #include <sys/bus.h>
32 #include <sys/machintr.h>
33 #include <machine/globaldata.h>
34 #include <machine/smp.h>
35 #include <machine/md_var.h>
36 #include <machine/pmap.h>
37 #include <machine/specialreg.h>
38 #include <machine_base/apic/lapic.h>
39 #include <machine_base/apic/ioapic.h>
40 #include <machine_base/apic/ioapic_abi.h>
41 #include <machine_base/apic/apicvar.h>
42 #include <machine_base/icu/icu_var.h>
43 #include <machine/segments.h>
44 #include <sys/thread2.h>
45 
46 #include <machine/cputypes.h>
47 #include <machine/intr_machdep.h>
48 
49 extern int naps;
50 
51 volatile lapic_t *lapic;
52 
53 static void	lapic_timer_calibrate(void);
54 static void	lapic_timer_set_divisor(int);
55 static void	lapic_timer_fixup_handler(void *);
56 static void	lapic_timer_restart_handler(void *);
57 
58 void		lapic_timer_process(void);
59 void		lapic_timer_process_frame(struct intrframe *);
60 void		lapic_timer_always(struct intrframe *);
61 
62 static int	lapic_timer_enable = 1;
63 TUNABLE_INT("hw.lapic_timer_enable", &lapic_timer_enable);
64 
65 static void	lapic_timer_intr_reload(struct cputimer_intr *, sysclock_t);
66 static void	lapic_timer_intr_enable(struct cputimer_intr *);
67 static void	lapic_timer_intr_restart(struct cputimer_intr *);
68 static void	lapic_timer_intr_pmfixup(struct cputimer_intr *);
69 
70 static struct cputimer_intr lapic_cputimer_intr = {
71 	.freq = 0,
72 	.reload = lapic_timer_intr_reload,
73 	.enable = lapic_timer_intr_enable,
74 	.config = cputimer_intr_default_config,
75 	.restart = lapic_timer_intr_restart,
76 	.pmfixup = lapic_timer_intr_pmfixup,
77 	.initclock = cputimer_intr_default_initclock,
78 	.next = SLIST_ENTRY_INITIALIZER,
79 	.name = "lapic",
80 	.type = CPUTIMER_INTR_LAPIC,
81 	.prio = CPUTIMER_INTR_PRIO_LAPIC,
82 	.caps = CPUTIMER_INTR_CAP_NONE
83 };
84 
85 static int		lapic_timer_divisor_idx = -1;
86 static const uint32_t	lapic_timer_divisors[] = {
87 	APIC_TDCR_2,	APIC_TDCR_4,	APIC_TDCR_8,	APIC_TDCR_16,
88 	APIC_TDCR_32,	APIC_TDCR_64,	APIC_TDCR_128,	APIC_TDCR_1
89 };
90 #define APIC_TIMER_NDIVISORS (int)(NELEM(lapic_timer_divisors))
91 
92 /*
93  * APIC ID <-> CPU ID mapping structures.
94  */
95 int	cpu_id_to_apic_id[NAPICID];
96 int	apic_id_to_cpu_id[NAPICID];
97 int	lapic_enable = 1;
98 
99 /*
100  * Enable LAPIC, configure interrupts.
101  */
102 void
103 lapic_init(boolean_t bsp)
104 {
105 	uint32_t timer;
106 	u_int   temp;
107 
108 	/*
109 	 * Install vectors
110 	 *
111 	 * Since IDT is shared between BSP and APs, these vectors
112 	 * only need to be installed once; we do it on BSP.
113 	 */
114 	if (bsp) {
115 		if (cpu_vendor_id == CPU_VENDOR_AMD &&
116 		    CPUID_TO_FAMILY(cpu_id) >= 0xf) {
117 			uint32_t tcr;
118 
119 			/*
120 			 * Set the LINTEN bit in the HyperTransport
121 			 * Transaction Control Register.
122 			 *
123 			 * This will cause EXTINT and NMI interrupts
124 			 * routed over the hypertransport bus to be
125 			 * fed into the LAPIC LINT0/LINT1.  If the bit
126 			 * isn't set, the interrupts will go to the
127 			 * general cpu INTR/NMI pins.  On a dual-core
128 			 * cpu the interrupt winds up going to BOTH cpus.
129 			 * The first cpu that does the interrupt ack
130 			 * cycle will get the correct interrupt.  The
131 			 * second cpu that does it will get a spurious
132 			 * interrupt vector (typically IRQ 7).
133 			 */
134 			outl(0x0cf8,
135 			    (1 << 31) |	/* enable */
136 			    (0 << 16) |	/* bus */
137 			    (0x18 << 11) | /* dev (cpu + 0x18) */
138 			    (0 << 8) |	/* func */
139 			    0x68	/* reg */
140 			    );
141 			tcr = inl(0xcfc);
142 			if ((tcr & 0x00010000) == 0) {
143 				kprintf("LAPIC: AMD LINTEN on\n");
144 				outl(0xcfc, tcr|0x00010000);
145 			}
146 			outl(0x0cf8, 0);
147 		}
148 
149 		/* Install a 'Spurious INTerrupt' vector */
150 		setidt_global(XSPURIOUSINT_OFFSET, Xspuriousint,
151 		    SDT_SYSIGT, SEL_KPL, 0);
152 
153 		/* Install a timer vector */
154 		setidt_global(XTIMER_OFFSET, Xtimer,
155 		    SDT_SYSIGT, SEL_KPL, 0);
156 
157 		/* Install an inter-CPU IPI for TLB invalidation */
158 		setidt_global(XINVLTLB_OFFSET, Xinvltlb,
159 		    SDT_SYSIGT, SEL_KPL, 0);
160 
161 		/* Install an inter-CPU IPI for IPIQ messaging */
162 		setidt_global(XIPIQ_OFFSET, Xipiq,
163 		    SDT_SYSIGT, SEL_KPL, 0);
164 
165 		/* Install an inter-CPU IPI for CPU stop/restart */
166 		setidt_global(XCPUSTOP_OFFSET, Xcpustop,
167 		    SDT_SYSIGT, SEL_KPL, 0);
168 	}
169 
170 	/*
171 	 * Setup LINT0 as ExtINT on the BSP.  This is theoretically an
172 	 * aggregate interrupt input from the 8259.  The INTA cycle
173 	 * will be routed to the external controller (the 8259) which
174 	 * is expected to supply the vector.
175 	 *
176 	 * Must be setup edge triggered, active high.
177 	 *
178 	 * Disable LINT0 on BSP, if I/O APIC is enabled.
179 	 *
180 	 * Disable LINT0 on the APs.  It doesn't matter what delivery
181 	 * mode we use because we leave it masked.
182 	 */
183 	temp = lapic->lvt_lint0;
184 	temp &= ~(APIC_LVT_MASKED | APIC_LVT_TRIG_MASK |
185 		  APIC_LVT_POLARITY_MASK | APIC_LVT_DM_MASK);
186 	if (bsp) {
187 		temp |= APIC_LVT_DM_EXTINT;
188 		if (ioapic_enable)
189 			temp |= APIC_LVT_MASKED;
190 	} else {
191 		temp |= APIC_LVT_DM_FIXED | APIC_LVT_MASKED;
192 	}
193 	lapic->lvt_lint0 = temp;
194 
195 	/*
196 	 * Setup LINT1 as NMI.
197 	 *
198 	 * Must be setup edge trigger, active high.
199 	 *
200 	 * Enable LINT1 on BSP, if I/O APIC is enabled.
201 	 *
202 	 * Disable LINT1 on the APs.
203 	 */
204 	temp = lapic->lvt_lint1;
205 	temp &= ~(APIC_LVT_MASKED | APIC_LVT_TRIG_MASK |
206 		  APIC_LVT_POLARITY_MASK | APIC_LVT_DM_MASK);
207 	temp |= APIC_LVT_MASKED | APIC_LVT_DM_NMI;
208 	if (bsp && ioapic_enable)
209 		temp &= ~APIC_LVT_MASKED;
210 	lapic->lvt_lint1 = temp;
211 
212 	/*
213 	 * Mask the LAPIC error interrupt, LAPIC performance counter
214 	 * interrupt.
215 	 */
216 	lapic->lvt_error = lapic->lvt_error | APIC_LVT_MASKED;
217 	lapic->lvt_pcint = lapic->lvt_pcint | APIC_LVT_MASKED;
218 
219 	/*
220 	 * Set LAPIC timer vector and mask the LAPIC timer interrupt.
221 	 */
222 	timer = lapic->lvt_timer;
223 	timer &= ~APIC_LVTT_VECTOR;
224 	timer |= XTIMER_OFFSET;
225 	timer |= APIC_LVTT_MASKED;
226 	lapic->lvt_timer = timer;
227 
228 	/*
229 	 * Set the Task Priority Register as needed.   At the moment allow
230 	 * interrupts on all cpus (the APs will remain CLId until they are
231 	 * ready to deal).
232 	 */
233 	temp = lapic->tpr;
234 	temp &= ~APIC_TPR_PRIO;		/* clear priority field */
235 	lapic->tpr = temp;
236 
237 	/*
238 	 * Enable the LAPIC
239 	 */
240 	temp = lapic->svr;
241 	temp |= APIC_SVR_ENABLE;	/* enable the LAPIC */
242 	temp &= ~APIC_SVR_FOCUS_DISABLE; /* enable lopri focus processor */
243 
244 	/*
245 	 * Set the spurious interrupt vector.  The low 4 bits of the vector
246 	 * must be 1111.
247 	 */
248 	if ((XSPURIOUSINT_OFFSET & 0x0F) != 0x0F)
249 		panic("bad XSPURIOUSINT_OFFSET: 0x%08x", XSPURIOUSINT_OFFSET);
250 	temp &= ~APIC_SVR_VECTOR;
251 	temp |= XSPURIOUSINT_OFFSET;
252 
253 	lapic->svr = temp;
254 
255 	/*
256 	 * Pump out a few EOIs to clean out interrupts that got through
257 	 * before we were able to set the TPR.
258 	 */
259 	lapic->eoi = 0;
260 	lapic->eoi = 0;
261 	lapic->eoi = 0;
262 
263 	if (bsp) {
264 		lapic_timer_calibrate();
265 		if (lapic_timer_enable) {
266 			cputimer_intr_register(&lapic_cputimer_intr);
267 			cputimer_intr_select(&lapic_cputimer_intr, 0);
268 		}
269 	} else {
270 		lapic_timer_set_divisor(lapic_timer_divisor_idx);
271 	}
272 
273 	if (bootverbose)
274 		apic_dump("apic_initialize()");
275 }
276 
277 static void
278 lapic_timer_set_divisor(int divisor_idx)
279 {
280 	KKASSERT(divisor_idx >= 0 && divisor_idx < APIC_TIMER_NDIVISORS);
281 	lapic->dcr_timer = lapic_timer_divisors[divisor_idx];
282 }
283 
284 static void
285 lapic_timer_oneshot(u_int count)
286 {
287 	uint32_t value;
288 
289 	value = lapic->lvt_timer;
290 	value &= ~APIC_LVTT_PERIODIC;
291 	lapic->lvt_timer = value;
292 	lapic->icr_timer = count;
293 }
294 
295 static void
296 lapic_timer_oneshot_quick(u_int count)
297 {
298 	lapic->icr_timer = count;
299 }
300 
301 static void
302 lapic_timer_calibrate(void)
303 {
304 	sysclock_t value;
305 
306 	/* Try to calibrate the local APIC timer. */
307 	for (lapic_timer_divisor_idx = 0;
308 	     lapic_timer_divisor_idx < APIC_TIMER_NDIVISORS;
309 	     lapic_timer_divisor_idx++) {
310 		lapic_timer_set_divisor(lapic_timer_divisor_idx);
311 		lapic_timer_oneshot(APIC_TIMER_MAX_COUNT);
312 		DELAY(2000000);
313 		value = APIC_TIMER_MAX_COUNT - lapic->ccr_timer;
314 		if (value != APIC_TIMER_MAX_COUNT)
315 			break;
316 	}
317 	if (lapic_timer_divisor_idx >= APIC_TIMER_NDIVISORS)
318 		panic("lapic: no proper timer divisor?!");
319 	lapic_cputimer_intr.freq = value / 2;
320 
321 	kprintf("lapic: divisor index %d, frequency %u Hz\n",
322 		lapic_timer_divisor_idx, lapic_cputimer_intr.freq);
323 }
324 
325 static void
326 lapic_timer_process_oncpu(struct globaldata *gd, struct intrframe *frame)
327 {
328 	sysclock_t count;
329 
330 	gd->gd_timer_running = 0;
331 
332 	count = sys_cputimer->count();
333 	if (TAILQ_FIRST(&gd->gd_systimerq) != NULL)
334 		systimer_intr(&count, 0, frame);
335 }
336 
337 void
338 lapic_timer_process(void)
339 {
340 	lapic_timer_process_oncpu(mycpu, NULL);
341 }
342 
343 void
344 lapic_timer_process_frame(struct intrframe *frame)
345 {
346 	lapic_timer_process_oncpu(mycpu, frame);
347 }
348 
349 /*
350  * This manual debugging code is called unconditionally from Xtimer
351  * (the lapic timer interrupt) whether the current thread is in a
352  * critical section or not) and can be useful in tracking down lockups.
353  *
354  * NOTE: MANUAL DEBUG CODE
355  */
356 #if 0
357 static int saveticks[SMP_MAXCPU];
358 static int savecounts[SMP_MAXCPU];
359 #endif
360 
361 void
362 lapic_timer_always(struct intrframe *frame)
363 {
364 #if 0
365 	globaldata_t gd = mycpu;
366 	int cpu = gd->gd_cpuid;
367 	char buf[64];
368 	short *gptr;
369 	int i;
370 
371 	if (cpu <= 20) {
372 		gptr = (short *)0xFFFFFFFF800b8000 + 80 * cpu;
373 		*gptr = ((*gptr + 1) & 0x00FF) | 0x0700;
374 		++gptr;
375 
376 		ksnprintf(buf, sizeof(buf), " %p %16s %d %16s ",
377 		    (void *)frame->if_rip, gd->gd_curthread->td_comm, ticks,
378 		    gd->gd_infomsg);
379 		for (i = 0; buf[i]; ++i) {
380 			gptr[i] = 0x0700 | (unsigned char)buf[i];
381 		}
382 	}
383 #if 0
384 	if (saveticks[gd->gd_cpuid] != ticks) {
385 		saveticks[gd->gd_cpuid] = ticks;
386 		savecounts[gd->gd_cpuid] = 0;
387 	}
388 	++savecounts[gd->gd_cpuid];
389 	if (savecounts[gd->gd_cpuid] > 2000 && panicstr == NULL) {
390 		panic("cpud %d panicing on ticks failure",
391 			gd->gd_cpuid);
392 	}
393 	for (i = 0; i < ncpus; ++i) {
394 		int delta;
395 		if (saveticks[i] && panicstr == NULL) {
396 			delta = saveticks[i] - ticks;
397 			if (delta < -10 || delta > 10) {
398 				panic("cpu %d panicing on cpu %d watchdog",
399 				      gd->gd_cpuid, i);
400 			}
401 		}
402 	}
403 #endif
404 #endif
405 }
406 
407 static void
408 lapic_timer_intr_reload(struct cputimer_intr *cti, sysclock_t reload)
409 {
410 	struct globaldata *gd = mycpu;
411 
412 	reload = (int64_t)reload * cti->freq / sys_cputimer->freq;
413 	if (reload < 2)
414 		reload = 2;
415 
416 	if (gd->gd_timer_running) {
417 		if (reload < lapic->ccr_timer)
418 			lapic_timer_oneshot_quick(reload);
419 	} else {
420 		gd->gd_timer_running = 1;
421 		lapic_timer_oneshot_quick(reload);
422 	}
423 }
424 
425 static void
426 lapic_timer_intr_enable(struct cputimer_intr *cti __unused)
427 {
428 	uint32_t timer;
429 
430 	timer = lapic->lvt_timer;
431 	timer &= ~(APIC_LVTT_MASKED | APIC_LVTT_PERIODIC);
432 	lapic->lvt_timer = timer;
433 
434 	lapic_timer_fixup_handler(NULL);
435 }
436 
437 static void
438 lapic_timer_fixup_handler(void *arg)
439 {
440 	int *started = arg;
441 
442 	if (started != NULL)
443 		*started = 0;
444 
445 	if (cpu_vendor_id == CPU_VENDOR_AMD) {
446 		/*
447 		 * Detect the presence of C1E capability mostly on latest
448 		 * dual-cores (or future) k8 family.  This feature renders
449 		 * the local APIC timer dead, so we disable it by reading
450 		 * the Interrupt Pending Message register and clearing both
451 		 * C1eOnCmpHalt (bit 28) and SmiOnCmpHalt (bit 27).
452 		 *
453 		 * Reference:
454 		 *   "BIOS and Kernel Developer's Guide for AMD NPT
455 		 *    Family 0Fh Processors"
456 		 *   #32559 revision 3.00
457 		 */
458 		if ((cpu_id & 0x00000f00) == 0x00000f00 &&
459 		    (cpu_id & 0x0fff0000) >= 0x00040000) {
460 			uint64_t msr;
461 
462 			msr = rdmsr(0xc0010055);
463 			if (msr & 0x18000000) {
464 				struct globaldata *gd = mycpu;
465 
466 				kprintf("cpu%d: AMD C1E detected\n",
467 					gd->gd_cpuid);
468 				wrmsr(0xc0010055, msr & ~0x18000000ULL);
469 
470 				/*
471 				 * We are kinda stalled;
472 				 * kick start again.
473 				 */
474 				gd->gd_timer_running = 1;
475 				lapic_timer_oneshot_quick(2);
476 
477 				if (started != NULL)
478 					*started = 1;
479 			}
480 		}
481 	}
482 }
483 
484 static void
485 lapic_timer_restart_handler(void *dummy __unused)
486 {
487 	int started;
488 
489 	lapic_timer_fixup_handler(&started);
490 	if (!started) {
491 		struct globaldata *gd = mycpu;
492 
493 		gd->gd_timer_running = 1;
494 		lapic_timer_oneshot_quick(2);
495 	}
496 }
497 
498 /*
499  * This function is called only by ACPI-CA code currently:
500  * - AMD C1E fixup.  AMD C1E only seems to happen after ACPI
501  *   module controls PM.  So once ACPI-CA is attached, we try
502  *   to apply the fixup to prevent LAPIC timer from hanging.
503  */
504 static void
505 lapic_timer_intr_pmfixup(struct cputimer_intr *cti __unused)
506 {
507 	lwkt_send_ipiq_mask(smp_active_mask,
508 			    lapic_timer_fixup_handler, NULL);
509 }
510 
511 static void
512 lapic_timer_intr_restart(struct cputimer_intr *cti __unused)
513 {
514 	lwkt_send_ipiq_mask(smp_active_mask, lapic_timer_restart_handler, NULL);
515 }
516 
517 
518 /*
519  * dump contents of local APIC registers
520  */
521 void
522 apic_dump(char* str)
523 {
524 	kprintf("SMP: CPU%d %s:\n", mycpu->gd_cpuid, str);
525 	kprintf("     lint0: 0x%08x lint1: 0x%08x TPR: 0x%08x SVR: 0x%08x\n",
526 		lapic->lvt_lint0, lapic->lvt_lint1, lapic->tpr, lapic->svr);
527 }
528 
529 /*
530  * Inter Processor Interrupt functions.
531  */
532 
533 /*
534  * Send APIC IPI 'vector' to 'destType' via 'deliveryMode'.
535  *
536  *  destType is 1 of: APIC_DEST_SELF, APIC_DEST_ALLISELF, APIC_DEST_ALLESELF
537  *  vector is any valid SYSTEM INT vector
538  *  delivery_mode is 1 of: APIC_DELMODE_FIXED, APIC_DELMODE_LOWPRIO
539  *
540  * WARNINGS!
541  *
542  * We now implement a per-cpu interlock (gd->gd_npoll) to prevent more than
543  * one IPI from being sent to any given cpu at a time.  Thus we no longer
544  * have to process incoming IPIs while waiting for the status to clear.
545  * No deadlock should be possible.
546  *
547  * We now physically disable interrupts for the lapic ICR operation.  If
548  * we do not do this then it looks like an EOI sent to the lapic (which
549  * occurs even with a critical section) can interfere with the command
550  * register ready status and cause an IPI to be lost.
551  *
552  * e.g. an interrupt can occur, issue the EOI, IRET, and cause the command
553  * register to busy just before we write to icr_lo, resulting in a lost
554  * issuance.  This only appears to occur on Intel cpus and is not
555  * documented.  It could simply be that cpus are so fast these days that
556  * it was always an issue, but is only now rearing its ugly head.  This
557  * is conjecture.
558  */
559 int
560 apic_ipi(int dest_type, int vector, int delivery_mode)
561 {
562 	unsigned long rflags;
563 	u_long  icr_lo;
564 
565 	rflags = read_rflags();
566 	cpu_disable_intr();
567 	while ((lapic->icr_lo & APIC_DELSTAT_MASK) != 0) {
568 		cpu_pause();
569 	}
570 	icr_lo = (lapic->icr_lo & APIC_ICRLO_RESV_MASK) | dest_type |
571 		delivery_mode | vector;
572 	lapic->icr_lo = icr_lo;
573 	write_rflags(rflags);
574 
575 	return 0;
576 }
577 
578 void
579 single_apic_ipi(int cpu, int vector, int delivery_mode)
580 {
581 	unsigned long rflags;
582 	u_long  icr_lo;
583 	u_long  icr_hi;
584 
585 	rflags = read_rflags();
586 	cpu_disable_intr();
587 	while ((lapic->icr_lo & APIC_DELSTAT_MASK) != 0) {
588 		cpu_pause();
589 	}
590 	icr_hi = lapic->icr_hi & ~APIC_ID_MASK;
591 	icr_hi |= (CPUID_TO_APICID(cpu) << 24);
592 	lapic->icr_hi = icr_hi;
593 
594 	/* build ICR_LOW */
595 	icr_lo = (lapic->icr_lo & APIC_ICRLO_RESV_MASK) |
596 		 APIC_DEST_DESTFLD | delivery_mode | vector;
597 
598 	/* write APIC ICR */
599 	lapic->icr_lo = icr_lo;
600 	write_rflags(rflags);
601 }
602 
603 #if 0
604 
605 /*
606  * Returns 0 if the apic is busy, 1 if we were able to queue the request.
607  *
608  * NOT WORKING YET!  The code as-is may end up not queueing an IPI at all
609  * to the target, and the scheduler does not 'poll' for IPI messages.
610  */
611 int
612 single_apic_ipi_passive(int cpu, int vector, int delivery_mode)
613 {
614 	u_long  icr_lo;
615 	u_long  icr_hi;
616 
617 	crit_enter();
618 	if ((lapic->icr_lo & APIC_DELSTAT_MASK) != 0) {
619 	    crit_exit();
620 	    return(0);
621 	}
622 	icr_hi = lapic->icr_hi & ~APIC_ID_MASK;
623 	icr_hi |= (CPUID_TO_APICID(cpu) << 24);
624 	lapic->icr_hi = icr_hi;
625 
626 	/* build IRC_LOW */
627 	icr_lo = (lapic->icr_lo & APIC_RESV2_MASK)
628 	    | APIC_DEST_DESTFLD | delivery_mode | vector;
629 
630 	/* write APIC ICR */
631 	lapic->icr_lo = icr_lo;
632 	crit_exit();
633 	return(1);
634 }
635 
636 #endif
637 
638 /*
639  * Send APIC IPI 'vector' to 'target's via 'delivery_mode'.
640  *
641  * target is a bitmask of destination cpus.  Vector is any
642  * valid system INT vector.  Delivery mode may be either
643  * APIC_DELMODE_FIXED or APIC_DELMODE_LOWPRIO.
644  */
645 void
646 selected_apic_ipi(cpumask_t target, int vector, int delivery_mode)
647 {
648 	crit_enter();
649 	while (target) {
650 		int n = BSFCPUMASK(target);
651 		target &= ~CPUMASK(n);
652 		single_apic_ipi(n, vector, delivery_mode);
653 	}
654 	crit_exit();
655 }
656 
657 /*
658  * Timer code, in development...
659  *  - suggested by rgrimes@gndrsh.aac.dev.com
660  */
661 int
662 get_apic_timer_frequency(void)
663 {
664 	return(lapic_cputimer_intr.freq);
665 }
666 
667 /*
668  * Load a 'downcount time' in uSeconds.
669  */
670 void
671 set_apic_timer(int us)
672 {
673 	u_int count;
674 
675 	/*
676 	 * When we reach here, lapic timer's frequency
677 	 * must have been calculated as well as the
678 	 * divisor (lapic->dcr_timer is setup during the
679 	 * divisor calculation).
680 	 */
681 	KKASSERT(lapic_cputimer_intr.freq != 0 &&
682 		 lapic_timer_divisor_idx >= 0);
683 
684 	count = ((us * (int64_t)lapic_cputimer_intr.freq) + 999999) / 1000000;
685 	lapic_timer_oneshot(count);
686 }
687 
688 
689 /*
690  * Read remaining time in timer.
691  */
692 int
693 read_apic_timer(void)
694 {
695 #if 0
696 	/** XXX FIXME: we need to return the actual remaining time,
697          *         for now we just return the remaining count.
698          */
699 #else
700 	return lapic->ccr_timer;
701 #endif
702 }
703 
704 
705 /*
706  * Spin-style delay, set delay time in uS, spin till it drains.
707  */
708 void
709 u_sleep(int count)
710 {
711 	set_apic_timer(count);
712 	while (read_apic_timer())
713 		 /* spin */ ;
714 }
715 
716 int
717 lapic_unused_apic_id(int start)
718 {
719 	int i;
720 
721 	for (i = start; i < APICID_MAX; ++i) {
722 		if (APICID_TO_CPUID(i) == -1)
723 			return i;
724 	}
725 	return NAPICID;
726 }
727 
728 void
729 lapic_map(vm_paddr_t lapic_addr)
730 {
731 	lapic = pmap_mapdev_uncacheable(lapic_addr, sizeof(struct LAPIC));
732 }
733 
734 static TAILQ_HEAD(, lapic_enumerator) lapic_enumerators =
735 	TAILQ_HEAD_INITIALIZER(lapic_enumerators);
736 
737 int
738 lapic_config(void)
739 {
740 	struct lapic_enumerator *e;
741 	int error, i, ap_max;
742 
743 	KKASSERT(lapic_enable);
744 
745 	for (i = 0; i < NAPICID; ++i)
746 		APICID_TO_CPUID(i) = -1;
747 
748 	TAILQ_FOREACH(e, &lapic_enumerators, lapic_link) {
749 		error = e->lapic_probe(e);
750 		if (!error)
751 			break;
752 	}
753 	if (e == NULL) {
754 		kprintf("LAPIC: Can't find LAPIC\n");
755 		return ENXIO;
756 	}
757 
758 	error = e->lapic_enumerate(e);
759 	if (error) {
760 		kprintf("LAPIC: enumeration failed\n");
761 		return ENXIO;
762 	}
763 
764 	ap_max = MAXCPU - 1;
765 	TUNABLE_INT_FETCH("hw.ap_max", &ap_max);
766 	if (ap_max > MAXCPU - 1)
767 		ap_max = MAXCPU - 1;
768 
769 	if (naps > ap_max) {
770 		kprintf("LAPIC: Warning use only %d out of %d "
771 			"available APs\n",
772 			ap_max, naps);
773 		naps = ap_max;
774 	}
775 
776 	return 0;
777 }
778 
779 void
780 lapic_enumerator_register(struct lapic_enumerator *ne)
781 {
782 	struct lapic_enumerator *e;
783 
784 	TAILQ_FOREACH(e, &lapic_enumerators, lapic_link) {
785 		if (e->lapic_prio < ne->lapic_prio) {
786 			TAILQ_INSERT_BEFORE(e, ne, lapic_link);
787 			return;
788 		}
789 	}
790 	TAILQ_INSERT_TAIL(&lapic_enumerators, ne, lapic_link);
791 }
792 
793 void
794 lapic_set_cpuid(int cpu_id, int apic_id)
795 {
796 	CPUID_TO_APICID(cpu_id) = apic_id;
797 	APICID_TO_CPUID(apic_id) = cpu_id;
798 }
799 
800 void
801 lapic_fixup_noioapic(void)
802 {
803 	u_int   temp;
804 
805 	/* Only allowed on BSP */
806 	KKASSERT(mycpuid == 0);
807 	KKASSERT(!ioapic_enable);
808 
809 	temp = lapic->lvt_lint0;
810 	temp &= ~APIC_LVT_MASKED;
811 	lapic->lvt_lint0 = temp;
812 
813 	temp = lapic->lvt_lint1;
814 	temp |= APIC_LVT_MASKED;
815 	lapic->lvt_lint1 = temp;
816 }
817 
818 static void
819 lapic_sysinit(void *dummy __unused)
820 {
821 	if (lapic_enable) {
822 		int error;
823 
824 		error = lapic_config();
825 		if (error)
826 			lapic_enable = 0;
827 	}
828 
829 	if (lapic_enable) {
830 		/* Initialize BSP's local APIC */
831 		lapic_init(TRUE);
832 	} else if (ioapic_enable) {
833 		ioapic_enable = 0;
834 		icu_reinit_noioapic();
835 	}
836 }
837 SYSINIT(lapic, SI_BOOT2_LAPIC, SI_ORDER_FIRST, lapic_sysinit, NULL)
838