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