Merge from vendor branch CVS:
[dragonfly.git] / sys / i386 / isa / intr_machdep.c
1 /*-
2  * Copyright (c) 1991 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * William Jolitz.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following 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  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *      from: @(#)isa.c 7.2 (Berkeley) 5/13/91
37  * $FreeBSD: src/sys/i386/isa/intr_machdep.c,v 1.29.2.5 2001/10/14 06:54:27 luigi Exp $
38  * $DragonFly: src/sys/i386/isa/Attic/intr_machdep.c,v 1.30 2005/06/11 09:03:49 swildner Exp $
39  */
40 /*
41  * This file contains an aggregated module marked:
42  * Copyright (c) 1997, Stefan Esser <se@freebsd.org>
43  * All rights reserved.
44  * See the notice for details.
45  */
46
47 #include "use_isa.h"
48 #include "opt_auto_eoi.h"
49
50 #include <sys/param.h>
51 #ifndef SMP
52 #include <machine/lock.h>
53 #endif
54 #include <sys/systm.h>
55 #include <sys/syslog.h>
56 #include <sys/malloc.h>
57 #include <sys/errno.h>
58 #include <sys/interrupt.h>
59 #include <machine/ipl.h>
60 #include <machine/md_var.h>
61 #include <machine/segments.h>
62 #include <sys/bus.h> 
63 #include <machine/globaldata.h>
64 #include <sys/proc.h>
65 #include <sys/thread2.h>
66
67 #include <machine/smptests.h>                   /** FAST_HI */
68 #include <machine/smp.h>
69 #include <bus/isa/i386/isa.h>
70 #include <i386/isa/icu.h>
71
72 #if NISA > 0
73 #include <bus/isa/isavar.h>
74 #endif
75 #include <i386/isa/intr_machdep.h>
76 #include <bus/isa/isavar.h>
77 #include <sys/interrupt.h>
78 #ifdef APIC_IO
79 #include <machine/clock.h>
80 #endif
81 #include <machine/cpu.h>
82
83 /* XXX should be in suitable include files */
84 #define ICU_IMR_OFFSET          1               /* IO_ICU{1,2} + 1 */
85 #define ICU_SLAVEID                     2
86
87 #ifdef APIC_IO
88 /*
89  * This is to accommodate "mixed-mode" programming for 
90  * motherboards that don't connect the 8254 to the IO APIC.
91  */
92 #define AUTO_EOI_1      1
93 #endif
94
95 #define NR_INTRNAMES    (1 + ICU_LEN + 2 * ICU_LEN)
96
97 static inthand2_t isa_strayintr;
98 #if defined(FAST_HI) && defined(APIC_IO)
99 static inthand2_t isa_wrongintr;
100 #endif
101 static void     init_i8259(void);
102
103 void    *intr_unit[ICU_LEN*2];
104 u_long  *intr_countp[ICU_LEN*2];
105 inthand2_t *intr_handler[ICU_LEN*2] = {
106         isa_strayintr, isa_strayintr, isa_strayintr, isa_strayintr,
107         isa_strayintr, isa_strayintr, isa_strayintr, isa_strayintr,
108         isa_strayintr, isa_strayintr, isa_strayintr, isa_strayintr,
109         isa_strayintr, isa_strayintr, isa_strayintr, isa_strayintr,
110         isa_strayintr, isa_strayintr, isa_strayintr, isa_strayintr,
111         isa_strayintr, isa_strayintr, isa_strayintr, isa_strayintr,
112         isa_strayintr, isa_strayintr, isa_strayintr, isa_strayintr,
113         isa_strayintr, isa_strayintr, isa_strayintr, isa_strayintr,
114 };
115
116 static struct md_intr_info {
117     int         irq;
118     u_int       mask;
119     int         mihandler_installed;
120     u_int       *maskp;
121 } intr_info[ICU_LEN*2];
122
123 static inthand_t *fastintr[ICU_LEN] = {
124         &IDTVEC(fastintr0), &IDTVEC(fastintr1),
125         &IDTVEC(fastintr2), &IDTVEC(fastintr3),
126         &IDTVEC(fastintr4), &IDTVEC(fastintr5),
127         &IDTVEC(fastintr6), &IDTVEC(fastintr7),
128         &IDTVEC(fastintr8), &IDTVEC(fastintr9),
129         &IDTVEC(fastintr10), &IDTVEC(fastintr11),
130         &IDTVEC(fastintr12), &IDTVEC(fastintr13),
131         &IDTVEC(fastintr14), &IDTVEC(fastintr15),
132 #if defined(APIC_IO)
133         &IDTVEC(fastintr16), &IDTVEC(fastintr17),
134         &IDTVEC(fastintr18), &IDTVEC(fastintr19),
135         &IDTVEC(fastintr20), &IDTVEC(fastintr21),
136         &IDTVEC(fastintr22), &IDTVEC(fastintr23),
137 #endif /* APIC_IO */
138 };
139
140 unpendhand_t *fastunpend[ICU_LEN] = {
141         IDTVEC(fastunpend0), IDTVEC(fastunpend1),
142         IDTVEC(fastunpend2), IDTVEC(fastunpend3),
143         IDTVEC(fastunpend4), IDTVEC(fastunpend5),
144         IDTVEC(fastunpend6), IDTVEC(fastunpend7),
145         IDTVEC(fastunpend8), IDTVEC(fastunpend9),
146         IDTVEC(fastunpend10), IDTVEC(fastunpend11),
147         IDTVEC(fastunpend12), IDTVEC(fastunpend13),
148         IDTVEC(fastunpend14), IDTVEC(fastunpend15),
149 #if defined(APIC_IO)
150         IDTVEC(fastunpend16), IDTVEC(fastunpend17),
151         IDTVEC(fastunpend18), IDTVEC(fastunpend19),
152         IDTVEC(fastunpend20), IDTVEC(fastunpend21),
153         IDTVEC(fastunpend22), IDTVEC(fastunpend23),
154 #endif
155 };
156
157 static inthand_t *slowintr[ICU_LEN] = {
158         &IDTVEC(intr0), &IDTVEC(intr1), &IDTVEC(intr2), &IDTVEC(intr3),
159         &IDTVEC(intr4), &IDTVEC(intr5), &IDTVEC(intr6), &IDTVEC(intr7),
160         &IDTVEC(intr8), &IDTVEC(intr9), &IDTVEC(intr10), &IDTVEC(intr11),
161         &IDTVEC(intr12), &IDTVEC(intr13), &IDTVEC(intr14), &IDTVEC(intr15),
162 #if defined(APIC_IO)
163         &IDTVEC(intr16), &IDTVEC(intr17), &IDTVEC(intr18), &IDTVEC(intr19),
164         &IDTVEC(intr20), &IDTVEC(intr21), &IDTVEC(intr22), &IDTVEC(intr23),
165 #endif /* APIC_IO */
166 };
167
168 #define NMI_PARITY (1 << 7)
169 #define NMI_IOCHAN (1 << 6)
170 #define ENMI_WATCHDOG (1 << 7)
171 #define ENMI_BUSTIMER (1 << 6)
172 #define ENMI_IOSTATUS (1 << 5)
173
174 /*
175  * Handle a NMI, possibly a machine check.
176  * return true to panic system, false to ignore.
177  */
178 int
179 isa_nmi(cd)
180         int cd;
181 {
182         int retval = 0;
183         int isa_port = inb(0x61);
184         int eisa_port = inb(0x461);
185
186         log(LOG_CRIT, "NMI ISA %x, EISA %x\n", isa_port, eisa_port);
187         
188         if (isa_port & NMI_PARITY) {
189                 log(LOG_CRIT, "RAM parity error, likely hardware failure.");
190                 retval = 1;
191         }
192
193         if (isa_port & NMI_IOCHAN) {
194                 log(LOG_CRIT, "I/O channel check, likely hardware failure.");
195                 retval = 1;
196         }
197
198         /*
199          * On a real EISA machine, this will never happen.  However it can
200          * happen on ISA machines which implement XT style floating point
201          * error handling (very rare).  Save them from a meaningless panic.
202          */
203         if (eisa_port == 0xff)
204                 return(retval);
205
206         if (eisa_port & ENMI_WATCHDOG) {
207                 log(LOG_CRIT, "EISA watchdog timer expired, likely hardware failure.");
208                 retval = 1;
209         }
210
211         if (eisa_port & ENMI_BUSTIMER) {
212                 log(LOG_CRIT, "EISA bus timeout, likely hardware failure.");
213                 retval = 1;
214         }
215
216         if (eisa_port & ENMI_IOSTATUS) {
217                 log(LOG_CRIT, "EISA I/O port status error.");
218                 retval = 1;
219         }
220         return(retval);
221 }
222
223 /*
224  *  ICU reinitialize when ICU configuration has lost.
225  */
226 void
227 icu_reinit()
228 {
229        int i;
230
231        init_i8259();
232        for(i=0;i<ICU_LEN;i++)
233                if(intr_handler[i] != isa_strayintr)
234                        INTREN(1<<i);
235 }
236
237
238 /*
239  * Fill in default interrupt table (in case of spurious interrupt
240  * during configuration of kernel, setup interrupt control unit
241  */
242 void
243 isa_defaultirq()
244 {
245         int i;
246
247         /* icu vectors */
248         for (i = 0; i < ICU_LEN; i++)
249                 icu_unset(i, isa_strayintr);
250         init_i8259();
251 }
252
253 static void
254 init_i8259(void)
255 {
256
257         /* initialize 8259's */
258         outb(IO_ICU1, 0x11);            /* reset; program device, four bytes */
259         outb(IO_ICU1+ICU_IMR_OFFSET, NRSVIDT);  /* starting at this vector index */
260         outb(IO_ICU1+ICU_IMR_OFFSET, IRQ_SLAVE);                /* slave on line 7 */
261 #ifdef AUTO_EOI_1
262         outb(IO_ICU1+ICU_IMR_OFFSET, 2 | 1);            /* auto EOI, 8086 mode */
263 #else
264         outb(IO_ICU1+ICU_IMR_OFFSET, 1);                /* 8086 mode */
265 #endif
266         outb(IO_ICU1+ICU_IMR_OFFSET, 0xff);             /* leave interrupts masked */
267         outb(IO_ICU1, 0x0a);            /* default to IRR on read */
268         outb(IO_ICU1, 0xc0 | (3 - 1));  /* pri order 3-7, 0-2 (com2 first) */
269         outb(IO_ICU2, 0x11);            /* reset; program device, four bytes */
270         outb(IO_ICU2+ICU_IMR_OFFSET, NRSVIDT+8); /* staring at this vector index */
271         outb(IO_ICU2+ICU_IMR_OFFSET, ICU_SLAVEID);         /* my slave id is 7 */
272 #ifdef AUTO_EOI_2
273         outb(IO_ICU2+ICU_IMR_OFFSET, 2 | 1);            /* auto EOI, 8086 mode */
274 #else
275         outb(IO_ICU2+ICU_IMR_OFFSET,1);         /* 8086 mode */
276 #endif
277         outb(IO_ICU2+ICU_IMR_OFFSET, 0xff);          /* leave interrupts masked */
278         outb(IO_ICU2, 0x0a);            /* default to IRR on read */
279 }
280
281 /*
282  * Caught a stray interrupt, notify
283  */
284 static void
285 isa_strayintr(void *vcookiep)
286 {
287         int intr = (void **)vcookiep - &intr_unit[0];
288
289         /* DON'T BOTHER FOR NOW! */
290         /* for some reason, we get bursts of intr #7, even if not enabled! */
291         /*
292          * Well the reason you got bursts of intr #7 is because someone
293          * raised an interrupt line and dropped it before the 8259 could
294          * prioritize it.  This is documented in the intel data book.  This
295          * means you have BAD hardware!  I have changed this so that only
296          * the first 5 get logged, then it quits logging them, and puts
297          * out a special message. rgrimes 3/25/1993
298          */
299         /*
300          * XXX TODO print a different message for #7 if it is for a
301          * glitch.  Glitches can be distinguished from real #7's by
302          * testing that the in-service bit is _not_ set.  The test
303          * must be done before sending an EOI so it can't be done if
304          * we are using AUTO_EOI_1.
305          */
306         if (intrcnt[1 + intr] <= 5)
307                 log(LOG_ERR, "stray irq %d\n", intr);
308         if (intrcnt[1 + intr] == 5)
309                 log(LOG_CRIT,
310                     "too many stray irq %d's; not logging any more\n", intr);
311 }
312
313 #if defined(FAST_HI) && defined(APIC_IO)
314
315 /*
316  * This occurs if we mis-programmed the APIC and its vector is still
317  * pointing to the slow vector even when we thought we reprogrammed it
318  * to the high vector.  This can occur when interrupts are improperly
319  * routed by the APIC.  The unit data is opaque so we have to try to
320  * find it in the unit array.
321  */
322 static void
323 isa_wrongintr(void *vcookiep)
324 {
325         int intr;
326
327         for (intr = 0; intr < ICU_LEN*2; ++intr) {
328                 if (intr_unit[intr] == vcookiep)
329                         break;
330         }
331         if (intr == ICU_LEN*2) {
332                 log(LOG_ERR, "stray unknown irq (APIC misprogrammed)\n");
333         } else if (intrcnt[1 + intr] <= 5) {
334                 log(LOG_ERR, "stray irq ~%d (APIC misprogrammed)\n", intr);
335         } else if (intrcnt[1 + intr] == 6) {
336                 log(LOG_CRIT,
337                     "too many stray irq ~%d's; not logging any more\n", intr);
338         }
339 }
340
341 #endif
342
343 #if NISA > 0
344 /*
345  * Return a bitmap of the current interrupt requests.  This is 8259-specific
346  * and is only suitable for use at probe time.
347  */
348 intrmask_t
349 isa_irq_pending(void)
350 {
351         u_char irr1;
352         u_char irr2;
353
354         irr1 = inb(IO_ICU1);
355         irr2 = inb(IO_ICU2);
356         return ((irr2 << 8) | irr1);
357 }
358 #endif
359
360 int
361 update_intr_masks(void)
362 {
363         int intr, n=0;
364         u_int mask,*maskptr;
365
366         for (intr=0; intr < ICU_LEN; intr ++) {
367 #if defined(APIC_IO)
368                 /* no 8259 SLAVE to ignore */
369 #else
370                 if (intr==ICU_SLAVEID) continue;        /* ignore 8259 SLAVE output */
371 #endif /* APIC_IO */
372                 maskptr = intr_info[intr].maskp;
373                 if (!maskptr)
374                         continue;
375                 *maskptr |= SWI_CLOCK_MASK | (1 << intr);
376                 mask = *maskptr;
377                 if (mask != intr_info[intr].mask) {
378 #if 0
379                         printf ("intr_mask[%2d] old=%08x new=%08x ptr=%p.\n",
380                                 intr, intr_info[intr].mask, mask, maskptr);
381 #endif
382                         intr_info[intr].mask = mask;
383                         n++;
384                 }
385
386         }
387         return (n);
388 }
389
390 static void
391 update_intrname(int intr, char *name)
392 {
393         char buf[32];
394         char *cp;
395         int name_index, off, strayintr;
396
397         /*
398          * Initialise strings for bitbucket and stray interrupt counters.
399          * These have statically allocated indices 0 and 1 through ICU_LEN.
400          */
401         if (intrnames[0] == '\0') {
402                 off = sprintf(intrnames, "???") + 1;
403                 for (strayintr = 0; strayintr < ICU_LEN; strayintr++)
404                         off += sprintf(intrnames + off, "stray irq%d",
405                             strayintr) + 1;
406         }
407
408         if (name == NULL)
409                 name = "???";
410         if (snprintf(buf, sizeof(buf), "%s irq%d", name, intr) >= sizeof(buf))
411                 goto use_bitbucket;
412
413         /*
414          * Search for `buf' in `intrnames'.  In the usual case when it is
415          * not found, append it to the end if there is enough space (the \0
416          * terminator for the previous string, if any, becomes a separator).
417          */
418         for (cp = intrnames, name_index = 0;
419             cp != eintrnames && name_index < NR_INTRNAMES;
420             cp += strlen(cp) + 1, name_index++) {
421                 if (*cp == '\0') {
422                         if (strlen(buf) >= eintrnames - cp)
423                                 break;
424                         strcpy(cp, buf);
425                         goto found;
426                 }
427                 if (strcmp(cp, buf) == 0)
428                         goto found;
429         }
430
431 use_bitbucket:
432         printf("update_intrname: counting %s irq%d as %s\n", name, intr,
433             intrnames);
434         name_index = 0;
435 found:
436         intr_countp[intr] = &intrcnt[name_index];
437 }
438
439 /*
440  * NOTE!  intr_handler[] is only used for FAST interrupts, the *vector.s
441  * code ignores it for normal interrupts.
442  */
443 int
444 icu_setup(int intr, inthand2_t *handler, void *arg, u_int *maskptr, int flags)
445 {
446 #if defined(FAST_HI) && defined(APIC_IO)
447         int             select;         /* the select register is 8 bits */
448         int             vector;
449         u_int32_t       value;          /* the window register is 32 bits */
450 #endif /* FAST_HI */
451         u_long  ef;
452         u_int   mask = (maskptr ? *maskptr : 0);
453
454 #if defined(APIC_IO)
455         if ((u_int)intr >= ICU_LEN)     /* no 8259 SLAVE to ignore */
456 #else
457         if ((u_int)intr >= ICU_LEN || intr == ICU_SLAVEID)
458 #endif /* APIC_IO */
459                 return (EINVAL);
460         if (intr_handler[intr] != isa_strayintr)
461                 return (EBUSY);
462
463         ef = read_eflags();
464         cpu_disable_intr();     /* YYY */
465         intr_handler[intr] = handler;
466         intr_unit[intr] = arg;
467         intr_info[intr].maskp = maskptr;
468         intr_info[intr].mask = mask | SWI_CLOCK_MASK | (1 << intr);
469 #if 0
470         /* YYY  fast ints supported and mp protected but ... */
471         flags &= ~INTR_FAST;
472 #endif
473 #if defined(FAST_HI) && defined(APIC_IO)
474         if (flags & INTR_FAST) {
475                 /*
476                  * Install a spurious interrupt in the low space in case
477                  * the IO apic is not properly reprogrammed.
478                  */
479                 vector = TPR_SLOW_INTS + intr;
480                 setidt(vector, isa_wrongintr,
481                        SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
482                 vector = TPR_FAST_INTS + intr;
483                 setidt(vector, fastintr[intr],
484                        SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
485         } else {
486                 vector = TPR_SLOW_INTS + intr;
487 #ifdef APIC_INTR_REORDER
488 #ifdef APIC_INTR_HIGHPRI_CLOCK
489                 /* XXX: Hack (kludge?) for more accurate clock. */
490                 if (intr == apic_8254_intr || intr == 8) {
491                         vector = TPR_FAST_INTS + intr;
492                 }
493 #endif
494 #endif
495                 setidt(vector, slowintr[intr],
496                        SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
497         }
498 #ifdef APIC_INTR_REORDER
499         set_lapic_isrloc(intr, vector);
500 #endif
501         /*
502          * Reprogram the vector in the IO APIC.
503          *
504          * XXX EOI/mask a pending (stray) interrupt on the old vector?
505          */
506         if (int_to_apicintpin[intr].ioapic >= 0) {
507                 select = int_to_apicintpin[intr].redirindex;
508                 value = io_apic_read(int_to_apicintpin[intr].ioapic, 
509                                      select) & ~IOART_INTVEC;
510                 io_apic_write(int_to_apicintpin[intr].ioapic, 
511                               select, value | vector);
512         }
513 #else
514         setidt(ICU_OFFSET + intr,
515                flags & INTR_FAST ? fastintr[intr] : slowintr[intr],
516                SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
517 #endif /* FAST_HI && APIC_IO */
518         INTREN(1 << intr);
519         write_eflags(ef);
520         return (0);
521 }
522
523 int
524 icu_unset(intr, handler)
525         int     intr;
526         inthand2_t *handler;
527 {
528         u_long  ef;
529
530         if ((u_int)intr >= ICU_LEN || handler != intr_handler[intr]) {
531                 printf("icu_unset: invalid handler %d %p/%p\n", intr, handler, 
532                     (((u_int)intr >= ICU_LEN) ? (void *)-1 : intr_handler[intr]));
533                 return (EINVAL);
534         }
535
536         INTRDIS(1 << intr);
537         ef = read_eflags();
538         cpu_disable_intr();     /* YYY */
539         intr_countp[intr] = &intrcnt[1 + intr];
540         intr_handler[intr] = isa_strayintr;
541         intr_info[intr].maskp = NULL;
542         intr_info[intr].mask = HWI_MASK | SWI_MASK;
543         intr_unit[intr] = &intr_unit[intr];
544 #ifdef FAST_HI_XXX
545         /* XXX how do I re-create dvp here? */
546         setidt(flags & INTR_FAST ? TPR_FAST_INTS + intr : TPR_SLOW_INTS + intr,
547             slowintr[intr], SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
548 #else /* FAST_HI */
549 #ifdef APIC_INTR_REORDER
550         set_lapic_isrloc(intr, ICU_OFFSET + intr);
551 #endif
552         setidt(ICU_OFFSET + intr, slowintr[intr], SDT_SYS386IGT, SEL_KPL,
553             GSEL(GCODE_SEL, SEL_KPL));
554 #endif /* FAST_HI */
555         write_eflags(ef);
556         return (0);
557 }
558
559
560 /* The following notice applies beyond this point in the file */
561
562 /*
563  * Copyright (c) 1997, Stefan Esser <se@freebsd.org>
564  * All rights reserved.
565  *
566  * Redistribution and use in source and binary forms, with or without
567  * modification, are permitted provided that the following conditions
568  * are met:
569  * 1. Redistributions of source code must retain the above copyright
570  *    notice unmodified, this list of conditions, and the following
571  *    disclaimer.
572  * 2. Redistributions in binary form must reproduce the above copyright
573  *    notice, this list of conditions and the following disclaimer in the
574  *    documentation and/or other materials provided with the distribution.
575  *
576  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
577  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
578  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
579  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
580  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
581  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
582  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
583  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
584  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
585  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
586  *
587  * $FreeBSD: src/sys/i386/isa/intr_machdep.c,v 1.29.2.5 2001/10/14 06:54:27 luigi Exp $
588  *
589  */
590
591 typedef struct intrec {
592         intrmask_t      mask;
593         inthand2_t      *handler;
594         void            *argument;
595         struct intrec   *next;
596         char            *name;
597         int             intr;
598         intrmask_t      *maskptr;
599         int             flags;
600         lwkt_serialize_t serializer;
601         volatile int    in_handler;
602 } intrec;
603
604 static intrec *intreclist_head[ICU_LEN];
605
606 /*
607  * The interrupt multiplexer calls each of the handlers in turn.  A handler
608  * is called only if we can successfully obtain the interlock, meaning
609  * (1) we aren't recursed and (2) the handler has not been disabled via
610  * inthand_disabled().
611  *
612  * XXX the IPL is currently raised as necessary for the handler.  However,
613  * IPLs are not MP safe so the IPL code will be removed when the device
614  * drivers, BIO, and VM no longer depend on it.
615  */
616 static void
617 intr_mux(void *arg)
618 {
619         intrec **pp;
620         intrec *p;
621
622         for (pp = arg; (p = *pp) != NULL; pp = &p->next) {
623                 if (p->serializer) {
624                         /*
625                          * New handler dispatch method.  Only the serializer
626                          * is used to interlock access.  Note that this
627                          * API includes a handler disablement feature.
628                          */
629                         lwkt_serialize_handler_call(p->serializer,
630                                                     p->handler, p->argument);
631                 } else {
632                         /*
633                          * Old handlers may expect multiple interrupt
634                          * sources to be masked.  We must use a critical
635                          * section.
636                          */
637                         crit_enter();
638                         p->handler(p->argument);
639                         crit_exit();
640                 }
641         }
642 }
643
644 static intrec*
645 find_idesc(unsigned *maskptr, int irq)
646 {
647         intrec *p = intreclist_head[irq];
648
649         while (p && p->maskptr != maskptr)
650                 p = p->next;
651
652         return (p);
653 }
654
655 /*
656  * Both the low level handler and the shared interrupt multiplexer
657  * block out further interrupts as set in the handlers "mask", while
658  * the handler is running. In fact *maskptr should be used for this
659  * purpose, but since this requires one more pointer dereference on
660  * each interrupt, we rather bother update "mask" whenever *maskptr
661  * changes. The function "update_masks" should be called **after**
662  * all manipulation of the linked list of interrupt handlers hung
663  * off of intrdec_head[irq] is complete, since the chain of handlers
664  * will both determine the *maskptr values and the instances of mask
665  * that are fixed. This function should be called with the irq for
666  * which a new handler has been add blocked, since the masks may not
667  * yet know about the use of this irq for a device of a certain class.
668  */
669
670 static void
671 update_mux_masks(void)
672 {
673         int irq;
674         for (irq = 0; irq < ICU_LEN; irq++) {
675                 intrec *idesc = intreclist_head[irq];
676                 while (idesc != NULL) {
677                         if (idesc->maskptr != NULL) {
678                                 /* our copy of *maskptr may be stale, refresh */
679                                 idesc->mask = *idesc->maskptr;
680                         }
681                         idesc = idesc->next;
682                 }
683         }
684 }
685
686 static void
687 update_masks(intrmask_t *maskptr, int irq)
688 {
689         intrmask_t mask = 1 << irq;
690
691         if (maskptr == NULL)
692                 return;
693
694         if (find_idesc(maskptr, irq) == NULL) {
695                 /* no reference to this maskptr was found in this irq's chain */
696                 *maskptr &= ~mask;
697         } else {
698                 /* a reference to this maskptr was found in this irq's chain */
699                 *maskptr |= mask;
700         }
701         /* we need to update all values in the intr_mask[irq] array */
702         update_intr_masks();
703         /* update mask in chains of the interrupt multiplex handler as well */
704         update_mux_masks();
705 }
706
707 /*
708  * Add an interrupt handler to the linked list hung off of intreclist_head[irq]
709  * and install a shared interrupt multiplex handler.  Install an interrupt
710  * thread for each interrupt (though FAST interrupts will not use it).
711  * The preemption procedure checks the CPL.  lwkt_preempt() will check
712  * relative thread priorities for us as long as we properly pass through
713  * critpri.
714  *
715  * The interrupt thread has already been put on the run queue, so if we cannot
716  * preempt we should force a reschedule.
717  */
718 static void
719 cpu_intr_preempt(struct thread *td, int critpri)
720 {
721         struct md_intr_info *info = td->td_info.intdata;
722
723         if ((curthread->td_cpl & (1 << info->irq)) == 0)
724                 lwkt_preempt(td, critpri);
725         else
726                 need_lwkt_resched(); /* XXX may not be required */
727 }
728
729 static int
730 add_intrdesc(intrec *idesc)
731 {
732         int irq = idesc->intr;
733         intrec *head;
734         intrec **headp;
735
736         /*
737          * There are two ways to enter intr_mux().  (1) via the scheduled
738          * interrupt thread or (2) directly.   The thread mechanism is the
739          * normal mechanism used by SLOW interrupts, while the direct method
740          * is used by FAST interrupts.
741          *
742          * We need to create an interrupt thread if none exists.
743          */
744         if (intr_info[irq].mihandler_installed == 0) {
745                 struct thread *td;
746
747                 intr_info[irq].mihandler_installed = 1;
748                 intr_info[irq].irq = irq;
749                 td = register_int(irq, intr_mux, &intreclist_head[irq], idesc->name, idesc->maskptr);
750                 td->td_info.intdata = &intr_info[irq];
751                 td->td_preemptable = cpu_intr_preempt;
752                 printf("installed MI handler for int %d\n", irq);
753         }
754
755         headp = &intreclist_head[irq];
756         head = *headp;
757
758         /*
759          * Check exclusion
760          */
761         if (head) {
762                 if ((idesc->flags & INTR_EXCL) || (head->flags & INTR_EXCL)) {
763                         printf("\tdevice combination doesn't support "
764                                "shared irq%d\n", irq);
765                         return (-1);
766                 }
767                 if ((idesc->flags & INTR_FAST) || (head->flags & INTR_FAST)) {
768                         printf("\tdevice combination doesn't support "
769                                "multiple FAST interrupts on IRQ%d\n", irq);
770                 }
771         }
772
773         /*
774          * Always install intr_mux as the hard handler so it can deal with
775          * individual enablement on handlers.
776          */
777         if (head == NULL) {
778                 if (icu_setup(irq, idesc->handler, idesc->argument, idesc->maskptr, idesc->flags) != 0)
779                         return (-1);
780                 update_intrname(irq, idesc->name);
781         } else if (head->next == NULL) {
782                 icu_unset(irq, head->handler);
783                 if (icu_setup(irq, intr_mux, &intreclist_head[irq], 0, 0) != 0)
784                         return (-1);
785                 if (bootverbose && head->next == NULL)
786                         printf("\tusing shared irq%d.\n", irq);
787                 update_intrname(irq, "mux");
788         }
789
790         /*
791          * Append to the end of the chain and update our SPL masks.
792          */
793         while (*headp != NULL)
794                 headp = &(*headp)->next;
795         *headp = idesc;
796
797         update_masks(idesc->maskptr, irq);
798         return (0);
799 }
800
801 /*
802  * Create and activate an interrupt handler descriptor data structure.
803  *
804  * The dev_instance pointer is required for resource management, and will
805  * only be passed through to resource_claim().
806  *
807  * There will be functions that derive a driver and unit name from a
808  * dev_instance variable, and those functions will be used to maintain the
809  * interrupt counter label array referenced by systat and vmstat to report
810  * device interrupt rates (->update_intrlabels).
811  *
812  * Add the interrupt handler descriptor data structure created by an
813  * earlier call of create_intr() to the linked list for its irq and
814  * adjust the interrupt masks if necessary.
815  *
816  * WARNING: This is an internal function and not to be used by device
817  * drivers.  It is subject to change without notice.
818  */
819
820 intrec *
821 inthand_add(const char *name, int irq, inthand2_t handler, void *arg,
822              intrmask_t *maskptr, int flags, lwkt_serialize_t serializer)
823 {
824         intrec *idesc;
825         int errcode = -1;
826
827         if (ICU_LEN > 8 * sizeof *maskptr) {
828                 printf("create_intr: ICU_LEN of %d too high for %d bit intrmask\n",
829                        ICU_LEN, 8 * sizeof *maskptr);
830                 return (NULL);
831         }
832         if ((unsigned)irq >= ICU_LEN) {
833                 printf("create_intr: requested irq%d too high, limit is %d\n",
834                        irq, ICU_LEN -1);
835                 return (NULL);
836         }
837
838         idesc = malloc(sizeof *idesc, M_DEVBUF, M_WAITOK | M_ZERO);
839         if (idesc == NULL)
840                 return NULL;
841
842         if (name == NULL)
843                 name = "???";
844         idesc->name = malloc(strlen(name) + 1, M_DEVBUF, M_WAITOK);
845         if (idesc->name == NULL) {
846                 free(idesc, M_DEVBUF);
847                 return NULL;
848         }
849         strcpy(idesc->name, name);
850
851         idesc->handler  = handler;
852         idesc->argument = arg;
853         idesc->maskptr  = maskptr;
854         idesc->intr     = irq;
855         idesc->flags    = flags;
856         idesc->serializer = serializer;
857
858         /* add irq to class selected by maskptr */
859         crit_enter();
860         errcode = add_intrdesc(idesc);
861         crit_exit();
862
863         if (errcode != 0) {
864                 if (bootverbose)
865                         printf("\tintr_connect(irq%d) failed, result=%d\n", 
866                                irq, errcode);
867                 free(idesc->name, M_DEVBUF);
868                 free(idesc, M_DEVBUF);
869                 idesc = NULL;
870         }
871
872         return (idesc);
873 }
874
875 /*
876  * Deactivate and remove the interrupt handler descriptor data connected
877  * created by an earlier call of intr_connect() from the linked list and
878  * adjust theinterrupt masks if necessary.
879  *
880  * Return the memory held by the interrupt handler descriptor data structure
881  * to the system. Make sure, the handler is not actively used anymore, before.
882  */
883 int
884 inthand_remove(intrec *idesc)
885 {
886         intrec **hook, *head;
887         int irq;
888
889         if (idesc == NULL)
890                 return (-1);
891
892         irq = idesc->intr;
893         crit_enter();
894
895         /*
896          * Find and remove the interrupt descriptor.
897          */
898         hook = &intreclist_head[irq];
899         while (*hook != idesc) {
900                 if (*hook == NULL) {
901                         crit_exit();
902                         return(-1);
903                 }
904                 hook = &(*hook)->next;
905         }
906         *hook = idesc->next;
907
908         /*
909          * If the list is now empty, revert the hard vector to the spurious
910          * interrupt.
911          */
912         head = intreclist_head[irq];
913         if (head == NULL) {
914                 /*
915                  * No more interrupts on this irq
916                  */
917                 icu_unset(irq, idesc->handler);
918                 update_intrname(irq, NULL);
919         } else if (head->next) {
920                 /*
921                  * This irq is still shared (has at least two handlers)
922                  * (the name should already be set to "mux").
923                  */
924         } else {
925                 /*
926                  * This irq is no longer shared
927                  */
928                 icu_unset(irq, intr_mux);
929                 icu_setup(irq, head->handler, head->argument, head->maskptr, head->flags);
930                 update_intrname(irq, head->name);
931         }
932         update_masks(idesc->maskptr, irq);
933         crit_exit();
934         free(idesc, M_DEVBUF);
935
936         return (0);
937 }
938
939 /*
940  * ithread_done()
941  *
942  *      This function is called by an interrupt thread when it has completed
943  *      processing a loop.  We re-enable interrupts and interlock with
944  *      ipending.
945  *
946  *      See kern/kern_intr.c for more information.
947  */
948 void
949 ithread_done(int irq)
950 {
951     struct mdglobaldata *gd = mdcpu;
952     int mask = 1 << irq;
953     thread_t td;
954
955     td = gd->mi.gd_curthread;
956
957     KKASSERT(td->td_pri >= TDPRI_CRIT);
958     lwkt_deschedule_self(td);
959     INTREN(mask);
960     if (gd->gd_ipending & mask) {
961         atomic_clear_int_nonlocked(&gd->gd_ipending, mask);
962         INTRDIS(mask);
963         lwkt_schedule_self(td);
964     } else {
965         lwkt_switch();
966     }
967 }
968
969 #ifdef SMP
970 /*
971  * forward_fast_remote()
972  *
973  *      This function is called from the receiving end of an IPIQ when a
974  *      remote cpu wishes to forward a fast interrupt to us.  All we have to
975  *      do is set the interrupt pending and let the IPI's doreti deal with it.
976  */
977 void
978 forward_fastint_remote(void *arg)
979 {
980     int irq = (int)arg;
981     struct mdglobaldata *gd = mdcpu;
982
983     atomic_set_int_nonlocked(&gd->gd_fpending, 1 << irq);
984     atomic_set_int_nonlocked(&gd->mi.gd_reqflags, RQF_INTPEND);
985 }
986
987 #endif