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