original comment: +Wilson03172004,marked due to this pci host does not support MWI
[linux-2.4.git] / arch / x86_64 / kernel / irq.c
1 /*
2  *      linux/arch/x86_64/kernel/irq.c
3  *
4  *      Copyright (C) 1992, 1998 Linus Torvalds, Ingo Molnar
5  *
6  * This file contains the code used by various IRQ handling routines:
7  * asking for different IRQ's should be done through these routines
8  * instead of just grabbing them. Thus setups with different IRQ numbers
9  * shouldn't result in any weird surprises, and installing new handlers
10  * should be easier.
11  */
12
13 /*
14  * (mostly architecture independent, will move to kernel/irq.c in 2.5.)
15  *
16  * IRQs are in fact implemented a bit like signal handlers for the kernel.
17  * Naturally it's not a 1:1 relation, but there are similarities.
18  */
19
20 #include <linux/config.h>
21 #include <linux/ptrace.h>
22 #include <linux/errno.h>
23 #include <linux/signal.h>
24 #include <linux/sched.h>
25 #include <linux/ioport.h>
26 #include <linux/interrupt.h>
27 #include <linux/timex.h>
28 #include <linux/slab.h>
29 #include <linux/random.h>
30 #include <linux/smp_lock.h>
31 #include <linux/init.h>
32 #include <linux/kernel_stat.h>
33 #include <linux/irq.h>
34 #include <linux/proc_fs.h>
35 #include <linux/seq_file.h>
36
37 #include <asm/atomic.h>
38 #include <asm/io.h>
39 #include <asm/smp.h>
40 #include <asm/system.h>
41 #include <asm/bitops.h>
42 #include <asm/uaccess.h>
43 #include <asm/pgalloc.h>
44 #include <asm/delay.h>
45 #include <asm/desc.h>
46 #include <asm/irq.h>
47 #include <asm/proto.h>
48
49 #ifdef CONFIG_DEBUG_STACKOVERFLOW
50 /* 
51  * Probalistic stack overflow check: 
52  * 
53  * Only check the stack in process context, because everything else
54  * runs on the big interrupt stacks. Checking reliably is too expensive,
55  * so we just check from interrupts. 
56  */ 
57 static inline void stack_overflow_check(struct pt_regs *regs)
58
59         u64 curbase = (u64) current;
60         static unsigned long warned = -60*HZ; 
61
62         if (regs->rsp >= curbase && regs->rsp <= curbase + THREAD_SIZE &&
63             regs->rsp <  curbase + sizeof(struct task_struct) + 128 && 
64             warned + 60*HZ >= jiffies) { 
65                 printk("do_IRQ: %s near stack overflow (cur:%Lx,rsp:%lx)\n",
66                        current->comm, curbase, regs->rsp); 
67                 show_stack(NULL);
68                 warned = jiffies;
69         }
70 }
71 #endif
72
73 /*
74  * Linux has a controller-independent x86 interrupt architecture.
75  * every controller has a 'controller-template', that is used
76  * by the main code to do the right thing. Each driver-visible
77  * interrupt source is transparently wired to the apropriate
78  * controller. Thus drivers need not be aware of the
79  * interrupt-controller.
80  *
81  * Various interrupt controllers we handle: 8259 PIC, SMP IO-APIC,
82  * PIIX4's internal 8259 PIC and SGI's Visual Workstation Cobalt (IO-)APIC.
83  * (IO-APICs assumed to be messaging to Pentium local-APICs)
84  *
85  * the code is designed to be easily extended with new/different
86  * interrupt controllers, without having to do assembly magic.
87  */
88
89 /*
90  * Controller mappings for all interrupt sources:
91  */
92 irq_desc_t irq_desc[NR_IRQS] __cacheline_aligned =
93         { [0 ... NR_IRQS-1] = { 0, &no_irq_type, NULL, 0, SPIN_LOCK_UNLOCKED}};
94
95 static void register_irq_proc (unsigned int irq);
96
97 /*
98  * Special irq handlers.
99  */
100
101 void no_action(int cpl, void *dev_id, struct pt_regs *regs) { }
102
103 /*
104  * Generic no controller code
105  */
106
107 static void enable_none(unsigned int irq) { }
108 static unsigned int startup_none(unsigned int irq) { return 0; }
109 static void disable_none(unsigned int irq) { }
110 static void ack_none(unsigned int irq)
111 {
112 /*
113  * 'what should we do if we get a hw irq event on an illegal vector'.
114  * each architecture has to answer this themselves, it doesnt deserve
115  * a generic callback i think.
116  */
117 #if CONFIG_X86
118         printk("unexpected IRQ trap at vector %02x\n", irq);
119 #ifdef CONFIG_X86_LOCAL_APIC
120         /*
121          * Currently unexpected vectors happen only on SMP and APIC.
122          * We _must_ ack these because every local APIC has only N
123          * irq slots per priority level, and a 'hanging, unacked' IRQ
124          * holds up an irq slot - in excessive cases (when multiple
125          * unexpected vectors occur) that might lock up the APIC
126          * completely.
127          */
128         ack_APIC_irq();
129 #endif
130 #endif
131 }
132
133 /* startup is the same as "enable", shutdown is same as "disable" */
134 #define shutdown_none   disable_none
135 #define end_none        enable_none
136
137 struct hw_interrupt_type no_irq_type = {
138         "none",
139         startup_none,
140         shutdown_none,
141         enable_none,
142         disable_none,
143         ack_none,
144         end_none
145 };
146
147 atomic_t irq_err_count;
148 #ifdef CONFIG_X86_IO_APIC
149 #ifdef APIC_MISMATCH_DEBUG
150 atomic_t irq_mis_count;
151 #endif
152 #endif
153
154 /*
155  * Generic, controller-independent functions:
156  */
157
158 int show_interrupts(struct seq_file *p, void *v)
159 {
160         int i, j;
161         struct irqaction * action;
162
163         seq_printf(p, "           ");
164         for (j=0; j<smp_num_cpus; j++)
165                 seq_printf(p, "CPU%d       ",j);
166         seq_putc(p,'\n');
167
168         for (i = 0 ; i < NR_IRQS ; i++) {
169                 action = irq_desc[i].action;
170                 if (!action) 
171                         continue;
172                 seq_printf(p, "%3d: ",i);
173 #ifndef CONFIG_SMP
174                 seq_printf(p, "%10u ", kstat_irqs(i));
175 #else
176                 for (j = 0; j < smp_num_cpus; j++)
177                         seq_printf(p, "%10u ",
178                                 kstat.irqs[cpu_logical_map(j)][i]);
179 #endif
180                 seq_printf(p, " %14s", irq_desc[i].handler->typename);
181                 seq_printf(p, "  %s", action->name);
182
183                 for (action=action->next; action; action = action->next)
184                         seq_printf(p, ", %s", action->name);
185                 seq_putc(p,'\n');
186         }
187         seq_printf(p, "NMI: ");
188         for (j = 0; j < smp_num_cpus; j++)
189                 seq_printf(p, "%10u ",
190                         nmi_count(cpu_logical_map(j)));
191         seq_printf(p, "\n");
192 #if CONFIG_X86_LOCAL_APIC
193         seq_printf(p, "LOC: ");
194         for (j = 0; j < smp_num_cpus; j++)
195                 seq_printf(p, "%10u ",
196                         apic_timer_irqs[cpu_logical_map(j)]);
197         seq_printf(p, "\n");
198 #endif
199         seq_printf(p, "ERR: %10u\n", atomic_read(&irq_err_count));
200 #ifdef CONFIG_X86_IO_APIC
201 #ifdef APIC_MISMATCH_DEBUG
202         seq_printf(p, "MIS: %10u\n", atomic_read(&irq_mis_count));
203 #endif
204 #endif
205
206         return 0;
207 }
208
209 /*
210  * Global interrupt locks for SMP. Allow interrupts to come in on any
211  * CPU, yet make cli/sti act globally to protect critical regions..
212  */
213
214 #ifdef CONFIG_SMP
215 unsigned char global_irq_holder = NO_PROC_ID;
216 unsigned volatile long global_irq_lock; /* pendantic: long for set_bit --RR */
217
218 extern void show_stack(unsigned long* esp);
219
220
221 /* XXX: this unfortunately doesn't support irqs/exception stacks currently, 
222    should check the other PDAs */
223 static void show(char * str)
224 {
225         int i;
226         int cpu = smp_processor_id();
227
228         printk("\n%s, CPU %d:\n", str, cpu);
229         printk("irq:  %d [",irqs_running());
230         for(i=0;i < smp_num_cpus;i++)
231                 printk(" %d",local_irq_count(i));
232         printk(" ]\nbh:   %d [",spin_is_locked(&global_bh_lock) ? 1 : 0);
233         for(i=0;i < smp_num_cpus;i++)
234                 printk(" %d",local_bh_count(i));
235
236         printk(" ]\nStack dumps:");
237         for(i = 0; i < smp_num_cpus; i++) {
238                 unsigned long esp;
239                 if (i == cpu)
240                         continue;
241                 printk("\nCPU %d:",i);
242                 esp = init_tss[i].rsp0;
243                 if (!esp) {
244                         /* tss->esp0 is set to NULL in cpu_init(),
245                          * it's initialized when the cpu returns to user
246                          * space. -- manfreds
247                          */
248                         printk(" <unknown> ");
249                         continue;
250                 }
251                 esp &= ~(THREAD_SIZE-1);
252                 esp += sizeof(struct task_struct);
253                 show_stack((void*)esp);
254         }
255         printk("\nCPU %d:",cpu);
256         show_stack(NULL);
257         printk("\n");
258 }
259         
260 #define MAXCOUNT 100000000
261
262 /*
263  * I had a lockup scenario where a tight loop doing
264  * spin_unlock()/spin_lock() on CPU#1 was racing with
265  * spin_lock() on CPU#0. CPU#0 should have noticed spin_unlock(), but
266  * apparently the spin_unlock() information did not make it
267  * through to CPU#0 ... nasty, is this by design, do we have to limit
268  * 'memory update oscillation frequency' artificially like here?
269  *
270  * Such 'high frequency update' races can be avoided by careful design, but
271  * some of our major constructs like spinlocks use similar techniques,
272  * it would be nice to clarify this issue. Set this define to 0 if you
273  * want to check whether your system freezes.  I suspect the delay done
274  * by SYNC_OTHER_CORES() is in correlation with 'snooping latency', but
275  * i thought that such things are guaranteed by design, since we use
276  * the 'LOCK' prefix.
277  */
278 #define SUSPECTED_CPU_OR_CHIPSET_BUG_WORKAROUND 0
279
280 #if SUSPECTED_CPU_OR_CHIPSET_BUG_WORKAROUND
281 # define SYNC_OTHER_CORES(x) udelay(x+1)
282 #else
283 /*
284  * We have to allow irqs to arrive between __sti and __cli
285  */
286 # define SYNC_OTHER_CORES(x) __asm__ __volatile__ ("nop")
287 #endif
288
289 static inline void wait_on_irq(int cpu)
290 {
291         int count = MAXCOUNT;
292
293         for (;;) {
294
295                 /*
296                  * Wait until all interrupts are gone. Wait
297                  * for bottom half handlers unless we're
298                  * already executing in one..
299                  */
300                 if (!irqs_running())
301                         if (local_bh_count(cpu) || !spin_is_locked(&global_bh_lock))
302                                 break;
303
304                 /* Duh, we have to loop. Release the lock to avoid deadlocks */
305                 clear_bit(0,&global_irq_lock);
306
307                 for (;;) {
308                         if (!--count) {
309                                 show("wait_on_irq");
310                                 count = ~0;
311                         }
312                         __sti();
313                         SYNC_OTHER_CORES(cpu);
314                         __cli();
315                         if (irqs_running())
316                                 continue;
317                         if (global_irq_lock)
318                                 continue;
319                         if (!local_bh_count(cpu) && spin_is_locked(&global_bh_lock))
320                                 continue;
321                         if (!test_and_set_bit(0,&global_irq_lock))
322                                 break;
323                 }
324         }
325 }
326
327 /*
328  * This is called when we want to synchronize with
329  * interrupts. We may for example tell a device to
330  * stop sending interrupts: but to make sure there
331  * are no interrupts that are executing on another
332  * CPU we need to call this function.
333  */
334 void synchronize_irq(void)
335 {
336         if (irqs_running()) {
337                 /* Stupid approach */
338                 cli();
339                 sti();
340         }
341 }
342
343 static inline void get_irqlock(int cpu)
344 {
345         if (test_and_set_bit(0,&global_irq_lock)) {
346                 /* do we already hold the lock? */
347                 if ((unsigned char) cpu == global_irq_holder)
348                         return;
349                 /* Uhhuh.. Somebody else got it. Wait.. */
350                 do {
351                         do {
352                                 rep_nop();
353                         } while (test_bit(0,&global_irq_lock));
354                 } while (test_and_set_bit(0,&global_irq_lock));         
355         }
356         /* 
357          * We also to make sure that nobody else is running
358          * in an interrupt context. 
359          */
360         wait_on_irq(cpu);
361
362         /*
363          * Ok, finally..
364          */
365         global_irq_holder = cpu;
366 }
367
368 #define EFLAGS_IF_SHIFT 9
369
370 /*
371  * A global "cli()" while in an interrupt context
372  * turns into just a local cli(). Interrupts
373  * should use spinlocks for the (very unlikely)
374  * case that they ever want to protect against
375  * each other.
376  *
377  * If we already have local interrupts disabled,
378  * this will not turn a local disable into a
379  * global one (problems with spinlocks: this makes
380  * save_flags+cli+sti usable inside a spinlock).
381  */
382 void __global_cli(void)
383 {
384         unsigned long flags;
385
386         __save_flags(flags);
387         if (flags & (1U << EFLAGS_IF_SHIFT)) {
388                 int cpu = smp_processor_id();
389                 __cli();
390                 if (!local_irq_count(cpu))
391                         get_irqlock(cpu);
392         }
393 }
394
395 void __global_sti(void)
396 {
397         int cpu = smp_processor_id();
398
399         if (!local_irq_count(cpu))
400                 release_irqlock(cpu);
401         __sti();
402 }
403
404 /*
405  * SMP flags value to restore to:
406  * 0 - global cli
407  * 1 - global sti
408  * 2 - local cli
409  * 3 - local sti
410  */
411 unsigned long __global_save_flags(void)
412 {
413         int retval;
414         int local_enabled;
415         unsigned long flags;
416         int cpu = smp_processor_id();
417
418         __save_flags(flags);
419         local_enabled = (flags >> EFLAGS_IF_SHIFT) & 1;
420         /* default to local */
421         retval = 2 + local_enabled;
422
423         /* check for global flags if we're not in an interrupt */
424         if (!local_irq_count(cpu)) {
425                 if (local_enabled)
426                         retval = 1;
427                 if (global_irq_holder == cpu)
428                         retval = 0;
429         }
430         return retval;
431 }
432
433 void __global_restore_flags(unsigned long flags)
434 {
435         switch (flags) {
436         case 0:
437                 __global_cli();
438                 break;
439         case 1:
440                 __global_sti();
441                 break;
442         case 2:
443                 __cli();
444                 break;
445         case 3:
446                 __sti();
447                 break;
448         default:
449                 printk("global_restore_flags: %08lx (%08lx)\n",
450                         flags, (&flags)[-1]);
451         }
452 }
453
454 #endif
455
456 /*
457  * This should really return information about whether
458  * we should do bottom half handling etc. Right now we
459  * end up _always_ checking the bottom half, which is a
460  * waste of time and is not what some drivers would
461  * prefer.
462  */
463 int handle_IRQ_event(unsigned int irq, struct pt_regs * regs, struct irqaction * action)
464 {
465         int status;
466         int cpu = smp_processor_id();
467
468         irq_enter(cpu, irq);
469
470         status = 1;     /* Force the "do bottom halves" bit */
471
472         if (!(action->flags & SA_INTERRUPT))
473                 __sti();
474
475         do {
476                 status |= action->flags;
477                 action->handler(irq, action->dev_id, regs);
478                 action = action->next;
479         } while (action);
480         if (status & SA_SAMPLE_RANDOM)
481                 add_interrupt_randomness(irq);
482         __cli();
483
484         irq_exit(cpu, irq);
485
486         return status;
487 }
488
489 /*
490  * Generic enable/disable code: this just calls
491  * down into the PIC-specific version for the actual
492  * hardware disable after having gotten the irq
493  * controller lock. 
494  */
495  
496 /**
497  *      disable_irq_nosync - disable an irq without waiting
498  *      @irq: Interrupt to disable
499  *
500  *      Disable the selected interrupt line.  Disables and Enables are
501  *      nested.
502  *      Unlike disable_irq(), this function does not ensure existing
503  *      instances of the IRQ handler have completed before returning.
504  *
505  *      This function may be called from IRQ context.
506  */
507  
508 inline void disable_irq_nosync(unsigned int irq)
509 {
510         irq_desc_t *desc = irq_desc + irq;
511         unsigned long flags;
512
513         spin_lock_irqsave(&desc->lock, flags);
514         if (!desc->depth++) {
515                 desc->status |= IRQ_DISABLED;
516                 desc->handler->disable(irq);
517         }
518         spin_unlock_irqrestore(&desc->lock, flags);
519 }
520
521 /**
522  *      disable_irq - disable an irq and wait for completion
523  *      @irq: Interrupt to disable
524  *
525  *      Disable the selected interrupt line.  Enables and Disables are
526  *      nested.
527  *      This function waits for any pending IRQ handlers for this interrupt
528  *      to complete before returning. If you use this function while
529  *      holding a resource the IRQ handler may need you will deadlock.
530  *
531  *      This function may be called - with care - from IRQ context.
532  */
533  
534 void disable_irq(unsigned int irq)
535 {
536         disable_irq_nosync(irq);
537
538         if (!local_irq_count(smp_processor_id())) {
539                 do {
540                         barrier();
541                         cpu_relax();
542                 } while (irq_desc[irq].status & IRQ_INPROGRESS);
543         }
544 }
545
546 /**
547  *      enable_irq - enable handling of an irq
548  *      @irq: Interrupt to enable
549  *
550  *      Undoes the effect of one call to disable_irq().  If this
551  *      matches the last disable, processing of interrupts on this
552  *      IRQ line is re-enabled.
553  *
554  *      This function may be called from IRQ context.
555  */
556  
557 void enable_irq(unsigned int irq)
558 {
559         irq_desc_t *desc = irq_desc + irq;
560         unsigned long flags;
561
562         spin_lock_irqsave(&desc->lock, flags);
563         switch (desc->depth) {
564         case 1: {
565                 unsigned int status = desc->status & ~IRQ_DISABLED;
566                 desc->status = status;
567                 if ((status & (IRQ_PENDING | IRQ_REPLAY)) == IRQ_PENDING) {
568                         desc->status = status | IRQ_REPLAY;
569                         hw_resend_irq(desc->handler,irq);
570                 }
571                 desc->handler->enable(irq);
572                 /* fall-through */
573         }
574         default:
575                 desc->depth--;
576                 break;
577         case 0:
578                 printk("enable_irq(%u) unbalanced from %p\n", irq,
579                        __builtin_return_address(0));
580         }
581         spin_unlock_irqrestore(&desc->lock, flags);
582 }
583
584 /*
585  * do_IRQ handles all normal device IRQ's (the special
586  * SMP cross-CPU interrupts have their own specific
587  * handlers).
588  */
589 asmlinkage unsigned int do_IRQ(struct pt_regs *regs)
590 {       
591         /* 
592          * We ack quickly, we don't want the irq controller
593          * thinking we're snobs just because some other CPU has
594          * disabled global interrupts (we have already done the
595          * INT_ACK cycles, it's too late to try to pretend to the
596          * controller that we aren't taking the interrupt).
597          *
598          * 0 return value means that this irq is already being
599          * handled by some other CPU. (or is disabled)
600          */
601         int irq = regs->orig_rax & 0xff; /* high bits used in ret_from_ code  */
602         int cpu = smp_processor_id();
603         irq_desc_t *desc = irq_desc + irq;
604         struct irqaction * action;
605         unsigned int status;
606
607
608 #ifdef CONFIG_DEBUG_STACKOVERFLOW
609         stack_overflow_check(regs); 
610 #endif
611                
612         kstat.irqs[cpu][irq]++;
613         spin_lock(&desc->lock);
614         desc->handler->ack(irq);
615         /*
616            REPLAY is when Linux resends an IRQ that was dropped earlier
617            WAITING is used by probe to mark irqs that are being tested */
618         status = desc->status & ~(IRQ_REPLAY | IRQ_WAITING);
619         status |= IRQ_PENDING; /* we _want_ to handle it */
620
621         /*
622          * If the IRQ is disabled for whatever reason, we cannot
623          * use the action we have.
624          */
625         action = NULL;
626         if (!(status & (IRQ_DISABLED | IRQ_INPROGRESS))) {
627                 action = desc->action;
628                 status &= ~IRQ_PENDING; /* we commit to handling */
629                 status |= IRQ_INPROGRESS; /* we are handling it */
630         }
631         desc->status = status;
632
633         /*
634          * If there is no IRQ handler or it was disabled, exit early.
635            Since we set PENDING, if another processor is handling
636            a different instance of this same irq, the other processor
637            will take care of it.
638          */
639         if (!action)
640                 goto out;
641
642         /*
643          * Edge triggered interrupts need to remember
644          * pending events.
645          * This applies to any hw interrupts that allow a second
646          * instance of the same irq to arrive while we are in do_IRQ
647          * or in the handler. But the code here only handles the _second_
648          * instance of the irq, not the third or fourth. So it is mostly
649          * useful for irq hardware that does not mask cleanly in an
650          * SMP environment.
651          */
652         for (;;) {
653                 spin_unlock(&desc->lock);
654                 handle_IRQ_event(irq, regs, action);
655                 spin_lock(&desc->lock);
656                 
657                 if (!(desc->status & IRQ_PENDING))
658                         break;
659                 desc->status &= ~IRQ_PENDING;
660         }
661         desc->status &= ~IRQ_INPROGRESS;
662 out:
663         /*
664          * The ->end() handler has to deal with interrupts which got
665          * disabled while the handler was running.
666          */
667         desc->handler->end(irq);
668         spin_unlock(&desc->lock);
669
670         if (softirq_pending(cpu))
671                 do_softirq();
672         return 1;
673 }
674
675 /**
676  *      request_irq - allocate an interrupt line
677  *      @irq: Interrupt line to allocate
678  *      @handler: Function to be called when the IRQ occurs
679  *      @irqflags: Interrupt type flags
680  *      @devname: An ascii name for the claiming device
681  *      @dev_id: A cookie passed back to the handler function
682  *
683  *      This call allocates interrupt resources and enables the
684  *      interrupt line and IRQ handling. From the point this
685  *      call is made your handler function may be invoked. Since
686  *      your handler function must clear any interrupt the board 
687  *      raises, you must take care both to initialise your hardware
688  *      and to set up the interrupt handler in the right order.
689  *
690  *      Dev_id must be globally unique. Normally the address of the
691  *      device data structure is used as the cookie. Since the handler
692  *      receives this value it makes sense to use it.
693  *
694  *      If your interrupt is shared you must pass a non NULL dev_id
695  *      as this is required when freeing the interrupt.
696  *
697  *      Flags:
698  *
699  *      SA_SHIRQ                Interrupt is shared
700  *
701  *      SA_INTERRUPT            Disable local interrupts while processing
702  *
703  *      SA_SAMPLE_RANDOM        The interrupt can be used for entropy
704  *
705  */
706  
707 int request_irq(unsigned int irq, 
708                 void (*handler)(int, void *, struct pt_regs *),
709                 unsigned long irqflags, 
710                 const char * devname,
711                 void *dev_id)
712 {
713         int retval;
714         struct irqaction * action;
715
716 #if 1
717         /*
718          * Sanity-check: shared interrupts should REALLY pass in
719          * a real dev-ID, otherwise we'll have trouble later trying
720          * to figure out which interrupt is which (messes up the
721          * interrupt freeing logic etc).
722          */
723         if (irqflags & SA_SHIRQ) {
724                 if (!dev_id)
725                         printk("Bad boy: %s (at 0x%x) called us without a dev_id!\n", devname, (&irq)[-1]);
726         }
727 #endif
728
729         if (irq >= NR_IRQS)
730                 return -EINVAL;
731         if (!handler)
732                 return -EINVAL;
733
734         action = (struct irqaction *)
735                         kmalloc(sizeof(struct irqaction), GFP_KERNEL);
736         if (!action)
737                 return -ENOMEM;
738
739         action->handler = handler;
740         action->flags = irqflags;
741         action->mask = 0;
742         action->name = devname;
743         action->next = NULL;
744         action->dev_id = dev_id;
745
746         retval = setup_irq(irq, action);
747         if (retval)
748                 kfree(action);
749         return retval;
750 }
751
752 /**
753  *      free_irq - free an interrupt
754  *      @irq: Interrupt line to free
755  *      @dev_id: Device identity to free
756  *
757  *      Remove an interrupt handler. The handler is removed and if the
758  *      interrupt line is no longer in use by any driver it is disabled.
759  *      On a shared IRQ the caller must ensure the interrupt is disabled
760  *      on the card it drives before calling this function. The function
761  *      does not return until any executing interrupts for this IRQ
762  *      have completed.
763  *
764  *      This function may be called from interrupt context. 
765  *
766  *      Bugs: Attempting to free an irq in a handler for the same irq hangs
767  *            the machine.
768  */
769  
770 void free_irq(unsigned int irq, void *dev_id)
771 {
772         irq_desc_t *desc;
773         struct irqaction **p;
774         unsigned long flags;
775
776         if (irq >= NR_IRQS)
777                 return;
778
779         desc = irq_desc + irq;
780         spin_lock_irqsave(&desc->lock,flags);
781         p = &desc->action;
782         for (;;) {
783                 struct irqaction * action = *p;
784                 if (action) {
785                         struct irqaction **pp = p;
786                         p = &action->next;
787                         if (action->dev_id != dev_id)
788                                 continue;
789
790                         /* Found it - now remove it from the list of entries */
791                         *pp = action->next;
792                         if (!desc->action) {
793                                 desc->status |= IRQ_DISABLED;
794                                 desc->handler->shutdown(irq);
795                         }
796                         spin_unlock_irqrestore(&desc->lock,flags);
797
798 #ifdef CONFIG_SMP
799                         /* Wait to make sure it's not being used on another CPU */
800                         while (desc->status & IRQ_INPROGRESS) {
801                                 barrier();
802                                 cpu_relax();
803                         }
804 #endif
805                         kfree(action);
806                         return;
807                 }
808                 printk("Trying to free free IRQ%d\n",irq);
809                 spin_unlock_irqrestore(&desc->lock,flags);
810                 return;
811         }
812 }
813
814 /*
815  * IRQ autodetection code..
816  *
817  * This depends on the fact that any interrupt that
818  * comes in on to an unassigned handler will get stuck
819  * with "IRQ_WAITING" cleared and the interrupt
820  * disabled.
821  */
822
823 static DECLARE_MUTEX(probe_sem);
824
825 /**
826  *      probe_irq_on    - begin an interrupt autodetect
827  *
828  *      Commence probing for an interrupt. The interrupts are scanned
829  *      and a mask of potential interrupt lines is returned.
830  *
831  */
832  
833 unsigned long probe_irq_on(void)
834 {
835         unsigned int i;
836         irq_desc_t *desc;
837         unsigned long val;
838         unsigned long delay;
839
840         down(&probe_sem);
841         /* 
842          * something may have generated an irq long ago and we want to
843          * flush such a longstanding irq before considering it as spurious. 
844          */
845         for (i = NR_IRQS-1; i > 0; i--)  {
846                 desc = irq_desc + i;
847
848                 spin_lock_irq(&desc->lock);
849                 if (!irq_desc[i].action) 
850                         irq_desc[i].handler->startup(i);
851                 spin_unlock_irq(&desc->lock);
852         }
853
854         /* Wait for longstanding interrupts to trigger. */
855         for (delay = jiffies + HZ/50; time_after(delay, jiffies); )
856                 /* about 20ms delay */ synchronize_irq();
857
858         /*
859          * enable any unassigned irqs
860          * (we must startup again here because if a longstanding irq
861          * happened in the previous stage, it may have masked itself)
862          */
863         for (i = NR_IRQS-1; i > 0; i--) {
864                 desc = irq_desc + i;
865
866                 spin_lock_irq(&desc->lock);
867                 if (!desc->action) {
868                         desc->status |= IRQ_AUTODETECT | IRQ_WAITING;
869                         if (desc->handler->startup(i))
870                                 desc->status |= IRQ_PENDING;
871                 }
872                 spin_unlock_irq(&desc->lock);
873         }
874
875         /*
876          * Wait for spurious interrupts to trigger
877          */
878         for (delay = jiffies + HZ/10; time_after(delay, jiffies); )
879                 /* about 100ms delay */ synchronize_irq();
880
881         /*
882          * Now filter out any obviously spurious interrupts
883          */
884         val = 0;
885         for (i = 0; i < NR_IRQS; i++) {
886                 irq_desc_t *desc = irq_desc + i;
887                 unsigned int status;
888
889                 spin_lock_irq(&desc->lock);
890                 status = desc->status;
891
892                 if (status & IRQ_AUTODETECT) {
893                         /* It triggered already - consider it spurious. */
894                         if (!(status & IRQ_WAITING)) {
895                                 desc->status = status & ~IRQ_AUTODETECT;
896                                 desc->handler->shutdown(i);
897                         } else
898                                 if (i < 32)
899                                         val |= 1 << i;
900                 }
901                 spin_unlock_irq(&desc->lock);
902         }
903
904         return val;
905 }
906
907 /*
908  * Return a mask of triggered interrupts (this
909  * can handle only legacy ISA interrupts).
910  */
911  
912 /**
913  *      probe_irq_mask - scan a bitmap of interrupt lines
914  *      @val:   mask of interrupts to consider
915  *
916  *      Scan the ISA bus interrupt lines and return a bitmap of
917  *      active interrupts. The interrupt probe logic state is then
918  *      returned to its previous value.
919  *
920  *      Note: we need to scan all the irq's even though we will
921  *      only return ISA irq numbers - just so that we reset them
922  *      all to a known state.
923  */
924 unsigned int probe_irq_mask(unsigned long val)
925 {
926         int i;
927         unsigned int mask;
928
929         mask = 0;
930         for (i = 0; i < NR_IRQS; i++) {
931                 irq_desc_t *desc = irq_desc + i;
932                 unsigned int status;
933
934                 spin_lock_irq(&desc->lock);
935                 status = desc->status;
936
937                 if (status & IRQ_AUTODETECT) {
938                         if (i < 16 && !(status & IRQ_WAITING))
939                                 mask |= 1 << i;
940
941                         desc->status = status & ~IRQ_AUTODETECT;
942                         desc->handler->shutdown(i);
943                 }
944                 spin_unlock_irq(&desc->lock);
945         }
946         up(&probe_sem);
947
948         return mask & val;
949 }
950
951 /*
952  * Return the one interrupt that triggered (this can
953  * handle any interrupt source).
954  */
955
956 /**
957  *      probe_irq_off   - end an interrupt autodetect
958  *      @val: mask of potential interrupts (unused)
959  *
960  *      Scans the unused interrupt lines and returns the line which
961  *      appears to have triggered the interrupt. If no interrupt was
962  *      found then zero is returned. If more than one interrupt is
963  *      found then minus the first candidate is returned to indicate
964  *      their is doubt.
965  *
966  *      The interrupt probe logic state is returned to its previous
967  *      value.
968  *
969  *      BUGS: When used in a module (which arguably shouldnt happen)
970  *      nothing prevents two IRQ probe callers from overlapping. The
971  *      results of this are non-optimal.
972  */
973  
974 int probe_irq_off(unsigned long val)
975 {
976         int i, irq_found, nr_irqs;
977
978         nr_irqs = 0;
979         irq_found = 0;
980         for (i = 0; i < NR_IRQS; i++) {
981                 irq_desc_t *desc = irq_desc + i;
982                 unsigned int status;
983
984                 spin_lock_irq(&desc->lock);
985                 status = desc->status;
986
987                 if (status & IRQ_AUTODETECT) {
988                         if (!(status & IRQ_WAITING)) {
989                                 if (!nr_irqs)
990                                         irq_found = i;
991                                 nr_irqs++;
992                         }
993                         desc->status = status & ~IRQ_AUTODETECT;
994                         desc->handler->shutdown(i);
995                 }
996                 spin_unlock_irq(&desc->lock);
997         }
998         up(&probe_sem);
999
1000         if (nr_irqs > 1)
1001                 irq_found = -irq_found;
1002         return irq_found;
1003 }
1004
1005 /* this was setup_x86_irq but it seems pretty generic */
1006 int setup_irq(unsigned int irq, struct irqaction * new)
1007 {
1008         int shared = 0;
1009         unsigned long flags;
1010         struct irqaction *old, **p;
1011         irq_desc_t *desc = irq_desc + irq;
1012
1013         /*
1014          * Some drivers like serial.c use request_irq() heavily,
1015          * so we have to be careful not to interfere with a
1016          * running system.
1017          */
1018         if (new->flags & SA_SAMPLE_RANDOM) {
1019                 /*
1020                  * This function might sleep, we want to call it first,
1021                  * outside of the atomic block.
1022                  * Yes, this might clear the entropy pool if the wrong
1023                  * driver is attempted to be loaded, without actually
1024                  * installing a new handler, but is this really a problem,
1025                  * only the sysadmin is able to do this.
1026                  */
1027                 rand_initialize_irq(irq);
1028         }
1029
1030         /*
1031          * The following block of code has to be executed atomically
1032          */
1033         spin_lock_irqsave(&desc->lock,flags);
1034         p = &desc->action;
1035         if ((old = *p) != NULL) {
1036                 /* Can't share interrupts unless both agree to */
1037                 if (!(old->flags & new->flags & SA_SHIRQ)) {
1038                         spin_unlock_irqrestore(&desc->lock,flags);
1039                         return -EBUSY;
1040                 }
1041
1042                 /* add new interrupt at end of irq queue */
1043                 do {
1044                         p = &old->next;
1045                         old = *p;
1046                 } while (old);
1047                 shared = 1;
1048         }
1049
1050         *p = new;
1051
1052         if (!shared) {
1053                 desc->depth = 0;
1054                 desc->status &= ~(IRQ_DISABLED | IRQ_AUTODETECT | IRQ_WAITING | IRQ_INPROGRESS);
1055                 desc->handler->startup(irq);
1056         }
1057         spin_unlock_irqrestore(&desc->lock,flags);
1058
1059         register_irq_proc(irq);
1060         return 0;
1061 }
1062
1063 static struct proc_dir_entry * root_irq_dir;
1064 static struct proc_dir_entry * irq_dir [NR_IRQS];
1065
1066 #define HEX_DIGITS 8
1067
1068 static unsigned int parse_hex_value (const char *buffer,
1069                 unsigned long count, unsigned long *ret)
1070 {
1071         unsigned char hexnum [HEX_DIGITS];
1072         unsigned long value;
1073         int i;
1074
1075         if (!count)
1076                 return -EINVAL;
1077         if (count > HEX_DIGITS)
1078                 count = HEX_DIGITS;
1079         if (copy_from_user(hexnum, buffer, count))
1080                 return -EFAULT;
1081
1082         /*
1083          * Parse the first 8 characters as a hex string, any non-hex char
1084          * is end-of-string. '00e1', 'e1', '00E1', 'E1' are all the same.
1085          */
1086         value = 0;
1087
1088         for (i = 0; i < count; i++) {
1089                 unsigned int c = hexnum[i];
1090
1091                 switch (c) {
1092                         case '0' ... '9': c -= '0'; break;
1093                         case 'a' ... 'f': c -= 'a'-10; break;
1094                         case 'A' ... 'F': c -= 'A'-10; break;
1095                 default:
1096                         goto out;
1097                 }
1098                 value = (value << 4) | c;
1099         }
1100 out:
1101         *ret = value;
1102         return 0;
1103 }
1104
1105 #if CONFIG_SMP
1106
1107 static struct proc_dir_entry * smp_affinity_entry [NR_IRQS];
1108
1109 static unsigned long irq_affinity [NR_IRQS] = { [0 ... NR_IRQS-1] = ~0UL };
1110 static int irq_affinity_read_proc (char *page, char **start, off_t off,
1111                         int count, int *eof, void *data)
1112 {
1113         if (count < HEX_DIGITS+1)
1114                 return -EINVAL;
1115         return sprintf (page, "%08lx\n", irq_affinity[(long)data]);
1116 }
1117
1118 static int irq_affinity_write_proc (struct file *file, const char *buffer,
1119                                         unsigned long count, void *data)
1120 {
1121         int irq = (long) data, full_count = count, err;
1122         unsigned long new_value;
1123
1124         if (!irq_desc[irq].handler->set_affinity)
1125                 return -EIO;
1126
1127         err = parse_hex_value(buffer, count, &new_value);
1128
1129         /*
1130          * Do not allow disabling IRQs completely - it's a too easy
1131          * way to make the system unusable accidentally :-) At least
1132          * one online CPU still has to be targeted.
1133          */
1134         if (!(new_value & cpu_online_map))
1135                 return -EINVAL;
1136
1137         irq_affinity[irq] = new_value;
1138         irq_desc[irq].handler->set_affinity(irq, new_value);
1139
1140         return full_count;
1141 }
1142
1143 #endif
1144
1145 static int prof_cpu_mask_read_proc (char *page, char **start, off_t off,
1146                         int count, int *eof, void *data)
1147 {
1148         unsigned long *mask = (unsigned long *) data;
1149         if (count < HEX_DIGITS+1)
1150                 return -EINVAL;
1151         return sprintf (page, "%08lx\n", *mask);
1152 }
1153
1154 static int prof_cpu_mask_write_proc (struct file *file, const char *buffer,
1155                                         unsigned long count, void *data)
1156 {
1157         unsigned long *mask = (unsigned long *) data, full_count = count, err;
1158         unsigned long new_value;
1159
1160         err = parse_hex_value(buffer, count, &new_value);
1161         if (err)
1162                 return err;
1163
1164         *mask = new_value;
1165         return full_count;
1166 }
1167
1168 #define MAX_NAMELEN 10
1169
1170 static void register_irq_proc (unsigned int irq)
1171 {
1172         char name [MAX_NAMELEN];
1173
1174         if (!root_irq_dir || (irq_desc[irq].handler == &no_irq_type) ||
1175                         irq_dir[irq])
1176                 return;
1177
1178         memset(name, 0, MAX_NAMELEN);
1179         sprintf(name, "%d", irq);
1180
1181         /* create /proc/irq/1234 */
1182         irq_dir[irq] = proc_mkdir(name, root_irq_dir);
1183
1184 #if CONFIG_SMP
1185         {
1186                 struct proc_dir_entry *entry;
1187
1188                 /* create /proc/irq/1234/smp_affinity */
1189                 entry = create_proc_entry("smp_affinity", 0600, irq_dir[irq]);
1190
1191                 if (entry) {
1192                         entry->nlink = 1;
1193                         entry->data = (void *)(long)irq;
1194                         entry->read_proc = irq_affinity_read_proc;
1195                         entry->write_proc = irq_affinity_write_proc;
1196                 }
1197
1198                 smp_affinity_entry[irq] = entry;
1199         }
1200 #endif
1201 }
1202
1203 unsigned long prof_cpu_mask = -1;
1204
1205 void init_irq_proc (void)
1206 {
1207         struct proc_dir_entry *entry;
1208         int i;
1209
1210         /* create /proc/irq */
1211         root_irq_dir = proc_mkdir("irq", 0);
1212
1213         /* create /proc/irq/prof_cpu_mask */
1214         entry = create_proc_entry("prof_cpu_mask", 0600, root_irq_dir);
1215
1216         if (!entry)
1217             return;
1218
1219         entry->nlink = 1;
1220         entry->data = (void *)&prof_cpu_mask;
1221         entry->read_proc = prof_cpu_mask_read_proc;
1222         entry->write_proc = prof_cpu_mask_write_proc;
1223
1224         /*
1225          * Create entries for all existing IRQs.
1226          */
1227         for (i = 0; i < NR_IRQS; i++)
1228                 register_irq_proc(i);
1229 }
1230