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.34 2005/11/21 18:02:44 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>
42 #include <sys/machintr.h>
44 #include <machine/ipl.h>
45 #include <machine/frame.h>
47 #include <sys/interrupt.h>
51 typedef struct intrec {
53 struct intr_info *info;
59 struct lwkt_serialize *serializer;
64 struct thread i_thread;
65 struct random_softc i_random;
71 } intr_info_ary[MAX_INTS];
73 int max_installed_hard_intr;
74 int max_installed_soft_intr;
76 #define EMERGENCY_INTR_POLLING_FREQ_MAX 20000
78 static int sysctl_emergency_freq(SYSCTL_HANDLER_ARGS);
79 static int sysctl_emergency_enable(SYSCTL_HANDLER_ARGS);
80 static void emergency_intr_timer_callback(systimer_t, struct intrframe *);
81 static void ithread_handler(void *arg);
82 static void ithread_emergency(void *arg);
84 int intr_info_size = sizeof(intr_info_ary) / sizeof(intr_info_ary[0]);
86 static struct systimer emergency_intr_timer;
87 static struct thread emergency_intr_thread;
89 #define ISTATE_NOTHREAD 0
90 #define ISTATE_NORMAL 1
91 #define ISTATE_LIVELOCKED 2
93 static int livelock_limit = 50000;
94 static int livelock_lowater = 20000;
95 SYSCTL_INT(_kern, OID_AUTO, livelock_limit,
96 CTLFLAG_RW, &livelock_limit, 0, "Livelock interrupt rate limit");
97 SYSCTL_INT(_kern, OID_AUTO, livelock_lowater,
98 CTLFLAG_RW, &livelock_lowater, 0, "Livelock low-water mark restore");
100 static int emergency_intr_enable = 0; /* emergency interrupt polling */
101 TUNABLE_INT("kern.emergency_intr_enable", &emergency_intr_enable);
102 SYSCTL_PROC(_kern, OID_AUTO, emergency_intr_enable, CTLTYPE_INT | CTLFLAG_RW,
103 0, 0, sysctl_emergency_enable, "I", "Emergency Interrupt Poll Enable");
105 static int emergency_intr_freq = 10; /* emergency polling frequency */
106 TUNABLE_INT("kern.emergency_intr_freq", &emergency_intr_freq);
107 SYSCTL_PROC(_kern, OID_AUTO, emergency_intr_freq, CTLTYPE_INT | CTLFLAG_RW,
108 0, 0, sysctl_emergency_freq, "I", "Emergency Interrupt Poll Frequency");
111 * Sysctl support routines
114 sysctl_emergency_enable(SYSCTL_HANDLER_ARGS)
118 enabled = emergency_intr_enable;
119 error = sysctl_handle_int(oidp, &enabled, 0, req);
120 if (error || req->newptr == NULL)
122 emergency_intr_enable = enabled;
123 if (emergency_intr_enable) {
124 emergency_intr_timer.periodic =
125 sys_cputimer->fromhz(emergency_intr_freq);
127 emergency_intr_timer.periodic = sys_cputimer->fromhz(1);
133 sysctl_emergency_freq(SYSCTL_HANDLER_ARGS)
137 phz = emergency_intr_freq;
138 error = sysctl_handle_int(oidp, &phz, 0, req);
139 if (error || req->newptr == NULL)
143 else if (phz > EMERGENCY_INTR_POLLING_FREQ_MAX)
144 phz = EMERGENCY_INTR_POLLING_FREQ_MAX;
146 emergency_intr_freq = phz;
147 if (emergency_intr_enable) {
148 emergency_intr_timer.periodic =
149 sys_cputimer->fromhz(emergency_intr_freq);
151 emergency_intr_timer.periodic = sys_cputimer->fromhz(1);
157 * Register an SWI or INTerrupt handler.
160 register_swi(int intr, inthand2_t *handler, void *arg, const char *name,
161 struct lwkt_serialize *serializer)
163 if (intr < FIRST_SOFTINT || intr >= MAX_INTS)
164 panic("register_swi: bad intr %d", intr);
165 return(register_int(intr, handler, arg, name, serializer, 0));
169 register_int(int intr, inthand2_t *handler, void *arg, const char *name,
170 struct lwkt_serialize *serializer, int intr_flags)
172 struct intr_info *info;
173 struct intrec **list;
176 if (intr < 0 || intr >= MAX_INTS)
177 panic("register_int: bad intr %d", intr);
180 info = &intr_info_ary[intr];
183 * Construct an interrupt handler record
185 rec = malloc(sizeof(struct intrec), M_DEVBUF, M_INTWAIT);
186 rec->name = malloc(strlen(name) + 1, M_DEVBUF, M_INTWAIT);
187 strcpy(rec->name, name);
190 rec->handler = handler;
193 rec->intr_flags = intr_flags;
195 rec->serializer = serializer;
198 * Create an emergency polling thread and set up a systimer to wake
201 if (emergency_intr_thread.td_kstack == NULL) {
202 lwkt_create(ithread_emergency, NULL, NULL,
203 &emergency_intr_thread, TDF_STOPREQ|TDF_INTTHREAD, -1,
205 systimer_init_periodic_nq(&emergency_intr_timer,
206 emergency_intr_timer_callback, &emergency_intr_thread,
207 (emergency_intr_enable ? emergency_intr_freq : 1));
211 * Create an interrupt thread if necessary, leave it in an unscheduled
214 if (info->i_state == ISTATE_NOTHREAD) {
215 info->i_state = ISTATE_NORMAL;
216 lwkt_create((void *)ithread_handler, (void *)intr, NULL,
217 &info->i_thread, TDF_STOPREQ|TDF_INTTHREAD, -1,
219 if (intr >= FIRST_SOFTINT)
220 lwkt_setpri(&info->i_thread, TDPRI_SOFT_NORM);
222 lwkt_setpri(&info->i_thread, TDPRI_INT_MED);
223 info->i_thread.td_preemptable = lwkt_preempt;
226 list = &info->i_reclist;
229 * Keep track of how many fast and slow interrupts we have.
231 if (intr_flags & INTR_FAST)
237 * Add the record to the interrupt list.
240 while (*list != NULL)
241 list = &(*list)->next;
246 * Update max_installed_hard_intr to make the emergency intr poll
247 * a bit more efficient.
249 if (intr < FIRST_SOFTINT) {
250 if (max_installed_hard_intr <= intr)
251 max_installed_hard_intr = intr + 1;
253 if (max_installed_soft_intr <= intr)
254 max_installed_soft_intr = intr + 1;
258 * Setup the machine level interrupt vector
260 if (info->i_slow + info->i_fast == 1) {
261 if (machintr_vector_setup(intr, intr_flags))
262 printf("machintr_vector_setup: failed on irq %d\n", intr);
269 unregister_swi(void *id)
275 unregister_int(void *id)
277 struct intr_info *info;
278 struct intrec **list;
282 intr = ((intrec_t)id)->intr;
284 if (intr < 0 || intr >= MAX_INTS)
285 panic("register_int: bad intr %d", intr);
287 info = &intr_info_ary[intr];
290 * Remove the interrupt descriptor, adjust the descriptor count,
291 * and teardown the machine level vector if this was the last interrupt.
294 list = &info->i_reclist;
295 while ((rec = *list) != NULL) {
302 if (rec->intr_flags & INTR_FAST)
306 if (info->i_fast + info->i_slow == 0)
307 machintr_vector_teardown(intr);
315 free(rec->name, M_DEVBUF);
318 printf("warning: unregister_int: int %d handler for %s not found\n",
319 intr, ((intrec_t)id)->name);
324 get_registered_name(int intr)
328 if (intr < 0 || intr >= MAX_INTS)
329 panic("register_int: bad intr %d", intr);
331 if ((rec = intr_info_ary[intr].i_reclist) == NULL)
340 count_registered_ints(int intr)
342 struct intr_info *info;
344 if (intr < 0 || intr >= MAX_INTS)
345 panic("register_int: bad intr %d", intr);
346 info = &intr_info_ary[intr];
347 return(info->i_fast + info->i_slow);
351 get_interrupt_counter(int intr)
353 struct intr_info *info;
355 if (intr < 0 || intr >= MAX_INTS)
356 panic("register_int: bad intr %d", intr);
357 info = &intr_info_ary[intr];
358 return(info->i_count);
363 swi_setpriority(int intr, int pri)
365 struct intr_info *info;
367 if (intr < FIRST_SOFTINT || intr >= MAX_INTS)
368 panic("register_swi: bad intr %d", intr);
369 info = &intr_info_ary[intr];
370 if (info->i_state != ISTATE_NOTHREAD)
371 lwkt_setpri(&info->i_thread, pri);
375 register_randintr(int intr)
377 struct intr_info *info;
379 if (intr < 0 || intr >= MAX_INTS)
380 panic("register_randintr: bad intr %d", intr);
381 info = &intr_info_ary[intr];
382 info->i_random.sc_intr = intr;
383 info->i_random.sc_enabled = 1;
387 unregister_randintr(int intr)
389 struct intr_info *info;
391 if (intr < 0 || intr >= MAX_INTS)
392 panic("register_swi: bad intr %d", intr);
393 info = &intr_info_ary[intr];
394 info->i_random.sc_enabled = 0;
398 next_registered_randintr(int intr)
400 struct intr_info *info;
402 if (intr < 0 || intr >= MAX_INTS)
403 panic("register_swi: bad intr %d", intr);
404 while (intr < MAX_INTS) {
405 info = &intr_info_ary[intr];
406 if (info->i_random.sc_enabled)
414 * Dispatch an interrupt. If there's nothing to do we have a stray
415 * interrupt and can just return, leaving the interrupt masked.
417 * We need to schedule the interrupt and set its i_running bit. If
418 * we are not on the interrupt thread's cpu we have to send a message
419 * to the correct cpu that will issue the desired action (interlocking
420 * with the interrupt thread's critical section). We do NOT attempt to
421 * reschedule interrupts whos i_running bit is already set because
422 * this would prematurely wakeup a livelock-limited interrupt thread.
424 * i_running is only tested/set on the same cpu as the interrupt thread.
426 * We are NOT in a critical section, which will allow the scheduled
427 * interrupt to preempt us. The MP lock might *NOT* be held here.
432 sched_ithd_remote(void *arg)
434 sched_ithd((int)arg);
442 struct intr_info *info;
444 info = &intr_info_ary[intr];
447 if (info->i_state != ISTATE_NOTHREAD) {
448 if (info->i_reclist == NULL) {
449 printf("sched_ithd: stray interrupt %d\n", intr);
452 if (info->i_thread.td_gd == mycpu) {
453 if (info->i_running == 0) {
455 if (info->i_state != ISTATE_LIVELOCKED)
456 lwkt_schedule(&info->i_thread); /* MIGHT PREEMPT */
459 lwkt_send_ipiq(info->i_thread.td_gd,
460 sched_ithd_remote, (void *)intr);
463 if (info->i_running == 0) {
465 if (info->i_state != ISTATE_LIVELOCKED)
466 lwkt_schedule(&info->i_thread); /* MIGHT PREEMPT */
471 printf("sched_ithd: stray interrupt %d\n", intr);
476 * This is run from a periodic SYSTIMER (and thus must be MP safe, the BGL
477 * might not be held).
480 ithread_livelock_wakeup(systimer_t st)
482 struct intr_info *info;
484 info = &intr_info_ary[(int)st->data];
485 if (info->i_state != ISTATE_NOTHREAD)
486 lwkt_schedule(&info->i_thread);
490 * This function is called drectly from the ICU or APIC vector code assembly
491 * to process an interrupt. The critical section and interrupt deferral
492 * checks have already been done but the function is entered WITHOUT
493 * a critical section held. The BGL may or may not be held.
495 * Must return non-zero if we do not want the vector code to re-enable
496 * the interrupt (which we don't if we have to schedule the interrupt)
498 int ithread_fast_handler(struct intrframe frame);
501 ithread_fast_handler(struct intrframe frame)
504 struct intr_info *info;
505 struct intrec **list;
510 intrec_t rec, next_rec;
516 info = &intr_info_ary[intr];
519 * If we are not processing any FAST interrupts, just schedule the thing.
520 * (since we aren't in a critical section, this can result in a
523 if (info->i_fast == 0) {
529 * This should not normally occur since interrupts ought to be
530 * masked if the ithread has been scheduled or is running.
536 * Bump the interrupt nesting level to process any FAST interrupts.
537 * Obtain the MP lock as necessary. If the MP lock cannot be obtained,
538 * schedule the interrupt thread to deal with the issue instead.
540 * To reduce overhead, just leave the MP lock held once it has been
544 ++gd->gd_intr_nesting_level;
546 must_schedule = info->i_slow;
551 list = &info->i_reclist;
552 for (rec = *list; rec; rec = next_rec) {
553 next_rec = rec->next; /* rec may be invalid after call */
555 if (rec->intr_flags & INTR_FAST) {
557 if ((rec->intr_flags & INTR_MPSAFE) == 0 && got_mplock == 0) {
558 if (try_mplock() == 0) {
562 * If we couldn't get the MP lock try to forward it
563 * to the cpu holding the MP lock, setting must_schedule
564 * to -1 so we do not schedule and also do not unmask
565 * the interrupt. Otherwise just schedule it.
567 owner = owner_mplock();
568 if (owner >= 0 && owner != gd->gd_cpuid) {
569 lwkt_send_ipiq_bycpu(owner, forward_fastint_remote,
572 ++gd->gd_cnt.v_forwarded_ints;
581 if (rec->serializer) {
582 must_schedule += lwkt_serialize_handler_try(
583 rec->serializer, rec->handler,
584 rec->argument, &frame);
586 rec->handler(rec->argument, &frame);
594 --gd->gd_intr_nesting_level;
602 * If we had a problem, schedule the thread to catch the missed
603 * records (it will just re-run all of them). A return value of 0
604 * indicates that all handlers have been run and the interrupt can
605 * be re-enabled, and a non-zero return indicates that the interrupt
606 * thread controls re-enablement.
608 if (must_schedule > 0)
610 else if (must_schedule == 0)
612 return(must_schedule);
618 /* could not get the MP lock, forward the interrupt */ \
619 movl mp_lock, %eax ; /* check race */ \
620 cmpl $MP_FREE_LOCK,%eax ; \
622 incl PCPU(cnt)+V_FORWARDED_INTS ; \
624 movl $irq_num,8(%esp) ; \
625 movl $forward_fastint_remote,4(%esp) ; \
627 call lwkt_send_ipiq_bycpu ; \
635 * Interrupt threads run this as their main loop.
637 * The handler begins execution outside a critical section and with the BGL
640 * The i_running state starts at 0. When an interrupt occurs, the hardware
641 * interrupt is disabled and sched_ithd() The HW interrupt remains disabled
642 * until all routines have run. We then call ithread_done() to reenable
643 * the HW interrupt and deschedule us until the next interrupt.
645 * We are responsible for atomically checking i_running and ithread_done()
646 * is responsible for atomically checking for platform-specific delayed
647 * interrupts. i_running for our irq is only set in the context of our cpu,
648 * so a critical section is a sufficient interlock.
650 #define LIVELOCK_TIMEFRAME(freq) ((freq) >> 2) /* 1/4 second */
653 ithread_handler(void *arg)
655 struct intr_info *info;
661 struct intrec **list;
664 struct systimer ill_timer; /* enforced freq. timer */
665 u_int ill_count; /* interrupt livelock counter */
671 info = &intr_info_ary[intr];
672 list = &info->i_reclist;
676 * The loop must be entered with one critical section held. We start
677 * out with the MP lock released.
684 * If an interrupt is pending, clear i_running and execute the
685 * handlers. Note that certain types of interrupts can re-trigger
686 * and set i_running again.
688 * Each handler is run in a critical section. Note that we run both
689 * FAST and SLOW designated service routines. The chain is only
690 * considered MPSAFE if all interrupt handlers are MPSAFE.
692 if (info->i_running) {
696 for (rec = *list; rec; rec = nrec) {
698 if (rec->serializer) {
699 lwkt_serialize_handler_call(rec->serializer, rec->handler,
700 rec->argument, NULL);
702 rec->handler(rec->argument, NULL);
708 * This is our interrupt hook to add rate randomness to the random
711 if (info->i_random.sc_enabled)
712 add_interrupt_randomness(intr);
715 * Unmask the interrupt to allow it to trigger again. This only
716 * applies to certain types of interrupts (typ level interrupts).
717 * This can result in the interrupt retriggering, but the retrigger
718 * will not be processed until we cycle our critical section.
720 * Only unmask interrupts while handlers are installed. It is
721 * possible to hit a situation where no handlers are installed
722 * due to a device driver livelocking and then tearing down its
723 * interrupt on close (the parallel bus being a good example).
726 machintr_intren(intr);
729 * Do a quick exit/enter to catch any higher-priority interrupt
730 * sources, such as the statclock, so thread time accounting
731 * will still work. This may also cause an interrupt to re-trigger.
737 * LIVELOCK STATE MACHINE
739 switch(info->i_state) {
742 * Calculate a running average every tick.
744 if (lticks != ticks) {
746 ill_count -= ill_count / hz;
750 * If we did not exceed the frequency limit, we are done.
751 * If the interrupt has not retriggered we deschedule ourselves.
753 if (ill_count <= livelock_limit) {
754 if (info->i_running == 0) {
755 lwkt_deschedule_self(gd->gd_curthread);
762 * Otherwise we are livelocked. Set up a periodic systimer
763 * to wake the thread up at the limit frequency.
765 printf("intr %d at %d > %d hz, livelocked limit engaged!\n",
766 intr, livelock_limit, ill_count);
767 info->i_state = ISTATE_LIVELOCKED;
768 if ((use_limit = livelock_limit) < 100)
770 else if (use_limit > 500000)
772 systimer_init_periodic(&ill_timer, ithread_livelock_wakeup,
773 (void *)intr, use_limit);
776 case ISTATE_LIVELOCKED:
778 * Wait for our periodic timer to go off. Since the interrupt
779 * has re-armed it can still set i_running, but it will not
780 * reschedule us while we are in a livelocked state.
782 lwkt_deschedule_self(gd->gd_curthread);
786 * Check to see if the livelock condition no longer applies.
787 * The interrupt must be able to operate normally for one
788 * full second before we restore normal operation.
790 if (lticks != ticks) {
792 if (ill_count < livelock_lowater) {
793 if (++lcount >= hz) {
794 info->i_state = ISTATE_NORMAL;
795 systimer_del(&ill_timer);
796 printf("intr %d at %d < %d hz, livelock removed\n",
797 intr, ill_count, livelock_lowater);
802 ill_count -= ill_count / hz;
811 * Emergency interrupt polling thread. The thread begins execution
812 * outside a critical section with the BGL held.
814 * If emergency interrupt polling is enabled, this thread will
815 * execute all system interrupts not marked INTR_NOPOLL at the
816 * specified polling frequency.
818 * WARNING! This thread runs *ALL* interrupt service routines that
819 * are not marked INTR_NOPOLL, which basically means everything except
820 * the 8254 clock interrupt and the ATA interrupt. It has very high
821 * overhead and should only be used in situations where the machine
822 * cannot otherwise be made to work. Due to the severe performance
823 * degredation, it should not be enabled on production machines.
826 ithread_emergency(void *arg __unused)
828 struct intr_info *info;
833 for (intr = 0; intr < max_installed_hard_intr; ++intr) {
834 info = &intr_info_ary[intr];
835 for (rec = info->i_reclist; rec; rec = nrec) {
836 if ((rec->intr_flags & INTR_NOPOLL) == 0) {
837 if (rec->serializer) {
838 lwkt_serialize_handler_call(rec->serializer,
839 rec->handler, rec->argument, NULL);
841 rec->handler(rec->argument, NULL);
847 lwkt_deschedule_self(curthread);
853 * Systimer callback - schedule the emergency interrupt poll thread
854 * if emergency polling is enabled.
858 emergency_intr_timer_callback(systimer_t info, struct intrframe *frame __unused)
860 if (emergency_intr_enable)
861 lwkt_schedule(info->data);
865 * Sysctls used by systat and others: hw.intrnames and hw.intrcnt.
866 * The data for this machine dependent, and the declarations are in machine
867 * dependent code. The layout of intrnames and intrcnt however is machine
870 * We do not know the length of intrcnt and intrnames at compile time, so
871 * calculate things at run time.
875 sysctl_intrnames(SYSCTL_HANDLER_ARGS)
877 struct intr_info *info;
884 for (intr = 0; error == 0 && intr < MAX_INTS; ++intr) {
885 info = &intr_info_ary[intr];
889 for (rec = info->i_reclist; rec; rec = rec->next) {
890 snprintf(buf + len, sizeof(buf) - len, "%s%s",
891 (len ? "/" : ""), rec->name);
892 len += strlen(buf + len);
895 snprintf(buf, sizeof(buf), "irq%d", intr);
898 error = SYSCTL_OUT(req, buf, len + 1);
904 SYSCTL_PROC(_hw, OID_AUTO, intrnames, CTLTYPE_OPAQUE | CTLFLAG_RD,
905 NULL, 0, sysctl_intrnames, "", "Interrupt Names");
908 sysctl_intrcnt(SYSCTL_HANDLER_ARGS)
910 struct intr_info *info;
914 for (intr = 0; intr < max_installed_hard_intr; ++intr) {
915 info = &intr_info_ary[intr];
917 error = SYSCTL_OUT(req, &info->i_count, sizeof(info->i_count));
921 for (intr = FIRST_SOFTINT; intr < max_installed_soft_intr; ++intr) {
922 info = &intr_info_ary[intr];
924 error = SYSCTL_OUT(req, &info->i_count, sizeof(info->i_count));
932 SYSCTL_PROC(_hw, OID_AUTO, intrcnt, CTLTYPE_OPAQUE | CTLFLAG_RD,
933 NULL, 0, sysctl_intrcnt, "", "Interrupt Counts");