Irq0 Assignment Management

Chapter 7. Interrupts and Interrupt Handlers

Processors can be orders of magnitudes faster than the hardware they talk to; it is not ideal for the kernel to issue a request and wait for a response from slower hardware. Instead, the kernel must be free to go and handle other work, dealing with the hardware only after that hardware has actually completed its work. [p113]

How can the processor work with hardware without impacting the machine's overall performance? As one solution, polling incurs overhead, because it must occur repeatedly regardless of whether the hardware is active or ready. A better solution is to provide a mechanism for the hardware to signal to the kernel when attention is needed. This mechanism is called an interrupt. This chapter dicusses interrupts and how the kernel responds to them, with special functions called interrupt handlers.


  • Interrupts enable hardware to signal to the processor.
    • For example, as you type, the keyboard controller (the hardware device that manages the keyboard) issues an electrical signal to the processor to alert the operating system to newly available key presses. These electrical signals are interrupts. The processor receives the interrupt and signals the operating system to enable the operating system to respond to the new data.
  • Hardware devices generate interrupts asynchronously (with respect to the processor clock). Consequently, the kernel can be interrupted at any time to process interrupts.

An interrupt is produced by electronic signals from hardware devices and directed into input pins on an interrupt controller (a simple chip that multiplexes multiple interrupt lines into a single line to the processor):

  1. Upon receiving an interrupt, the interrupt controller sends a signal to the processor.
  2. The processor detects this signal and interrupts its current execution to handle the interrupt.
  3. The processor can then notify the operating system that an interrupt has occurred, and the operating system can handle the interrupt appropriately.

Different devices are associated with different interrupts using a unique value associated with each interrupt. This enables the operating system to differentiate between interrupts and to know which hardware device caused which interrupt. In turn, the operating system can service each interrupt with its corresponding handler.

These interrupt values are often called interrupt request (IRQ) lines:

  • Each IRQ line is assigned a numeric value. For example, on the classic PC, IRQ zero is the timer interrupt and IRQ one is the keyboard interrupt.
  • Some interrupts are dynamically assigned, such as interrupts associated with devices on the PCI bus. Other non-PC architectures have similar dynamic assignments for interrupt values.
  • The kernel knows that a specific interrupt is associated with a specific device. The hardware then issues interrupts to get the kernel's attention.

Exceptions and Interrupts *¶

Exceptions are often discussed at the same time as interrupts. Unlike interrupts, exceptions occur synchronously with respect to the processor clock; they are often called synchronous interrupts. Exceptions are produced by the processor while executing instructions either in response to a programming error (e.g. divide by zero) or abnormal conditions that must be handled by the kernel (e.g. a page fault). Because many processor architectures handle exceptions in a similar manner to interrupts, the kernel infrastructure for handling the two is similar.

Simple definitions of the two:

  • Interrupts: asynchronous interrupts generated by hardware.
  • Exceptions: synchronous interrupts generated by the processor.

System calls (one type of exception) on the x86 architecture are implemented by the issuance of a software interrupt, which traps into the kernel and causes execution of a special system call handler. Interrupts work in a similar way, except hardware (not software) issues interrupts.

Interrupt Handlers¶

An interrupt handler or interrupt service routine (ISR) is the function that the kernel runs in response to a specific interrupt:

  • Each device that generates interrupts has an associated interrupt handler.
  • The interrupt handler for a device is part of the device's driver (the kernel code that manages the device).

In Linux, interrupt handlers are normal C functions, which match a specific prototype and thus enables the kernel to pass the handler information in a standard way. What differentiates interrupt handlers from other kernel functions is that the kernel invokes them in response to interrupts and that they run in a special context called interrupt context. This special context is occasionally called atomic context because code executing in this context is unable to block.

Because an interrupt can occur at any time, an interrupt handler can be executed at any time. It is imperative that the handler runs quickly, to resume execution of the interrupted code as soon as possible. It is important that

  • To the hardware: the operating system services the interrupt without delay.
  • To the rest of the system: the interrupt handler executes in as short a period as possible.

At the very least, an interrupt handler's job is to acknowledge the interrupt's receipt to the hardware. However, interrupt handlers can oftern have a large amount of work to perform.

Top Halves Versus Bottom Halves¶

These two goals of an interrupt handler conflict with one another:

  • Execute quickly
  • Perform a large amount of work

Because of these competing goals, the processing of interrupts is split into two parts, or halves:

  • Top half. The interrupt handler is the top half. The top half is run immediately upon receipt of the interrupt and performs only the work that is time-critical, such as acknowledging receipt of the interrupt or resetting the hardware.
  • Bottom half. Work that can be performed later is deferred until the bottom half. The bottom half runs in the future, at a more convenient time, with all interrupts enabled.

