The Complete Guide to Interrupt Handling in Linux Drivers
Everything a driver author needs about interrupts in Linux 6.12: request_irq, handler rules, shared lines, threaded IRQs, bottom halves, affinity and debugging.

A network card has just received a packet. The CPU is in the middle of a loop in user space and knows nothing about it. Within a few microseconds the card raises a wire, the CPU stops what it was doing, saves its state and jumps to a function your driver registered months ago. That function has almost no time, cannot sleep, may be running while the same code runs on another CPU, and must leave the device quiet enough that the wire drops. Nearly every bug in interrupt code comes from forgetting one of those four facts. This guide covers the whole path in Linux 6.12: how an interrupt reaches your handler, how to register and write one, how to split the work between the handler and process context, how to share lines, how to tune and observe interrupts from user space, and how to debug the failures. The individual subjects have their own deeper posts on SystemCoding; this page is the map that connects them, with a complete driver at the end.
The shape of the problem
An interrupt is the hardware's way of saying "I need attention now" without the CPU polling for it. The alternative, polling a status register in a loop, burns a CPU for a device that might be idle ninety-nine percent of the time. Interrupts invert the arrangement: the device waits, and the CPU is taken only when there is work.
The cost of that arrangement is that your code now runs at a time you did not choose, on top of whatever was executing. That produces four rules, and every rule in this guide is a consequence of one of them.
First, the handler is asynchronous: it can run between any two instructions of your own driver's other code, so data shared with it needs protection that handles being interrupted. Second, it runs in interrupt context, where there is no process to put to sleep, so it must not block. Third, it must be quick, because while it runs the same interrupt is usually masked and other work on that CPU waits. Fourth, it may run concurrently on several CPUs if the line is shared or the device has several vectors, so it needs to be reentrant with respect to other instances of itself or ordered by a lock.
How an interrupt reaches your handler
It helps to know the route, because debugging means finding where along it something went wrong.
The device asserts a signal, either a wire into an interrupt controller or a message written to a special address (MSI, covered below).
The interrupt controller (the APIC on x86, the GIC on most arm64 parts, the PLIC on RISC-V) decides which CPU to deliver it to, applying priorities and masks.
The CPU finishes the current instruction, saves a minimal state and jumps through its vector table to an architecture entry stub.
The stub calls into the generic interrupt layer in
kernel/irq/. The chip-specific flow handler for this interrupt (a function such ashandle_fasteoi_irq()orhandle_edge_irq()) acknowledges and masks as the hardware requires, then walks the list of actions registered on this line.Each action is one registered handler, the function you passed to
request_irq(). If it reportsIRQ_HANDLED, the generic layer counts it; if every action returnsIRQ_NONE, the line is counted as spurious.The flow handler unmasks the interrupt and returns, and the CPU resumes what it was doing.
Linux gives every interrupt source a Linux IRQ number, which is a software identifier and is not the controller's own hardware interrupt number. The mapping between the two is the job of irq_domain. A driver almost never touches hardware interrupt numbers; it gets a Linux IRQ number from platform_get_irq(), pci_irq_vector() or the device tree and uses that. The pieces are documented in the kernel's IRQ guide at https://docs.kernel.org/core-api/irq/index.html.
Registering a handler with request_irq
The core call, declared in linux/interrupt.h:
int request_irq(unsigned int irq, irq_handler_t handler,
unsigned long flags, const char *name, void *dev);irq is the Linux IRQ number. handler is a function with the signature irqreturn_t handler(int irq, void *dev_id). flags describes the line, name shows in /proc/interrupts, and dev is a cookie passed back to the handler and used later to identify this registration. It returns zero or a negative errno. -EBUSY means the line is already in use by something that did not agree to share it. -EINVAL is bad flags or a NULL handler. -ENOMEM is an allocation failure while setting up bookkeeping.
The flags you will use most:
| Flag | Meaning |
|---|---|
IRQF_SHARED | The line may be shared with other devices. Requires a non-NULL dev |
IRQF_TRIGGER_RISING, IRQF_TRIGGER_FALLING, IRQF_TRIGGER_HIGH, IRQF_TRIGGER_LOW | How the line signals. Usually left to firmware or device tree |
IRQF_ONESHOT | Keep the line masked until the threaded handler finishes |
IRQF_NO_THREAD | Never force this handler into a thread, even on a threadirqs kernel |
IRQF_NO_SUSPEND | Keep the interrupt enabled during suspend |
Most modern drivers do not call request_irq() directly. They use the managed variant, devm_request_irq(), which unregisters the handler automatically when the device is removed or probing fails:
ret = devm_request_irq(&pdev->dev, irq, mydev_isr, IRQF_SHARED,
dev_name(&pdev->dev), priv);
if (ret)
return dev_err_probe(&pdev->dev, ret, "cannot get irq %d\n", irq);dev_err_probe() prints the error and handles the -EPROBE_DEFER case quietly, which matters when the interrupt controller has not been probed yet.
Where the interrupt number comes from
For a platform device described in the device tree, call platform_get_irq(pdev, index). It returns the Linux IRQ number or a negative errno, and it prints a diagnostic on failure:
irq = platform_get_irq(pdev, 0);
if (irq < 0)
return irq;The device tree binding for this device would contain interrupts = <GIC_SPI 42 IRQ_TYPE_LEVEL_HIGH>; and a parent interrupt-parent pointing at the controller. The irq_domain of that controller translates the specifier into a mapping and a trigger type. For a PCI device, you call pci_alloc_irq_vectors() and then pci_irq_vector(pdev, n), covered in the MSI section. Never hardcode a number: numbers differ between boards, kernel versions and even boots.
Writing the handler
A handler has a fixed job: find out whether this device raised the interrupt, quiet the device, capture what must be captured while the data is fresh, and defer the rest. In code:
static irqreturn_t mydev_isr(int irq, void *dev_id)
{
struct mydev *d = dev_id;
u32 status = readl(d->regs + REG_STATUS);
if (!(status & STATUS_IRQ_PENDING))
return IRQ_NONE; /* not ours: a shared-line neighbour */
writel(status, d->regs + REG_ACK); /* write-1-to-clear */
d->last_status = status;
schedule_work(&d->work); /* the slow part runs later */
return IRQ_HANDLED;
}Every line is deliberate. Reading the status register first is how a handler on a shared line learns whether the interrupt was for it. Returning IRQ_NONE when it was not is not optional, because the kernel uses that to detect stuck lines. Writing the acknowledge before returning is what makes a level-triggered line go inactive; skipping it causes an interrupt storm, covered later. Storing the status for later keeps the slow path from re-reading a register that may have changed. And schedule_work() hands off the remaining processing.
What the handler must not do
Hard interrupt context forbids anything that can sleep. That excludes mutex_lock(), msleep(), kmalloc(..., GFP_KERNEL), copy_to_user(), and anything that calls them, which includes most of the I2C and SPI APIs, because those wait for a bus transfer. The kernel enforces this with might_sleep() checks: on a kernel with CONFIG_DEBUG_ATOMIC_SLEEP, a violation prints:
BUG: sleeping function called from invalid context at kernel/locking/mutex.c:283
in_atomic(): 1, irqs_disabled(): 1, non_block: 0, pid: 0, name: swapper/1The fix is never to silence the check. It is to move the work to a context that can sleep, using one of the mechanisms below. A separate post explains why sleeping in interrupt context is impossible and not just discouraged: the interrupted code may hold a lock, or have no task_struct that can be rescheduled.
What the handler can do
It can read and write registers, take spinlocks (always with the right variant, see below), allocate with GFP_ATOMIC, signal completions with complete(), wake wait queues with wake_up(), queue work, and raise tasklets or softirqs. It can also call dev_dbg(), though not in the same quantity as a printing loop.
Locking between handler and process code
Suppose process context (a read() method, say) and the handler share a buffer index. If the process code takes a spinlock and the interrupt arrives on the same CPU while the lock is held, the handler tries to take the same lock and spins forever on a CPU that cannot release it. The deadlock is on a single CPU. The cure is to disable local interrupts while holding the lock in process context:
unsigned long flags;
spin_lock_irqsave(&d->lock, flags);
/* touch data the handler also touches */
spin_unlock_irqrestore(&d->lock, flags);The handler itself takes spin_lock(&d->lock) plain, because interrupts are already off on its CPU, and the lock still protects against other CPUs. spin_lock_irqsave() saves the previous interrupt state, so it also works when the caller already had interrupts off. If you know the code runs with interrupts enabled, spin_lock_irq() is slightly cheaper. A separate post on spin_lock_irqsave covers the reasoning in detail and the PREEMPT_RT caveat, where these locks become sleeping locks and handlers run in threads.
Splitting the work: top half and bottom half
The handler is the top half. Its work should take microseconds. The remainder, which might be parsing a packet, copying data, waking a reader or talking to another chip over I2C, runs as a bottom half after the interrupt line is released. Linux has four mechanisms for that, each with a different context and cost.
| Mechanism | Runs in | May sleep | Typical use |
|---|---|---|---|
| Softirq | Softirq context, same CPU | No | Networking, block layer, timers; static, subsystem-level only |
| Tasklet | Softirq context, same CPU | No | Older drivers; being replaced by BH workqueues |
| Workqueue | Kernel thread, process context | Yes | Anything that sleeps; default choice |
| Threaded IRQ | Dedicated kernel thread per IRQ | Yes | Most new device drivers |
A separate post compares the first three at length. For a driver author today the decision is simpler than the table suggests. If the bottom half can sleep or takes more than a few tens of microseconds, use a threaded IRQ or a workqueue. If it must run at softirq speed and does not sleep, use a BH workqueue on a recent kernel. Do not add a new softirq vector: they are a fixed list in include/linux/interrupt.h, shared by the whole kernel, and the kernel's own documentation states that they are for a handful of high-frequency subsystems.
Workqueues
A work item is a function plus a struct work_struct, queued to a pool of kernel threads. Use it when you want the simplest deferral:
struct mydev {
void __iomem *regs;
struct work_struct work;
u32 last_status;
spinlock_t lock;
};
static void mydev_work(struct work_struct *w)
{
struct mydev *d = container_of(w, struct mydev, work);
/* process context: may sleep, take mutexes, talk over I2C */
dev_info(d->dev, "handling status 0x%x\n", d->last_status);
}
/* at probe */
INIT_WORK(&d->work, mydev_work);schedule_work() queues to the system workqueue, shared with the rest of the kernel. If your work is latency-sensitive, or can block for long, or must not share fate with unrelated work, create a dedicated queue with alloc_workqueue(). On removal you must call cancel_work_sync(&d->work) after the interrupt is disabled so no work runs against freed memory. Two further posts cover alloc_workqueue() flags and the workqueue API in depth.
One weakness of schedule_work() from a handler is that if it fires again before the work runs, the second call does nothing: a work item that is already pending is not queued twice. The work function must therefore handle everything that has accumulated, not exactly one event. Latching state into a small queue or counter (d->last_status above is too weak for that purpose; a kfifo or ring buffer is the usual answer) is how drivers avoid losing events.
Threaded interrupts
Linux can run the slow half of an interrupt handler in a kernel thread dedicated to that IRQ, with no work item at all. You register two functions:
int request_threaded_irq(unsigned int irq, irq_handler_t handler,
irq_handler_t thread_fn, unsigned long irqflags,
const char *devname, void *dev_id);The first, handler, is the quick top half in hard interrupt context. It checks the device, quiets it if necessary, and returns IRQ_WAKE_THREAD to ask for the second, thread_fn, to run. thread_fn runs in a thread named irq/<number>-<name> with process context, can sleep, and returns IRQ_HANDLED when done. If you pass NULL as handler, the kernel substitutes a default primary handler that just returns IRQ_WAKE_THREAD, and it then demands IRQF_ONESHOT, because a level-triggered line would otherwise fire again the moment the primary handler returned, before the thread had a chance to clear the cause.
IRQF_ONESHOT tells the core to leave the line masked from the moment the primary handler ends until thread_fn returns. For devices whose interrupt cause is cleared by an I2C read in the thread, which describes most sensors and PMICs, request_threaded_irq(irq, NULL, thread_fn, IRQF_ONESHOT | trigger, name, dev) is the standard pattern. A separate post goes through threaded IRQs, including how the forced-threading threadirqs boot option interacts with handlers.
Trigger types
A device holds its interrupt line in one of two ways. A level-triggered line stays asserted as long as the condition persists, so the CPU sees an interrupt until the driver clears the cause at the device. An edge-triggered line produces a pulse when the condition begins, and a second pulse for the next occurrence; if the CPU misses a pulse, the event can be lost unless the controller latches it.
Level-triggered lines are forgiving about timing and necessary for sharing. Edge-triggered lines need the handler to drain all pending work each time, because while the interrupt is masked a second edge might merge with the first. Pick the type in the device tree with IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_EDGE_RISING and the other constants, or pass IRQF_TRIGGER_* when the platform does not describe it. A separate post covers what each means for your handler's structure, including why a level line plus an unacknowledged cause produces a storm.
Shared interrupt lines
Two devices on the same PCI legacy line, or a few peripheral blocks wired to one SoC interrupt, share a number. Each registers with IRQF_SHARED and a unique dev_id. When the line fires, the core calls every registered handler in turn, and each must work out whether the interrupt was its own.
ret = request_irq(irq, mydev_isr, IRQF_SHARED, "mydev", d);The rules for sharing are strict. Every driver on the line must pass IRQF_SHARED, or the second request_irq() fails with -EBUSY. dev_id must be non-NULL and unique, because free_irq() uses it to pick which action to remove. The handler must read a status register and return IRQ_NONE if its device did not interrupt. And all sharers must use compatible trigger flags. A handler that returns IRQ_HANDLED unconditionally masks real failures and starves its neighbour of the information the core needs.
Free the interrupt before the memory it uses
On teardown the order matters more than on setup. The handler can run at any moment until free_irq() returns, and it dereferences dev_id. So free the interrupt first, then stop the work that the handler queues, then release the memory:
static void mydev_remove(struct platform_device *pdev)
{
struct mydev *d = platform_get_drvdata(pdev);
writel(0, d->regs + REG_IRQ_ENABLE); /* the device stops asserting */
devm_free_irq(&pdev->dev, d->irq, d); /* waits for a running handler */
cancel_work_sync(&d->work);
}free_irq() waits until a handler running on another CPU has finished (synchronize_irq() is built in), so after it returns, no handler is executing or will execute. It must therefore not be called from within the handler or while holding a lock the handler takes, or it deadlocks. If you use devm_request_irq(), the automatic release happens after your remove callback returns, which can be too late for resources you free in remove: that is the standard cause of a use-after-free on module unload, and why the explicit devm_free_irq() above, or ordering the device's own disable first, is worth the extra line. On a kernel with KASAN, such a bug appears as a slab-use-after-free report in the handler.
Also disable the device's own interrupt generation before freeing, so a late edge does not arrive after the handler is gone and leave the line unhandled.
MSI and MSI-X
Modern PCI devices do not use shared wires. They signal an interrupt by writing a small value to a memory address that the interrupt controller watches, a Message Signaled Interrupt. MSI-X extends this to up to 2048 independent vectors per device, each with its own address, data and mask. The benefits are no sharing, no wire to acknowledge, and per-queue interrupts that can be steered to different CPUs, which is what makes multi-queue network cards and NVMe drives scale.
The driver API:
int nvec = pci_alloc_irq_vectors(pdev, 1, 8,
PCI_IRQ_MSIX | PCI_IRQ_MSI | PCI_IRQ_INTX);
if (nvec < 0)
return nvec;
for (i = 0; i < nvec; i++) {
int irq = pci_irq_vector(pdev, i);
ret = devm_request_irq(&pdev->dev, irq, queue_isr, 0,
"mydev-queue", &priv->queue[i]);
if (ret)
return ret;
}pci_alloc_irq_vectors() takes a minimum and maximum count and a set of acceptable types; it prefers MSI-X, then MSI, then legacy INTx, and returns how many vectors it got. pci_irq_vector() converts a vector index into a Linux IRQ number. Because MSI interrupts are never shared, the handler can skip the "is this mine?" check, though reading a status register is still often useful. Older code spells the legacy type PCI_IRQ_LEGACY; current kernels use PCI_IRQ_INTX. A flag PCI_IRQ_AFFINITY asks the core to spread vectors across CPUs automatically.
Affinity and observing interrupts
An interrupt's CPU assignment matters: a network queue's interrupt on the same CPU as the thread that consumes the data keeps the cache warm, and pinning a latency-critical interrupt away from busy cores reduces jitter. The kernel exposes it per IRQ:
cat /proc/irq/42/smp_affinity_list
echo 2-3 | sudo tee /proc/irq/42/smp_affinity_list0-7
2-3The first line is the current mask, all CPUs 0 to 7. After writing, interrupts for IRQ 42 are delivered only to CPUs 2 and 3. Some controllers cannot honor an arbitrary mask and the write fails with EINVAL; managed interrupts (from PCI_IRQ_AFFINITY) cannot be changed from user space at all. The daemon irqbalance automates placement on many distributions. A companion post shows how to read /proc/interrupts and set affinity in detail; here is the table's reading in short:
head -4 /proc/interrupts CPU0 CPU1 CPU2 CPU3
0: 12 0 0 0 IO-APIC 2-edge timer
24: 418302 0 0 0 PCI-MSIX-0000:00:1f.6 0-edge eth0
25: 0 302114 0 0 PCI-MSIX-0000:00:1f.6 1-edge eth0-rx-1Each row is a Linux IRQ number with per-CPU counts, the controller and hardware number, the trigger, and the name you passed to request_irq(). A device whose count never moves is not interrupting; a count racing upward with no useful work is a storm. The numbers above are an illustration of the format.
Interrupt storms and spurious interrupts
A storm is an interrupt that fires continuously. The usual cause with a level-triggered line is a handler that does not clear the device's cause, so the line stays asserted and the CPU re-enters the handler forever. The machine becomes unresponsive, with one CPU consumed.
The kernel has a guard. If a line produces 99,900 of its last 100,000 interrupts unhandled (every action returning IRQ_NONE), note_interrupt() in kernel/irq/spurious.c prints a message and disables the line:
irq 19: nobody cared (try booting with the "irqpoll" option)
CPU: 0 UID: 0 PID: 0 Comm: swapper/0 Not tainted 6.12.0 #1
Call Trace:
<IRQ>
dump_stack_lvl+0x5d/0x80
__report_bad_irq+0x3a/0xd0
note_interrupt+0x2f6/0x340
handle_irq_event+0x8f/0xb0
...
handlers:
[<ffffffffc0a31080>] mydev_isr [mydev]
Disabling IRQ #19"nobody cared" means every handler returned IRQ_NONE. Either the device raised an interrupt your handler failed to recognize, usually because the status test is wrong, or an unrelated device on a shared line is stuck. The handler list in the message tells you which drivers were registered. Check your status mask, check that you acknowledge, and check that your handler returns IRQ_HANDLED when it did the work. The opposite error, returning IRQ_HANDLED when nothing was done, hides the problem and keeps the storm alive; the kernel cannot detect it.
Timers and delays are not interrupts, but they run like them
Kernel timers (timer_setup() and mod_timer()) run their callbacks in softirq context, so the rules for the handler above apply to them as well: no sleeping, short, careful locking. High-resolution timers can run in hard interrupt context. Both have their own posts. When you need a delay in thread context, usleep_range() and msleep() are the right calls and udelay() is for sub-10-microsecond hardware waits only.
A complete driver
Here is a platform driver for an imaginary block with a status register at offset 0, an acknowledge register at offset 4 and an enable register at offset 8, that delivers a level-triggered interrupt. The handler acknowledges and wakes a threaded handler, which logs the event and could do slow work:
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/of.h>
#define REG_STATUS 0x00
#define REG_ACK 0x04
#define REG_ENABLE 0x08
#define STATUS_DONE BIT(0)
#define STATUS_ERROR BIT(1)
struct mydev {
struct device *dev;
void __iomem *regs;
int irq;
u32 pending;
spinlock_t lock;
unsigned long events;
};
static irqreturn_t mydev_hardirq(int irq, void *dev_id)
{
struct mydev *d = dev_id;
u32 status = readl(d->regs + REG_STATUS);
if (!(status & (STATUS_DONE | STATUS_ERROR)))
return IRQ_NONE;
writel(status, d->regs + REG_ACK); /* clear the cause */
spin_lock(&d->lock);
d->pending |= status;
spin_unlock(&d->lock);
return IRQ_WAKE_THREAD;
}
static irqreturn_t mydev_thread(int irq, void *dev_id)
{
struct mydev *d = dev_id;
unsigned long flags;
u32 status;
spin_lock_irqsave(&d->lock, flags);
status = d->pending;
d->pending = 0;
d->events++;
spin_unlock_irqrestore(&d->lock, flags);
if (status & STATUS_ERROR)
dev_warn(d->dev, "device reported an error\n");
if (status & STATUS_DONE)
dev_info(d->dev, "transfer done (event %lu)\n", d->events);
return IRQ_HANDLED;
}
static int mydev_probe(struct platform_device *pdev)
{
struct mydev *d;
int ret;
d = devm_kzalloc(&pdev->dev, sizeof(*d), GFP_KERNEL);
if (!d)
return -ENOMEM;
d->dev = &pdev->dev;
spin_lock_init(&d->lock);
d->regs = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(d->regs))
return PTR_ERR(d->regs);
d->irq = platform_get_irq(pdev, 0);
if (d->irq < 0)
return d->irq;
writel(0, d->regs + REG_ENABLE);
ret = devm_request_threaded_irq(&pdev->dev, d->irq, mydev_hardirq,
mydev_thread, IRQF_ONESHOT,
dev_name(&pdev->dev), d);
if (ret)
return dev_err_probe(&pdev->dev, ret, "irq request failed\n");
platform_set_drvdata(pdev, d);
writel(STATUS_DONE | STATUS_ERROR, d->regs + REG_ENABLE);
dev_info(&pdev->dev, "ready on irq %d\n", d->irq);
return 0;
}
static void mydev_remove(struct platform_device *pdev)
{
struct mydev *d = platform_get_drvdata(pdev);
writel(0, d->regs + REG_ENABLE);
devm_free_irq(&pdev->dev, d->irq, d);
}
static const struct of_device_id mydev_of_match[] = {
{ .compatible = "example,mydev" },
{ }
};
MODULE_DEVICE_TABLE(of, mydev_of_match);
static struct platform_driver mydev_driver = {
.probe = mydev_probe,
.remove = mydev_remove,
.driver = {
.name = "mydev",
.of_match_table = mydev_of_match,
},
};
module_platform_driver(mydev_driver);
MODULE_LICENSE("GPL");Some design decisions are worth naming. The register enable happens after the IRQ is registered and the device is fully initialized, not before, so an interrupt can never arrive for a half-built object. The top half takes spin_lock plain, because it already runs with the line masked on its CPU, and the thread takes spin_lock_irqsave because it runs with interrupts enabled and the top half could preempt it on the same CPU. Both are needed to guard pending. IRQF_ONESHOT is passed because the thread, not the top half, finishes the work, and the line must stay masked until then. The remove function uses .remove returning void, the form used since Linux 6.11 for platform drivers. On an older tree the signature returns int.
With a bound device and one event on a device tree node mydev@40001000 using interrupt 42, the kernel log shows:
mydev 40001000.mydev: ready on irq 42
mydev 40001000.mydev: transfer done (event 1)and /proc/interrupts has a new row whose count increments with each transfer:
42: 1 0 0 0 GICv3 74 Level 40001000.mydevThe row's last column is dev_name(&pdev->dev), which is what we passed as the name. The hardware number 74 is arbitrary here; it comes from the GIC mapping of the device tree specifier.
Testing without hardware
Hardware is not always on the bench, so test the logic without it. A kernel built with CONFIG_GENERIC_IRQ_INJECTION can fire an interrupt on demand through the IRQ debugfs directory, which proves that registration works and that your handler returns the right value. It does not fake register contents, so a handler that reads a status register needs a stand-in for the device: a small test module that implements the register file in ordinary memory, or a virtual device in an emulator. The cheapest approach is structural. Keep the register-reading shell of the handler thin and put every decision in a function that takes the status value as an argument. That function can then be checked with KUnit tests, or compiled for a host, with every branch covered and no interrupt involved.
Debugging checklist
When an interrupt-driven driver misbehaves, work through this order.
Is the interrupt registered?
grep mydev /proc/interrupts. No row meansrequest_irq()failed or was never called; read theprobelog for-EBUSYor-EPROBE_DEFER.Is it arriving? The count column should rise when the device acts. If it does not, check the trigger type in the device tree against the datasheet: a level-high line described as edge-rising is the single most common mistake, and it produces a driver that works once and then hangs.
Is it unhandled? Compare
/proc/interruptswith theERRline and/proc/irq/<n>/spurious, which showscount,unhandledandlast_unhandledfor the line:
cat /proc/irq/42/spuriouscount 1
unhandled 0
last_unhandled 0 msIs the handler fast enough? Enable the
irq:irq_handler_entryandirq:irq_handler_exittrace events throughtrace-cmdor tracefs and read the timestamps; long handlers show as large gaps. Theirqsofftracer shows the longest stretch with interrupts disabled.Is context wrong? Build with
CONFIG_DEBUG_ATOMIC_SLEEP,CONFIG_PROVE_LOCKINGandCONFIG_DEBUG_SPINLOCK. Lockdep will flag a lock taken with and without interrupts disabled before it can cost you a deadlock; the lockdep post shows how to read its reports.Is teardown ordered? Unload and reload the module in a loop under KASAN. A use-after-free after
rmmodalmost always means the interrupt, a timer or a work item outlived the memory.
Performance considerations
Each interrupt costs a pipeline flush, a stack switch, a controller acknowledgement and cache pollution, which together make a high interrupt rate expensive independently of how short the handler is. Drivers for fast devices counter this in a few established ways. Interrupt coalescing makes the device raise one interrupt per batch or per time window, set through ethtool for network cards. NAPI in the network stack turns off the device interrupt once the first packet arrives and polls for more, falling back to interrupts when the queue goes empty; the same pattern applies in any driver where load can exceed the interrupt rate the CPU can serve. Per-queue MSI-X vectors spread load across CPUs. We do not quote latency figures here because they depend on the controller, the CPU and the kernel configuration; measure with the tracing events above on your own hardware.
What this guide does not cover
Four boundaries are worth stating plainly. If you are writing an interrupt controller driver, you need irq_domain and irq_chip, a separate subject with its own post. If you write for a hard real-time system, read the PREEMPT_RT documentation: there, handlers run in threads by default and spin_lock sleeps, which changes which guarantees you can rely on. If your device is behind a USB, I2C or SPI bridge, the "interrupt" is not a CPU interrupt at all, it is a message your bus driver turns into a callback, and the context rules differ. And if your driver is a user-space one using UIO or VFIO, interrupts reach you through a file descriptor read, not a function the kernel calls.
Contexts, and how the kernel tells you which one you are in
The kernel tracks what kind of context code runs in with a counter, preempt_count, split into fields for preemption disable depth, softirq depth, hardirq depth and NMI. You can query it with a few macros from linux/preempt.h: in_hardirq() is true inside a hard interrupt handler, in_softirq() inside softirq or bottom-half-disabled sections, in_nmi() in a non-maskable interrupt, and in_task() when you are in an ordinary process. A function that must behave differently in the two worlds, for example choosing GFP_ATOMIC versus GFP_KERNEL, can ask these questions, though the sound design is to make the caller pass the flag rather than guess.
The might_sleep() annotation is the other side of the same coin. Put it at the top of any function that can block, and a debug kernel will complain the first time it is called from a context where blocking is illegal, even if the sleep never actually happens on that run. This is the cheapest bug detector available for interrupt code, because the invalid call is caught on the path that executes, not only when memory happens to be low.
Masking, disabling and synchronizing
Three similarly named operations are easy to confuse. local_irq_disable() and local_irq_save() turn off interrupts on the current CPU only, and they are what the spinlock variants use under the hood. disable_irq(irq) masks one specific interrupt line at the controller, for all CPUs, and waits until any running handler for that line has finished, so it must not be called from that line's own handler. disable_irq_nosync() masks without waiting and is the version to use inside a handler. enable_irq() undoes either, and the calls nest, so two disables need two enables.
synchronize_irq(irq) is the one for teardown and reconfiguration: it waits until no handler for that line is running anywhere, without changing the mask. A common pattern is to stop the device from raising new interrupts by writing its enable register, call synchronize_irq(), and then safely change state that the handler reads. Together they give you the ordering guarantee you cannot get from the register write alone, since an interrupt already in flight on another CPU would otherwise still be executing against the old state.
Interrupts and power management
An interrupt that fires while the system is suspended has to be able to wake it, and one that fires at the wrong time can prevent suspend. By default the core disables most interrupts during suspend. A device that is a wake source calls device_init_wakeup(dev, true) at probe and enable_irq_wake(irq) in its suspend callback, and the core keeps that line armed as a wake interrupt, paired with disable_irq_wake() on resume. The flag IRQF_NO_SUSPEND is for the rare interrupts that must keep running through suspend, such as a timer or an inter-processor interrupt; using it on an ordinary device means its handler can run while the device's own state is frozen, which is a recipe for hangs on resume.
On resume there is a second hazard: an edge that arrived while the interrupt was disabled can be lost. The core resends such an interrupt for lines that are marked as needing it, using a mechanism called check_irq_resend(), and a driver on a level-triggered line is naturally safe because the line is still asserted when it is unmasked.
Interrupts on a real-time kernel
With CONFIG_PREEMPT_RT, the rules change in ways that matter to driver authors. Most interrupt handlers are forced into threads, as if registered with request_threaded_irq(), and spinlock_t becomes a sleeping lock built on an rt-mutex, so ordinary spinlock code can be preempted and may sleep. Handlers that truly must run in hard interrupt context, such as those for the timer tick, pass IRQF_NO_THREAD, and locks that must remain real spinlocks are declared as raw_spinlock_t. A driver written correctly for the mainline kernel, that does not sleep in its handler and takes the right spinlock variant, works unchanged on RT; the bugs it exposes are the ones that were already latent, such as taking a spinlock in a context that assumed it would never be preempted. The documentation at https://docs.kernel.org/locking/locktypes.html lists the lock types and what each means under RT.
Logging from a handler
dev_info() and pr_info() from a handler are safe, because the printk machinery is designed to be called from any context, but they are slow and they generate output at the rate of the interrupt. A handler that logs on every event of a device interrupting a thousand times a second will flood the ring buffer and slow the system. The tools are dev_dbg(), which compiles away or is controlled at run time with dynamic debug, and the _ratelimited variants such as dev_warn_ratelimited(), which print at most a few messages per interval and note how many were suppressed. For counting events, prefer a counter exposed through sysfs or debugfs to a log line.
A worked failure: the interrupt that fires once
A driver registers its handler, the device raises one interrupt, the log shows "transfer done", and then nothing happens again even though the device keeps producing events. The pieces to check, in order: the count in /proc/interrupts stopped at 1, so the line is not delivering. With a level-triggered line and a device whose acknowledge register was written with the wrong bit pattern, the cause stays asserted and the core's IRQF_ONESHOT logic keeps the line masked until the thread finishes; if the thread returned without clearing anything, the line was unmasked and fires again, giving a storm rather than silence. Silence instead means the line stayed masked: the thread function returned IRQ_NONE or never ran to completion, or the primary handler returned IRQ_HANDLED without ever returning IRQ_WAKE_THREAD on a oneshot line. Reading /sys/kernel/debug/irq/irqs/42 (with debugfs and CONFIG_GENERIC_IRQ_DEBUGFS) prints the state flags of the interrupt, including IRQD_IRQ_MASKED and IRQD_IRQ_DISABLED, which confirms the diagnosis in one read.


