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