Friday, April 18, 2014

Interrupts in Linux

What is an interrupt in linux?
       An interrupt is simply a signal that the hardware can send when it wants the processor’s attention.
Why we need interrupt?
        We need interrupt to save the CPU cycle. For an instance, we have a keyboard, when we press any key, we need response, CPU can’t wait for our input all the time. So the keyboard driver registers an interrupt handler, so that we press a key, the interrupt will signal to CPU.
How to register interrupt hanlder?
Interupt handler must be register in kernel module. we can register the handler in init or open. I would suggest to put it in open().
Here is the example:
int request_irq (
unsigned int  
irq,

irq_handler_t  
handler,

unsigned long  
irqflags,

const char *  
devname,

void *  
dev_id);



void my_interrupt(int irq, void *dev_id, struct pt_regs *regs)
{
    printk("Interrupt should be handled there\n");
}

static int __init
my_init(void)
{
    unsigned int irq;
    unsigned int irqflags;
    int ret;

    irq=68;
    irqflags=IRQF_SHARED | IRQF_NO_SUSPEND;
    ret = request_irq(irq, my_interrupt,
            irqflags, "my_dev", NULL);
    if (ret!=0) {
            printk("ERROR: Cannot request IRQ %d", irq);
           
    }
}
static void __exit
my_exit(void)
{
    unsigned int irq;
    irq=68;
    free_irq(irq, NULL);
    printk("CLCDINT_EXIT\n");
}


Parameters for request_irq:

unsigned int irq
          The interrupt number being requested.

irq_hander_t
          The pointer to the handling function being installed.

unsigned long flags
          The bit mask, to manage the interrupt

const char *dev_name
          The string passed to request_irq is used in /proc/interrupts to show the owner of the interrupt

void *dev_id
          The set to NULL, if the interrupt line is not shared, if interrupt line is shared then, it has the pointer to provate data to identify which device is interrupting.

unsigned long flags: SA_INTERRUPT
          When set, this indicates a “fast” interrupt handler. Fast handlers are executed with interrupts disabled on the current processor.

unsigned long flags: SA_SHIRQ
          This bit signals that the interrupt can be shared between devices.

unsigned long flags: SA_SAMPLE_RANDOM
          This bit indicates that the generated interrupts can contribute to the entropy pool used by /dev/random and /dev/urandom. These devices return truly random numbers when read and are designed to help application software choose secure keys for encryption. Such random numbers are extracted from an entropy pool that is contributed by various random events. If your device generates interrupts at truly random times, you should set this flag. 



No comments: