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