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.29 2005/10/26 01:16:04 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 ISTATE_NOTHREAD 0
83 #define ISTATE_NORMAL 1
84 #define ISTATE_LIVELOCKED 2
86 static int livelock_limit = 50000;
87 static int livelock_lowater = 20000;
88 SYSCTL_INT(_kern, OID_AUTO, livelock_limit,
89 CTLFLAG_RW, &livelock_limit, 0, "Livelock interrupt rate limit");
90 SYSCTL_INT(_kern, OID_AUTO, livelock_lowater,
91 CTLFLAG_RW, &livelock_lowater, 0, "Livelock low-water mark restore");
93 static int emergency_intr_enable = 0; /* emergency interrupt polling */
94 TUNABLE_INT("kern.emergency_intr_enable", &emergency_intr_enable);
95 SYSCTL_PROC(_kern, OID_AUTO, emergency_intr_enable, CTLTYPE_INT | CTLFLAG_RW,
96 0, 0, sysctl_emergency_enable, "I", "Emergency Interrupt Poll Enable");
98 static int emergency_intr_freq = 10; /* emergency polling frequency */
99 TUNABLE_INT("kern.emergency_intr_freq", &emergency_intr_freq);
100 SYSCTL_PROC(_kern, OID_AUTO, emergency_intr_freq, CTLTYPE_INT | CTLFLAG_RW,
101 0, 0, sysctl_emergency_freq, "I", "Emergency Interrupt Poll Frequency");
104 * Sysctl support routines
107 sysctl_emergency_enable(SYSCTL_HANDLER_ARGS)
111 enabled = emergency_intr_enable;
112 error = sysctl_handle_int(oidp, &enabled, 0, req);
113 if (error || req->newptr == NULL)
115 emergency_intr_enable = enabled;
116 if (emergency_intr_enable) {
117 emergency_intr_timer.periodic =
118 sys_cputimer->fromhz(emergency_intr_freq);
120 emergency_intr_timer.periodic = sys_cputimer->fromhz(1);
126 sysctl_emergency_freq(SYSCTL_HANDLER_ARGS)
130 phz = emergency_intr_freq;
131 error = sysctl_handle_int(oidp, &phz, 0, req);
132 if (error || req->newptr == NULL)
136 else if (phz > EMERGENCY_INTR_POLLING_FREQ_MAX)
137 phz = EMERGENCY_INTR_POLLING_FREQ_MAX;
139 emergency_intr_freq = phz;
140 if (emergency_intr_enable) {
141 emergency_intr_timer.periodic =
142 sys_cputimer->fromhz(emergency_intr_freq);
144 emergency_intr_timer.periodic = sys_cputimer->fromhz(1);
150 * Register an SWI or INTerrupt handler.
153 register_swi(int intr, inthand2_t *handler, void *arg, const char *name,
154 struct lwkt_serialize *serializer)
156 if (intr < NHWI || intr >= NHWI + NSWI)
157 panic("register_swi: bad intr %d", intr);
158 return(register_int(intr, handler, arg, name, serializer, 0));
162 register_int(int intr, inthand2_t *handler, void *arg, const char *name,
163 struct lwkt_serialize *serializer, int intr_flags)
165 struct intr_info *info;
166 struct intrec **list;
169 if (intr < 0 || intr >= NHWI + NSWI)
170 panic("register_int: bad intr %d", intr);
173 info = &intr_info_ary[intr];
175 rec = malloc(sizeof(struct intrec), M_DEVBUF, M_INTWAIT);
176 rec->name = malloc(strlen(name) + 1, M_DEVBUF, M_INTWAIT);
177 strcpy(rec->name, name);
179 rec->handler = handler;
182 rec->intr_flags = intr_flags;
184 rec->serializer = serializer;
186 list = &info->i_reclist;
189 * Keep track of how many fast and slow interrupts we have.
191 if (intr_flags & INTR_FAST)
197 * Create an emergency polling thread and set up a systimer to wake
200 if (emergency_intr_thread.td_kstack == NULL) {
201 lwkt_create(ithread_emergency, NULL, NULL,
202 &emergency_intr_thread, TDF_STOPREQ|TDF_INTTHREAD, -1,
204 systimer_init_periodic_nq(&emergency_intr_timer,
205 emergency_intr_timer_callback, &emergency_intr_thread,
206 (emergency_intr_enable ? emergency_intr_freq : 1));
210 * Create an interrupt thread if necessary, leave it in an unscheduled
213 if (info->i_state == ISTATE_NOTHREAD) {
214 info->i_state = ISTATE_NORMAL;
215 lwkt_create((void *)ithread_handler, (void *)intr, NULL,
216 &info->i_thread, TDF_STOPREQ|TDF_INTTHREAD, -1,
218 if (intr >= NHWI && intr < NHWI + NSWI)
219 lwkt_setpri(&info->i_thread, TDPRI_SOFT_NORM);
221 lwkt_setpri(&info->i_thread, TDPRI_INT_MED);
222 info->i_thread.td_preemptable = lwkt_preempt;
226 * Add the record to the interrupt list
228 crit_enter(); /* token */
229 while (*list != NULL)
230 list = &(*list)->next;
237 unregister_swi(void *id)
239 return(unregister_int(id));
243 unregister_int(void *id)
245 struct intr_info *info;
246 struct intrec **list;
250 intr = ((intrec_t)id)->intr;
252 if (intr < 0 || intr > NHWI + NSWI)
253 panic("register_int: bad intr %d", intr);
255 info = &intr_info_ary[intr];
258 * Remove the interrupt descriptor
261 list = &info->i_reclist;
262 while ((rec = *list) != NULL) {
272 * Free it, adjust interrupt type counts
275 if (rec->intr_flags & INTR_FAST)
279 free(rec->name, M_DEVBUF);
282 printf("warning: unregister_int: int %d handler for %s not found\n",
283 intr, ((intrec_t)id)->name);
287 * Return the number of interrupt vectors still registered on this intr
289 return(info->i_fast + info->i_slow);
293 get_registered_intr(void *id)
295 return(((intrec_t)id)->intr);
299 get_registered_name(int intr)
303 if (intr < 0 || intr > NHWI + NSWI)
304 panic("register_int: bad intr %d", intr);
306 if ((rec = intr_info_ary[intr].i_reclist) == NULL)
315 count_registered_ints(int intr)
317 struct intr_info *info;
319 if (intr < 0 || intr > NHWI + NSWI)
320 panic("register_int: bad intr %d", intr);
321 info = &intr_info_ary[intr];
322 return(info->i_fast + info->i_slow);
326 get_interrupt_counter(int intr)
328 struct intr_info *info;
330 if (intr < 0 || intr > NHWI + NSWI)
331 panic("register_int: bad intr %d", intr);
332 info = &intr_info_ary[intr];
333 return(info->i_count);
338 swi_setpriority(int intr, int pri)
340 struct intr_info *info;
342 if (intr < NHWI || intr >= NHWI + NSWI)
343 panic("register_swi: bad intr %d", intr);
344 info = &intr_info_ary[intr];
345 if (info->i_state != ISTATE_NOTHREAD)
346 lwkt_setpri(&info->i_thread, pri);
350 register_randintr(int intr)
352 struct intr_info *info;
354 if ((unsigned int)intr >= NHWI + NSWI)
355 panic("register_randintr: bad intr %d", intr);
356 info = &intr_info_ary[intr];
357 info->i_random.sc_intr = intr;
358 info->i_random.sc_enabled = 1;
362 unregister_randintr(int intr)
364 struct intr_info *info;
366 if (intr < NHWI || intr >= NHWI + NSWI)
367 panic("register_swi: bad intr %d", intr);
368 info = &intr_info_ary[intr];
369 info->i_random.sc_enabled = 0;
373 * Dispatch an interrupt. If there's nothing to do we have a stray
374 * interrupt and can just return, leaving the interrupt masked.
376 * We need to schedule the interrupt and set its i_running bit. If
377 * we are not on the interrupt thread's cpu we have to send a message
378 * to the correct cpu that will issue the desired action (interlocking
379 * with the interrupt thread's critical section). We do NOT attempt to
380 * reschedule interrupts whos i_running bit is already set because
381 * this would prematurely wakeup a livelock-limited interrupt thread.
383 * i_running is only tested/set on the same cpu as the interrupt thread.
385 * We are NOT in a critical section, which will allow the scheduled
386 * interrupt to preempt us. The MP lock might *NOT* be held here.
391 sched_ithd_remote(void *arg)
393 sched_ithd((int)arg);
401 struct intr_info *info;
403 info = &intr_info_ary[intr];
406 if (info->i_state != ISTATE_NOTHREAD) {
407 if (info->i_reclist == NULL) {
408 printf("sched_ithd: stray interrupt %d\n", intr);
411 if (info->i_thread.td_gd == mycpu) {
412 if (info->i_running == 0) {
414 if (info->i_state != ISTATE_LIVELOCKED)
415 lwkt_schedule(&info->i_thread); /* MIGHT PREEMPT */
418 lwkt_send_ipiq(info->i_thread.td_gd,
419 sched_ithd_remote, (void *)intr);
422 if (info->i_running == 0) {
424 if (info->i_state != ISTATE_LIVELOCKED)
425 lwkt_schedule(&info->i_thread); /* MIGHT PREEMPT */
430 printf("sched_ithd: stray interrupt %d\n", intr);
435 * This is run from a periodic SYSTIMER (and thus must be MP safe, the BGL
436 * might not be held).
439 ithread_livelock_wakeup(systimer_t st)
441 struct intr_info *info;
443 info = &intr_info_ary[(int)st->data];
444 if (info->i_state != ISTATE_NOTHREAD)
445 lwkt_schedule(&info->i_thread);
449 * This function is called drectly from the ICU or APIC vector code assembly
450 * to process an interrupt. The critical section and interrupt deferral
451 * checks have already been done but the function is entered WITHOUT
452 * a critical section held. The BGL may or may not be held.
454 * Must return non-zero if we do not want the vector code to re-enable
455 * the interrupt (which we don't if we have to schedule the interrupt)
457 int ithread_fast_handler(struct intrframe frame);
460 ithread_fast_handler(struct intrframe frame)
463 struct intr_info *info;
464 struct intrec **list;
469 intrec_t rec, next_rec;
475 info = &intr_info_ary[intr];
478 * If we are not processing any FAST interrupts, just schedule the thing.
479 * (since we aren't in a critical section, this can result in a
482 if (info->i_fast == 0) {
488 * This should not normally occur since interrupts ought to be
489 * masked if the ithread has been scheduled or is running.
495 * Bump the interrupt nesting level to process any FAST interrupts.
496 * Obtain the MP lock as necessary. If the MP lock cannot be obtained,
497 * schedule the interrupt thread to deal with the issue instead.
499 * To reduce overhead, just leave the MP lock held once it has been
503 ++gd->gd_intr_nesting_level;
505 must_schedule = info->i_slow;
510 list = &info->i_reclist;
511 for (rec = *list; rec; rec = next_rec) {
512 next_rec = rec->next; /* rec may be invalid after call */
514 if (rec->intr_flags & INTR_FAST) {
516 if ((rec->intr_flags & INTR_MPSAFE) == 0 && got_mplock == 0) {
517 if (try_mplock() == 0) {
519 * XXX forward to the cpu holding the MP lock
527 if (rec->serializer) {
528 must_schedule += lwkt_serialize_handler_try(
529 rec->serializer, rec->handler,
530 rec->argument, &frame);
532 rec->handler(rec->argument, &frame);
540 --gd->gd_intr_nesting_level;
548 * If we had a problem, schedule the thread to catch the missed
549 * records (it will just re-run all of them). A return value of 0
550 * indicates that all handlers have been run and the interrupt can
551 * be re-enabled, and a non-zero return indicates that the interrupt
552 * thread controls re-enablement.
558 return(must_schedule);
564 /* could not get the MP lock, forward the interrupt */ \
565 movl mp_lock, %eax ; /* check race */ \
566 cmpl $MP_FREE_LOCK,%eax ; \
568 incl PCPU(cnt)+V_FORWARDED_INTS ; \
570 movl $irq_num,8(%esp) ; \
571 movl $forward_fastint_remote,4(%esp) ; \
573 call lwkt_send_ipiq_bycpu ; \
581 * Interrupt threads run this as their main loop.
583 * The handler begins execution outside a critical section and with the BGL
586 * The i_running state starts at 0. When an interrupt occurs, the hardware
587 * interrupt is disabled and sched_ithd() The HW interrupt remains disabled
588 * until all routines have run. We then call ithread_done() to reenable
589 * the HW interrupt and deschedule us until the next interrupt.
591 * We are responsible for atomically checking i_running and ithread_done()
592 * is responsible for atomically checking for platform-specific delayed
593 * interrupts. i_running for our irq is only set in the context of our cpu,
594 * so a critical section is a sufficient interlock.
596 #define LIVELOCK_TIMEFRAME(freq) ((freq) >> 2) /* 1/4 second */
599 ithread_handler(void *arg)
601 struct intr_info *info;
606 struct intrec **list;
609 struct systimer ill_timer; /* enforced freq. timer */
610 u_int ill_count; /* interrupt livelock counter */
616 info = &intr_info_ary[intr];
617 list = &info->i_reclist;
621 * The loop must be entered with one critical section held.
627 * If an interrupt is pending, clear i_running and execute the
628 * handlers. Note that certain types of interrupts can re-trigger
629 * and set i_running again.
631 * Each handler is run in a critical section. Note that we run both
632 * FAST and SLOW designated service routines.
634 if (info->i_running) {
637 for (rec = *list; rec; rec = nrec) {
639 if (rec->serializer) {
640 lwkt_serialize_handler_call(rec->serializer, rec->handler,
641 rec->argument, NULL);
643 rec->handler(rec->argument, NULL);
649 * This is our interrupt hook to add rate randomness to the random
652 if (info->i_random.sc_enabled)
653 add_interrupt_randomness(intr);
656 * Unmask the interrupt to allow it to trigger again. This only
657 * applies to certain types of interrupts (typ level interrupts).
658 * This can result in the interrupt retriggering, but the retrigger
659 * will not be processed until we cycle our critical section.
661 * Only unmask interrupts while handlers are installed. It is
662 * possible to hit a situation where no handlers are installed
663 * due to a device driver livelocking and then tearing down its
664 * interrupt on close (the parallel bus being a good example).
667 ithread_unmask(intr);
670 * Do a quick exit/enter to catch any higher-priority interrupt
671 * sources, such as the statclock, so thread time accounting
672 * will still work. This may also cause an interrupt to re-trigger.
678 * LIVELOCK STATE MACHINE
680 switch(info->i_state) {
683 * Calculate a running average every tick.
685 if (lticks != ticks) {
687 ill_count -= ill_count / hz;
691 * If we did not exceed the frequency limit, we are done.
692 * If the interrupt has not retriggered we deschedule ourselves.
694 if (ill_count <= livelock_limit) {
695 if (info->i_running == 0) {
696 lwkt_deschedule_self(gd->gd_curthread);
703 * Otherwise we are livelocked. Set up a periodic systimer
704 * to wake the thread up at the limit frequency.
706 printf("intr %d at %d > %d hz, livelocked limit engaged!\n",
707 intr, livelock_limit, ill_count);
708 info->i_state = ISTATE_LIVELOCKED;
709 if ((use_limit = livelock_limit) < 100)
711 else if (use_limit > 500000)
713 systimer_init_periodic(&ill_timer, ithread_livelock_wakeup,
714 (void *)intr, use_limit);
717 case ISTATE_LIVELOCKED:
719 * Wait for our periodic timer to go off. Since the interrupt
720 * has re-armed it can still set i_running, but it will not
721 * reschedule us while we are in a livelocked state.
723 lwkt_deschedule_self(gd->gd_curthread);
727 * Check to see if the livelock condition no longer applies.
728 * The interrupt must be able to operate normally for one
729 * full second before we restore normal operation.
731 if (lticks != ticks) {
733 if (ill_count < livelock_lowater) {
734 if (++lcount >= hz) {
735 info->i_state = ISTATE_NORMAL;
736 systimer_del(&ill_timer);
737 printf("intr %d at %d < %d hz, livelock removed\n",
738 intr, ill_count, livelock_lowater);
743 ill_count -= ill_count / hz;
752 * Emergency interrupt polling thread. The thread begins execution
753 * outside a critical section with the BGL held.
755 * If emergency interrupt polling is enabled, this thread will
756 * execute all system interrupts not marked INTR_NOPOLL at the
757 * specified polling frequency.
759 * WARNING! This thread runs *ALL* interrupt service routines that
760 * are not marked INTR_NOPOLL, which basically means everything except
761 * the 8254 clock interrupt and the ATA interrupt. It has very high
762 * overhead and should only be used in situations where the machine
763 * cannot otherwise be made to work. Due to the severe performance
764 * degredation, it should not be enabled on production machines.
767 ithread_emergency(void *arg __unused)
769 struct intr_info *info;
774 for (intr = 0; intr < NHWI + NSWI; ++intr) {
775 info = &intr_info_ary[intr];
776 for (rec = info->i_reclist; rec; rec = nrec) {
777 if ((rec->intr_flags & INTR_NOPOLL) == 0) {
778 if (rec->serializer) {
779 lwkt_serialize_handler_call(rec->serializer,
780 rec->handler, rec->argument, NULL);
782 rec->handler(rec->argument, NULL);
788 lwkt_deschedule_self(curthread);
794 * Systimer callback - schedule the emergency interrupt poll thread
795 * if emergency polling is enabled.
799 emergency_intr_timer_callback(systimer_t info, struct intrframe *frame __unused)
801 if (emergency_intr_enable)
802 lwkt_schedule(info->data);
806 * Sysctls used by systat and others: hw.intrnames and hw.intrcnt.
807 * The data for this machine dependent, and the declarations are in machine
808 * dependent code. The layout of intrnames and intrcnt however is machine
811 * We do not know the length of intrcnt and intrnames at compile time, so
812 * calculate things at run time.
816 sysctl_intrnames(SYSCTL_HANDLER_ARGS)
818 struct intr_info *info;
825 for (intr = 0; error == 0 && intr < NHWI + NSWI; ++intr) {
826 info = &intr_info_ary[intr];
830 for (rec = info->i_reclist; rec; rec = rec->next) {
831 snprintf(buf + len, sizeof(buf) - len, "%s%s",
832 (len ? "/" : ""), rec->name);
833 len += strlen(buf + len);
836 snprintf(buf, sizeof(buf), "irq%d", intr);
839 error = SYSCTL_OUT(req, buf, len + 1);
845 SYSCTL_PROC(_hw, OID_AUTO, intrnames, CTLTYPE_OPAQUE | CTLFLAG_RD,
846 NULL, 0, sysctl_intrnames, "", "Interrupt Names");
849 sysctl_intrcnt(SYSCTL_HANDLER_ARGS)
851 struct intr_info *info;
855 for (intr = 0; intr < NHWI + NSWI; ++intr) {
856 info = &intr_info_ary[intr];
858 error = SYSCTL_OUT(req, &info->i_count, sizeof(info->i_count));
865 SYSCTL_PROC(_hw, OID_AUTO, intrcnt, CTLTYPE_OPAQUE | CTLFLAG_RD,
866 NULL, 0, sysctl_intrcnt, "", "Interrupt Counts");