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