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