Linux provides various mechanisms for implementing bottom halves (discussed in Chapter 8).

For example using the network card:

  1. When network cards receive packets from the network, the network cards immediately issue an interrupt. This optimizes network throughput and latency and avoids timeouts. [p115]
  2. The kernel responds by executing the network card's registered interrupt.
  3. The interrupt runs, acknowledges the hardware, copies the new networking packets into main memory, and readies the network card for more packets. These jobs are the important, time-critical, and hardware-specific work.
    • The kernel generally needs to quickly copy the networking packet into main memory because the network data buffer on the networking card is fixed and miniscule in size, particularly compared to main memory. Delays in copying the packets can result in a buffer overrun, with incoming packets overwhelming the networking card's buffer and thus packets being dropped.
    • After the networking data is safely in the main memory, the interrupt's job is done, and it can return control of the system to whatever code was interrupted when the interrupt was generated.
  4. The rest of the processing and handling of the packets occurs later, in the bottom half.

This chapter discusses the top half. The next chapter covers the bottom.

Registering an Interrupt Handler¶

Each device has one associated driver. If that device uses interrupts (and most do), that driver must register one interrupt handler.

Drivers can register an interrupt handler and enable a given interrupt line for handling with the function , which is declared in :


/* request_irq: allocate a given interrupt line */intrequest_irq(unsignedintirq,irq_handler_thandler,unsignedlongflags,constchar*name,void*dev)

The first parameter, , specifies the interrupt number to allocate

  • For some devices (e.g. legacy PC devices such as the system timer or keyboard), this value is typically hard-coded.
  • For most other devices, it is probed or otherwise determined programmatically and dynamically.

The second parameter, , is a function pointer to the actual interrupt handler that services this interrupt. This function is invoked whenever the operating system receives the interrupt.



Note the specific prototype of the handler function: It takes two parameters and has a return value of .

Interrupt Handler Flags¶

The third parameter, , can be either zero or a bit mask of one or more of the flags defined in . The most important of these flags are:


  • .

    • When set, this flag instructs the kernel to disable all interrupts when executing this interrupt handler.
    • When unset, interrupt handlers run with all interrupts except their own enabled.

    Most interrupt handlers do not set this flag, as disabling all interrupts is bad form. Its use is reserved for performance-sensitive interrupts that execute quickly. This flag is the current manifestation of the flag, which in the past distinguished between "fast" and "slow" interrupts.

  • . This flag specifies that interrupts generated by this device should contribute to the kernel entropy pool. The kernel entropy pool provides truly random numbers derived from various random events. If this flag is specified, the timing of interrupts from this device are fed to the pool as entropy. Do not set this if your device issues interrupts at a predictable rate (e.g. the system timer) or can be influenced by external attackers (e.g. a networking device). On the other hand, most other hardware generates interrupts at nondeterministic times and is therefore a good source of entropy.

  • . This flag specifies that this handler processes interrupts for the system timer.
  • . This flag specifies that the interrupt line can be shared among multiple interrupt handlers. Each handler registered on a given line must specify this flag; otherwise, only one handler can exist per line.

The fourth parameter, , is name of the device associated with the interrupt. For example, this value for the keyboard interrupt on a PC is "keyboard". These text names are used by and .

The fifth parameter, , is used for shared interrupt lines. When an interrupt handler is freed (discussed later), provides a unique cookie to enable the removal of only the desired interrupt handler from the interrupt line. Without this parameter, it would be impossible for the kernel to know which handler to remove on a given interrupt line. You can pass here if the line is not shared, but you must pass a unique cookie if your interrupt line is shared. This pointer is also passed into the interrupt handler on each invocation. A common practice is to pass the driver's device structure. This pointer is unique and might be useful to have within the handlers.

returns zero on success and nonzero value indicates an error, in which case the specified interrupt handler was not registered. A common error is , which denotes that the given interrupt line is already in use (and either the current user or you did not specify ).

cannot be called from interrupt context (other situations where code cannot block), because it can block. It is a common mistake to call when it is unsafe to sleep. On registration, an entry corresponding to the interrupt is created in . The function creates new procfs entries. This function calls to set up the new procfs entries, which in turn calls to allocate memory. can sleep (Chapter 12).

An Interrupt Example¶

In a driver, requesting an interrupt line and installing a handler is done via :

if(request_irq(irqn,my_interrupt,IRQF_SHARED,"my_device",my_dev)){printk(KERN_ERR"my_device: cannot register IRQ %d\n",irqn);return-EIO;}

In this example:

  • is the requested interrupt line
  • is the handler;
  • specifies that the line can be shared;
  • The device is named ;
  • We passed for .

On failure, the code prints an error and returns. If the call returns zero, the handler has been successfully installed. From that point forward, the handler is invoked in response to an interrupt. It is important to initialize hardware and register an interrupt handler in the proper order to prevent the interrupt handler from running before the device is fully initialized.

Freeing an Interrupt Handler¶

When your driver unloads, you need to unregister your interrupt handler and disable the interrupt line, by calling:


  • If the specified interrupt line is not shared, this function removes the handler and disables the line.
  • If the interrupt line is shared, the handler identified via is removed, but the interrupt line is disabled only when the last handler is removed. With shared interrupt lines, a unique cookie is required to differentiate between the multiple handlers that can exist on a single line and enable to remove only the correct handler.

In either case (shared or unshared), if is non-, it must match the desired handler. A call to must be made from process context.

The following table reviews the functions for registering and deregistering an interrupt handler.

Register a given interrupt handler on a given interrupt line.
Unregister a given interrupt handler; if no handlers remain on the line, the given interrupt line is disabled.

Writing an Interrupt Handler¶

The following is a declaration of an interrupt handler, which matches the prototype of the argument given to :

  • The first parameter, , is the numeric value of the interrupt line the handler is servicing. This value is not used very often, except in printing log messages.
    • was useful before version 2.0 of the Linux kernel, when there was not a parameter and was used to differentiate between multiple devices using the same driver and therefore the same interrupt handler, e.g. a computer with multiple hard drive controllers of the same type. [p118-119]
  • The second parameter, , is a generic pointer to the same given to when the interrupt handler was registered. [p119]
    • It can be a unique value (which is required to support sharing) to act as a cookie to differentiate between multiple devices potentially using the same interrupt handler.
    • It might also point to a structure of use to the interrupt handler. This structure is typically the structure, which is both unique to each device and potentially useful to have within the handler.

The return value of an interrupt handler is the special type , which has two special values:

  • , returned when the interrupt handler detects an interrupt for which its device was not the originator.
  • , returned if the interrupt handler was correctly invoked, and its device caused the interrupt.

Alternatively, may be used. If is nonzero, this macro returns . Otherwise, the macro returns .

These special values are used to let the kernel know whether devices are issuing spurious (unrequested) interrupts. If all the interrupt handlers on a given interrupt line return , then the kernel can detect the problem.

The return type which is simply an . This value provides backward compatibility with earlier kernels, which did not have this feature. Before 2.6, interrupt handlers returned void. Drivers may simply typedef to and define the different return values to no-ops and then work in 2.4 without further modification.

The interrupt handler is normally because it is never called directly from another file.

The role of the interrupt handler depends entirely on the device and its reasons for issuing the interrupt.

  • At a minimum, most interrupt handlers need to provide acknowledgment to the device that they received the interrupt.
  • More complex devices need to additionally send and receive data and perform extended work in the interrupt handler. The extended work is pushed as much as possible into the bottom half handler.

Reentrancy and Interrupt Handlers *¶

Interrupt handlers in Linux need not be reentrant. When a given interrupt handler is executing, the corresponding interrupt line is masked out on all processors, preventing another interrupt on the same line from being received. Normally all other interrupts are enabled, so other interrupts are serviced, but the current line is always disabled. Consequently, the same interrupt handler is never invoked concurrently to service a nested interrupt. This greatly simplifies writing your interrupt handler.

Shared Handlers¶

A shared handler is similar to a nonshared handler, but has three main differences:

  • The flag must be set in the flags argument to .
  • The argument must be unique to each registered handler.
    • A pointer to any per-device structure is sufficient: a common choice is the structure as it is both unique and potentially useful to the handler.
    • It cannot be for a shared handler.
  • The interrupt handler must be capable of distinguishing whether its device actually generated an interrupt, which requires both hardware support and associated logic in the interrupt handler; otherwise the interrupt handler would not know whether its associated device or some other device sharing the line caused the interrupt.

All drivers sharing the interrupt line must meet the previous requirements. If any one device does not share fairly, none can share the line. The call to with specified can succeed only if:

  • The interrupt line is currently not registered, or,
  • All registered handlers on the line also specified .

Shared handlers, however, can mix usage of .

When the kernel receives an interrupt, it invokes sequentially each registered handler on the line. Therefore, it is important that the handler be capable of distinguishing whether it generated a given interrupt. The handler must quickly exit if its associated device did not generate the interrupt. This requires the hardware device to have a status register (or similar mechanism) that the handler can check. Most hardware has such a feature.

A Real-Life Interrupt Handler¶

