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