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