The real-time clock (RTC) driver is a real interrupt handler, which can be found in .

It is a device (separate from the system timer) which can do the following:

  • Sets the system clock.
  • Provides an alarm.
  • Supplies a periodic timer.

On most architectures, the system clock is set by writing the desired time into a specific register or I/O range. An alarm or periodic timer functionality is normally implemented via interrupt. The interrupt is equivalent to a real-world clock alarm and the receipt of the interrupt is analogous to a buzzing alarm.

When the RTC driver loads, the function is invoked to initialize the driver, which includes registering the interrupt handler:

/* register rtc_interrupt on rtc_irq */if(request_irq(rtc_irq,rtc_interrupt,IRQF_SHARED,"rtc",(void*)&rtc_port)){printk(KERN_ERR"rtc: cannot register IRQ %d\n",rtc_irq);return-EIO;}

In this example:

  • The interrupt line is stored in . This variable is set to the RTC interrupt for a given architecture. On a PC, the RTC is located at IRQ 8.
  • The second parameter is the interrupt handler, which shares the interrupt line with other handlers with flag.
  • The fourth parameter indicates that the driver name is .
  • Because this device shares the interrupt line, it passes a unique per-device value for .

The handler code is:


staticirqreturn_trtc_interrupt(intirq,void*dev_id){/* * Can be an alarm interrupt, update complete interrupt, * or a periodic interrupt. We store the status in the * low byte and the number of interrupts received since * the last read in the remainder of rtc_irq_data. */spin_lock(&rtc_lock);rtc_irq_data+=0x100;rtc_irq_data&=~0xff;if(is_hpet_enabled()){/* * In this case it is HPET RTC interrupt handler * calling us, with the interrupt information * passed as arg1, instead of irq. */rtc_irq_data|=(unsignedlong)irq&0xF0;}else{rtc_irq_data|=(CMOS_READ(RTC_INTR_FLAGS)&0xF0);}if(rtc_status&RTC_TIMER_ON)mod_timer(&rtc_irq_timer,jiffies+HZ/rtc_freq+2*HZ/100);spin_unlock(&rtc_lock);/* Now do the rest of the actions */spin_lock(&rtc_task_lock);if(rtc_callback)rtc_callback->func(rtc_callback->private_data);spin_unlock(&rtc_task_lock);wake_up_interruptible(&rtc_wait);kill_fasync(&rtc_async_queue,SIGIO,POLL_IN);returnIRQ_HANDLED;}

This function is invoked whenever the machine receives the RTC interrupt.

  1. Note the spin lock calls:
    • The first set ensures that is not accessed concurrently by another processor on an SMP machine. The variable is an that stores information about the RTC and is updated on each interrupt to reflect the status of the interrupt.
    • The second set protects , similarly to the first one. Locks are discussed in Chapter 10 Kernel Synchronization Methods
  2. If an RTC periodic timer is set, it is updated via . Timers are discussed in Chapter 11 Timers and Time Management.
  3. The code under the comment "now do the rest of the actions" executes a possible preset callback function.The RTC driver enables a callback function to be registered and executed on each RTC interrupt.
  4. This function returns to signify that it properly handled this device. Because the interrupt handler does not support sharing, and there is no mechanism for the RTC to detect a spurious interrupt, this handler always returns .

Interrupt Context¶

When executing an interrupt handler, the kernel is in interrupt context.

Difference from the process context *¶

As discussed in Chapter 3, the process context is the mode of operation the kernel is in while it is executing on behalf of a process, such as executing a system call or running a kernel thread.

  • In process context, the macro points to the associated task.
  • Since a process is coupled to the kernel in process context, process context can sleep or otherwise invoke the scheduler.

Interrupt context is not associated with a process.

  • The macro is not relevant, though it points to the interrupted process.
  • Without a backing process, interrupt context cannot sleep and cannot reschedule. Therefore, you cannot call certain functions from interrupt context. If a function sleeps, you cannot use it from your interrupt handler: this limits the functions that can be called from an interrupt handler.

Interrupt context is time-critical, because the interrupt handler interrupts other code.

  • It should be kept in mind that the interrupt handler has interrupted other code (possibly even another interrupt handler on a different line). Due to asynchronous nature, it is imperative that all interrupt handlers be as quick and as simple as possible.
  • As much as possible, work should be pushed out from the interrupt handler and performed in a bottom half, which runs at a more convenient time.

Stacks of an interrupt handler *¶

