fe3ab42616a74fb3a9cd1b0d8ed5389f487c415e
[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  *
28  */
29
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/malloc.h>
33 #include <sys/kernel.h>
34 #include <sys/sysctl.h>
35 #include <sys/thread.h>
36 #include <sys/proc.h>
37 #include <sys/random.h>
38 #include <sys/serialize.h>
39 #include <sys/interrupt.h>
40 #include <sys/bus.h>
41 #include <sys/machintr.h>
42
43 #include <machine/frame.h>
44
45 #include <sys/thread2.h>
46 #include <sys/mplock2.h>
47
48 struct info_info;
49
50 typedef struct intrec {
51     struct intrec *next;
52     struct intr_info *info;
53     inthand2_t  *handler;
54     void        *argument;
55     char        *name;
56     int         intr;
57     int         intr_flags;
58     struct lwkt_serialize *serializer;
59 } *intrec_t;
60
61 struct intr_info {
62         intrec_t        i_reclist;
63         struct thread   i_thread;
64         struct random_softc i_random;
65         int             i_running;
66         long            i_count;        /* interrupts dispatched */
67         int             i_mplock_required;
68         int             i_fast;
69         int             i_slow;
70         int             i_state;
71         int             i_errorticks;
72         unsigned long   i_straycount;
73 } intr_info_ary[MAX_INTS];
74
75 int max_installed_hard_intr;
76 int max_installed_soft_intr;
77
78 #define EMERGENCY_INTR_POLLING_FREQ_MAX 20000
79
80 /*
81  * Assert that callers into interrupt handlers don't return with
82  * dangling tokens, spinlocks, or mp locks.
83  */
84 #ifdef INVARIANTS
85
86 #define TD_INVARIANTS_DECLARE   \
87         int spincount;          \
88         lwkt_tokref_t curstop
89
90 #define TD_INVARIANTS_GET(td)                                   \
91         do {                                                    \
92                 spincount = (td)->td_gd->gd_spinlocks_wr;       \
93                 curstop = (td)->td_toks_stop;                   \
94         } while(0)
95
96 #define TD_INVARIANTS_TEST(td, name)                                    \
97         do {                                                            \
98                 KASSERT(spincount == (td)->td_gd->gd_spinlocks_wr,      \
99                         ("spincount mismatch after interrupt handler %s", \
100                         name));                                         \
101                 KASSERT(curstop == (td)->td_toks_stop,                  \
102                         ("token count mismatch after interrupt handler %s", \
103                         name));                                         \
104         } while(0)
105
106 #else
107
108 /* !INVARIANTS */
109
110 #define TD_INVARIANTS_DECLARE
111 #define TD_INVARIANTS_GET(td)
112 #define TD_INVARIANTS_TEST(td, name)
113
114 #endif /* ndef INVARIANTS */
115
116 static int sysctl_emergency_freq(SYSCTL_HANDLER_ARGS);
117 static int sysctl_emergency_enable(SYSCTL_HANDLER_ARGS);
118 static void emergency_intr_timer_callback(systimer_t, int, struct intrframe *);
119 static void ithread_handler(void *arg);
120 static void ithread_emergency(void *arg);
121 static void report_stray_interrupt(int intr, struct intr_info *info);
122 static void int_moveto_destcpu(int *, int);
123 static void int_moveto_origcpu(int, int);
124
125 int intr_info_size = NELEM(intr_info_ary);
126
127 static struct systimer emergency_intr_timer;
128 static struct thread emergency_intr_thread;
129
130 #define ISTATE_NOTHREAD         0
131 #define ISTATE_NORMAL           1
132 #define ISTATE_LIVELOCKED       2
133
134 static int livelock_limit = 40000;
135 static int livelock_lowater = 20000;
136 static int livelock_debug = -1;
137 SYSCTL_INT(_kern, OID_AUTO, livelock_limit,
138         CTLFLAG_RW, &livelock_limit, 0, "Livelock interrupt rate limit");
139 SYSCTL_INT(_kern, OID_AUTO, livelock_lowater,
140         CTLFLAG_RW, &livelock_lowater, 0, "Livelock low-water mark restore");
141 SYSCTL_INT(_kern, OID_AUTO, livelock_debug,
142         CTLFLAG_RW, &livelock_debug, 0, "Livelock debug intr#");
143
144 static int emergency_intr_enable = 0;   /* emergency interrupt polling */
145 TUNABLE_INT("kern.emergency_intr_enable", &emergency_intr_enable);
146 SYSCTL_PROC(_kern, OID_AUTO, emergency_intr_enable, CTLTYPE_INT | CTLFLAG_RW,
147         0, 0, sysctl_emergency_enable, "I", "Emergency Interrupt Poll Enable");
148
149 static int emergency_intr_freq = 10;    /* emergency polling frequency */
150 TUNABLE_INT("kern.emergency_intr_freq", &emergency_intr_freq);
151 SYSCTL_PROC(_kern, OID_AUTO, emergency_intr_freq, CTLTYPE_INT | CTLFLAG_RW,
152         0, 0, sysctl_emergency_freq, "I", "Emergency Interrupt Poll Frequency");
153
154 /*
155  * Sysctl support routines
156  */
157 static int
158 sysctl_emergency_enable(SYSCTL_HANDLER_ARGS)
159 {
160         int error, enabled;
161
162         enabled = emergency_intr_enable;
163         error = sysctl_handle_int(oidp, &enabled, 0, req);
164         if (error || req->newptr == NULL)
165                 return error;
166         emergency_intr_enable = enabled;
167         if (emergency_intr_enable) {
168                 systimer_adjust_periodic(&emergency_intr_timer,
169                                          emergency_intr_freq);
170         } else {
171                 systimer_adjust_periodic(&emergency_intr_timer, 1);
172         }
173         return 0;
174 }
175
176 static int
177 sysctl_emergency_freq(SYSCTL_HANDLER_ARGS)
178 {
179         int error, phz;
180
181         phz = emergency_intr_freq;
182         error = sysctl_handle_int(oidp, &phz, 0, req);
183         if (error || req->newptr == NULL)
184                 return error;
185         if (phz <= 0)
186                 return EINVAL;
187         else if (phz > EMERGENCY_INTR_POLLING_FREQ_MAX)
188                 phz = EMERGENCY_INTR_POLLING_FREQ_MAX;
189
190         emergency_intr_freq = phz;
191         if (emergency_intr_enable) {
192                 systimer_adjust_periodic(&emergency_intr_timer,
193                                          emergency_intr_freq);
194         } else {
195                 systimer_adjust_periodic(&emergency_intr_timer, 1);
196         }
197         return 0;
198 }
199
200 /*
201  * Register an SWI or INTerrupt handler.
202  */
203 void *
204 register_swi(int intr, inthand2_t *handler, void *arg, const char *name,
205                 struct lwkt_serialize *serializer, int cpuid)
206 {
207     if (intr < FIRST_SOFTINT || intr >= MAX_INTS)
208         panic("register_swi: bad intr %d", intr);
209
210     if (cpuid < 0)
211         cpuid = intr % ncpus;
212     return(register_int(intr, handler, arg, name, serializer, 0, cpuid));
213 }
214
215 void *
216 register_swi_mp(int intr, inthand2_t *handler, void *arg, const char *name,
217                 struct lwkt_serialize *serializer, int cpuid)
218 {
219     if (intr < FIRST_SOFTINT || intr >= MAX_INTS)
220         panic("register_swi: bad intr %d", intr);
221
222     if (cpuid < 0)
223         cpuid = intr % ncpus;
224     return(register_int(intr, handler, arg, name, serializer,
225         INTR_MPSAFE, cpuid));
226 }
227
228 void *
229 register_int(int intr, inthand2_t *handler, void *arg, const char *name,
230                 struct lwkt_serialize *serializer, int intr_flags, int cpuid)
231 {
232     struct intr_info *info;
233     struct intrec **list;
234     intrec_t rec;
235     int orig_cpuid;
236
237     KKASSERT(cpuid >= 0 && cpuid < ncpus);
238
239     if (intr < 0 || intr >= MAX_INTS)
240         panic("register_int: bad intr %d", intr);
241     if (name == NULL)
242         name = "???";
243     info = &intr_info_ary[intr];
244
245     /*
246      * Construct an interrupt handler record
247      */
248     rec = kmalloc(sizeof(struct intrec), M_DEVBUF, M_INTWAIT);
249     rec->name = kmalloc(strlen(name) + 1, M_DEVBUF, M_INTWAIT);
250     strcpy(rec->name, name);
251
252     rec->info = info;
253     rec->handler = handler;
254     rec->argument = arg;
255     rec->intr = intr;
256     rec->intr_flags = intr_flags;
257     rec->next = NULL;
258     rec->serializer = serializer;
259
260     /*
261      * Create an emergency polling thread and set up a systimer to wake
262      * it up.
263      */
264     if (emergency_intr_thread.td_kstack == NULL) {
265         lwkt_create(ithread_emergency, NULL, NULL, &emergency_intr_thread,
266                     TDF_NOSTART | TDF_INTTHREAD, ncpus - 1, "ithread emerg");
267         systimer_init_periodic_nq(&emergency_intr_timer,
268                     emergency_intr_timer_callback, &emergency_intr_thread, 
269                     (emergency_intr_enable ? emergency_intr_freq : 1));
270     }
271
272     int_moveto_destcpu(&orig_cpuid, cpuid);
273
274     /*
275      * Create an interrupt thread if necessary, leave it in an unscheduled
276      * state.
277      */
278     if (info->i_state == ISTATE_NOTHREAD) {
279         info->i_state = ISTATE_NORMAL;
280         lwkt_create(ithread_handler, (void *)(intptr_t)intr, NULL,
281                     &info->i_thread, TDF_NOSTART | TDF_INTTHREAD, cpuid,
282                     "ithread %d", intr);
283         if (intr >= FIRST_SOFTINT)
284             lwkt_setpri(&info->i_thread, TDPRI_SOFT_NORM);
285         else
286             lwkt_setpri(&info->i_thread, TDPRI_INT_MED);
287         info->i_thread.td_preemptable = lwkt_preempt;
288     }
289
290     list = &info->i_reclist;
291
292     /*
293      * Keep track of how many fast and slow interrupts we have.
294      * Set i_mplock_required if any handler in the chain requires
295      * the MP lock to operate.
296      */
297     if ((intr_flags & INTR_MPSAFE) == 0)
298         info->i_mplock_required = 1;
299     if (intr_flags & INTR_CLOCK)
300         ++info->i_fast;
301     else
302         ++info->i_slow;
303
304     /*
305      * Enable random number generation keying off of this interrupt.
306      */
307     if ((intr_flags & INTR_NOENTROPY) == 0 && info->i_random.sc_enabled == 0) {
308         info->i_random.sc_enabled = 1;
309         info->i_random.sc_intr = intr;
310     }
311
312     /*
313      * Add the record to the interrupt list.
314      */
315     crit_enter();
316     while (*list != NULL)
317         list = &(*list)->next;
318     *list = rec;
319     crit_exit();
320
321     /*
322      * Update max_installed_hard_intr to make the emergency intr poll
323      * a bit more efficient.
324      */
325     if (intr < FIRST_SOFTINT) {
326         if (max_installed_hard_intr <= intr)
327             max_installed_hard_intr = intr + 1;
328     } else {
329         if (max_installed_soft_intr <= intr)
330             max_installed_soft_intr = intr + 1;
331     }
332
333     /*
334      * Setup the machine level interrupt vector
335      */
336     if (intr < FIRST_SOFTINT && info->i_slow + info->i_fast == 1)
337         machintr_intr_setup(intr, intr_flags);
338
339     int_moveto_origcpu(orig_cpuid, cpuid);
340
341     return(rec);
342 }
343
344 void
345 unregister_swi(void *id, int intr, int cpuid)
346 {
347     if (cpuid < 0)
348         cpuid = intr % ncpus;
349
350     unregister_int(id, cpuid);
351 }
352
353 void
354 unregister_int(void *id, int cpuid)
355 {
356     struct intr_info *info;
357     struct intrec **list;
358     intrec_t rec;
359     int intr, orig_cpuid;
360
361     KKASSERT(cpuid >= 0 && cpuid < ncpus);
362
363     intr = ((intrec_t)id)->intr;
364
365     if (intr < 0 || intr >= MAX_INTS)
366         panic("register_int: bad intr %d", intr);
367
368     info = &intr_info_ary[intr];
369
370     int_moveto_destcpu(&orig_cpuid, cpuid);
371
372     /*
373      * Remove the interrupt descriptor, adjust the descriptor count,
374      * and teardown the machine level vector if this was the last interrupt.
375      */
376     crit_enter();
377     list = &info->i_reclist;
378     while ((rec = *list) != NULL) {
379         if (rec == id)
380             break;
381         list = &rec->next;
382     }
383     if (rec) {
384         intrec_t rec0;
385
386         *list = rec->next;
387         if (rec->intr_flags & INTR_CLOCK)
388             --info->i_fast;
389         else
390             --info->i_slow;
391         if (intr < FIRST_SOFTINT && info->i_fast + info->i_slow == 0)
392             machintr_intr_teardown(intr);
393
394         /*
395          * Clear i_mplock_required if no handlers in the chain require the
396          * MP lock.
397          */
398         for (rec0 = info->i_reclist; rec0; rec0 = rec0->next) {
399             if ((rec0->intr_flags & INTR_MPSAFE) == 0)
400                 break;
401         }
402         if (rec0 == NULL)
403             info->i_mplock_required = 0;
404     }
405
406     crit_exit();
407
408     int_moveto_origcpu(orig_cpuid, cpuid);
409
410     /*
411      * Free the record.
412      */
413     if (rec != NULL) {
414         kfree(rec->name, M_DEVBUF);
415         kfree(rec, M_DEVBUF);
416     } else {
417         kprintf("warning: unregister_int: int %d handler for %s not found\n",
418                 intr, ((intrec_t)id)->name);
419     }
420 }
421
422 int
423 count_registered_ints(int intr)
424 {
425     struct intr_info *info;
426
427     if (intr < 0 || intr >= MAX_INTS)
428         panic("register_int: bad intr %d", intr);
429     info = &intr_info_ary[intr];
430     return(info->i_fast + info->i_slow);
431 }
432
433 long
434 get_interrupt_counter(int intr)
435 {
436     struct intr_info *info;
437
438     if (intr < 0 || intr >= MAX_INTS)
439         panic("register_int: bad intr %d", intr);
440     info = &intr_info_ary[intr];
441     return(info->i_count);
442 }
443
444 void
445 register_randintr(int intr)
446 {
447     struct intr_info *info;
448
449     if (intr < 0 || intr >= MAX_INTS)
450         panic("register_randintr: bad intr %d", intr);
451     info = &intr_info_ary[intr];
452     info->i_random.sc_intr = intr;
453     info->i_random.sc_enabled = 1;
454 }
455
456 void
457 unregister_randintr(int intr)
458 {
459     struct intr_info *info;
460
461     if (intr < 0 || intr >= MAX_INTS)
462         panic("register_swi: bad intr %d", intr);
463     info = &intr_info_ary[intr];
464     info->i_random.sc_enabled = -1;
465 }
466
467 int
468 next_registered_randintr(int intr)
469 {
470     struct intr_info *info;
471
472     if (intr < 0 || intr >= MAX_INTS)
473         panic("register_swi: bad intr %d", intr);
474     while (intr < MAX_INTS) {
475         info = &intr_info_ary[intr];
476         if (info->i_random.sc_enabled > 0)
477             break;
478         ++intr;
479     }
480     return(intr);
481 }
482
483 /*
484  * Dispatch an interrupt.  If there's nothing to do we have a stray
485  * interrupt and can just return, leaving the interrupt masked.
486  *
487  * We need to schedule the interrupt and set its i_running bit.  If
488  * we are not on the interrupt thread's cpu we have to send a message
489  * to the correct cpu that will issue the desired action (interlocking
490  * with the interrupt thread's critical section).  We do NOT attempt to
491  * reschedule interrupts whos i_running bit is already set because
492  * this would prematurely wakeup a livelock-limited interrupt thread.
493  *
494  * i_running is only tested/set on the same cpu as the interrupt thread.
495  *
496  * We are NOT in a critical section, which will allow the scheduled
497  * interrupt to preempt us.  The MP lock might *NOT* be held here.
498  */
499 #ifdef SMP
500
501 static void
502 sched_ithd_remote(void *arg)
503 {
504     sched_ithd((int)(intptr_t)arg);
505 }
506
507 #endif
508
509 void
510 sched_ithd(int intr)
511 {
512     struct intr_info *info;
513
514     info = &intr_info_ary[intr];
515
516     ++info->i_count;
517     if (info->i_state != ISTATE_NOTHREAD) {
518         if (info->i_reclist == NULL) {
519             report_stray_interrupt(intr, info);
520         } else {
521 #ifdef SMP
522             if (info->i_thread.td_gd == mycpu) {
523                 if (info->i_running == 0) {
524                     info->i_running = 1;
525                     if (info->i_state != ISTATE_LIVELOCKED)
526                         lwkt_schedule(&info->i_thread); /* MIGHT PREEMPT */
527                 }
528             } else {
529                 lwkt_send_ipiq(info->i_thread.td_gd, 
530                                 sched_ithd_remote, (void *)(intptr_t)intr);
531             }
532 #else
533             if (info->i_running == 0) {
534                 info->i_running = 1;
535                 if (info->i_state != ISTATE_LIVELOCKED)
536                     lwkt_schedule(&info->i_thread); /* MIGHT PREEMPT */
537             }
538 #endif
539         }
540     } else {
541         report_stray_interrupt(intr, info);
542     }
543 }
544
545 static void
546 report_stray_interrupt(int intr, struct intr_info *info)
547 {
548         ++info->i_straycount;
549         if (info->i_straycount < 10) {
550                 if (info->i_errorticks == ticks)
551                         return;
552                 info->i_errorticks = ticks;
553                 kprintf("sched_ithd: stray interrupt %d on cpu %d\n",
554                         intr, mycpuid);
555         } else if (info->i_straycount == 10) {
556                 kprintf("sched_ithd: %ld stray interrupts %d on cpu %d - "
557                         "there will be no further reports\n",
558                         info->i_straycount, intr, mycpuid);
559         }
560 }
561
562 /*
563  * This is run from a periodic SYSTIMER (and thus must be MP safe, the BGL
564  * might not be held).
565  */
566 static void
567 ithread_livelock_wakeup(systimer_t st, int in_ipi __unused,
568     struct intrframe *frame __unused)
569 {
570     struct intr_info *info;
571
572     info = &intr_info_ary[(int)(intptr_t)st->data];
573     if (info->i_state != ISTATE_NOTHREAD)
574         lwkt_schedule(&info->i_thread);
575 }
576
577 /*
578  * Schedule ithread within fast intr handler
579  *
580  * XXX Protect sched_ithd() call with gd_intr_nesting_level?
581  * Interrupts aren't enabled, but still...
582  */
583 static __inline void
584 ithread_fast_sched(int intr, thread_t td)
585 {
586     ++td->td_nest_count;
587
588     /*
589      * We are already in critical section, exit it now to
590      * allow preemption.
591      */
592     crit_exit_quick(td);
593     sched_ithd(intr);
594     crit_enter_quick(td);
595
596     --td->td_nest_count;
597 }
598
599 /*
600  * This function is called directly from the ICU or APIC vector code assembly
601  * to process an interrupt.  The critical section and interrupt deferral
602  * checks have already been done but the function is entered WITHOUT
603  * a critical section held.  The BGL may or may not be held.
604  *
605  * Must return non-zero if we do not want the vector code to re-enable
606  * the interrupt (which we don't if we have to schedule the interrupt)
607  */
608 int ithread_fast_handler(struct intrframe *frame);
609
610 int
611 ithread_fast_handler(struct intrframe *frame)
612 {
613     int intr;
614     struct intr_info *info;
615     struct intrec **list;
616     int must_schedule;
617 #ifdef SMP
618     int got_mplock;
619 #endif
620     TD_INVARIANTS_DECLARE;
621     intrec_t rec, nrec;
622     globaldata_t gd;
623     thread_t td;
624
625     intr = frame->if_vec;
626     gd = mycpu;
627     td = curthread;
628
629     /* We must be in critical section. */
630     KKASSERT(td->td_critcount);
631
632     info = &intr_info_ary[intr];
633
634     /*
635      * If we are not processing any FAST interrupts, just schedule the thing.
636      */
637     if (info->i_fast == 0) {
638         ++gd->gd_cnt.v_intr;
639         ithread_fast_sched(intr, td);
640         return(1);
641     }
642
643     /*
644      * This should not normally occur since interrupts ought to be 
645      * masked if the ithread has been scheduled or is running.
646      */
647     if (info->i_running)
648         return(1);
649
650     /*
651      * Bump the interrupt nesting level to process any FAST interrupts.
652      * Obtain the MP lock as necessary.  If the MP lock cannot be obtained,
653      * schedule the interrupt thread to deal with the issue instead.
654      *
655      * To reduce overhead, just leave the MP lock held once it has been
656      * obtained.
657      */
658     ++gd->gd_intr_nesting_level;
659     ++gd->gd_cnt.v_intr;
660     must_schedule = info->i_slow;
661 #ifdef SMP
662     got_mplock = 0;
663 #endif
664
665     TD_INVARIANTS_GET(td);
666     list = &info->i_reclist;
667
668     for (rec = *list; rec; rec = nrec) {
669         /* rec may be invalid after call */
670         nrec = rec->next;
671
672         if (rec->intr_flags & INTR_CLOCK) {
673 #ifdef SMP
674             if ((rec->intr_flags & INTR_MPSAFE) == 0 && got_mplock == 0) {
675                 if (try_mplock() == 0) {
676                     /* Couldn't get the MP lock; just schedule it. */
677                     must_schedule = 1;
678                     break;
679                 }
680                 got_mplock = 1;
681             }
682 #endif
683             if (rec->serializer) {
684                 must_schedule += lwkt_serialize_handler_try(
685                                         rec->serializer, rec->handler,
686                                         rec->argument, frame);
687             } else {
688                 rec->handler(rec->argument, frame);
689             }
690             TD_INVARIANTS_TEST(td, rec->name);
691         }
692     }
693
694     /*
695      * Cleanup
696      */
697     --gd->gd_intr_nesting_level;
698 #ifdef SMP
699     if (got_mplock)
700         rel_mplock();
701 #endif
702
703     /*
704      * If we had a problem, or mixed fast and slow interrupt handlers are
705      * registered, schedule the ithread to catch the missed records (it
706      * will just re-run all of them).  A return value of 0 indicates that
707      * all handlers have been run and the interrupt can be re-enabled, and
708      * a non-zero return indicates that the interrupt thread controls
709      * re-enablement.
710      */
711     if (must_schedule > 0)
712         ithread_fast_sched(intr, td);
713     else if (must_schedule == 0)
714         ++info->i_count;
715     return(must_schedule);
716 }
717
718 /*
719  * Interrupt threads run this as their main loop.
720  *
721  * The handler begins execution outside a critical section and no MP lock.
722  *
723  * The i_running state starts at 0.  When an interrupt occurs, the hardware
724  * interrupt is disabled and sched_ithd() The HW interrupt remains disabled
725  * until all routines have run.  We then call ithread_done() to reenable 
726  * the HW interrupt and deschedule us until the next interrupt. 
727  *
728  * We are responsible for atomically checking i_running and ithread_done()
729  * is responsible for atomically checking for platform-specific delayed
730  * interrupts.  i_running for our irq is only set in the context of our cpu,
731  * so a critical section is a sufficient interlock.
732  */
733 #define LIVELOCK_TIMEFRAME(freq)        ((freq) >> 2)   /* 1/4 second */
734
735 static void
736 ithread_handler(void *arg)
737 {
738     struct intr_info *info;
739     int use_limit;
740     __uint32_t lseconds;
741     int intr;
742     int mpheld;
743     struct intrec **list;
744     intrec_t rec, nrec;
745     globaldata_t gd;
746     struct systimer ill_timer;  /* enforced freq. timer */
747     u_int ill_count;            /* interrupt livelock counter */
748     TD_INVARIANTS_DECLARE;
749
750     ill_count = 0;
751     intr = (int)(intptr_t)arg;
752     info = &intr_info_ary[intr];
753     list = &info->i_reclist;
754
755     /*
756      * The loop must be entered with one critical section held.  The thread
757      * does not hold the mplock on startup.
758      */
759     gd = mycpu;
760     lseconds = gd->gd_time_seconds;
761     crit_enter_gd(gd);
762     mpheld = 0;
763
764     for (;;) {
765         /*
766          * The chain is only considered MPSAFE if all its interrupt handlers
767          * are MPSAFE.  However, if intr_mpsafe has been turned off we
768          * always operate with the BGL.
769          */
770 #ifdef SMP
771         if (info->i_mplock_required != mpheld) {
772             if (info->i_mplock_required) {
773                 KKASSERT(mpheld == 0);
774                 get_mplock();
775                 mpheld = 1;
776             } else {
777                 KKASSERT(mpheld != 0);
778                 rel_mplock();
779                 mpheld = 0;
780             }
781         }
782 #endif
783
784         TD_INVARIANTS_GET(gd->gd_curthread);
785
786         /*
787          * If an interrupt is pending, clear i_running and execute the
788          * handlers.  Note that certain types of interrupts can re-trigger
789          * and set i_running again.
790          *
791          * Each handler is run in a critical section.  Note that we run both
792          * FAST and SLOW designated service routines.
793          */
794         if (info->i_running) {
795             ++ill_count;
796             info->i_running = 0;
797
798             if (*list == NULL)
799                 report_stray_interrupt(intr, info);
800
801             for (rec = *list; rec; rec = nrec) {
802                 /* rec may be invalid after call */
803                 nrec = rec->next;
804                 if (rec->serializer) {
805                     lwkt_serialize_handler_call(rec->serializer, rec->handler,
806                                                 rec->argument, NULL);
807                 } else {
808                     rec->handler(rec->argument, NULL);
809                 }
810                 TD_INVARIANTS_TEST(gd->gd_curthread, rec->name);
811             }
812         }
813
814         /*
815          * This is our interrupt hook to add rate randomness to the random
816          * number generator.
817          */
818         if (info->i_random.sc_enabled > 0)
819             add_interrupt_randomness(intr);
820
821         /*
822          * Unmask the interrupt to allow it to trigger again.  This only
823          * applies to certain types of interrupts (typ level interrupts).
824          * This can result in the interrupt retriggering, but the retrigger
825          * will not be processed until we cycle our critical section.
826          *
827          * Only unmask interrupts while handlers are installed.  It is
828          * possible to hit a situation where no handlers are installed
829          * due to a device driver livelocking and then tearing down its
830          * interrupt on close (the parallel bus being a good example).
831          */
832         if (intr < FIRST_SOFTINT && *list)
833             machintr_intr_enable(intr);
834
835         /*
836          * Do a quick exit/enter to catch any higher-priority interrupt
837          * sources, such as the statclock, so thread time accounting
838          * will still work.  This may also cause an interrupt to re-trigger.
839          */
840         crit_exit_gd(gd);
841         crit_enter_gd(gd);
842
843         /*
844          * LIVELOCK STATE MACHINE
845          */
846         switch(info->i_state) {
847         case ISTATE_NORMAL:
848             /*
849              * Reset the count each second.
850              */
851             if (lseconds != gd->gd_time_seconds) {
852                 lseconds = gd->gd_time_seconds;
853                 ill_count = 0;
854             }
855
856             /*
857              * If we did not exceed the frequency limit, we are done.  
858              * If the interrupt has not retriggered we deschedule ourselves.
859              */
860             if (ill_count <= livelock_limit) {
861                 if (info->i_running == 0) {
862                     lwkt_deschedule_self(gd->gd_curthread);
863                     lwkt_switch();
864                 }
865                 break;
866             }
867
868             /*
869              * Otherwise we are livelocked.  Set up a periodic systimer
870              * to wake the thread up at the limit frequency.
871              */
872             kprintf("intr %d at %d/%d hz, livelocked limit engaged!\n",
873                    intr, ill_count, livelock_limit);
874             info->i_state = ISTATE_LIVELOCKED;
875             if ((use_limit = livelock_limit) < 100)
876                 use_limit = 100;
877             else if (use_limit > 500000)
878                 use_limit = 500000;
879             systimer_init_periodic_nq(&ill_timer, ithread_livelock_wakeup,
880                                       (void *)(intptr_t)intr, use_limit);
881             /* fall through */
882         case ISTATE_LIVELOCKED:
883             /*
884              * Wait for our periodic timer to go off.  Since the interrupt
885              * has re-armed it can still set i_running, but it will not
886              * reschedule us while we are in a livelocked state.
887              */
888             lwkt_deschedule_self(gd->gd_curthread);
889             lwkt_switch();
890
891             /*
892              * Check once a second to see if the livelock condition no
893              * longer applies.
894              */
895             if (lseconds != gd->gd_time_seconds) {
896                 lseconds = gd->gd_time_seconds;
897                 if (ill_count < livelock_lowater) {
898                     info->i_state = ISTATE_NORMAL;
899                     systimer_del(&ill_timer);
900                     kprintf("intr %d at %d/%d hz, livelock removed\n",
901                            intr, ill_count, livelock_lowater);
902                 } else if (livelock_debug == intr ||
903                            (bootverbose && cold)) {
904                     kprintf("intr %d at %d/%d hz, in livelock\n",
905                            intr, ill_count, livelock_lowater);
906                 }
907                 ill_count = 0;
908             }
909             break;
910         }
911     }
912     /* NOT REACHED */
913 }
914
915 /*
916  * Emergency interrupt polling thread.  The thread begins execution
917  * outside a critical section with the BGL held.
918  *
919  * If emergency interrupt polling is enabled, this thread will 
920  * execute all system interrupts not marked INTR_NOPOLL at the
921  * specified polling frequency.
922  *
923  * WARNING!  This thread runs *ALL* interrupt service routines that
924  * are not marked INTR_NOPOLL, which basically means everything except
925  * the 8254 clock interrupt and the ATA interrupt.  It has very high
926  * overhead and should only be used in situations where the machine
927  * cannot otherwise be made to work.  Due to the severe performance
928  * degredation, it should not be enabled on production machines.
929  */
930 static void
931 ithread_emergency(void *arg __unused)
932 {
933     globaldata_t gd = mycpu;
934     struct intr_info *info;
935     intrec_t rec, nrec;
936     int intr;
937     TD_INVARIANTS_DECLARE;
938
939     get_mplock();
940     crit_enter_gd(gd);
941     TD_INVARIANTS_GET(gd->gd_curthread);
942
943     for (;;) {
944         for (intr = 0; intr < max_installed_hard_intr; ++intr) {
945             info = &intr_info_ary[intr];
946             for (rec = info->i_reclist; rec; rec = nrec) {
947                 /* rec may be invalid after call */
948                 nrec = rec->next;
949                 if ((rec->intr_flags & INTR_NOPOLL) == 0) {
950                     if (rec->serializer) {
951                         lwkt_serialize_handler_try(rec->serializer,
952                                                 rec->handler, rec->argument, NULL);
953                     } else {
954                         rec->handler(rec->argument, NULL);
955                     }
956                     TD_INVARIANTS_TEST(gd->gd_curthread, rec->name);
957                 }
958             }
959         }
960         lwkt_deschedule_self(gd->gd_curthread);
961         lwkt_switch();
962     }
963     /* NOT REACHED */
964 }
965
966 /*
967  * Systimer callback - schedule the emergency interrupt poll thread
968  *                     if emergency polling is enabled.
969  */
970 static
971 void
972 emergency_intr_timer_callback(systimer_t info, int in_ipi __unused,
973     struct intrframe *frame __unused)
974 {
975     if (emergency_intr_enable)
976         lwkt_schedule(info->data);
977 }
978
979 int
980 ithread_cpuid(int intr)
981 {
982         const struct intr_info *info;
983
984         KKASSERT(intr >= 0 && intr < MAX_INTS);
985         info = &intr_info_ary[intr];
986
987         if (info->i_state == ISTATE_NOTHREAD)
988                 return -1;
989         return info->i_thread.td_gd->gd_cpuid;
990 }
991
992 /* 
993  * Sysctls used by systat and others: hw.intrnames and hw.intrcnt.
994  * The data for this machine dependent, and the declarations are in machine
995  * dependent code.  The layout of intrnames and intrcnt however is machine
996  * independent.
997  *
998  * We do not know the length of intrcnt and intrnames at compile time, so
999  * calculate things at run time.
1000  */
1001
1002 static int
1003 sysctl_intrnames(SYSCTL_HANDLER_ARGS)
1004 {
1005     struct intr_info *info;
1006     intrec_t rec;
1007     int error = 0;
1008     int len;
1009     int intr;
1010     char buf[64];
1011
1012     for (intr = 0; error == 0 && intr < MAX_INTS; ++intr) {
1013         info = &intr_info_ary[intr];
1014
1015         len = 0;
1016         buf[0] = 0;
1017         for (rec = info->i_reclist; rec; rec = rec->next) {
1018             ksnprintf(buf + len, sizeof(buf) - len, "%s%s", 
1019                 (len ? "/" : ""), rec->name);
1020             len += strlen(buf + len);
1021         }
1022         if (len == 0) {
1023             ksnprintf(buf, sizeof(buf), "irq%d", intr);
1024             len = strlen(buf);
1025         }
1026         error = SYSCTL_OUT(req, buf, len + 1);
1027     }
1028     return (error);
1029 }
1030
1031
1032 SYSCTL_PROC(_hw, OID_AUTO, intrnames, CTLTYPE_OPAQUE | CTLFLAG_RD,
1033         NULL, 0, sysctl_intrnames, "", "Interrupt Names");
1034
1035 static int
1036 sysctl_intrcnt(SYSCTL_HANDLER_ARGS)
1037 {
1038     struct intr_info *info;
1039     int error = 0;
1040     int intr;
1041
1042     for (intr = 0; intr < max_installed_hard_intr; ++intr) {
1043         info = &intr_info_ary[intr];
1044
1045         error = SYSCTL_OUT(req, &info->i_count, sizeof(info->i_count));
1046         if (error)
1047                 goto failed;
1048     }
1049     for (intr = FIRST_SOFTINT; intr < max_installed_soft_intr; ++intr) {
1050         info = &intr_info_ary[intr];
1051
1052         error = SYSCTL_OUT(req, &info->i_count, sizeof(info->i_count));
1053         if (error)
1054                 goto failed;
1055     }
1056 failed:
1057     return(error);
1058 }
1059
1060 SYSCTL_PROC(_hw, OID_AUTO, intrcnt, CTLTYPE_OPAQUE | CTLFLAG_RD,
1061         NULL, 0, sysctl_intrcnt, "", "Interrupt Counts");
1062
1063 static int
1064 sysctl_intrcnt_all(SYSCTL_HANDLER_ARGS)
1065 {
1066     struct intr_info *info;
1067     int error = 0;
1068     int intr;
1069
1070     for (intr = 0; intr < MAX_INTS; ++intr) {
1071         info = &intr_info_ary[intr];
1072
1073         error = SYSCTL_OUT(req, &info->i_count, sizeof(info->i_count));
1074         if (error)
1075                 goto failed;
1076     }
1077 failed:
1078     return(error);
1079 }
1080
1081 SYSCTL_PROC(_hw, OID_AUTO, intrcnt_all, CTLTYPE_OPAQUE | CTLFLAG_RD,
1082         NULL, 0, sysctl_intrcnt_all, "", "Interrupt Counts");
1083
1084 static void
1085 int_moveto_destcpu(int *orig_cpuid0, int cpuid)
1086 {
1087     int orig_cpuid = mycpuid;
1088
1089     if (cpuid != orig_cpuid)
1090         lwkt_migratecpu(cpuid);
1091
1092     *orig_cpuid0 = orig_cpuid;
1093 }
1094
1095 static void
1096 int_moveto_origcpu(int orig_cpuid, int cpuid)
1097 {
1098     if (cpuid != orig_cpuid)
1099         lwkt_migratecpu(orig_cpuid);
1100 }