Add a thread flag, TDF_MPSAFE, which is used during thread creation to
[dragonfly.git] / sys / kern / kern_intr.c
1 /*
2  * Copyright (c) 2003 Matthew Dillon <dillon@backplane.com> All rights reserved.
3  * Copyright (c) 1997, Stefan Esser <se@freebsd.org> 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 unmodified, this list of conditions, and the following
10  *    disclaimer.
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.
14  *
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.
25  *
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 $
28  *
29  */
30
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>
37 #include <sys/proc.h>
38 #include <sys/thread2.h>
39 #include <sys/random.h>
40 #include <sys/serialize.h>
41 #include <sys/bus.h>
42 #include <sys/machintr.h>
43
44 #include <machine/ipl.h>
45 #include <machine/frame.h>
46
47 #include <sys/interrupt.h>
48
49 struct info_info;
50
51 typedef struct intrec {
52     struct intrec *next;
53     struct intr_info *info;
54     inthand2_t  *handler;
55     void        *argument;
56     char        *name;
57     int         intr;
58     int         intr_flags;
59     struct lwkt_serialize *serializer;
60 } *intrec_t;
61
62 struct intr_info {
63         intrec_t        i_reclist;
64         struct thread   i_thread;
65         struct random_softc i_random;
66         int             i_running;
67         long            i_count;
68         int             i_fast;
69         int             i_slow;
70         int             i_state;
71 } intr_info_ary[MAX_INTS];
72
73 int max_installed_hard_intr;
74 int max_installed_soft_intr;
75
76 #define EMERGENCY_INTR_POLLING_FREQ_MAX 20000
77
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);
83
84 int intr_info_size = sizeof(intr_info_ary) / sizeof(intr_info_ary[0]);
85
86 static struct systimer emergency_intr_timer;
87 static struct thread emergency_intr_thread;
88
89 #define ISTATE_NOTHREAD         0
90 #define ISTATE_NORMAL           1
91 #define ISTATE_LIVELOCKED       2
92
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");
99
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");
104
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");
109
110 /*
111  * Sysctl support routines
112  */
113 static int
114 sysctl_emergency_enable(SYSCTL_HANDLER_ARGS)
115 {
116         int error, enabled;
117
118         enabled = emergency_intr_enable;
119         error = sysctl_handle_int(oidp, &enabled, 0, req);
120         if (error || req->newptr == NULL)
121                 return error;
122         emergency_intr_enable = enabled;
123         if (emergency_intr_enable) {
124                 emergency_intr_timer.periodic = 
125                         sys_cputimer->fromhz(emergency_intr_freq);
126         } else {
127                 emergency_intr_timer.periodic = sys_cputimer->fromhz(1);
128         }
129         return 0;
130 }
131
132 static int
133 sysctl_emergency_freq(SYSCTL_HANDLER_ARGS)
134 {
135         int error, phz;
136
137         phz = emergency_intr_freq;
138         error = sysctl_handle_int(oidp, &phz, 0, req);
139         if (error || req->newptr == NULL)
140                 return error;
141         if (phz <= 0)
142                 return EINVAL;
143         else if (phz > EMERGENCY_INTR_POLLING_FREQ_MAX)
144                 phz = EMERGENCY_INTR_POLLING_FREQ_MAX;
145
146         emergency_intr_freq = phz;
147         if (emergency_intr_enable) {
148                 emergency_intr_timer.periodic = 
149                         sys_cputimer->fromhz(emergency_intr_freq);
150         } else {
151                 emergency_intr_timer.periodic = sys_cputimer->fromhz(1);
152         }
153         return 0;
154 }
155
156 /*
157  * Register an SWI or INTerrupt handler.
158  */
159 void *
160 register_swi(int intr, inthand2_t *handler, void *arg, const char *name,
161                 struct lwkt_serialize *serializer)
162 {
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));
166 }
167
168 void *
169 register_int(int intr, inthand2_t *handler, void *arg, const char *name,
170                 struct lwkt_serialize *serializer, int intr_flags)
171 {
172     struct intr_info *info;
173     struct intrec **list;
174     intrec_t rec;
175
176     if (intr < 0 || intr >= MAX_INTS)
177         panic("register_int: bad intr %d", intr);
178     if (name == NULL)
179         name = "???";
180     info = &intr_info_ary[intr];
181
182     /*
183      * Construct an interrupt handler record
184      */
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);
188
189     rec->info = info;
190     rec->handler = handler;
191     rec->argument = arg;
192     rec->intr = intr;
193     rec->intr_flags = intr_flags;
194     rec->next = NULL;
195     rec->serializer = serializer;
196
197     /*
198      * Create an emergency polling thread and set up a systimer to wake
199      * it up.
200      */
201     if (emergency_intr_thread.td_kstack == NULL) {
202         lwkt_create(ithread_emergency, NULL, NULL,
203                     &emergency_intr_thread, TDF_STOPREQ|TDF_INTTHREAD, -1,
204                     "ithread emerg");
205         systimer_init_periodic_nq(&emergency_intr_timer,
206                     emergency_intr_timer_callback, &emergency_intr_thread, 
207                     (emergency_intr_enable ? emergency_intr_freq : 1));
208     }
209
210     /*
211      * Create an interrupt thread if necessary, leave it in an unscheduled
212      * state.
213      */
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, 
218             "ithread %d", intr);
219         if (intr >= FIRST_SOFTINT)
220             lwkt_setpri(&info->i_thread, TDPRI_SOFT_NORM);
221         else
222             lwkt_setpri(&info->i_thread, TDPRI_INT_MED);
223         info->i_thread.td_preemptable = lwkt_preempt;
224     }
225
226     list = &info->i_reclist;
227
228     /*
229      * Keep track of how many fast and slow interrupts we have.
230      */
231     if (intr_flags & INTR_FAST)
232         ++info->i_fast;
233     else
234         ++info->i_slow;
235
236     /*
237      * Add the record to the interrupt list.
238      */
239     crit_enter();
240     while (*list != NULL)
241         list = &(*list)->next;
242     *list = rec;
243     crit_exit();
244
245     /*
246      * Update max_installed_hard_intr to make the emergency intr poll
247      * a bit more efficient.
248      */
249     if (intr < FIRST_SOFTINT) {
250         if (max_installed_hard_intr <= intr)
251             max_installed_hard_intr = intr + 1;
252     } else {
253         if (max_installed_soft_intr <= intr)
254             max_installed_soft_intr = intr + 1;
255     }
256
257     /*
258      * Setup the machine level interrupt vector
259      */
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);
263     }
264
265     return(rec);
266 }
267
268 void
269 unregister_swi(void *id)
270 {
271     unregister_int(id);
272 }
273
274 void
275 unregister_int(void *id)
276 {
277     struct intr_info *info;
278     struct intrec **list;
279     intrec_t rec;
280     int intr;
281
282     intr = ((intrec_t)id)->intr;
283
284     if (intr < 0 || intr >= MAX_INTS)
285         panic("register_int: bad intr %d", intr);
286
287     info = &intr_info_ary[intr];
288
289     /*
290      * Remove the interrupt descriptor, adjust the descriptor count,
291      * and teardown the machine level vector if this was the last interrupt.
292      */
293     crit_enter();
294     list = &info->i_reclist;
295     while ((rec = *list) != NULL) {
296         if (rec == id)
297             break;
298         list = &rec->next;
299     }
300     if (rec) {
301         *list = rec->next;
302         if (rec->intr_flags & INTR_FAST)
303             --info->i_fast;
304         else
305             --info->i_slow;
306         if (info->i_fast + info->i_slow == 0)
307             machintr_vector_teardown(intr);
308     }
309     crit_exit();
310
311     /*
312      * Free the record.
313      */
314     if (rec != NULL) {
315         free(rec->name, M_DEVBUF);
316         free(rec, M_DEVBUF);
317     } else {
318         printf("warning: unregister_int: int %d handler for %s not found\n",
319                 intr, ((intrec_t)id)->name);
320     }
321 }
322
323 const char *
324 get_registered_name(int intr)
325 {
326     intrec_t rec;
327
328     if (intr < 0 || intr >= MAX_INTS)
329         panic("register_int: bad intr %d", intr);
330
331     if ((rec = intr_info_ary[intr].i_reclist) == NULL)
332         return(NULL);
333     else if (rec->next)
334         return("mux");
335     else
336         return(rec->name);
337 }
338
339 int
340 count_registered_ints(int intr)
341 {
342     struct intr_info *info;
343
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);
348 }
349
350 long
351 get_interrupt_counter(int intr)
352 {
353     struct intr_info *info;
354
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);
359 }
360
361
362 void
363 swi_setpriority(int intr, int pri)
364 {
365     struct intr_info *info;
366
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);
372 }
373
374 void
375 register_randintr(int intr)
376 {
377     struct intr_info *info;
378
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;
384 }
385
386 void
387 unregister_randintr(int intr)
388 {
389     struct intr_info *info;
390
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;
395 }
396
397 int
398 next_registered_randintr(int intr)
399 {
400     struct intr_info *info;
401
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)
407             break;
408         ++intr;
409     }
410     return(intr);
411 }
412
413 /*
414  * Dispatch an interrupt.  If there's nothing to do we have a stray
415  * interrupt and can just return, leaving the interrupt masked.
416  *
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.
423  *
424  * i_running is only tested/set on the same cpu as the interrupt thread.
425  *
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.
428  */
429 #ifdef SMP
430
431 static void
432 sched_ithd_remote(void *arg)
433 {
434     sched_ithd((int)arg);
435 }
436
437 #endif
438
439 void
440 sched_ithd(int intr)
441 {
442     struct intr_info *info;
443
444     info = &intr_info_ary[intr];
445
446     ++info->i_count;
447     if (info->i_state != ISTATE_NOTHREAD) {
448         if (info->i_reclist == NULL) {
449             printf("sched_ithd: stray interrupt %d\n", intr);
450         } else {
451 #ifdef SMP
452             if (info->i_thread.td_gd == mycpu) {
453                 if (info->i_running == 0) {
454                     info->i_running = 1;
455                     if (info->i_state != ISTATE_LIVELOCKED)
456                         lwkt_schedule(&info->i_thread); /* MIGHT PREEMPT */
457                 }
458             } else {
459                 lwkt_send_ipiq(info->i_thread.td_gd, 
460                                 sched_ithd_remote, (void *)intr);
461             }
462 #else
463             if (info->i_running == 0) {
464                 info->i_running = 1;
465                 if (info->i_state != ISTATE_LIVELOCKED)
466                     lwkt_schedule(&info->i_thread); /* MIGHT PREEMPT */
467             }
468 #endif
469         }
470     } else {
471         printf("sched_ithd: stray interrupt %d\n", intr);
472     }
473 }
474
475 /*
476  * This is run from a periodic SYSTIMER (and thus must be MP safe, the BGL
477  * might not be held).
478  */
479 static void
480 ithread_livelock_wakeup(systimer_t st)
481 {
482     struct intr_info *info;
483
484     info = &intr_info_ary[(int)st->data];
485     if (info->i_state != ISTATE_NOTHREAD)
486         lwkt_schedule(&info->i_thread);
487 }
488
489 /*
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.
494  *
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)
497  */
498 int ithread_fast_handler(struct intrframe frame);
499
500 int
501 ithread_fast_handler(struct intrframe frame)
502 {
503     int intr;
504     struct intr_info *info;
505     struct intrec **list;
506     int must_schedule;
507 #ifdef SMP
508     int got_mplock;
509 #endif
510     intrec_t rec, next_rec;
511     globaldata_t gd;
512
513     intr = frame.if_vec;
514     gd = mycpu;
515
516     info = &intr_info_ary[intr];
517
518     /*
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
521      * preemption)
522      */
523     if (info->i_fast == 0) {
524         sched_ithd(intr);
525         return(1);
526     }
527
528     /*
529      * This should not normally occur since interrupts ought to be 
530      * masked if the ithread has been scheduled or is running.
531      */
532     if (info->i_running)
533         return(1);
534
535     /*
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.
539      *
540      * To reduce overhead, just leave the MP lock held once it has been
541      * obtained.
542      */
543     crit_enter_gd(gd);
544     ++gd->gd_intr_nesting_level;
545     ++gd->gd_cnt.v_intr;
546     must_schedule = info->i_slow;
547 #ifdef SMP
548     got_mplock = 0;
549 #endif
550
551     list = &info->i_reclist;
552     for (rec = *list; rec; rec = next_rec) {
553         next_rec = rec->next;   /* rec may be invalid after call */
554
555         if (rec->intr_flags & INTR_FAST) {
556 #ifdef SMP
557             if ((rec->intr_flags & INTR_MPSAFE) == 0 && got_mplock == 0) {
558                 if (try_mplock() == 0) {
559                     int owner;
560
561                     /*
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.
566                      */
567                     owner = owner_mplock();
568                     if (owner >= 0 && owner != gd->gd_cpuid) {
569                         lwkt_send_ipiq_bycpu(owner, forward_fastint_remote,
570                                                 (void *)intr);
571                         must_schedule = -1;
572                         ++gd->gd_cnt.v_forwarded_ints;
573                     } else {
574                         must_schedule = 1;
575                     }
576                     break;
577                 }
578                 got_mplock = 1;
579             }
580 #endif
581             if (rec->serializer) {
582                 must_schedule += lwkt_serialize_handler_try(
583                                         rec->serializer, rec->handler,
584                                         rec->argument, &frame);
585             } else {
586                 rec->handler(rec->argument, &frame);
587             }
588         }
589     }
590
591     /*
592      * Cleanup
593      */
594     --gd->gd_intr_nesting_level;
595 #ifdef SMP
596     if (got_mplock)
597         rel_mplock();
598 #endif
599     crit_exit_gd(gd);
600
601     /*
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.
607      */
608     if (must_schedule > 0)
609         sched_ithd(intr);
610     else if (must_schedule == 0)
611         ++info->i_count;
612     return(must_schedule);
613 }
614
615 #if 0
616
617 6: ;                                                                    \
618         /* could not get the MP lock, forward the interrupt */          \
619         movl    mp_lock, %eax ;          /* check race */               \
620         cmpl    $MP_FREE_LOCK,%eax ;                                    \
621         je      2b ;                                                    \
622         incl    PCPU(cnt)+V_FORWARDED_INTS ;                            \
623         subl    $12,%esp ;                                              \
624         movl    $irq_num,8(%esp) ;                                      \
625         movl    $forward_fastint_remote,4(%esp) ;                       \
626         movl    %eax,(%esp) ;                                           \
627         call    lwkt_send_ipiq_bycpu ;                                  \
628         addl    $12,%esp ;                                              \
629         jmp     5f ;                   
630
631 #endif
632
633
634 /*
635  * Interrupt threads run this as their main loop.
636  *
637  * The handler begins execution outside a critical section and with the BGL
638  * held.
639  *
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. 
644  *
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.
649  */
650 #define LIVELOCK_TIMEFRAME(freq)        ((freq) >> 2)   /* 1/4 second */
651
652 static void
653 ithread_handler(void *arg)
654 {
655     struct intr_info *info;
656     int use_limit;
657     int lticks;
658     int lcount;
659     int intr;
660     int mpheld;
661     struct intrec **list;
662     intrec_t rec, nrec;
663     globaldata_t gd;
664     struct systimer ill_timer;  /* enforced freq. timer */
665     u_int ill_count;            /* interrupt livelock counter */
666
667     ill_count = 0;
668     lticks = ticks;
669     lcount = 0;
670     intr = (int)arg;
671     info = &intr_info_ary[intr];
672     list = &info->i_reclist;
673     gd = mycpu;
674
675     /*
676      * The loop must be entered with one critical section held.  We start
677      * out with the MP lock released.
678      */
679     crit_enter_gd(gd);
680     mpheld = 1;
681
682     for (;;) {
683         /*
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.
687          *
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.
691          */
692         if (info->i_running) {
693             ++ill_count;
694             info->i_running = 0;
695
696             for (rec = *list; rec; rec = nrec) {
697                 nrec = rec->next;
698                 if (rec->serializer) {
699                     lwkt_serialize_handler_call(rec->serializer, rec->handler,
700                                                 rec->argument, NULL);
701                 } else {
702                     rec->handler(rec->argument, NULL);
703                 }
704             }
705         }
706
707         /*
708          * This is our interrupt hook to add rate randomness to the random
709          * number generator.
710          */
711         if (info->i_random.sc_enabled)
712             add_interrupt_randomness(intr);
713
714         /*
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.
719          *
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).
724          */
725         if (*list)
726             machintr_intren(intr);
727
728         /*
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.
732          */
733         crit_exit_gd(gd);
734         crit_enter_gd(gd);
735
736         /*
737          * LIVELOCK STATE MACHINE
738          */
739         switch(info->i_state) {
740         case ISTATE_NORMAL:
741             /*
742              * Calculate a running average every tick.
743              */
744             if (lticks != ticks) {
745                 lticks = ticks;
746                 ill_count -= ill_count / hz;
747             }
748
749             /*
750              * If we did not exceed the frequency limit, we are done.  
751              * If the interrupt has not retriggered we deschedule ourselves.
752              */
753             if (ill_count <= livelock_limit) {
754                 if (info->i_running == 0) {
755                     lwkt_deschedule_self(gd->gd_curthread);
756                     lwkt_switch();
757                 }
758                 break;
759             }
760
761             /*
762              * Otherwise we are livelocked.  Set up a periodic systimer
763              * to wake the thread up at the limit frequency.
764              */
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)
769                 use_limit = 100;
770             else if (use_limit > 500000)
771                 use_limit = 500000;
772             systimer_init_periodic(&ill_timer, ithread_livelock_wakeup,
773                                    (void *)intr, use_limit);
774             lcount = 0;
775             /* fall through */
776         case ISTATE_LIVELOCKED:
777             /*
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.
781              */
782             lwkt_deschedule_self(gd->gd_curthread);
783             lwkt_switch();
784
785             /*
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.
789              */
790             if (lticks != ticks) {
791                 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);
798                     }
799                 } else {
800                     lcount = 0;
801                 }
802                 ill_count -= ill_count / hz;
803             }
804             break;
805         }
806     }
807     /* not reached */
808 }
809
810 /*
811  * Emergency interrupt polling thread.  The thread begins execution
812  * outside a critical section with the BGL held.
813  *
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.
817  *
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.
824  */
825 static void
826 ithread_emergency(void *arg __unused)
827 {
828     struct intr_info *info;
829     intrec_t rec, nrec;
830     int intr;
831
832     for (;;) {
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);
840                     } else {
841                         rec->handler(rec->argument, NULL);
842                     }
843                 }
844                 nrec = rec->next;
845             }
846         }
847         lwkt_deschedule_self(curthread);
848         lwkt_switch();
849     }
850 }
851
852 /*
853  * Systimer callback - schedule the emergency interrupt poll thread
854  *                     if emergency polling is enabled.
855  */
856 static
857 void
858 emergency_intr_timer_callback(systimer_t info, struct intrframe *frame __unused)
859 {
860     if (emergency_intr_enable)
861         lwkt_schedule(info->data);
862 }
863
864 /* 
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
868  * independent.
869  *
870  * We do not know the length of intrcnt and intrnames at compile time, so
871  * calculate things at run time.
872  */
873
874 static int
875 sysctl_intrnames(SYSCTL_HANDLER_ARGS)
876 {
877     struct intr_info *info;
878     intrec_t rec;
879     int error = 0;
880     int len;
881     int intr;
882     char buf[64];
883
884     for (intr = 0; error == 0 && intr < MAX_INTS; ++intr) {
885         info = &intr_info_ary[intr];
886
887         len = 0;
888         buf[0] = 0;
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);
893         }
894         if (len == 0) {
895             snprintf(buf, sizeof(buf), "irq%d", intr);
896             len = strlen(buf);
897         }
898         error = SYSCTL_OUT(req, buf, len + 1);
899     }
900     return (error);
901 }
902
903
904 SYSCTL_PROC(_hw, OID_AUTO, intrnames, CTLTYPE_OPAQUE | CTLFLAG_RD,
905         NULL, 0, sysctl_intrnames, "", "Interrupt Names");
906
907 static int
908 sysctl_intrcnt(SYSCTL_HANDLER_ARGS)
909 {
910     struct intr_info *info;
911     int error = 0;
912     int intr;
913
914     for (intr = 0; intr < max_installed_hard_intr; ++intr) {
915         info = &intr_info_ary[intr];
916
917         error = SYSCTL_OUT(req, &info->i_count, sizeof(info->i_count));
918         if (error)
919                 goto failed;
920     }
921     for (intr = FIRST_SOFTINT; intr < max_installed_soft_intr; ++intr) {
922         info = &intr_info_ary[intr];
923
924         error = SYSCTL_OUT(req, &info->i_count, sizeof(info->i_count));
925         if (error)
926                 goto failed;
927     }
928 failed:
929     return(error);
930 }
931
932 SYSCTL_PROC(_hw, OID_AUTO, intrcnt, CTLTYPE_OPAQUE | CTLFLAG_RD,
933         NULL, 0, sysctl_intrcnt, "", "Interrupt Counts");
934