The setup of an interrupt handler's stacks is a configuration option.

  • Historically, interrupt handlers did not receive their own stacks. Instead, they would share the stack of the process that they interrupted.
    • Note that a process is always running. When nothing else is schedulable, the idle task runs.
    • The kernel stack is two pages in size:
      • 8KB on 32-bit architectures.
      • 16KB on 64-bit architectures.
    • Because of sharing the stack, interrupt handlers must be exceptionally frugal with what data they allocate there. [p122]
  • Early in the 2.6 kernel process, an option was added to reduce the stack size from two pages to one, providing only a 4KB stack on 32-bit system, and interrupt handlers were given their own stack, one stack per processor, one page in size. This stack is referred to as the interrupt stack.
    • Although the total size of the interrupt stack is half that of the original shared stack, the average stack space available is greater because interrupt handlers get the full page of memory to themselves, because previously every process on the system needed two pages of contiguous, nonswappable kernel memory.

Your interrupt handler should not care what stack setup is in use or what the size of the kernel stack is. Always use an absolute minimum amount of stack space.

Implementing Interrupt Handlers¶

The implementation of the interrupt handling system in Linux is architecture-dependent. The implementation depends on the processor, the type of interrupt controller used, and the design of the architecture and machine.

The following figure is a diagram of the path an interrupt takes through hardware and the kernel.

Interrupt from a device to the processor *¶

  1. A device issues an interrupt by sending an electric signal over its bus to the interrupt controller.
  2. If the interrupt line is enabled (they can be masked out), the interrupt controller sends the interrupt to the processor.
    • In most architectures, this is accomplished by an electrical signal sent over a special pin to the processor.
  3. If interrupts are not disabled in the processor, the processor immediately stops what it is doing, disables the interrupt system, and jumps to a predefined location in memory and executes the code located there. This predefined point is set up by the kernel and is the entry point for interrupt handlers.

Interrupt in the kernel *¶

The interrupt in the kernel begins at this predefined entry point (which is similar to system calls that enter the kernel through a predefined exception handler):

  1. For each interrupt line, the processor jumps to a unique location in memory and executes the code located there. In this manner, the kernel knows the IRQ number (the interrupt value) of the incoming interrupt.
  2. The initial entry point (assembly entry routine) saves the interrupt value and stores the current register values of the interrupted task on the stack.
  3. Then, the kernel calls .

From this point, most of the interrupt handling code is written in C, but is still architecture-dependent.

