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