2 * Copyright (c) 2003 Matthew Dillon <dillon@backplane.com> All rights reserved.
3 * Copyright (c) 1997, Stefan Esser <se@freebsd.org> All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice unmodified, this list of conditions, and the following
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 * $FreeBSD: src/sys/kern/kern_intr.c,v 1.24.2.1 2001/10/14 20:05:50 luigi Exp $
27 * $DragonFly: src/sys/kern/kern_intr.c,v 1.26 2005/10/15 03:23:01 dillon Exp $
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/malloc.h>
34 #include <sys/kernel.h>
35 #include <sys/sysctl.h>
36 #include <sys/thread.h>
38 #include <sys/thread2.h>
39 #include <sys/random.h>
40 #include <sys/serialize.h>
43 #include <machine/ipl.h>
44 #include <machine/frame.h>
46 #include <sys/interrupt.h>
48 typedef struct intrec {
55 struct lwkt_serialize *serializer;
60 struct thread i_thread;
61 struct random_softc i_random;
67 } intr_info_ary[NHWI + NSWI];
69 #define EMERGENCY_INTR_POLLING_FREQ_MAX 20000
71 static int sysctl_emergency_freq(SYSCTL_HANDLER_ARGS);
72 static int sysctl_emergency_enable(SYSCTL_HANDLER_ARGS);
73 static void emergency_intr_timer_callback(systimer_t, struct intrframe *);
74 static void ithread_handler(void *arg);
75 static void ithread_emergency(void *arg);
77 int intr_info_size = sizeof(intr_info_ary) / sizeof(intr_info_ary[0]);
79 static struct systimer emergency_intr_timer;
80 static struct thread emergency_intr_thread;
82 #define LIVELOCK_NONE 0
83 #define LIVELOCK_LIMITED 1
85 static int livelock_limit = 50000;
86 static int livelock_fallback = 20000;
87 SYSCTL_INT(_kern, OID_AUTO, livelock_limit,
88 CTLFLAG_RW, &livelock_limit, 0, "Livelock interrupt rate limit");
89 SYSCTL_INT(_kern, OID_AUTO, livelock_fallback,
90 CTLFLAG_RW, &livelock_fallback, 0, "Livelock interrupt fallback rate");
92 static int emergency_intr_enable = 0; /* emergency interrupt polling */
93 TUNABLE_INT("kern.emergency_intr_enable", &emergency_intr_enable);
94 SYSCTL_PROC(_kern, OID_AUTO, emergency_intr_enable, CTLTYPE_INT | CTLFLAG_RW,
95 0, 0, sysctl_emergency_enable, "I", "Emergency Interrupt Poll Enable");
97 static int emergency_intr_freq = 10; /* emergency polling frequency */
98 TUNABLE_INT("kern.emergency_intr_freq", &emergency_intr_freq);
99 SYSCTL_PROC(_kern, OID_AUTO, emergency_intr_freq, CTLTYPE_INT | CTLFLAG_RW,
100 0, 0, sysctl_emergency_freq, "I", "Emergency Interrupt Poll Frequency");
103 * Sysctl support routines
106 sysctl_emergency_enable(SYSCTL_HANDLER_ARGS)
110 enabled = emergency_intr_enable;
111 error = sysctl_handle_int(oidp, &enabled, 0, req);
112 if (error || req->newptr == NULL)
114 emergency_intr_enable = enabled;
115 if (emergency_intr_enable) {
116 emergency_intr_timer.periodic =
117 sys_cputimer->fromhz(emergency_intr_freq);
119 emergency_intr_timer.periodic = sys_cputimer->fromhz(1);
125 sysctl_emergency_freq(SYSCTL_HANDLER_ARGS)
129 phz = emergency_intr_freq;
130 error = sysctl_handle_int(oidp, &phz, 0, req);
131 if (error || req->newptr == NULL)
135 else if (phz > EMERGENCY_INTR_POLLING_FREQ_MAX)
136 phz = EMERGENCY_INTR_POLLING_FREQ_MAX;
138 emergency_intr_freq = phz;
139 if (emergency_intr_enable) {
140 emergency_intr_timer.periodic =
141 sys_cputimer->fromhz(emergency_intr_freq);
143 emergency_intr_timer.periodic = sys_cputimer->fromhz(1);
149 * Register an SWI or INTerrupt handler.
152 register_swi(int intr, inthand2_t *handler, void *arg, const char *name,
153 struct lwkt_serialize *serializer)
155 if (intr < NHWI || intr >= NHWI + NSWI)
156 panic("register_swi: bad intr %d", intr);
157 return(register_int(intr, handler, arg, name, serializer, 0));
161 register_int(int intr, inthand2_t *handler, void *arg, const char *name,
162 struct lwkt_serialize *serializer, int intr_flags)
164 struct intr_info *info;
165 struct intrec **list;
168 if (intr < 0 || intr >= NHWI + NSWI)
169 panic("register_int: bad intr %d", intr);
172 info = &intr_info_ary[intr];
174 rec = malloc(sizeof(struct intrec), M_DEVBUF, M_INTWAIT);
175 rec->name = malloc(strlen(name) + 1, M_DEVBUF, M_INTWAIT);
176 strcpy(rec->name, name);
178 rec->handler = handler;
181 rec->intr_flags = intr_flags;
183 rec->serializer = serializer;
185 list = &info->i_reclist;
188 * Keep track of how many fast and slow interrupts we have.
190 if (intr_flags & INTR_FAST)
196 * Create an emergency polling thread and set up a systimer to wake
199 if (emergency_intr_thread.td_kstack == NULL) {
200 lwkt_create(ithread_emergency, NULL, NULL,
201 &emergency_intr_thread, TDF_STOPREQ|TDF_INTTHREAD, -1,
203 systimer_init_periodic_nq(&emergency_intr_timer,
204 emergency_intr_timer_callback, &emergency_intr_thread,
205 (emergency_intr_enable ? emergency_intr_freq : 1));
209 * Create an interrupt thread if necessary, leave it in an unscheduled
212 if (info->i_valid_thread == 0) {
213 info->i_valid_thread = 1;
214 lwkt_create((void *)ithread_handler, (void *)intr, NULL,
215 &info->i_thread, TDF_STOPREQ|TDF_INTTHREAD, -1,
217 if (intr >= NHWI && intr < NHWI + NSWI)
218 lwkt_setpri(&info->i_thread, TDPRI_SOFT_NORM);
220 lwkt_setpri(&info->i_thread, TDPRI_INT_MED);
221 info->i_thread.td_preemptable = lwkt_preempt;
225 * Add the record to the interrupt list
227 crit_enter(); /* token */
228 while (*list != NULL)
229 list = &(*list)->next;
236 unregister_swi(void *id)
238 return(unregister_int(id));
242 unregister_int(void *id)
244 struct intr_info *info;
245 struct intrec **list;
249 intr = ((intrec_t)id)->intr;
251 if (intr < 0 || intr > NHWI + NSWI)
252 panic("register_int: bad intr %d", intr);
254 info = &intr_info_ary[intr];
257 * Remove the interrupt descriptor
260 list = &info->i_reclist;
261 while ((rec = *list) != NULL) {
271 * Free it, adjust interrupt type counts
274 if (rec->intr_flags & INTR_FAST)
278 free(rec->name, M_DEVBUF);
281 printf("warning: unregister_int: int %d handler for %s not found\n",
282 intr, ((intrec_t)id)->name);
286 * Return the number of interrupt vectors still registered on this intr
288 return(info->i_fast + info->i_slow);
292 get_registered_intr(void *id)
294 return(((intrec_t)id)->intr);
298 get_registered_name(int intr)
302 if (intr < 0 || intr > NHWI + NSWI)
303 panic("register_int: bad intr %d", intr);
305 if ((rec = intr_info_ary[intr].i_reclist) == NULL)
314 count_registered_ints(int intr)
316 struct intr_info *info;
318 if (intr < 0 || intr > NHWI + NSWI)
319 panic("register_int: bad intr %d", intr);
320 info = &intr_info_ary[intr];
321 return(info->i_fast + info->i_slow);
325 get_interrupt_counter(int intr)
327 struct intr_info *info;
329 if (intr < 0 || intr > NHWI + NSWI)
330 panic("register_int: bad intr %d", intr);
331 info = &intr_info_ary[intr];
332 return(info->i_count);
337 swi_setpriority(int intr, int pri)
339 struct intr_info *info;
341 if (intr < NHWI || intr >= NHWI + NSWI)
342 panic("register_swi: bad intr %d", intr);
343 info = &intr_info_ary[intr];
344 if (info->i_valid_thread)
345 lwkt_setpri(&info->i_thread, pri);
349 register_randintr(int intr)
351 struct intr_info *info;
353 if ((unsigned int)intr >= NHWI + NSWI)
354 panic("register_randintr: bad intr %d", intr);
355 info = &intr_info_ary[intr];
356 info->i_random.sc_intr = intr;
357 info->i_random.sc_enabled = 1;
361 unregister_randintr(int intr)
363 struct intr_info *info;
365 if (intr < NHWI || intr >= NHWI + NSWI)
366 panic("register_swi: bad intr %d", intr);
367 info = &intr_info_ary[intr];
368 info->i_random.sc_enabled = 0;
372 * Dispatch an interrupt. If there's nothing to do we have a stray
373 * interrupt and can just return, leaving the interrupt masked.
375 * We need to schedule the interrupt and set its i_running bit. If
376 * we are not on the interrupt thread's cpu we have to send a message
377 * to the correct cpu that will issue the desired action (interlocking
378 * with the interrupt thread's critical section).
380 * We are NOT in a critical section, which will allow the scheduled
381 * interrupt to preempt us. The MP lock might *NOT* be held here.
384 sched_ithd_remote(void *arg)
386 sched_ithd((int)arg);
392 struct intr_info *info;
394 info = &intr_info_ary[intr];
397 if (info->i_valid_thread) {
398 if (info->i_reclist == NULL) {
399 printf("sched_ithd: stray interrupt %d\n", intr);
401 if (info->i_thread.td_gd == mycpu) {
403 /* preemption handled internally */
404 lwkt_schedule(&info->i_thread);
406 lwkt_send_ipiq(info->i_thread.td_gd,
407 sched_ithd_remote, (void *)intr);
411 printf("sched_ithd: stray interrupt %d\n", intr);
416 * This is run from a periodic SYSTIMER (and thus must be MP safe, the BGL
417 * might not be held).
420 ithread_livelock_wakeup(systimer_t st)
422 struct intr_info *info;
424 info = &intr_info_ary[(int)st->data];
425 if (info->i_valid_thread)
426 lwkt_schedule(&info->i_thread);
430 * This function is called drectly from the ICU or APIC vector code assembly
431 * to process an interrupt. The critical section and interrupt deferral
432 * checks have already been done but the function is entered WITHOUT
433 * a critical section held. The BGL may or may not be held.
435 * Must return non-zero if we do not want the vector code to re-enable
436 * the interrupt (which we don't if we have to schedule the interrupt)
438 int ithread_fast_handler(struct intrframe frame);
441 ithread_fast_handler(struct intrframe frame)
444 struct intr_info *info;
445 struct intrec **list;
450 intrec_t rec, next_rec;
456 info = &intr_info_ary[intr];
459 * If we are not processing any FAST interrupts, just schedule the thing.
460 * (since we aren't in a critical section, this can result in a
463 if (info->i_fast == 0) {
469 * This should not normally occur since interrupts ought to be
470 * masked if the ithread has been scheduled or is running.
476 * Bump the interrupt nesting level to process any FAST interrupts.
477 * Obtain the MP lock as necessary. If the MP lock cannot be obtained,
478 * schedule the interrupt thread to deal with the issue instead.
480 * To reduce overhead, just leave the MP lock held once it has been
484 ++gd->gd_intr_nesting_level;
486 must_schedule = info->i_slow;
491 list = &info->i_reclist;
492 for (rec = *list; rec; rec = next_rec) {
493 next_rec = rec->next; /* rec may be invalid after call */
495 if (rec->intr_flags & INTR_FAST) {
497 if ((rec->intr_flags & INTR_MPSAFE) == 0 && got_mplock == 0) {
498 if (try_mplock() == 0) {
500 * XXX forward to the cpu holding the MP lock
508 if (rec->serializer) {
509 must_schedule += lwkt_serialize_handler_try(
510 rec->serializer, rec->handler,
511 rec->argument, &frame);
513 rec->handler(rec->argument, &frame);
521 --gd->gd_intr_nesting_level;
529 * If we had a problem, schedule the thread to catch the missed
530 * records (it will just re-run all of them). A return value of 0
531 * indicates that all handlers have been run and the interrupt can
532 * be re-enabled, and a non-zero return indicates that the interrupt
533 * thread controls re-enablement.
539 return(must_schedule);
545 /* could not get the MP lock, forward the interrupt */ \
546 movl mp_lock, %eax ; /* check race */ \
547 cmpl $MP_FREE_LOCK,%eax ; \
549 incl PCPU(cnt)+V_FORWARDED_INTS ; \
551 movl $irq_num,8(%esp) ; \
552 movl $forward_fastint_remote,4(%esp) ; \
554 call lwkt_send_ipiq_bycpu ; \
562 * Interrupt threads run this as their main loop.
564 * The handler begins execution outside a critical section and with the BGL
567 * The i_running state starts at 0. When an interrupt occurs, the hardware
568 * interrupt is disabled and sched_ithd() The HW interrupt remains disabled
569 * until all routines have run. We then call ithread_done() to reenable
570 * the HW interrupt and deschedule us until the next interrupt.
572 * We are responsible for atomically checking i_running and ithread_done()
573 * is responsible for atomically checking for platform-specific delayed
574 * interrupts. i_running for our irq is only set in the context of our cpu,
575 * so a critical section is a sufficient interlock.
577 #define LIVELOCK_TIMEFRAME(freq) ((freq) >> 2) /* 1/4 second */
580 ithread_handler(void *arg)
582 struct intr_info *info;
587 struct intrec **list;
589 globaldata_t gd = mycpu;
590 struct systimer ill_timer; /* enforced freq. timer */
591 struct systimer ill_rtimer; /* recovery timer */
592 u_int ill_count = 0; /* interrupt livelock counter */
593 u_int ill_ticks = 0; /* track elapsed to calculate freq */
594 u_int ill_delta = 0; /* track elapsed to calculate freq */
595 int ill_state = 0; /* current state */
598 info = &intr_info_ary[intr];
599 list = &info->i_reclist;
603 * The loop must be entered with one critical section held.
609 * We can get woken up by the livelock periodic code too, run the
610 * handlers only if there is a real interrupt pending. XXX
612 * Clear i_running prior to running the handlers to interlock
613 * again new events occuring during processing of existing events.
615 * Run each handler in a critical section. Note that we run both
616 * FAST and SLOW designated service routines.
619 for (rec = *list; rec; rec = nrec) {
621 if (rec->serializer) {
622 lwkt_serialize_handler_call(rec->serializer,
623 rec->handler, rec->argument, NULL);
625 rec->handler(rec->argument, NULL);
630 * Do a quick exit/enter to catch any higher-priority
631 * interrupt sources and so user/system/interrupt statistics
632 * work for interrupt threads.
638 * This is our interrupt hook to add rate randomness to the random
641 if (info->i_random.sc_enabled)
642 add_interrupt_randomness(intr);
645 * This is our livelock test. If we hit the rate limit we
646 * limit ourselves to X interrupts/sec until the rate
647 * falls below 50% of that value, then we unlimit again.
649 * XXX calling cputimer_count() is expensive but a livelock may
650 * prevent other interrupts from occuring so we cannot use ticks.
652 cputicks = sys_cputimer->count();
654 bticks = cputicks - ill_ticks;
655 ill_ticks = cputicks;
656 if (bticks > sys_cputimer->freq)
657 bticks = sys_cputimer->freq;
662 if (ill_delta < LIVELOCK_TIMEFRAME(sys_cputimer->freq))
664 freq = (int64_t)ill_count * sys_cputimer->freq /
668 if (freq < livelock_limit)
670 printf("intr %d at %d hz, livelocked! limiting at %d hz\n",
671 intr, freq, livelock_fallback);
672 ill_state = LIVELOCK_LIMITED;
674 /* force periodic check to avoid stale removal (if ints stop) */
675 systimer_init_periodic(&ill_rtimer, ithread_livelock_wakeup,
678 case LIVELOCK_LIMITED:
680 * Delay (us) before rearming the interrupt
682 systimer_init_oneshot(&ill_timer, ithread_livelock_wakeup,
683 (void *)intr, 1 + 1000000 / livelock_fallback);
684 lwkt_deschedule_self(curthread);
687 /* in case we were woken up by something else */
688 systimer_del(&ill_timer);
691 * Calculate interrupt rate (note that due to our delay it
692 * will not exceed livelock_fallback).
695 if (ill_delta < LIVELOCK_TIMEFRAME(sys_cputimer->freq))
697 freq = (int64_t)ill_count * sys_cputimer->freq / ill_delta;
700 if (freq < (livelock_fallback >> 1)) {
701 printf("intr %d at %d hz, removing livelock limit\n",
703 ill_state = LIVELOCK_NONE;
704 systimer_del(&ill_rtimer);
710 * There are two races here. i_running is set by sched_ithd()
711 * in the context of our cpu and is critical-section safe. We
712 * are responsible for checking it. ipending is not critical
713 * section safe and must be handled by the platform specific
714 * ithread_done() routine.
716 if (info->i_running == 0)
718 /* must be in critical section on loop */
724 * Emergency interrupt polling thread. The thread begins execution
725 * outside a critical section with the BGL held.
727 * If emergency interrupt polling is enabled, this thread will
728 * execute all system interrupts not marked INTR_NOPOLL at the
729 * specified polling frequency.
731 * WARNING! This thread runs *ALL* interrupt service routines that
732 * are not marked INTR_NOPOLL, which basically means everything except
733 * the 8254 clock interrupt and the ATA interrupt. It has very high
734 * overhead and should only be used in situations where the machine
735 * cannot otherwise be made to work. Due to the severe performance
736 * degredation, it should not be enabled on production machines.
739 ithread_emergency(void *arg __unused)
741 struct intr_info *info;
746 for (intr = 0; intr < NHWI + NSWI; ++intr) {
747 info = &intr_info_ary[intr];
748 for (rec = info->i_reclist; rec; rec = nrec) {
749 if ((rec->intr_flags & INTR_NOPOLL) == 0) {
750 if (rec->serializer) {
751 lwkt_serialize_handler_call(rec->serializer,
752 rec->handler, rec->argument, NULL);
754 rec->handler(rec->argument, NULL);
760 lwkt_deschedule_self(curthread);
766 * Systimer callback - schedule the emergency interrupt poll thread
767 * if emergency polling is enabled.
771 emergency_intr_timer_callback(systimer_t info, struct intrframe *frame __unused)
773 if (emergency_intr_enable)
774 lwkt_schedule(info->data);
778 * Sysctls used by systat and others: hw.intrnames and hw.intrcnt.
779 * The data for this machine dependent, and the declarations are in machine
780 * dependent code. The layout of intrnames and intrcnt however is machine
783 * We do not know the length of intrcnt and intrnames at compile time, so
784 * calculate things at run time.
788 sysctl_intrnames(SYSCTL_HANDLER_ARGS)
790 struct intr_info *info;
797 for (intr = 0; error == 0 && intr < NHWI + NSWI; ++intr) {
798 info = &intr_info_ary[intr];
802 for (rec = info->i_reclist; rec; rec = rec->next) {
803 snprintf(buf + len, sizeof(buf) - len, "%s%s",
804 (len ? "/" : ""), rec->name);
805 len += strlen(buf + len);
808 snprintf(buf, sizeof(buf), "irq%d", intr);
811 error = SYSCTL_OUT(req, buf, len + 1);
817 SYSCTL_PROC(_hw, OID_AUTO, intrnames, CTLTYPE_OPAQUE | CTLFLAG_RD,
818 NULL, 0, sysctl_intrnames, "", "Interrupt Names");
821 sysctl_intrcnt(SYSCTL_HANDLER_ARGS)
823 struct intr_info *info;
827 for (intr = 0; intr < NHWI + NSWI; ++intr) {
828 info = &intr_info_ary[intr];
830 error = SYSCTL_OUT(req, &info->i_count, sizeof(info->i_count));
837 SYSCTL_PROC(_hw, OID_AUTO, intrcnt, CTLTYPE_OPAQUE | CTLFLAG_RD,
838 NULL, 0, sysctl_intrcnt, "", "Interrupt Counts");