The function is declared as (kernel/irq/handle.c#L449):

  1. Because the C calling convention places function arguments at the top of the stack, the structure contains the initial register values and the interrupt value, which were previously saved on the stack in the assembly entry routine. can extract the interrupt value.
  2. After the interrupt line is calculated, acknowledges the receipt of the interrupt and disables interrupt delivery on the line.

On normal PC machines, these operations are handled by (arch/x86/kernel/i8259.c#L147).

Next, ensures that a valid handler is registered on the line and that it is enabled and not currently executing. If so, it calls , defined in kernel/irq/handle.c, to run the installed interrupt handlers for the line.


/** * handle_IRQ_event - irq action chain handler * @irq: the interrupt number * @action: the interrupt action chain for this irq * * Handles the action chain of an irq event */irqreturn_thandle_IRQ_event(unsignedintirq,structirqaction*action){irqreturn_tret,retval=IRQ_NONE;unsignedintstatus=0;if(!(action->flags&IRQF_DISABLED))local_irq_enable_in_hardirq();do{trace_irq_handler_entry(irq,action);ret=action->handler(irq,action->dev_id);trace_irq_handler_exit(irq,action,ret);switch(ret){caseIRQ_WAKE_THREAD:/* * Set result to handled so the spurious check * does not trigger. */ret=IRQ_HANDLED;/* * Catch drivers which return WAKE_THREAD but * did not set up a thread function */if(unlikely(!action->thread_fn)){warn_no_thread(irq,action);break;}/* * Wake up the handler thread for this * action. In case the thread crashed and was * killed we just pretend that we handled the * interrupt. The hardirq handler above has * disabled the device interrupt, so no irq * storm is lurking. */if(likely(!test_bit(IRQTF_DIED,&action->thread_flags))){set_bit(IRQTF_RUNTHREAD,&action->thread_flags);wake_up_process(action->thread);}/* Fall through to add to randomness */caseIRQ_HANDLED:status|=action->flags;break;default:break;}retval|=ret;action=action->next;}while(action);if(status&IRQF_SAMPLE_RANDOM)add_interrupt_randomness(irq);local_irq_disable();returnretval;}
  1. Since the processor disabled interrupts, they are turned back on if was not specified during the handler's registration.
    • IRQF_DISABLED specifies that the handler must be run with interrupts disabled.
  2. Each potential handler is executed in a loop. If this line is not shared, the loop terminates after the first iteration. Otherwise, all handlers are executed.
  3. is called if was specified during registration. This function uses the timing of the interrupt to generate entropy for the random number generator.
  4. Interrupts are again disabled ( expects them still to be disabled) and the function returns.

Back in , the function cleans up and returns to the initial entry point, which then jumps to ().

The routine (arch/x86/kernel/entry_64.S#L820) is written in assembly, as with the initial entry code. This routine checks whether a reschedule is pending (this implies that is set, as discussed in Chapter 4):

  • If a reschedule is pending:
    • If the kernel is returning to user-space (that is, the interrupt interrupted a user process), is called.
    • If the kernel is returning to kernel-space (that is, the interrupt interrupted the kernel itself), is called only if the is zero (see kernel preemption). Otherwise it is not safe to preempt the kernel.
  • After returns, or if there is no work pending, the initial registers are restored and the kernel resumes whatever was interrupted.

On x86, the initial assembly routines are located in arch/x86/kernel/entry_64.S (entry_32.S for 32-bit x86) and the C methods are located in arch/x86/kernel/irq.c. Other supported architectures are similar.

Procfs is a virtual filesystem that exists only in kernel memory and is typically mounted at . Reading or writing files in procfs invokes kernel functions that simulate reading or writing from a real file. The file is populated with statistics related to interrupts on the system.

CPU0 0: 3602371 XT-PIC timer 1: 3048 XT-PIC i8042 2: 0 XT-PIC cascade 4: 2689466 XT-PIC uhci-hcd, eth0 5: 0 XT-PIC EMU10K1 12: 85077 XT-PIC uhci-hcd 15: 24571 XT-PIC aic7xxx NMI: 0 LOC: 3602236 ERR: 0
  • The first column is the interrupt line.
    • Interrupts numbered 0–2, 4, 5, 12, and 15 are present this system.
    • Handlers not installed on lines are not displayed.
  • The second column is a counter of the number of interrupts received. A column is present for each processor on the system (this system has one processor: CPU0). On this system:
    • The timer interrupt has received 3,602,371 interrupts
    • The sound card (EMU10K1) has received none (which is an indication that it has not been used since the machine booted).
  • The third column is the interrupt controller handling this interrupt.
  • The last column is the device associated with this interrupt.
    • This name is supplied by the parameter to , as discussed previously.
    • If the interrupt is shared, as is the case with interrupt number 4 in this example, all the devices registered on the interrupt line are listed.

procfs code is located primarily in fs/proc. The function that provides architecture-dependent and named (include/linux/interrupt.h#L607).

Interrupt Control¶

The Linux kernel implements a family of interfaces for manipulating the state of interrupts . These interfaces enable you to disable the interrupt system for the current processor or mask out an interrupt line for the entire machine. These routines are all architecture-dependent and can be found in and .

Controlling the interrupt system provides synchronization.

  • Disabling interrupts guarantees that an interrupt handler will not preempt the current code.
  • Disabling interrupts also disables kernel preemption.

However, neither disabling interrupt delivery nor disabling kernel preemption provides any protection from concurrent access from another processor. Because Linux supports multiple processors, kernel code generally needs to obtain some sort of lock to prevent another processor from accessing shared data simultaneously. These locks are often obtained in conjunction with disabling local interrupts.

  • The lock provides protection against concurrent access from another processor.
  • Disabling interrupts provides protection against concurrent access from a possible interrupt handler.

Chapters 9 and [Chapter 10])( discuss the various problems of synchronization and their solutions.

Disabling and Enabling Interrupts¶

To disable interrupts locally for the current processor (only the current processor) and then later reenable them, do the following:

local_irq_disable();/* interrupts are disabled .. */local_irq_enable();
  • The routine is dangerous if interrupts were already disabled prior to its invocation.
  • The call to unconditionally enables interrupts, despite the fact that they were off to begin with.

These functions are usually implemented as a single assembly operation, which depends on the architecture. On x86, is a simple and is a simple instruction. and are the assembly calls to clear and set the interrupt flag, respectively. In other words, they disable and enable interrupt delivery on the issuing processor.

However, a common concern is a to restore interrupts to a previous state. It is much safer to save the state of the interrupt system before disabling it. Then, when you are ready to reenable interrupts, you simply restore them to their original state [p128]:

unsignedlongflags;local_irq_save(flags);/* interrupts are now disabled *//* ... */local_irq_restore(flags);/* interrupts are restored to their previous state */

Note that these methods are implemented at least in part as macros, so the parameter (which must be defined as an ) is seemingly passed by value. This parameter contains architecture-specific data containing the state of the interrupt systems. Because at least one supported architecture, such as SPARC, incorporates stack information into the value, flags cannot be passed to another function (specifically, it must remain on the same stack frame). For this reason, the call to save and the call to restore interrupts must occur in the same function.

All the previous functions can be called from both interrupt and process context.

No More Global *¶

The kernel formerly provided a function, to disable interrupts on all processors in the system. If another processor called this method, it would have to wait until interrupts were enabled before continuing. The corresponding enable call was named .

These interfaces were deprecated during 2.5, and consequently all interrupt synchronization must now use a combination of local interrupt control and spin locks (discussed in Chapter 9). This means that code that previously only had to disable interrupts globally to ensure mutual-exclusive access to shared data now needs to do a bit more work.

Previously, driver writers could assume a used in their interrupt handlers and anywhere else the shared data was accessed would provide mutual exclusion.

  • The call would ensure that no other interrupt handlers (and thus their specific handler) would run.
  • If another processor entered a protected region, it would not continue until the original processor exited its protected region with a call to .

The advantages of removing the global are:

  • It forces driver writers to implement real locking. A fine-grained lock with a specific purpose is faster than a global lock, which is effectively what is.
  • It streamlined a lot of code in the interrupt system and. The result is simpler and easier to comprehend.

Disabling a Specific Interrupt Line¶

The previous section covers functions that disable all interrupt delivery for an entire processor. In some cases, it is useful to disable only a specific interrupt line for the entire system. This is called masking out an interrupt line.

To disable delivery of a devices' interrupts before manipulating its state, Linux provides four interfaces for this task:

  • The first two functions disable a given interrupt line for all processors in the interrupt controller.
    • The function does not return until any currently executing handler completes. Thus, callers are assured not only that new interrupts will not be delivered on the given line, but also that any already executing handlers have exited.
    • The function does not wait for current handlers to complete.
  • The function waits for a specific interrupt handler to exit, if it is executing, before returning.

Calls to these functions nest. For each call to or on a given interrupt line, a corresponding call to is required. Only on the last call to is the interrupt line actually enabled. For example, if is called twice, the interrupt line is not actually reenabled until the second call to .

All three of these functions can be called from interrupt or process context and do not sleep. If calling from interrupt context, be careful, for example, not to enable an interrupt line while you are handling it. Recall that the interrupt line of a handler is masked out while it is serviced.

It is rude to disable an interrupt line shared among multiple interrupt handlers, because disabling the line disables interrupt delivery for all devices on the line. Therefore, drivers for newer devices tend not to use these interfaces:

  • Many older devices, particularly ISA devices, do not provide a method of obtaining whether they generated an interrupt. Therefore, often interrupt lines for ISA devices cannot be shared.
  • Because the PCI specification mandates the sharing of interrupts, modern PCI-based devices support interrupt sharing. In contemporary computers, nearly all interrupt lines can be shared. Since PCI devices have to support interrupt line sharing by specification, they should not use these interfaces at all.
  • and friends are found more often in drivers for older legacy devices, such as the PC parallel port.

Status of the Interrupt System¶

It is often useful to know:

  • The state of the interrupt system.
    • For example, whether interrupts are enabled or disabled.
  • Whether you are currently executing in interrupt context.

The macro , defined in , returns nonzero if the interrupt system on the local processor is disabled. Otherwise, it returns zero.

Two macros, defined in , provide an interface to check the kernel's current context:

  • The first function is the most useful. It returns nonzero if the kernel is performing any type of interrupt handling, including either executing an interrupt handler or a bottom half handler.
  • The macro returns nonzero only if the kernel is specifically executing an interrupt handler.

If returns zero, the kernel is in process context. This is useful if you want to check whether you are in process context, that is, you want to ensure you are not in interrupt context, which is often the case because code wants to do something that can only be done from process context, such as sleep.

The following table is a summary of the interrupt control methods and their description.

Disables local interrupt delivery
Enables local interrupt delivery
Saves the current state of local interrupt delivery and then disables it
Restores local interrupt delivery to the given state
Disables the given interrupt line and ensures no handler on the line is executing before returning
Disables the given interrupt line
Enables the given interrupt line
Returns nonzero if local interrupt delivery is disabled; otherwise returns zero
Returns nonzero if in interrupt context and zero if in process context
Returns nonzero if currently executing an interrupt handler and zero otherwise


This chapter discussed at interrupts, a hardware resource used by devices to asynchronously signal the processor. Interrupts are used by hardware to interrupt the operating system.

Most modern hardware uses interrupts to communicate with operating systems.The device driver, which manages a given piece of hardware, registers an interrupt handler to respond to and process interrupts issued from their associated hardware. Work performed in interrupts includes:

  • Acknowledging and resetting hardware
  • Copying data from the device to main memory and vice versa
  • Processing hardware requests
  • Sending out new hardware requests

The kernel provides interfaces for:

  • Registering and unregistering interrupt handlers
  • Disabling interrupts
  • Masking out interrupt lines
  • Checking the status of the interrupt system

Because interrupts interrupt other executing code (processes, the kernel itself, and even other interrupt handlers), they must execute quickly. Often there is a lot of work to do and to balance the large amount of work with the need for quick execution, the kernel divides the work of processing interrupts into two halves. The interrupt handler, the top half, was discussed in this chapter. The next chapter looks at the bottom half.

Doubts and Solution¶


p119 on interrupt handlers

The interrupt handler is normally because it is never called directly from another file.

Question: What does it mean?

p120 on shared handlers

Shared handlers, however, can mix usage of .

Question: What does it mean?

p128 on disabling and enabling interrupts

The routine is dangerous if interrupts were already disabled prior to its invocation?

Question: Why is it dangerous?

Solution: may have similar calling mechanisms as functions discussed in p129: calls to these functions nest. If is called twice, the interrupt line is not actually reenabled until the second call to .

IRQ Settings, how to view IRQ assignments and resolve IRQ conflicts.

IRQ stands for Interrupt ReQuest and refers to special numbered channels that are used by devices to get the processors attention.

For example, when you press a key on your keyboard it sends a signal to the processor via an IRQ channel (usually IRQ1) to let it know that it needs to process some data.

IRQ conflicts can occur when new hardware is installed or reconfigured. For example, it can cause problems if you have your mouse on COM 1 (IRQ4) and a modem on COM 3 (IRQ4), below is a list of the default assignments for IRQ channels in Windows.

Default ISA IRQ Assignments

IRQ 0System Timer
IRQ 1Keyboard
IRQ 2Cascaded with IRQ 9
IRQ 3Default COM2 and COM4
IRQ 4Default COM1 and COM3
IRQ 6Floppy Drive Controller
IRQ 8Real Time Clock
IRQ 10Open
IRQ 11Open
IRQ 12PS/2 mouse or Open
IRQ 13Math Coprocessor
IRQ 14Primary Hard Drive controller
IRQ 15Secondary Hard Drive controller

Viewing your current IRQ assignments

  • Using a mouse
    1. Hover the mouse at the top-right of your screen.
    2. Move the mouse down and click on Search.
    3. Type Control panel into the search box.
    4. Click on the Control panel icon.
    5. Click on the Hardware and Sound icon.
    6. Under Devices and Printers click on Device manager
  • Using touchscreen
    1. Swipe to the left from the right-edge of the screen.
    2. Tap on Search.
    3. Type Control panel into the search box.
    4. Tap on the Control panel icon.
    5. Tap on the Hardware and Sound icon.
    6. Under Devices and Printers tap on Device manager

Now see our section below "Opening the list of IRQs".
  1. Click on the START button then type Control panel into the search box.
  2. Click on the Control panel icon in the results (see screenshot below).

Now see our section below "Opening the list of IRQs".
  1. Click on START, click on CONTROL PANEL.
  2. If present, click on Performance and Maintenance (category view).
  3. Click on System.
  4. Click on the Hardware tab.
  5. Click the DEVICE MANAGER button.

Now see our section below "Opening the list of IRQs".

Opening the list of IRQs

Once you have Device Manager open select VIEW from the toolbar menu and then click Resources by Type.

Double click on Interrupt Request (IRQ) as seen in fig 1.1 below:

The list that appears on your machine will vary depending on the hardware you have.

If you are experiencing problems with a newly installed/configured piece of hardware and the drivers are installed correctly, then check to see if it has its own IRQ channel.

Changing IRQ Settings

Warning: Changing system resources such as IRQ channels can result in your computer not functioning correctly. Always make a note of the settings before you change anything so you can restore them back if required.

If you do have a conflict and need to change an IRQ setting:
  1. Right click on the device in the list (see above), and then select properties.
  2. Click the Resources tab.
  3. Remove the tick from the Use automatic settings option.
  4. Select a non-conflicting configuration from the pull down box.
  5. Click OK
You may find you cannot manually change your IRQ settings (the Use automatic settings will be greyed out), this is usually related to the ACPI function used by Windows XP.

To resolve conflicts with PCI or ISA cards try manually setting them in your motherboard's BIOS, or try a different slot for the newly installed device. You will usually find that by changing the slot you will change the IRQ channel as well.

Categories: 1

0 Replies to “Irq0 Assignment Management”

Leave a comment

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *