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