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.27 2005/10/25 17:26:54 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.
386 sched_ithd_remote(void *arg)
388 sched_ithd((int)arg);
396 struct intr_info *info;
398 info = &intr_info_ary[intr];
401 if (info->i_valid_thread) {
402 if (info->i_reclist == NULL) {
403 printf("sched_ithd: stray interrupt %d\n", intr);
406 if (info->i_thread.td_gd == mycpu) {
408 /* preemption handled internally */
409 lwkt_schedule(&info->i_thread);
411 lwkt_send_ipiq(info->i_thread.td_gd,
412 sched_ithd_remote, (void *)intr);
416 /* preemption handled internally */
417 lwkt_schedule(&info->i_thread);
421 printf("sched_ithd: stray interrupt %d\n", intr);
426 * This is run from a periodic SYSTIMER (and thus must be MP safe, the BGL
427 * might not be held).
430 ithread_livelock_wakeup(systimer_t st)
432 struct intr_info *info;
434 info = &intr_info_ary[(int)st->data];
435 if (info->i_valid_thread)
436 lwkt_schedule(&info->i_thread);
440 * This function is called drectly from the ICU or APIC vector code assembly
441 * to process an interrupt. The critical section and interrupt deferral
442 * checks have already been done but the function is entered WITHOUT
443 * a critical section held. The BGL may or may not be held.
445 * Must return non-zero if we do not want the vector code to re-enable
446 * the interrupt (which we don't if we have to schedule the interrupt)
448 int ithread_fast_handler(struct intrframe frame);
451 ithread_fast_handler(struct intrframe frame)
454 struct intr_info *info;
455 struct intrec **list;
460 intrec_t rec, next_rec;
466 info = &intr_info_ary[intr];
469 * If we are not processing any FAST interrupts, just schedule the thing.
470 * (since we aren't in a critical section, this can result in a
473 if (info->i_fast == 0) {
479 * This should not normally occur since interrupts ought to be
480 * masked if the ithread has been scheduled or is running.
486 * Bump the interrupt nesting level to process any FAST interrupts.
487 * Obtain the MP lock as necessary. If the MP lock cannot be obtained,
488 * schedule the interrupt thread to deal with the issue instead.
490 * To reduce overhead, just leave the MP lock held once it has been
494 ++gd->gd_intr_nesting_level;
496 must_schedule = info->i_slow;
501 list = &info->i_reclist;
502 for (rec = *list; rec; rec = next_rec) {
503 next_rec = rec->next; /* rec may be invalid after call */
505 if (rec->intr_flags & INTR_FAST) {
507 if ((rec->intr_flags & INTR_MPSAFE) == 0 && got_mplock == 0) {
508 if (try_mplock() == 0) {
510 * XXX forward to the cpu holding the MP lock
518 if (rec->serializer) {
519 must_schedule += lwkt_serialize_handler_try(
520 rec->serializer, rec->handler,
521 rec->argument, &frame);
523 rec->handler(rec->argument, &frame);
531 --gd->gd_intr_nesting_level;
539 * If we had a problem, schedule the thread to catch the missed
540 * records (it will just re-run all of them). A return value of 0
541 * indicates that all handlers have been run and the interrupt can
542 * be re-enabled, and a non-zero return indicates that the interrupt
543 * thread controls re-enablement.
549 return(must_schedule);
555 /* could not get the MP lock, forward the interrupt */ \
556 movl mp_lock, %eax ; /* check race */ \
557 cmpl $MP_FREE_LOCK,%eax ; \
559 incl PCPU(cnt)+V_FORWARDED_INTS ; \
561 movl $irq_num,8(%esp) ; \
562 movl $forward_fastint_remote,4(%esp) ; \
564 call lwkt_send_ipiq_bycpu ; \
572 * Interrupt threads run this as their main loop.
574 * The handler begins execution outside a critical section and with the BGL
577 * The i_running state starts at 0. When an interrupt occurs, the hardware
578 * interrupt is disabled and sched_ithd() The HW interrupt remains disabled
579 * until all routines have run. We then call ithread_done() to reenable
580 * the HW interrupt and deschedule us until the next interrupt.
582 * We are responsible for atomically checking i_running and ithread_done()
583 * is responsible for atomically checking for platform-specific delayed
584 * interrupts. i_running for our irq is only set in the context of our cpu,
585 * so a critical section is a sufficient interlock.
587 #define LIVELOCK_TIMEFRAME(freq) ((freq) >> 2) /* 1/4 second */
590 ithread_handler(void *arg)
592 struct intr_info *info;
597 struct intrec **list;
599 globaldata_t gd = mycpu;
600 struct systimer ill_timer; /* enforced freq. timer */
601 struct systimer ill_rtimer; /* recovery timer */
602 u_int ill_count = 0; /* interrupt livelock counter */
603 u_int ill_ticks = 0; /* track elapsed to calculate freq */
604 u_int ill_delta = 0; /* track elapsed to calculate freq */
605 int ill_state = 0; /* current state */
608 info = &intr_info_ary[intr];
609 list = &info->i_reclist;
613 * The loop must be entered with one critical section held.
619 * We can get woken up by the livelock periodic code too, run the
620 * handlers only if there is a real interrupt pending. XXX
622 * Clear i_running prior to running the handlers to interlock
623 * again new events occuring during processing of existing events.
625 * Run each handler in a critical section. Note that we run both
626 * FAST and SLOW designated service routines.
629 for (rec = *list; rec; rec = nrec) {
631 if (rec->serializer) {
632 lwkt_serialize_handler_call(rec->serializer,
633 rec->handler, rec->argument, NULL);
635 rec->handler(rec->argument, NULL);
640 * Do a quick exit/enter to catch any higher-priority
641 * interrupt sources and so user/system/interrupt statistics
642 * work for interrupt threads.
648 * This is our interrupt hook to add rate randomness to the random
651 if (info->i_random.sc_enabled)
652 add_interrupt_randomness(intr);
655 * This is our livelock test. If we hit the rate limit we
656 * limit ourselves to X interrupts/sec until the rate
657 * falls below 50% of that value, then we unlimit again.
659 * XXX calling cputimer_count() is expensive but a livelock may
660 * prevent other interrupts from occuring so we cannot use ticks.
662 cputicks = sys_cputimer->count();
664 bticks = cputicks - ill_ticks;
665 ill_ticks = cputicks;
666 if (bticks > sys_cputimer->freq)
667 bticks = sys_cputimer->freq;
672 if (ill_delta < LIVELOCK_TIMEFRAME(sys_cputimer->freq))
674 freq = (int64_t)ill_count * sys_cputimer->freq /
678 if (freq < livelock_limit)
680 printf("intr %d at %d hz, livelocked! limiting at %d hz\n",
681 intr, freq, livelock_fallback);
682 ill_state = LIVELOCK_LIMITED;
684 /* force periodic check to avoid stale removal (if ints stop) */
685 systimer_init_periodic(&ill_rtimer, ithread_livelock_wakeup,
688 case LIVELOCK_LIMITED:
690 * Delay (us) before rearming the interrupt
692 systimer_init_oneshot(&ill_timer, ithread_livelock_wakeup,
693 (void *)intr, 1 + 1000000 / livelock_fallback);
694 lwkt_deschedule_self(curthread);
697 /* in case we were woken up by something else */
698 systimer_del(&ill_timer);
701 * Calculate interrupt rate (note that due to our delay it
702 * will not exceed livelock_fallback).
705 if (ill_delta < LIVELOCK_TIMEFRAME(sys_cputimer->freq))
707 freq = (int64_t)ill_count * sys_cputimer->freq / ill_delta;
710 if (freq < (livelock_fallback >> 1)) {
711 printf("intr %d at %d hz, removing livelock limit\n",
713 ill_state = LIVELOCK_NONE;
714 systimer_del(&ill_rtimer);
720 * There are two races here. i_running is set by sched_ithd()
721 * in the context of our cpu and is critical-section safe. We
722 * are responsible for checking it. ipending is not critical
723 * section safe and must be handled by the platform specific
724 * ithread_done() routine.
726 if (info->i_running == 0)
728 /* must be in critical section on loop */
734 * Emergency interrupt polling thread. The thread begins execution
735 * outside a critical section with the BGL held.
737 * If emergency interrupt polling is enabled, this thread will
738 * execute all system interrupts not marked INTR_NOPOLL at the
739 * specified polling frequency.
741 * WARNING! This thread runs *ALL* interrupt service routines that
742 * are not marked INTR_NOPOLL, which basically means everything except
743 * the 8254 clock interrupt and the ATA interrupt. It has very high
744 * overhead and should only be used in situations where the machine
745 * cannot otherwise be made to work. Due to the severe performance
746 * degredation, it should not be enabled on production machines.
749 ithread_emergency(void *arg __unused)
751 struct intr_info *info;
756 for (intr = 0; intr < NHWI + NSWI; ++intr) {
757 info = &intr_info_ary[intr];
758 for (rec = info->i_reclist; rec; rec = nrec) {
759 if ((rec->intr_flags & INTR_NOPOLL) == 0) {
760 if (rec->serializer) {
761 lwkt_serialize_handler_call(rec->serializer,
762 rec->handler, rec->argument, NULL);
764 rec->handler(rec->argument, NULL);
770 lwkt_deschedule_self(curthread);
776 * Systimer callback - schedule the emergency interrupt poll thread
777 * if emergency polling is enabled.
781 emergency_intr_timer_callback(systimer_t info, struct intrframe *frame __unused)
783 if (emergency_intr_enable)
784 lwkt_schedule(info->data);
788 * Sysctls used by systat and others: hw.intrnames and hw.intrcnt.
789 * The data for this machine dependent, and the declarations are in machine
790 * dependent code. The layout of intrnames and intrcnt however is machine
793 * We do not know the length of intrcnt and intrnames at compile time, so
794 * calculate things at run time.
798 sysctl_intrnames(SYSCTL_HANDLER_ARGS)
800 struct intr_info *info;
807 for (intr = 0; error == 0 && intr < NHWI + NSWI; ++intr) {
808 info = &intr_info_ary[intr];
812 for (rec = info->i_reclist; rec; rec = rec->next) {
813 snprintf(buf + len, sizeof(buf) - len, "%s%s",
814 (len ? "/" : ""), rec->name);
815 len += strlen(buf + len);
818 snprintf(buf, sizeof(buf), "irq%d", intr);
821 error = SYSCTL_OUT(req, buf, len + 1);
827 SYSCTL_PROC(_hw, OID_AUTO, intrnames, CTLTYPE_OPAQUE | CTLFLAG_RD,
828 NULL, 0, sysctl_intrnames, "", "Interrupt Names");
831 sysctl_intrcnt(SYSCTL_HANDLER_ARGS)
833 struct intr_info *info;
837 for (intr = 0; intr < NHWI + NSWI; ++intr) {
838 info = &intr_info_ary[intr];
840 error = SYSCTL_OUT(req, &info->i_count, sizeof(info->i_count));
847 SYSCTL_PROC(_hw, OID_AUTO, intrcnt, CTLTYPE_OPAQUE | CTLFLAG_RD,
848 NULL, 0, sysctl_intrcnt, "", "Interrupt Counts");