xref: /freebsd/sys/kern/kern_intr.c (revision 39beb93c3f8bdbf72a61fda42300b5ebed7390c8)
1 /*-
2  * Copyright (c) 1997, Stefan Esser <se@freebsd.org>
3  * 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 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "opt_ddb.h"
31 
32 #include <sys/param.h>
33 #include <sys/bus.h>
34 #include <sys/conf.h>
35 #include <sys/cpuset.h>
36 #include <sys/rtprio.h>
37 #include <sys/systm.h>
38 #include <sys/interrupt.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
41 #include <sys/ktr.h>
42 #include <sys/limits.h>
43 #include <sys/lock.h>
44 #include <sys/malloc.h>
45 #include <sys/mutex.h>
46 #include <sys/proc.h>
47 #include <sys/random.h>
48 #include <sys/resourcevar.h>
49 #include <sys/sched.h>
50 #include <sys/smp.h>
51 #include <sys/sysctl.h>
52 #include <sys/syslog.h>
53 #include <sys/unistd.h>
54 #include <sys/vmmeter.h>
55 #include <machine/atomic.h>
56 #include <machine/cpu.h>
57 #include <machine/md_var.h>
58 #include <machine/stdarg.h>
59 #ifdef DDB
60 #include <ddb/ddb.h>
61 #include <ddb/db_sym.h>
62 #endif
63 
64 /*
65  * Describe an interrupt thread.  There is one of these per interrupt event.
66  */
67 struct intr_thread {
68 	struct intr_event *it_event;
69 	struct thread *it_thread;	/* Kernel thread. */
70 	int	it_flags;		/* (j) IT_* flags. */
71 	int	it_need;		/* Needs service. */
72 };
73 
74 /* Interrupt thread flags kept in it_flags */
75 #define	IT_DEAD		0x000001	/* Thread is waiting to exit. */
76 
77 struct	intr_entropy {
78 	struct	thread *td;
79 	uintptr_t event;
80 };
81 
82 struct	intr_event *clk_intr_event;
83 struct	intr_event *tty_intr_event;
84 void	*vm_ih;
85 struct proc *intrproc;
86 
87 static MALLOC_DEFINE(M_ITHREAD, "ithread", "Interrupt Threads");
88 
89 static int intr_storm_threshold = 1000;
90 TUNABLE_INT("hw.intr_storm_threshold", &intr_storm_threshold);
91 SYSCTL_INT(_hw, OID_AUTO, intr_storm_threshold, CTLFLAG_RW,
92     &intr_storm_threshold, 0,
93     "Number of consecutive interrupts before storm protection is enabled");
94 static TAILQ_HEAD(, intr_event) event_list =
95     TAILQ_HEAD_INITIALIZER(event_list);
96 static struct mtx event_lock;
97 MTX_SYSINIT(intr_event_list, &event_lock, "intr event list", MTX_DEF);
98 
99 static void	intr_event_update(struct intr_event *ie);
100 #ifdef INTR_FILTER
101 static int	intr_event_schedule_thread(struct intr_event *ie,
102 		    struct intr_thread *ithd);
103 static int	intr_filter_loop(struct intr_event *ie,
104 		    struct trapframe *frame, struct intr_thread **ithd);
105 static struct intr_thread *ithread_create(const char *name,
106 			      struct intr_handler *ih);
107 #else
108 static int	intr_event_schedule_thread(struct intr_event *ie);
109 static struct intr_thread *ithread_create(const char *name);
110 #endif
111 static void	ithread_destroy(struct intr_thread *ithread);
112 static void	ithread_execute_handlers(struct proc *p,
113 		    struct intr_event *ie);
114 #ifdef INTR_FILTER
115 static void	priv_ithread_execute_handler(struct proc *p,
116 		    struct intr_handler *ih);
117 #endif
118 static void	ithread_loop(void *);
119 static void	ithread_update(struct intr_thread *ithd);
120 static void	start_softintr(void *);
121 
122 /* Map an interrupt type to an ithread priority. */
123 u_char
124 intr_priority(enum intr_type flags)
125 {
126 	u_char pri;
127 
128 	flags &= (INTR_TYPE_TTY | INTR_TYPE_BIO | INTR_TYPE_NET |
129 	    INTR_TYPE_CAM | INTR_TYPE_MISC | INTR_TYPE_CLK | INTR_TYPE_AV);
130 	switch (flags) {
131 	case INTR_TYPE_TTY:
132 		pri = PI_TTYLOW;
133 		break;
134 	case INTR_TYPE_BIO:
135 		/*
136 		 * XXX We need to refine this.  BSD/OS distinguishes
137 		 * between tape and disk priorities.
138 		 */
139 		pri = PI_DISK;
140 		break;
141 	case INTR_TYPE_NET:
142 		pri = PI_NET;
143 		break;
144 	case INTR_TYPE_CAM:
145 		pri = PI_DISK;          /* XXX or PI_CAM? */
146 		break;
147 	case INTR_TYPE_AV:		/* Audio/video */
148 		pri = PI_AV;
149 		break;
150 	case INTR_TYPE_CLK:
151 		pri = PI_REALTIME;
152 		break;
153 	case INTR_TYPE_MISC:
154 		pri = PI_DULL;          /* don't care */
155 		break;
156 	default:
157 		/* We didn't specify an interrupt level. */
158 		panic("intr_priority: no interrupt type in flags");
159 	}
160 
161 	return pri;
162 }
163 
164 /*
165  * Update an ithread based on the associated intr_event.
166  */
167 static void
168 ithread_update(struct intr_thread *ithd)
169 {
170 	struct intr_event *ie;
171 	struct thread *td;
172 	u_char pri;
173 
174 	ie = ithd->it_event;
175 	td = ithd->it_thread;
176 
177 	/* Determine the overall priority of this event. */
178 	if (TAILQ_EMPTY(&ie->ie_handlers))
179 		pri = PRI_MAX_ITHD;
180 	else
181 		pri = TAILQ_FIRST(&ie->ie_handlers)->ih_pri;
182 
183 	/* Update name and priority. */
184 	strlcpy(td->td_name, ie->ie_fullname, sizeof(td->td_name));
185 	thread_lock(td);
186 	sched_prio(td, pri);
187 	thread_unlock(td);
188 }
189 
190 /*
191  * Regenerate the full name of an interrupt event and update its priority.
192  */
193 static void
194 intr_event_update(struct intr_event *ie)
195 {
196 	struct intr_handler *ih;
197 	char *last;
198 	int missed, space;
199 
200 	/* Start off with no entropy and just the name of the event. */
201 	mtx_assert(&ie->ie_lock, MA_OWNED);
202 	strlcpy(ie->ie_fullname, ie->ie_name, sizeof(ie->ie_fullname));
203 	ie->ie_flags &= ~IE_ENTROPY;
204 	missed = 0;
205 	space = 1;
206 
207 	/* Run through all the handlers updating values. */
208 	TAILQ_FOREACH(ih, &ie->ie_handlers, ih_next) {
209 		if (strlen(ie->ie_fullname) + strlen(ih->ih_name) + 1 <
210 		    sizeof(ie->ie_fullname)) {
211 			strcat(ie->ie_fullname, " ");
212 			strcat(ie->ie_fullname, ih->ih_name);
213 			space = 0;
214 		} else
215 			missed++;
216 		if (ih->ih_flags & IH_ENTROPY)
217 			ie->ie_flags |= IE_ENTROPY;
218 	}
219 
220 	/*
221 	 * If the handler names were too long, add +'s to indicate missing
222 	 * names. If we run out of room and still have +'s to add, change
223 	 * the last character from a + to a *.
224 	 */
225 	last = &ie->ie_fullname[sizeof(ie->ie_fullname) - 2];
226 	while (missed-- > 0) {
227 		if (strlen(ie->ie_fullname) + 1 == sizeof(ie->ie_fullname)) {
228 			if (*last == '+') {
229 				*last = '*';
230 				break;
231 			} else
232 				*last = '+';
233 		} else if (space) {
234 			strcat(ie->ie_fullname, " +");
235 			space = 0;
236 		} else
237 			strcat(ie->ie_fullname, "+");
238 	}
239 
240 	/*
241 	 * If this event has an ithread, update it's priority and
242 	 * name.
243 	 */
244 	if (ie->ie_thread != NULL)
245 		ithread_update(ie->ie_thread);
246 	CTR2(KTR_INTR, "%s: updated %s", __func__, ie->ie_fullname);
247 }
248 
249 int
250 intr_event_create(struct intr_event **event, void *source, int flags, int irq,
251     void (*pre_ithread)(void *), void (*post_ithread)(void *),
252     void (*post_filter)(void *), int (*assign_cpu)(void *, u_char),
253     const char *fmt, ...)
254 {
255 	struct intr_event *ie;
256 	va_list ap;
257 
258 	/* The only valid flag during creation is IE_SOFT. */
259 	if ((flags & ~IE_SOFT) != 0)
260 		return (EINVAL);
261 	ie = malloc(sizeof(struct intr_event), M_ITHREAD, M_WAITOK | M_ZERO);
262 	ie->ie_source = source;
263 	ie->ie_pre_ithread = pre_ithread;
264 	ie->ie_post_ithread = post_ithread;
265 	ie->ie_post_filter = post_filter;
266 	ie->ie_assign_cpu = assign_cpu;
267 	ie->ie_flags = flags;
268 	ie->ie_irq = irq;
269 	ie->ie_cpu = NOCPU;
270 	TAILQ_INIT(&ie->ie_handlers);
271 	mtx_init(&ie->ie_lock, "intr event", NULL, MTX_DEF);
272 
273 	va_start(ap, fmt);
274 	vsnprintf(ie->ie_name, sizeof(ie->ie_name), fmt, ap);
275 	va_end(ap);
276 	strlcpy(ie->ie_fullname, ie->ie_name, sizeof(ie->ie_fullname));
277 	mtx_lock(&event_lock);
278 	TAILQ_INSERT_TAIL(&event_list, ie, ie_list);
279 	mtx_unlock(&event_lock);
280 	if (event != NULL)
281 		*event = ie;
282 	CTR2(KTR_INTR, "%s: created %s", __func__, ie->ie_name);
283 	return (0);
284 }
285 
286 /*
287  * Bind an interrupt event to the specified CPU.  Note that not all
288  * platforms support binding an interrupt to a CPU.  For those
289  * platforms this request will fail.  For supported platforms, any
290  * associated ithreads as well as the primary interrupt context will
291  * be bound to the specificed CPU.  Using a cpu id of NOCPU unbinds
292  * the interrupt event.
293  */
294 int
295 intr_event_bind(struct intr_event *ie, u_char cpu)
296 {
297 	cpuset_t mask;
298 	lwpid_t id;
299 	int error;
300 
301 	/* Need a CPU to bind to. */
302 	if (cpu != NOCPU && CPU_ABSENT(cpu))
303 		return (EINVAL);
304 
305 	if (ie->ie_assign_cpu == NULL)
306 		return (EOPNOTSUPP);
307 	/*
308 	 * If we have any ithreads try to set their mask first since this
309 	 * can fail.
310 	 */
311 	mtx_lock(&ie->ie_lock);
312 	if (ie->ie_thread != NULL) {
313 		CPU_ZERO(&mask);
314 		if (cpu == NOCPU)
315 			CPU_COPY(cpuset_root, &mask);
316 		else
317 			CPU_SET(cpu, &mask);
318 		id = ie->ie_thread->it_thread->td_tid;
319 		mtx_unlock(&ie->ie_lock);
320 		error = cpuset_setthread(id, &mask);
321 		if (error)
322 			return (error);
323 	} else
324 		mtx_unlock(&ie->ie_lock);
325 	error = ie->ie_assign_cpu(ie->ie_source, cpu);
326 	if (error)
327 		return (error);
328 	mtx_lock(&ie->ie_lock);
329 	ie->ie_cpu = cpu;
330 	mtx_unlock(&ie->ie_lock);
331 
332 	return (error);
333 }
334 
335 static struct intr_event *
336 intr_lookup(int irq)
337 {
338 	struct intr_event *ie;
339 
340 	mtx_lock(&event_lock);
341 	TAILQ_FOREACH(ie, &event_list, ie_list)
342 		if (ie->ie_irq == irq &&
343 		    (ie->ie_flags & IE_SOFT) == 0 &&
344 		    TAILQ_FIRST(&ie->ie_handlers) != NULL)
345 			break;
346 	mtx_unlock(&event_lock);
347 	return (ie);
348 }
349 
350 int
351 intr_setaffinity(int irq, void *m)
352 {
353 	struct intr_event *ie;
354 	cpuset_t *mask;
355 	u_char cpu;
356 	int n;
357 
358 	mask = m;
359 	cpu = NOCPU;
360 	/*
361 	 * If we're setting all cpus we can unbind.  Otherwise make sure
362 	 * only one cpu is in the set.
363 	 */
364 	if (CPU_CMP(cpuset_root, mask)) {
365 		for (n = 0; n < CPU_SETSIZE; n++) {
366 			if (!CPU_ISSET(n, mask))
367 				continue;
368 			if (cpu != NOCPU)
369 				return (EINVAL);
370 			cpu = (u_char)n;
371 		}
372 	}
373 	ie = intr_lookup(irq);
374 	if (ie == NULL)
375 		return (ESRCH);
376 	intr_event_bind(ie, cpu);
377 	return (0);
378 }
379 
380 int
381 intr_getaffinity(int irq, void *m)
382 {
383 	struct intr_event *ie;
384 	cpuset_t *mask;
385 
386 	mask = m;
387 	ie = intr_lookup(irq);
388 	if (ie == NULL)
389 		return (ESRCH);
390 	CPU_ZERO(mask);
391 	mtx_lock(&ie->ie_lock);
392 	if (ie->ie_cpu == NOCPU)
393 		CPU_COPY(cpuset_root, mask);
394 	else
395 		CPU_SET(ie->ie_cpu, mask);
396 	mtx_unlock(&ie->ie_lock);
397 	return (0);
398 }
399 
400 int
401 intr_event_destroy(struct intr_event *ie)
402 {
403 
404 	mtx_lock(&event_lock);
405 	mtx_lock(&ie->ie_lock);
406 	if (!TAILQ_EMPTY(&ie->ie_handlers)) {
407 		mtx_unlock(&ie->ie_lock);
408 		mtx_unlock(&event_lock);
409 		return (EBUSY);
410 	}
411 	TAILQ_REMOVE(&event_list, ie, ie_list);
412 #ifndef notyet
413 	if (ie->ie_thread != NULL) {
414 		ithread_destroy(ie->ie_thread);
415 		ie->ie_thread = NULL;
416 	}
417 #endif
418 	mtx_unlock(&ie->ie_lock);
419 	mtx_unlock(&event_lock);
420 	mtx_destroy(&ie->ie_lock);
421 	free(ie, M_ITHREAD);
422 	return (0);
423 }
424 
425 #ifndef INTR_FILTER
426 static struct intr_thread *
427 ithread_create(const char *name)
428 {
429 	struct intr_thread *ithd;
430 	struct thread *td;
431 	int error;
432 
433 	ithd = malloc(sizeof(struct intr_thread), M_ITHREAD, M_WAITOK | M_ZERO);
434 
435 	error = kproc_kthread_add(ithread_loop, ithd, &intrproc,
436 		    &td, RFSTOPPED | RFHIGHPID,
437 	    	    0, "intr", "%s", name);
438 	if (error)
439 		panic("kproc_create() failed with %d", error);
440 	thread_lock(td);
441 	sched_class(td, PRI_ITHD);
442 	TD_SET_IWAIT(td);
443 	thread_unlock(td);
444 	td->td_pflags |= TDP_ITHREAD;
445 	ithd->it_thread = td;
446 	CTR2(KTR_INTR, "%s: created %s", __func__, name);
447 	return (ithd);
448 }
449 #else
450 static struct intr_thread *
451 ithread_create(const char *name, struct intr_handler *ih)
452 {
453 	struct intr_thread *ithd;
454 	struct thread *td;
455 	int error;
456 
457 	ithd = malloc(sizeof(struct intr_thread), M_ITHREAD, M_WAITOK | M_ZERO);
458 
459 	error = kproc_kthread_add(ithread_loop, ih, &intrproc,
460 		    &td, RFSTOPPED | RFHIGHPID,
461 	    	    0, "intr", "%s", name);
462 	if (error)
463 		panic("kproc_create() failed with %d", error);
464 	thread_lock(td);
465 	sched_class(td, PRI_ITHD);
466 	TD_SET_IWAIT(td);
467 	thread_unlock(td);
468 	td->td_pflags |= TDP_ITHREAD;
469 	ithd->it_thread = td;
470 	CTR2(KTR_INTR, "%s: created %s", __func__, name);
471 	return (ithd);
472 }
473 #endif
474 
475 static void
476 ithread_destroy(struct intr_thread *ithread)
477 {
478 	struct thread *td;
479 
480 	CTR2(KTR_INTR, "%s: killing %s", __func__, ithread->it_event->ie_name);
481 	td = ithread->it_thread;
482 	thread_lock(td);
483 	ithread->it_flags |= IT_DEAD;
484 	if (TD_AWAITING_INTR(td)) {
485 		TD_CLR_IWAIT(td);
486 		sched_add(td, SRQ_INTR);
487 	}
488 	thread_unlock(td);
489 }
490 
491 #ifndef INTR_FILTER
492 int
493 intr_event_add_handler(struct intr_event *ie, const char *name,
494     driver_filter_t filter, driver_intr_t handler, void *arg, u_char pri,
495     enum intr_type flags, void **cookiep)
496 {
497 	struct intr_handler *ih, *temp_ih;
498 	struct intr_thread *it;
499 
500 	if (ie == NULL || name == NULL || (handler == NULL && filter == NULL))
501 		return (EINVAL);
502 
503 	/* Allocate and populate an interrupt handler structure. */
504 	ih = malloc(sizeof(struct intr_handler), M_ITHREAD, M_WAITOK | M_ZERO);
505 	ih->ih_filter = filter;
506 	ih->ih_handler = handler;
507 	ih->ih_argument = arg;
508 	ih->ih_name = name;
509 	ih->ih_event = ie;
510 	ih->ih_pri = pri;
511 	if (flags & INTR_EXCL)
512 		ih->ih_flags = IH_EXCLUSIVE;
513 	if (flags & INTR_MPSAFE)
514 		ih->ih_flags |= IH_MPSAFE;
515 	if (flags & INTR_ENTROPY)
516 		ih->ih_flags |= IH_ENTROPY;
517 
518 	/* We can only have one exclusive handler in a event. */
519 	mtx_lock(&ie->ie_lock);
520 	if (!TAILQ_EMPTY(&ie->ie_handlers)) {
521 		if ((flags & INTR_EXCL) ||
522 		    (TAILQ_FIRST(&ie->ie_handlers)->ih_flags & IH_EXCLUSIVE)) {
523 			mtx_unlock(&ie->ie_lock);
524 			free(ih, M_ITHREAD);
525 			return (EINVAL);
526 		}
527 	}
528 
529 	/* Add the new handler to the event in priority order. */
530 	TAILQ_FOREACH(temp_ih, &ie->ie_handlers, ih_next) {
531 		if (temp_ih->ih_pri > ih->ih_pri)
532 			break;
533 	}
534 	if (temp_ih == NULL)
535 		TAILQ_INSERT_TAIL(&ie->ie_handlers, ih, ih_next);
536 	else
537 		TAILQ_INSERT_BEFORE(temp_ih, ih, ih_next);
538 	intr_event_update(ie);
539 
540 	/* Create a thread if we need one. */
541 	while (ie->ie_thread == NULL && handler != NULL) {
542 		if (ie->ie_flags & IE_ADDING_THREAD)
543 			msleep(ie, &ie->ie_lock, 0, "ithread", 0);
544 		else {
545 			ie->ie_flags |= IE_ADDING_THREAD;
546 			mtx_unlock(&ie->ie_lock);
547 			it = ithread_create("intr: newborn");
548 			mtx_lock(&ie->ie_lock);
549 			ie->ie_flags &= ~IE_ADDING_THREAD;
550 			ie->ie_thread = it;
551 			it->it_event = ie;
552 			ithread_update(it);
553 			wakeup(ie);
554 		}
555 	}
556 	CTR3(KTR_INTR, "%s: added %s to %s", __func__, ih->ih_name,
557 	    ie->ie_name);
558 	mtx_unlock(&ie->ie_lock);
559 
560 	if (cookiep != NULL)
561 		*cookiep = ih;
562 	return (0);
563 }
564 #else
565 int
566 intr_event_add_handler(struct intr_event *ie, const char *name,
567     driver_filter_t filter, driver_intr_t handler, void *arg, u_char pri,
568     enum intr_type flags, void **cookiep)
569 {
570 	struct intr_handler *ih, *temp_ih;
571 	struct intr_thread *it;
572 
573 	if (ie == NULL || name == NULL || (handler == NULL && filter == NULL))
574 		return (EINVAL);
575 
576 	/* Allocate and populate an interrupt handler structure. */
577 	ih = malloc(sizeof(struct intr_handler), M_ITHREAD, M_WAITOK | M_ZERO);
578 	ih->ih_filter = filter;
579 	ih->ih_handler = handler;
580 	ih->ih_argument = arg;
581 	ih->ih_name = name;
582 	ih->ih_event = ie;
583 	ih->ih_pri = pri;
584 	if (flags & INTR_EXCL)
585 		ih->ih_flags = IH_EXCLUSIVE;
586 	if (flags & INTR_MPSAFE)
587 		ih->ih_flags |= IH_MPSAFE;
588 	if (flags & INTR_ENTROPY)
589 		ih->ih_flags |= IH_ENTROPY;
590 
591 	/* We can only have one exclusive handler in a event. */
592 	mtx_lock(&ie->ie_lock);
593 	if (!TAILQ_EMPTY(&ie->ie_handlers)) {
594 		if ((flags & INTR_EXCL) ||
595 		    (TAILQ_FIRST(&ie->ie_handlers)->ih_flags & IH_EXCLUSIVE)) {
596 			mtx_unlock(&ie->ie_lock);
597 			free(ih, M_ITHREAD);
598 			return (EINVAL);
599 		}
600 	}
601 
602 	/* Add the new handler to the event in priority order. */
603 	TAILQ_FOREACH(temp_ih, &ie->ie_handlers, ih_next) {
604 		if (temp_ih->ih_pri > ih->ih_pri)
605 			break;
606 	}
607 	if (temp_ih == NULL)
608 		TAILQ_INSERT_TAIL(&ie->ie_handlers, ih, ih_next);
609 	else
610 		TAILQ_INSERT_BEFORE(temp_ih, ih, ih_next);
611 	intr_event_update(ie);
612 
613 	/* For filtered handlers, create a private ithread to run on. */
614 	if (filter != NULL && handler != NULL) {
615 		mtx_unlock(&ie->ie_lock);
616 		it = ithread_create("intr: newborn", ih);
617 		mtx_lock(&ie->ie_lock);
618 		it->it_event = ie;
619 		ih->ih_thread = it;
620 		ithread_update(it); // XXX - do we really need this?!?!?
621 	} else { /* Create the global per-event thread if we need one. */
622 		while (ie->ie_thread == NULL && handler != NULL) {
623 			if (ie->ie_flags & IE_ADDING_THREAD)
624 				msleep(ie, &ie->ie_lock, 0, "ithread", 0);
625 			else {
626 				ie->ie_flags |= IE_ADDING_THREAD;
627 				mtx_unlock(&ie->ie_lock);
628 				it = ithread_create("intr: newborn", ih);
629 				mtx_lock(&ie->ie_lock);
630 				ie->ie_flags &= ~IE_ADDING_THREAD;
631 				ie->ie_thread = it;
632 				it->it_event = ie;
633 				ithread_update(it);
634 				wakeup(ie);
635 			}
636 		}
637 	}
638 	CTR3(KTR_INTR, "%s: added %s to %s", __func__, ih->ih_name,
639 	    ie->ie_name);
640 	mtx_unlock(&ie->ie_lock);
641 
642 	if (cookiep != NULL)
643 		*cookiep = ih;
644 	return (0);
645 }
646 #endif
647 
648 /*
649  * Return the ie_source field from the intr_event an intr_handler is
650  * associated with.
651  */
652 void *
653 intr_handler_source(void *cookie)
654 {
655 	struct intr_handler *ih;
656 	struct intr_event *ie;
657 
658 	ih = (struct intr_handler *)cookie;
659 	if (ih == NULL)
660 		return (NULL);
661 	ie = ih->ih_event;
662 	KASSERT(ie != NULL,
663 	    ("interrupt handler \"%s\" has a NULL interrupt event",
664 	    ih->ih_name));
665 	return (ie->ie_source);
666 }
667 
668 #ifndef INTR_FILTER
669 int
670 intr_event_remove_handler(void *cookie)
671 {
672 	struct intr_handler *handler = (struct intr_handler *)cookie;
673 	struct intr_event *ie;
674 #ifdef INVARIANTS
675 	struct intr_handler *ih;
676 #endif
677 #ifdef notyet
678 	int dead;
679 #endif
680 
681 	if (handler == NULL)
682 		return (EINVAL);
683 	ie = handler->ih_event;
684 	KASSERT(ie != NULL,
685 	    ("interrupt handler \"%s\" has a NULL interrupt event",
686 	    handler->ih_name));
687 	mtx_lock(&ie->ie_lock);
688 	CTR3(KTR_INTR, "%s: removing %s from %s", __func__, handler->ih_name,
689 	    ie->ie_name);
690 #ifdef INVARIANTS
691 	TAILQ_FOREACH(ih, &ie->ie_handlers, ih_next)
692 		if (ih == handler)
693 			goto ok;
694 	mtx_unlock(&ie->ie_lock);
695 	panic("interrupt handler \"%s\" not found in interrupt event \"%s\"",
696 	    ih->ih_name, ie->ie_name);
697 ok:
698 #endif
699 	/*
700 	 * If there is no ithread, then just remove the handler and return.
701 	 * XXX: Note that an INTR_FAST handler might be running on another
702 	 * CPU!
703 	 */
704 	if (ie->ie_thread == NULL) {
705 		TAILQ_REMOVE(&ie->ie_handlers, handler, ih_next);
706 		mtx_unlock(&ie->ie_lock);
707 		free(handler, M_ITHREAD);
708 		return (0);
709 	}
710 
711 	/*
712 	 * If the interrupt thread is already running, then just mark this
713 	 * handler as being dead and let the ithread do the actual removal.
714 	 *
715 	 * During a cold boot while cold is set, msleep() does not sleep,
716 	 * so we have to remove the handler here rather than letting the
717 	 * thread do it.
718 	 */
719 	thread_lock(ie->ie_thread->it_thread);
720 	if (!TD_AWAITING_INTR(ie->ie_thread->it_thread) && !cold) {
721 		handler->ih_flags |= IH_DEAD;
722 
723 		/*
724 		 * Ensure that the thread will process the handler list
725 		 * again and remove this handler if it has already passed
726 		 * it on the list.
727 		 */
728 		ie->ie_thread->it_need = 1;
729 	} else
730 		TAILQ_REMOVE(&ie->ie_handlers, handler, ih_next);
731 	thread_unlock(ie->ie_thread->it_thread);
732 	while (handler->ih_flags & IH_DEAD)
733 		msleep(handler, &ie->ie_lock, 0, "iev_rmh", 0);
734 	intr_event_update(ie);
735 #ifdef notyet
736 	/*
737 	 * XXX: This could be bad in the case of ppbus(8).  Also, I think
738 	 * this could lead to races of stale data when servicing an
739 	 * interrupt.
740 	 */
741 	dead = 1;
742 	TAILQ_FOREACH(ih, &ie->ie_handlers, ih_next) {
743 		if (!(ih->ih_flags & IH_FAST)) {
744 			dead = 0;
745 			break;
746 		}
747 	}
748 	if (dead) {
749 		ithread_destroy(ie->ie_thread);
750 		ie->ie_thread = NULL;
751 	}
752 #endif
753 	mtx_unlock(&ie->ie_lock);
754 	free(handler, M_ITHREAD);
755 	return (0);
756 }
757 
758 static int
759 intr_event_schedule_thread(struct intr_event *ie)
760 {
761 	struct intr_entropy entropy;
762 	struct intr_thread *it;
763 	struct thread *td;
764 	struct thread *ctd;
765 	struct proc *p;
766 
767 	/*
768 	 * If no ithread or no handlers, then we have a stray interrupt.
769 	 */
770 	if (ie == NULL || TAILQ_EMPTY(&ie->ie_handlers) ||
771 	    ie->ie_thread == NULL)
772 		return (EINVAL);
773 
774 	ctd = curthread;
775 	it = ie->ie_thread;
776 	td = it->it_thread;
777 	p = td->td_proc;
778 
779 	/*
780 	 * If any of the handlers for this ithread claim to be good
781 	 * sources of entropy, then gather some.
782 	 */
783 	if (harvest.interrupt && ie->ie_flags & IE_ENTROPY) {
784 		CTR3(KTR_INTR, "%s: pid %d (%s) gathering entropy", __func__,
785 		    p->p_pid, td->td_name);
786 		entropy.event = (uintptr_t)ie;
787 		entropy.td = ctd;
788 		random_harvest(&entropy, sizeof(entropy), 2, 0,
789 		    RANDOM_INTERRUPT);
790 	}
791 
792 	KASSERT(p != NULL, ("ithread %s has no process", ie->ie_name));
793 
794 	/*
795 	 * Set it_need to tell the thread to keep running if it is already
796 	 * running.  Then, lock the thread and see if we actually need to
797 	 * put it on the runqueue.
798 	 */
799 	it->it_need = 1;
800 	thread_lock(td);
801 	if (TD_AWAITING_INTR(td)) {
802 		CTR3(KTR_INTR, "%s: schedule pid %d (%s)", __func__, p->p_pid,
803 		    td->td_name);
804 		TD_CLR_IWAIT(td);
805 		sched_add(td, SRQ_INTR);
806 	} else {
807 		CTR5(KTR_INTR, "%s: pid %d (%s): it_need %d, state %d",
808 		    __func__, p->p_pid, td->td_name, it->it_need, td->td_state);
809 	}
810 	thread_unlock(td);
811 
812 	return (0);
813 }
814 #else
815 int
816 intr_event_remove_handler(void *cookie)
817 {
818 	struct intr_handler *handler = (struct intr_handler *)cookie;
819 	struct intr_event *ie;
820 	struct intr_thread *it;
821 #ifdef INVARIANTS
822 	struct intr_handler *ih;
823 #endif
824 #ifdef notyet
825 	int dead;
826 #endif
827 
828 	if (handler == NULL)
829 		return (EINVAL);
830 	ie = handler->ih_event;
831 	KASSERT(ie != NULL,
832 	    ("interrupt handler \"%s\" has a NULL interrupt event",
833 	    handler->ih_name));
834 	mtx_lock(&ie->ie_lock);
835 	CTR3(KTR_INTR, "%s: removing %s from %s", __func__, handler->ih_name,
836 	    ie->ie_name);
837 #ifdef INVARIANTS
838 	TAILQ_FOREACH(ih, &ie->ie_handlers, ih_next)
839 		if (ih == handler)
840 			goto ok;
841 	mtx_unlock(&ie->ie_lock);
842 	panic("interrupt handler \"%s\" not found in interrupt event \"%s\"",
843 	    ih->ih_name, ie->ie_name);
844 ok:
845 #endif
846 	/*
847 	 * If there are no ithreads (per event and per handler), then
848 	 * just remove the handler and return.
849 	 * XXX: Note that an INTR_FAST handler might be running on another CPU!
850 	 */
851 	if (ie->ie_thread == NULL && handler->ih_thread == NULL) {
852 		TAILQ_REMOVE(&ie->ie_handlers, handler, ih_next);
853 		mtx_unlock(&ie->ie_lock);
854 		free(handler, M_ITHREAD);
855 		return (0);
856 	}
857 
858 	/* Private or global ithread? */
859 	it = (handler->ih_thread) ? handler->ih_thread : ie->ie_thread;
860 	/*
861 	 * If the interrupt thread is already running, then just mark this
862 	 * handler as being dead and let the ithread do the actual removal.
863 	 *
864 	 * During a cold boot while cold is set, msleep() does not sleep,
865 	 * so we have to remove the handler here rather than letting the
866 	 * thread do it.
867 	 */
868 	thread_lock(it->it_thread);
869 	if (!TD_AWAITING_INTR(it->it_thread) && !cold) {
870 		handler->ih_flags |= IH_DEAD;
871 
872 		/*
873 		 * Ensure that the thread will process the handler list
874 		 * again and remove this handler if it has already passed
875 		 * it on the list.
876 		 */
877 		it->it_need = 1;
878 	} else
879 		TAILQ_REMOVE(&ie->ie_handlers, handler, ih_next);
880 	thread_unlock(it->it_thread);
881 	while (handler->ih_flags & IH_DEAD)
882 		msleep(handler, &ie->ie_lock, 0, "iev_rmh", 0);
883 	/*
884 	 * At this point, the handler has been disconnected from the event,
885 	 * so we can kill the private ithread if any.
886 	 */
887 	if (handler->ih_thread) {
888 		ithread_destroy(handler->ih_thread);
889 		handler->ih_thread = NULL;
890 	}
891 	intr_event_update(ie);
892 #ifdef notyet
893 	/*
894 	 * XXX: This could be bad in the case of ppbus(8).  Also, I think
895 	 * this could lead to races of stale data when servicing an
896 	 * interrupt.
897 	 */
898 	dead = 1;
899 	TAILQ_FOREACH(ih, &ie->ie_handlers, ih_next) {
900 		if (handler != NULL) {
901 			dead = 0;
902 			break;
903 		}
904 	}
905 	if (dead) {
906 		ithread_destroy(ie->ie_thread);
907 		ie->ie_thread = NULL;
908 	}
909 #endif
910 	mtx_unlock(&ie->ie_lock);
911 	free(handler, M_ITHREAD);
912 	return (0);
913 }
914 
915 static int
916 intr_event_schedule_thread(struct intr_event *ie, struct intr_thread *it)
917 {
918 	struct intr_entropy entropy;
919 	struct thread *td;
920 	struct thread *ctd;
921 	struct proc *p;
922 
923 	/*
924 	 * If no ithread or no handlers, then we have a stray interrupt.
925 	 */
926 	if (ie == NULL || TAILQ_EMPTY(&ie->ie_handlers) || it == NULL)
927 		return (EINVAL);
928 
929 	ctd = curthread;
930 	td = it->it_thread;
931 	p = td->td_proc;
932 
933 	/*
934 	 * If any of the handlers for this ithread claim to be good
935 	 * sources of entropy, then gather some.
936 	 */
937 	if (harvest.interrupt && ie->ie_flags & IE_ENTROPY) {
938 		CTR3(KTR_INTR, "%s: pid %d (%s) gathering entropy", __func__,
939 		    p->p_pid, td->td_name);
940 		entropy.event = (uintptr_t)ie;
941 		entropy.td = ctd;
942 		random_harvest(&entropy, sizeof(entropy), 2, 0,
943 		    RANDOM_INTERRUPT);
944 	}
945 
946 	KASSERT(p != NULL, ("ithread %s has no process", ie->ie_name));
947 
948 	/*
949 	 * Set it_need to tell the thread to keep running if it is already
950 	 * running.  Then, lock the thread and see if we actually need to
951 	 * put it on the runqueue.
952 	 */
953 	it->it_need = 1;
954 	thread_lock(td);
955 	if (TD_AWAITING_INTR(td)) {
956 		CTR3(KTR_INTR, "%s: schedule pid %d (%s)", __func__, p->p_pid,
957 		    td->td_name);
958 		TD_CLR_IWAIT(td);
959 		sched_add(td, SRQ_INTR);
960 	} else {
961 		CTR5(KTR_INTR, "%s: pid %d (%s): it_need %d, state %d",
962 		    __func__, p->p_pid, td->td_name, it->it_need, td->td_state);
963 	}
964 	thread_unlock(td);
965 
966 	return (0);
967 }
968 #endif
969 
970 /*
971  * Add a software interrupt handler to a specified event.  If a given event
972  * is not specified, then a new event is created.
973  */
974 int
975 swi_add(struct intr_event **eventp, const char *name, driver_intr_t handler,
976 	    void *arg, int pri, enum intr_type flags, void **cookiep)
977 {
978 	struct intr_event *ie;
979 	int error;
980 
981 	if (flags & INTR_ENTROPY)
982 		return (EINVAL);
983 
984 	ie = (eventp != NULL) ? *eventp : NULL;
985 
986 	if (ie != NULL) {
987 		if (!(ie->ie_flags & IE_SOFT))
988 			return (EINVAL);
989 	} else {
990 		error = intr_event_create(&ie, NULL, IE_SOFT, 0,
991 		    NULL, NULL, NULL, NULL, "swi%d:", pri);
992 		if (error)
993 			return (error);
994 		if (eventp != NULL)
995 			*eventp = ie;
996 	}
997 	error = intr_event_add_handler(ie, name, NULL, handler, arg,
998 	    (pri * RQ_PPQ) + PI_SOFT, flags, cookiep);
999 	if (error)
1000 		return (error);
1001 	if (pri == SWI_CLOCK) {
1002 		struct proc *p;
1003 		p = ie->ie_thread->it_thread->td_proc;
1004 		PROC_LOCK(p);
1005 		p->p_flag |= P_NOLOAD;
1006 		PROC_UNLOCK(p);
1007 	}
1008 	return (0);
1009 }
1010 
1011 /*
1012  * Schedule a software interrupt thread.
1013  */
1014 void
1015 swi_sched(void *cookie, int flags)
1016 {
1017 	struct intr_handler *ih = (struct intr_handler *)cookie;
1018 	struct intr_event *ie = ih->ih_event;
1019 	int error;
1020 
1021 	CTR3(KTR_INTR, "swi_sched: %s %s need=%d", ie->ie_name, ih->ih_name,
1022 	    ih->ih_need);
1023 
1024 	/*
1025 	 * Set ih_need for this handler so that if the ithread is already
1026 	 * running it will execute this handler on the next pass.  Otherwise,
1027 	 * it will execute it the next time it runs.
1028 	 */
1029 	atomic_store_rel_int(&ih->ih_need, 1);
1030 
1031 	if (!(flags & SWI_DELAY)) {
1032 		PCPU_INC(cnt.v_soft);
1033 #ifdef INTR_FILTER
1034 		error = intr_event_schedule_thread(ie, ie->ie_thread);
1035 #else
1036 		error = intr_event_schedule_thread(ie);
1037 #endif
1038 		KASSERT(error == 0, ("stray software interrupt"));
1039 	}
1040 }
1041 
1042 /*
1043  * Remove a software interrupt handler.  Currently this code does not
1044  * remove the associated interrupt event if it becomes empty.  Calling code
1045  * may do so manually via intr_event_destroy(), but that's not really
1046  * an optimal interface.
1047  */
1048 int
1049 swi_remove(void *cookie)
1050 {
1051 
1052 	return (intr_event_remove_handler(cookie));
1053 }
1054 
1055 #ifdef INTR_FILTER
1056 static void
1057 priv_ithread_execute_handler(struct proc *p, struct intr_handler *ih)
1058 {
1059 	struct intr_event *ie;
1060 
1061 	ie = ih->ih_event;
1062 	/*
1063 	 * If this handler is marked for death, remove it from
1064 	 * the list of handlers and wake up the sleeper.
1065 	 */
1066 	if (ih->ih_flags & IH_DEAD) {
1067 		mtx_lock(&ie->ie_lock);
1068 		TAILQ_REMOVE(&ie->ie_handlers, ih, ih_next);
1069 		ih->ih_flags &= ~IH_DEAD;
1070 		wakeup(ih);
1071 		mtx_unlock(&ie->ie_lock);
1072 		return;
1073 	}
1074 
1075 	/* Execute this handler. */
1076 	CTR6(KTR_INTR, "%s: pid %d exec %p(%p) for %s flg=%x",
1077 	     __func__, p->p_pid, (void *)ih->ih_handler, ih->ih_argument,
1078 	     ih->ih_name, ih->ih_flags);
1079 
1080 	if (!(ih->ih_flags & IH_MPSAFE))
1081 		mtx_lock(&Giant);
1082 	ih->ih_handler(ih->ih_argument);
1083 	if (!(ih->ih_flags & IH_MPSAFE))
1084 		mtx_unlock(&Giant);
1085 }
1086 #endif
1087 
1088 /*
1089  * This is a public function for use by drivers that mux interrupt
1090  * handlers for child devices from their interrupt handler.
1091  */
1092 void
1093 intr_event_execute_handlers(struct proc *p, struct intr_event *ie)
1094 {
1095 	struct intr_handler *ih, *ihn;
1096 
1097 	TAILQ_FOREACH_SAFE(ih, &ie->ie_handlers, ih_next, ihn) {
1098 		/*
1099 		 * If this handler is marked for death, remove it from
1100 		 * the list of handlers and wake up the sleeper.
1101 		 */
1102 		if (ih->ih_flags & IH_DEAD) {
1103 			mtx_lock(&ie->ie_lock);
1104 			TAILQ_REMOVE(&ie->ie_handlers, ih, ih_next);
1105 			ih->ih_flags &= ~IH_DEAD;
1106 			wakeup(ih);
1107 			mtx_unlock(&ie->ie_lock);
1108 			continue;
1109 		}
1110 
1111 		/* Skip filter only handlers */
1112 		if (ih->ih_handler == NULL)
1113 			continue;
1114 
1115 		/*
1116 		 * For software interrupt threads, we only execute
1117 		 * handlers that have their need flag set.  Hardware
1118 		 * interrupt threads always invoke all of their handlers.
1119 		 */
1120 		if (ie->ie_flags & IE_SOFT) {
1121 			if (!ih->ih_need)
1122 				continue;
1123 			else
1124 				atomic_store_rel_int(&ih->ih_need, 0);
1125 		}
1126 
1127 		/* Execute this handler. */
1128 		CTR6(KTR_INTR, "%s: pid %d exec %p(%p) for %s flg=%x",
1129 		    __func__, p->p_pid, (void *)ih->ih_handler,
1130 		    ih->ih_argument, ih->ih_name, ih->ih_flags);
1131 
1132 		if (!(ih->ih_flags & IH_MPSAFE))
1133 			mtx_lock(&Giant);
1134 		ih->ih_handler(ih->ih_argument);
1135 		if (!(ih->ih_flags & IH_MPSAFE))
1136 			mtx_unlock(&Giant);
1137 	}
1138 }
1139 
1140 static void
1141 ithread_execute_handlers(struct proc *p, struct intr_event *ie)
1142 {
1143 
1144 	/* Interrupt handlers should not sleep. */
1145 	if (!(ie->ie_flags & IE_SOFT))
1146 		THREAD_NO_SLEEPING();
1147 	intr_event_execute_handlers(p, ie);
1148 	if (!(ie->ie_flags & IE_SOFT))
1149 		THREAD_SLEEPING_OK();
1150 
1151 	/*
1152 	 * Interrupt storm handling:
1153 	 *
1154 	 * If this interrupt source is currently storming, then throttle
1155 	 * it to only fire the handler once  per clock tick.
1156 	 *
1157 	 * If this interrupt source is not currently storming, but the
1158 	 * number of back to back interrupts exceeds the storm threshold,
1159 	 * then enter storming mode.
1160 	 */
1161 	if (intr_storm_threshold != 0 && ie->ie_count >= intr_storm_threshold &&
1162 	    !(ie->ie_flags & IE_SOFT)) {
1163 		/* Report the message only once every second. */
1164 		if (ppsratecheck(&ie->ie_warntm, &ie->ie_warncnt, 1)) {
1165 			printf(
1166 	"interrupt storm detected on \"%s\"; throttling interrupt source\n",
1167 			    ie->ie_name);
1168 		}
1169 		pause("istorm", 1);
1170 	} else
1171 		ie->ie_count++;
1172 
1173 	/*
1174 	 * Now that all the handlers have had a chance to run, reenable
1175 	 * the interrupt source.
1176 	 */
1177 	if (ie->ie_post_ithread != NULL)
1178 		ie->ie_post_ithread(ie->ie_source);
1179 }
1180 
1181 #ifndef INTR_FILTER
1182 /*
1183  * This is the main code for interrupt threads.
1184  */
1185 static void
1186 ithread_loop(void *arg)
1187 {
1188 	struct intr_thread *ithd;
1189 	struct intr_event *ie;
1190 	struct thread *td;
1191 	struct proc *p;
1192 
1193 	td = curthread;
1194 	p = td->td_proc;
1195 	ithd = (struct intr_thread *)arg;
1196 	KASSERT(ithd->it_thread == td,
1197 	    ("%s: ithread and proc linkage out of sync", __func__));
1198 	ie = ithd->it_event;
1199 	ie->ie_count = 0;
1200 
1201 	/*
1202 	 * As long as we have interrupts outstanding, go through the
1203 	 * list of handlers, giving each one a go at it.
1204 	 */
1205 	for (;;) {
1206 		/*
1207 		 * If we are an orphaned thread, then just die.
1208 		 */
1209 		if (ithd->it_flags & IT_DEAD) {
1210 			CTR3(KTR_INTR, "%s: pid %d (%s) exiting", __func__,
1211 			    p->p_pid, td->td_name);
1212 			free(ithd, M_ITHREAD);
1213 			kthread_exit();
1214 		}
1215 
1216 		/*
1217 		 * Service interrupts.  If another interrupt arrives while
1218 		 * we are running, it will set it_need to note that we
1219 		 * should make another pass.
1220 		 */
1221 		while (ithd->it_need) {
1222 			/*
1223 			 * This might need a full read and write barrier
1224 			 * to make sure that this write posts before any
1225 			 * of the memory or device accesses in the
1226 			 * handlers.
1227 			 */
1228 			atomic_store_rel_int(&ithd->it_need, 0);
1229 			ithread_execute_handlers(p, ie);
1230 		}
1231 		WITNESS_WARN(WARN_PANIC, NULL, "suspending ithread");
1232 		mtx_assert(&Giant, MA_NOTOWNED);
1233 
1234 		/*
1235 		 * Processed all our interrupts.  Now get the sched
1236 		 * lock.  This may take a while and it_need may get
1237 		 * set again, so we have to check it again.
1238 		 */
1239 		thread_lock(td);
1240 		if (!ithd->it_need && !(ithd->it_flags & IT_DEAD)) {
1241 			TD_SET_IWAIT(td);
1242 			ie->ie_count = 0;
1243 			mi_switch(SW_VOL | SWT_IWAIT, NULL);
1244 		}
1245 		thread_unlock(td);
1246 	}
1247 }
1248 
1249 /*
1250  * Main interrupt handling body.
1251  *
1252  * Input:
1253  * o ie:                        the event connected to this interrupt.
1254  * o frame:                     some archs (i.e. i386) pass a frame to some.
1255  *                              handlers as their main argument.
1256  * Return value:
1257  * o 0:                         everything ok.
1258  * o EINVAL:                    stray interrupt.
1259  */
1260 int
1261 intr_event_handle(struct intr_event *ie, struct trapframe *frame)
1262 {
1263 	struct intr_handler *ih;
1264 	struct thread *td;
1265 	int error, ret, thread;
1266 
1267 	td = curthread;
1268 
1269 	/* An interrupt with no event or handlers is a stray interrupt. */
1270 	if (ie == NULL || TAILQ_EMPTY(&ie->ie_handlers))
1271 		return (EINVAL);
1272 
1273 	/*
1274 	 * Execute fast interrupt handlers directly.
1275 	 * To support clock handlers, if a handler registers
1276 	 * with a NULL argument, then we pass it a pointer to
1277 	 * a trapframe as its argument.
1278 	 */
1279 	td->td_intr_nesting_level++;
1280 	thread = 0;
1281 	ret = 0;
1282 	critical_enter();
1283 	TAILQ_FOREACH(ih, &ie->ie_handlers, ih_next) {
1284 		if (ih->ih_filter == NULL) {
1285 			thread = 1;
1286 			continue;
1287 		}
1288 		CTR4(KTR_INTR, "%s: exec %p(%p) for %s", __func__,
1289 		    ih->ih_filter, ih->ih_argument == NULL ? frame :
1290 		    ih->ih_argument, ih->ih_name);
1291 		if (ih->ih_argument == NULL)
1292 			ret = ih->ih_filter(frame);
1293 		else
1294 			ret = ih->ih_filter(ih->ih_argument);
1295 		/*
1296 		 * Wrapper handler special handling:
1297 		 *
1298 		 * in some particular cases (like pccard and pccbb),
1299 		 * the _real_ device handler is wrapped in a couple of
1300 		 * functions - a filter wrapper and an ithread wrapper.
1301 		 * In this case (and just in this case), the filter wrapper
1302 		 * could ask the system to schedule the ithread and mask
1303 		 * the interrupt source if the wrapped handler is composed
1304 		 * of just an ithread handler.
1305 		 *
1306 		 * TODO: write a generic wrapper to avoid people rolling
1307 		 * their own
1308 		 */
1309 		if (!thread) {
1310 			if (ret == FILTER_SCHEDULE_THREAD)
1311 				thread = 1;
1312 		}
1313 	}
1314 
1315 	if (thread) {
1316 		if (ie->ie_pre_ithread != NULL)
1317 			ie->ie_pre_ithread(ie->ie_source);
1318 	} else {
1319 		if (ie->ie_post_filter != NULL)
1320 			ie->ie_post_filter(ie->ie_source);
1321 	}
1322 
1323 	/* Schedule the ithread if needed. */
1324 	if (thread) {
1325 		error = intr_event_schedule_thread(ie);
1326 #ifndef XEN
1327 		KASSERT(error == 0, ("bad stray interrupt"));
1328 #else
1329 		if (error != 0)
1330 			log(LOG_WARNING, "bad stray interrupt");
1331 #endif
1332 	}
1333 	critical_exit();
1334 	td->td_intr_nesting_level--;
1335 	return (0);
1336 }
1337 #else
1338 /*
1339  * This is the main code for interrupt threads.
1340  */
1341 static void
1342 ithread_loop(void *arg)
1343 {
1344 	struct intr_thread *ithd;
1345 	struct intr_handler *ih;
1346 	struct intr_event *ie;
1347 	struct thread *td;
1348 	struct proc *p;
1349 	int priv;
1350 
1351 	td = curthread;
1352 	p = td->td_proc;
1353 	ih = (struct intr_handler *)arg;
1354 	priv = (ih->ih_thread != NULL) ? 1 : 0;
1355 	ithd = (priv) ? ih->ih_thread : ih->ih_event->ie_thread;
1356 	KASSERT(ithd->it_thread == td,
1357 	    ("%s: ithread and proc linkage out of sync", __func__));
1358 	ie = ithd->it_event;
1359 	ie->ie_count = 0;
1360 
1361 	/*
1362 	 * As long as we have interrupts outstanding, go through the
1363 	 * list of handlers, giving each one a go at it.
1364 	 */
1365 	for (;;) {
1366 		/*
1367 		 * If we are an orphaned thread, then just die.
1368 		 */
1369 		if (ithd->it_flags & IT_DEAD) {
1370 			CTR3(KTR_INTR, "%s: pid %d (%s) exiting", __func__,
1371 			    p->p_pid, td->td_name);
1372 			free(ithd, M_ITHREAD);
1373 			kthread_exit();
1374 		}
1375 
1376 		/*
1377 		 * Service interrupts.  If another interrupt arrives while
1378 		 * we are running, it will set it_need to note that we
1379 		 * should make another pass.
1380 		 */
1381 		while (ithd->it_need) {
1382 			/*
1383 			 * This might need a full read and write barrier
1384 			 * to make sure that this write posts before any
1385 			 * of the memory or device accesses in the
1386 			 * handlers.
1387 			 */
1388 			atomic_store_rel_int(&ithd->it_need, 0);
1389 			if (priv)
1390 				priv_ithread_execute_handler(p, ih);
1391 			else
1392 				ithread_execute_handlers(p, ie);
1393 		}
1394 		WITNESS_WARN(WARN_PANIC, NULL, "suspending ithread");
1395 		mtx_assert(&Giant, MA_NOTOWNED);
1396 
1397 		/*
1398 		 * Processed all our interrupts.  Now get the sched
1399 		 * lock.  This may take a while and it_need may get
1400 		 * set again, so we have to check it again.
1401 		 */
1402 		thread_lock(td);
1403 		if (!ithd->it_need && !(ithd->it_flags & IT_DEAD)) {
1404 			TD_SET_IWAIT(td);
1405 			ie->ie_count = 0;
1406 			mi_switch(SW_VOL | SWT_IWAIT, NULL);
1407 		}
1408 		thread_unlock(td);
1409 	}
1410 }
1411 
1412 /*
1413  * Main loop for interrupt filter.
1414  *
1415  * Some architectures (i386, amd64 and arm) require the optional frame
1416  * parameter, and use it as the main argument for fast handler execution
1417  * when ih_argument == NULL.
1418  *
1419  * Return value:
1420  * o FILTER_STRAY:              No filter recognized the event, and no
1421  *                              filter-less handler is registered on this
1422  *                              line.
1423  * o FILTER_HANDLED:            A filter claimed the event and served it.
1424  * o FILTER_SCHEDULE_THREAD:    No filter claimed the event, but there's at
1425  *                              least one filter-less handler on this line.
1426  * o FILTER_HANDLED |
1427  *   FILTER_SCHEDULE_THREAD:    A filter claimed the event, and asked for
1428  *                              scheduling the per-handler ithread.
1429  *
1430  * In case an ithread has to be scheduled, in *ithd there will be a
1431  * pointer to a struct intr_thread containing the thread to be
1432  * scheduled.
1433  */
1434 
1435 static int
1436 intr_filter_loop(struct intr_event *ie, struct trapframe *frame,
1437 		 struct intr_thread **ithd)
1438 {
1439 	struct intr_handler *ih;
1440 	void *arg;
1441 	int ret, thread_only;
1442 
1443 	ret = 0;
1444 	thread_only = 0;
1445 	TAILQ_FOREACH(ih, &ie->ie_handlers, ih_next) {
1446 		/*
1447 		 * Execute fast interrupt handlers directly.
1448 		 * To support clock handlers, if a handler registers
1449 		 * with a NULL argument, then we pass it a pointer to
1450 		 * a trapframe as its argument.
1451 		 */
1452 		arg = ((ih->ih_argument == NULL) ? frame : ih->ih_argument);
1453 
1454 		CTR5(KTR_INTR, "%s: exec %p/%p(%p) for %s", __func__,
1455 		     ih->ih_filter, ih->ih_handler, arg, ih->ih_name);
1456 
1457 		if (ih->ih_filter != NULL)
1458 			ret = ih->ih_filter(arg);
1459 		else {
1460 			thread_only = 1;
1461 			continue;
1462 		}
1463 
1464 		if (ret & FILTER_STRAY)
1465 			continue;
1466 		else {
1467 			*ithd = ih->ih_thread;
1468 			return (ret);
1469 		}
1470 	}
1471 
1472 	/*
1473 	 * No filters handled the interrupt and we have at least
1474 	 * one handler without a filter.  In this case, we schedule
1475 	 * all of the filter-less handlers to run in the ithread.
1476 	 */
1477 	if (thread_only) {
1478 		*ithd = ie->ie_thread;
1479 		return (FILTER_SCHEDULE_THREAD);
1480 	}
1481 	return (FILTER_STRAY);
1482 }
1483 
1484 /*
1485  * Main interrupt handling body.
1486  *
1487  * Input:
1488  * o ie:                        the event connected to this interrupt.
1489  * o frame:                     some archs (i.e. i386) pass a frame to some.
1490  *                              handlers as their main argument.
1491  * Return value:
1492  * o 0:                         everything ok.
1493  * o EINVAL:                    stray interrupt.
1494  */
1495 int
1496 intr_event_handle(struct intr_event *ie, struct trapframe *frame)
1497 {
1498 	struct intr_thread *ithd;
1499 	struct thread *td;
1500 	int thread;
1501 
1502 	ithd = NULL;
1503 	td = curthread;
1504 
1505 	if (ie == NULL || TAILQ_EMPTY(&ie->ie_handlers))
1506 		return (EINVAL);
1507 
1508 	td->td_intr_nesting_level++;
1509 	thread = 0;
1510 	critical_enter();
1511 	thread = intr_filter_loop(ie, frame, &ithd);
1512 	if (thread & FILTER_HANDLED) {
1513 		if (ie->ie_post_filter != NULL)
1514 			ie->ie_post_filter(ie->ie_source);
1515 	} else {
1516 		if (ie->ie_pre_ithread != NULL)
1517 			ie->ie_pre_ithread(ie->ie_source);
1518 	}
1519 	critical_exit();
1520 
1521 	/* Interrupt storm logic */
1522 	if (thread & FILTER_STRAY) {
1523 		ie->ie_count++;
1524 		if (ie->ie_count < intr_storm_threshold)
1525 			printf("Interrupt stray detection not present\n");
1526 	}
1527 
1528 	/* Schedule an ithread if needed. */
1529 	if (thread & FILTER_SCHEDULE_THREAD) {
1530 		if (intr_event_schedule_thread(ie, ithd) != 0)
1531 			panic("%s: impossible stray interrupt", __func__);
1532 	}
1533 	td->td_intr_nesting_level--;
1534 	return (0);
1535 }
1536 #endif
1537 
1538 #ifdef DDB
1539 /*
1540  * Dump details about an interrupt handler
1541  */
1542 static void
1543 db_dump_intrhand(struct intr_handler *ih)
1544 {
1545 	int comma;
1546 
1547 	db_printf("\t%-10s ", ih->ih_name);
1548 	switch (ih->ih_pri) {
1549 	case PI_REALTIME:
1550 		db_printf("CLK ");
1551 		break;
1552 	case PI_AV:
1553 		db_printf("AV  ");
1554 		break;
1555 	case PI_TTYHIGH:
1556 	case PI_TTYLOW:
1557 		db_printf("TTY ");
1558 		break;
1559 	case PI_TAPE:
1560 		db_printf("TAPE");
1561 		break;
1562 	case PI_NET:
1563 		db_printf("NET ");
1564 		break;
1565 	case PI_DISK:
1566 	case PI_DISKLOW:
1567 		db_printf("DISK");
1568 		break;
1569 	case PI_DULL:
1570 		db_printf("DULL");
1571 		break;
1572 	default:
1573 		if (ih->ih_pri >= PI_SOFT)
1574 			db_printf("SWI ");
1575 		else
1576 			db_printf("%4u", ih->ih_pri);
1577 		break;
1578 	}
1579 	db_printf(" ");
1580 	db_printsym((uintptr_t)ih->ih_handler, DB_STGY_PROC);
1581 	db_printf("(%p)", ih->ih_argument);
1582 	if (ih->ih_need ||
1583 	    (ih->ih_flags & (IH_EXCLUSIVE | IH_ENTROPY | IH_DEAD |
1584 	    IH_MPSAFE)) != 0) {
1585 		db_printf(" {");
1586 		comma = 0;
1587 		if (ih->ih_flags & IH_EXCLUSIVE) {
1588 			if (comma)
1589 				db_printf(", ");
1590 			db_printf("EXCL");
1591 			comma = 1;
1592 		}
1593 		if (ih->ih_flags & IH_ENTROPY) {
1594 			if (comma)
1595 				db_printf(", ");
1596 			db_printf("ENTROPY");
1597 			comma = 1;
1598 		}
1599 		if (ih->ih_flags & IH_DEAD) {
1600 			if (comma)
1601 				db_printf(", ");
1602 			db_printf("DEAD");
1603 			comma = 1;
1604 		}
1605 		if (ih->ih_flags & IH_MPSAFE) {
1606 			if (comma)
1607 				db_printf(", ");
1608 			db_printf("MPSAFE");
1609 			comma = 1;
1610 		}
1611 		if (ih->ih_need) {
1612 			if (comma)
1613 				db_printf(", ");
1614 			db_printf("NEED");
1615 		}
1616 		db_printf("}");
1617 	}
1618 	db_printf("\n");
1619 }
1620 
1621 /*
1622  * Dump details about a event.
1623  */
1624 void
1625 db_dump_intr_event(struct intr_event *ie, int handlers)
1626 {
1627 	struct intr_handler *ih;
1628 	struct intr_thread *it;
1629 	int comma;
1630 
1631 	db_printf("%s ", ie->ie_fullname);
1632 	it = ie->ie_thread;
1633 	if (it != NULL)
1634 		db_printf("(pid %d)", it->it_thread->td_proc->p_pid);
1635 	else
1636 		db_printf("(no thread)");
1637 	if ((ie->ie_flags & (IE_SOFT | IE_ENTROPY | IE_ADDING_THREAD)) != 0 ||
1638 	    (it != NULL && it->it_need)) {
1639 		db_printf(" {");
1640 		comma = 0;
1641 		if (ie->ie_flags & IE_SOFT) {
1642 			db_printf("SOFT");
1643 			comma = 1;
1644 		}
1645 		if (ie->ie_flags & IE_ENTROPY) {
1646 			if (comma)
1647 				db_printf(", ");
1648 			db_printf("ENTROPY");
1649 			comma = 1;
1650 		}
1651 		if (ie->ie_flags & IE_ADDING_THREAD) {
1652 			if (comma)
1653 				db_printf(", ");
1654 			db_printf("ADDING_THREAD");
1655 			comma = 1;
1656 		}
1657 		if (it != NULL && it->it_need) {
1658 			if (comma)
1659 				db_printf(", ");
1660 			db_printf("NEED");
1661 		}
1662 		db_printf("}");
1663 	}
1664 	db_printf("\n");
1665 
1666 	if (handlers)
1667 		TAILQ_FOREACH(ih, &ie->ie_handlers, ih_next)
1668 		    db_dump_intrhand(ih);
1669 }
1670 
1671 /*
1672  * Dump data about interrupt handlers
1673  */
1674 DB_SHOW_COMMAND(intr, db_show_intr)
1675 {
1676 	struct intr_event *ie;
1677 	int all, verbose;
1678 
1679 	verbose = index(modif, 'v') != NULL;
1680 	all = index(modif, 'a') != NULL;
1681 	TAILQ_FOREACH(ie, &event_list, ie_list) {
1682 		if (!all && TAILQ_EMPTY(&ie->ie_handlers))
1683 			continue;
1684 		db_dump_intr_event(ie, verbose);
1685 		if (db_pager_quit)
1686 			break;
1687 	}
1688 }
1689 #endif /* DDB */
1690 
1691 /*
1692  * Start standard software interrupt threads
1693  */
1694 static void
1695 start_softintr(void *dummy)
1696 {
1697 
1698 	if (swi_add(NULL, "vm", swi_vm, NULL, SWI_VM, INTR_MPSAFE, &vm_ih))
1699 		panic("died while creating vm swi ithread");
1700 }
1701 SYSINIT(start_softintr, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softintr,
1702     NULL);
1703 
1704 /*
1705  * Sysctls used by systat and others: hw.intrnames and hw.intrcnt.
1706  * The data for this machine dependent, and the declarations are in machine
1707  * dependent code.  The layout of intrnames and intrcnt however is machine
1708  * independent.
1709  *
1710  * We do not know the length of intrcnt and intrnames at compile time, so
1711  * calculate things at run time.
1712  */
1713 static int
1714 sysctl_intrnames(SYSCTL_HANDLER_ARGS)
1715 {
1716 	return (sysctl_handle_opaque(oidp, intrnames, eintrnames - intrnames,
1717 	   req));
1718 }
1719 
1720 SYSCTL_PROC(_hw, OID_AUTO, intrnames, CTLTYPE_OPAQUE | CTLFLAG_RD,
1721     NULL, 0, sysctl_intrnames, "", "Interrupt Names");
1722 
1723 static int
1724 sysctl_intrcnt(SYSCTL_HANDLER_ARGS)
1725 {
1726 	return (sysctl_handle_opaque(oidp, intrcnt,
1727 	    (char *)eintrcnt - (char *)intrcnt, req));
1728 }
1729 
1730 SYSCTL_PROC(_hw, OID_AUTO, intrcnt, CTLTYPE_OPAQUE | CTLFLAG_RD,
1731     NULL, 0, sysctl_intrcnt, "", "Interrupt Counts");
1732 
1733 #ifdef DDB
1734 /*
1735  * DDB command to dump the interrupt statistics.
1736  */
1737 DB_SHOW_COMMAND(intrcnt, db_show_intrcnt)
1738 {
1739 	u_long *i;
1740 	char *cp;
1741 
1742 	cp = intrnames;
1743 	for (i = intrcnt; i != eintrcnt && !db_pager_quit; i++) {
1744 		if (*cp == '\0')
1745 			break;
1746 		if (*i != 0)
1747 			db_printf("%s\t%lu\n", cp, *i);
1748 		cp += strlen(cp) + 1;
1749 	}
1750 }
1751 #endif
1752