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