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