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