Interrupts & Polling

Hardware interrupts, IRQ handling, and interrupt bottom halves (tasklets, workqueues) for robust I/O processing.

published: reading time: 31 min read author: Geek Workbench updated: November 18, 2026
Quick Summary

Hardware interrupts, IRQ handling, and interrupt bottom halves (tasklets, workqueues) for robust I/O processing.

Introduction

Devices can notify the operating system when work is ready, but the path to the CPU depends on the platform and device. A legacy device may use a wired interrupt routed through a controller; a PCI device may send an MSI or MSI-X message, which is a memory write handled by platform interrupt-routing hardware. Some systems also use interrupt remapping. The CPU then enters an architecture-specific handler path, and Linux dispatches the logical IRQ to a registered driver handler. Many drivers defer packet or I/O processing instead of doing all of it in the hard interrupt handler.

Interrupts let hardware report events without constant polling. Polling is still useful in some workloads, and Linux drivers often combine both approaches.

When to Use / When Not to Use

When Hardware Interrupts Are Appropriate

  • Sparse, unpredictable events: Network packets arriving, user input, hardware faults
  • Latency-critical operations: Real-time systems where sub-millisecond response matters
  • Low-power designs: CPU can sleep until hardware signals need for service
  • High-bandwidth devices with flow control: Disks, high-speed network cards that can buffer temporarily

When Polling Is Appropriate

  • Dense, predictable events: High-frequency timers, status monitoring
  • Latency-jitter-tolerant designs: When consistent polling interval is acceptable
  • Interrupt storm prevention: Devices that naturally generate very high interrupt rates
  • Virtualized environments: Hypervisors may emulate interrupt delivery; polling vCPUs can be more efficient
  • Modern NVMe drives: Internal queue depths and interrupt coalescing make polling viable

Hybrid Approaches (The Common Case)

Interrupting once per event can create too much overhead at high event rates. A multi-queue device may use MSI-X vectors for separate queues, while interrupt coalescing and deferred polling let the driver batch work. Polling continuously wastes CPU time when a device is idle, so Linux drivers often combine both approaches.

Interrupt coalescing trades latency for throughput. A device may wait until it has accumulated events or a timer expires before notifying the CPU. That can reduce interrupt overhead, but adds delay while events are batched. On Linux, ethtool -C can change a network device’s coalescing settings when its driver supports them. The example below changes system behavior, requires administrative privileges, and uses values that may not suit your NIC or workload. Check the current settings and device support first:

sudo ethtool -c eth0
sudo ethtool -C eth0 rx-usecs 128 rx-frames 16

Deferred processing keeps hard interrupt handlers short. A primary handler may check device state, acknowledge or mask the source as required by that device, and queue follow-up work. Softirqs and tasklets run in atomic context and cannot sleep; threaded IRQ handlers and workqueues run in schedulable kernel-thread context and can sleep. Which mechanism fits depends on the work and the driver’s design.

Polled phases can reduce interrupt overhead during bursts. In a common Linux network-driver path, a hard IRQ schedules NAPI polling and the driver masks the relevant device interrupt. NAPI processes packets within a budget; when the queue is drained, the driver can re-enable interrupts. The exact arrangement depends on the driver and device. NAPI is a networking mechanism, not a general rule for storage or virtualized devices.

Architecture or Flow Diagram

This simplified Linux flow shows one common path. Wired interrupts, MSI/MSI-X, and platform interrupt controllers differ in how the request reaches a CPU.

sequenceDiagram
    participant HW as Hardware Device
    participant CPU
    participant IC as Interrupt Controller / IRQ Domain
    participant ENTRY as Architecture Entry Code
    participant IRQ as Linux IRQ Core
    participant ISR as Driver Primary Handler
    participant BH as Threaded Handler / Deferred Work
    participant DRV as Device Driver

    HW->>IC: Wired signal or MSI/MSI-X message
    IC->>CPU: Route interrupt to a CPU/vector
    CPU->>ENTRY: Enter architecture-specific handler path
    ENTRY->>IRQ: Pass mapped Linux IRQ to generic IRQ layer
    IRQ->>ISR: Dispatch registered driver handler
    ISR->>HW: Check status and acknowledge or mask source
    ISR->>BH: Wake thread or queue deferred work
    ISR-->>CPU: Return from hard interrupt
    BH->>DRV: Process queued I/O work
    DRV->>DRV: Handle data, wake waiters

On x86, architecture entry code uses interrupt vectors and IDT structures; other architectures use different exception and controller paths. Linux’s generic IRQ layer dispatches a logical IRQ through the controller-specific IRQ chip and any registered handlers. Deferred work may run as a softirq, a thread, or a workqueue, depending on the driver.

Core Concepts

Hardware Interrupts

An interrupt is a notification that reaches a CPU through platform interrupt hardware. It may originate as a wired signal or as a message such as PCI MSI/MSI-X; the interrupt controller and Linux IRQ layer map that source to a handler.

Types of interrupts:

  • Maskable interrupts: Can be masked through the architecture or interrupt-controller mechanisms. The x86 IF flag is one architecture-specific control.
  • Non-maskable interrupts (NMI): Cannot be ignored—used for critical events like hardware failures
  • Message-signaled interrupts (MSI/MSI-X): A PCI device writes to a programmed address and data value; interrupt-remapping/controller hardware routes the message. MSI-X supports more independently configurable vectors than MSI, but the device, platform, and driver determine how many can be used.

For PCI drivers, Linux allocates vectors with pci_alloc_irq_vectors() and maps a vector to a Linux IRQ with pci_irq_vector(). A Linux IRQ number is not necessarily the same as a hardware pin or vector number. See the kernel’s MSI Driver Guide.

Interrupt lifecycle: The example uses a shared legacy PCI INTx interrupt. MSI/MSI-X drivers allocate vectors separately and use pci_irq_vector() to obtain the Linux IRQ number for each vector.

// 1. Driver registers handler during initialization
static int my_driver_probe(struct pci_dev *pdev)
{
    int ret;

    // Register interrupt handler
    ret = request_threaded_irq(
        pdev->irq,                    // Linux IRQ for this legacy INTx example
        my_driver_isr,               // Primary handler: hard IRQ context, cannot sleep
        my_driver_thread,            // Thread function: schedulable context
        IRQF_SHARED,                  // Share this wired interrupt where supported
        "my_driver",                 // Name for /proc/interrupts
        my_dev);                     // Passed to handler

    return ret;
}

// 2. Linux IRQ core dispatches the mapped IRQ to the primary handler
static irqreturn_t my_driver_isr(int irq, void *dev_id)
{
    struct my_device *dev = dev_id;
    u32 status = readl(dev->regs + STATUS_REG);

    if (!(status & IRQ_PENDING))
        return IRQ_NONE;  // Not our interrupt

    // Acknowledge—prevention of spurious interrupts
    writel(status, dev->regs + STATUS_REG);

    // Store any needed state for bottom half
    dev->interrupt_status = status;

    return IRQ_WAKE_THREAD;  // Schedule threaded handler
}

// 3. Threaded handler runs in schedulable kernel-thread context
static irqreturn_t my_driver_thread(int irq, void *dev_id)
{
    struct my_device *dev = dev_id;
    u32 status = dev->interrupt_status;

    if (status & PACKET_AVAILABLE)
        process_packets(dev);

    if (status & BUFFER_DONE)
        complete_transfer(dev);

    return IRQ_HANDLED;
}

IRQ Handling in Linux

The path varies by architecture and interrupt controller. A device can raise a wired interrupt or send an MSI/MSI-X message. Low-level architecture code and the interrupt controller identify the source, then Linux’s generic IRQ layer uses an IRQ descriptor and controller-specific operations to dispatch the registered handler. Some wired interrupts can be shared; MSI interrupts are not shared in that way.

IRQ affinity limits which CPUs may receive an interrupt. Drivers can request affinity while allocating vectors, and the IRQ core can manage affinity as CPUs come online or offline. User changes through /proc/irq/ apply only to IRQs that permit them. The x86 APIC is one interrupt-controller implementation; Arm and other platforms use different controllers and routing models. See the kernel’s generic IRQ and managed IRQ affinity documentation.

Interrupt Bottom Halves

The primary hard IRQ handler must run quickly and cannot sleep. Deferred mechanisms handle work that does not belong in that context. Softirqs and tasklets remain atomic; a threaded IRQ or workqueue runs in schedulable kernel-thread context.

Tasklets — A legacy deferred-work mechanism that runs in softirq context. It cannot sleep, and a given tasklet is not run concurrently with itself:

// Tasklet structure embedded in device struct
struct my_device {
    // ... other fields ...
    struct tasklet_struct tlet;
    u32 pending_work;
};

// Initialize tasklet
void my_device_init(struct my_device *dev)
{
    tasklet_init(&dev->tlet, my_device_tasklet, (unsigned long)dev);
}

// Tasklet function (runs in interrupt context, but can schedule)
void my_device_tasklet(unsigned long data)
{
    struct my_device *dev = (struct my_device *)data;
    u32 work = xchg(&dev->pending_work, 0);  // Atomically grab and clear

    if (work & PACKET_WORK)
        process_packets(dev);
    if (work & TIMER_WORK)
        handle_timer(dev);
}

// In ISR: schedule tasklet instead of direct processing
static irqreturn_t my_isr(int irq, void *dev_id)
{
    struct my_device *dev = dev_id;
    u32 status = readl(dev->regs + STATUS_REG);

    dev->pending_work |= status;
    tasklet_schedule(&dev->tlet);  // Schedule bottom half

    return IRQ_HANDLED;
}

Workqueues — Run in kernel thread context, can sleep, can be delayed:

// Work structure for deferred processing
struct delayed_work {
    struct work_struct work;
    struct timer_list timer;
};

// Initialize work
INIT_WORK(&dev->work, process_workqueue);
INIT_DELAYED_WORK(&dev->delayed_work, process_delayed);

// Schedule immediate work
schedule_work(&dev->work);

// Schedule delayed work (5 jiffies)
schedule_delayed_work(&dev->delayed_work, 5);

// In driver cleanup
flush_work(&dev->work);
cancel_delayed_work_sync(&dev->delayed_work);

Threaded IRQs — Simpler model: handler runs as a kernel thread:

// request_threaded_irq combines ISR + thread in one call
// ISR is minimal (runs atomic), thread handles rest
ret = request_threaded_irq(
    irq,
    isr_routine,     // Optional primary handler (can return IRQ_WAKE_THREAD)
    threadRoutine,    // Threaded handler (can sleep)
    flags,
    name,
    dev_id);

Polling Model

Polling uses explicit software checking instead of hardware signals:

// Simple polling loop (inefficient—don't do this!)
while (device_has_work()) {
    handle_device_event();
}

// Better: timer-driven polling with adjustable rate
static void poll_timer_callback(struct timer_list *t)
{
    struct my_device *dev = from_timer(dev, t, poll_timer);

    // Check and handle any pending work
    u32 status = readl(dev->regs + STATUS_REG);
    if (status)
        process_status(dev);

    // Reschedule if device still needs servicing
    if (device_needs_poll(dev))
        mod_timer(&dev->poll_timer, jiffies + POLL_INTERVAL);
}

// Initialize polling
timer_setup(&dev->poll_timer, poll_timer_callback, 0);
add_timer(&dev->poll_timer);

Comparison: Interrupts vs Polling

Aspect Interrupts Polling
CPU overhead (idle device) Zero—CPU sleeps Constant—CPU checks repeatedly
Response latency Immediate—hardware signals Bounded by poll interval
Scalability Pin-limited (MSI helps) No hardware limit
Complexity More complex (handling race conditions) Simpler state machine
Event density Degrades at high rates Handles high rates naturally
Power consumption Lower when idle Higher when idle

Production Failure Scenarios

Scenario 1: Interrupt Storm from Misbehaving Hardware

What happened: A faulty network card repeatedly signaled an interrupt after certain packet patterns. The high interrupt rate consumed CPU time in the handler and deferred network processing, increasing latency for other work.

Detection: cat /proc/interrupts showed interrupt count incrementing in thousands per second for that IRQ line. top showed softirq CPU time dominating.

Mitigation:

// Limit interrupt rate by returning IRQ_NONE for spurious events
static irqreturn_t net_driver_isr(int irq, void *dev_id)
{
    struct net_device *ndev = dev_id;
    u32 status = readl(ndev->regs + IRQ_STATUS);

    // If no real interrupt source, pretend we didn't see it
    if (!(status & (TX_DONE | RX_PENDING | LINK_CHANGE)))
        return IRQ_NONE;  // Spurious—don't reschedule

    // Handle real sources, acknowledge, schedule NAPI if needed
    // ...
    return IRQ_HANDLED;
}

Also configure interrupt coalescing in hardware to reduce interrupt frequency.

Scenario 2: Deadlock from Blocking in ISR

What happened: A driver’s hard IRQ handler tried to access a userspace pointer. copy_to_user() and put_user() may fault and are not safe in hard interrupt or softirq context.

Detection: System hang with “scheduling while atomic” kernel panic.

Mitigation:

// Hard IRQ: record device state in a kernel-owned buffer.
static irqreturn_t my_isr(int irq, void *dev_id)
{
    struct my_device *dev = dev_id;

    dev->pending_data_len = readl(dev->regs + LEN_REG);
    schedule_work(&dev->work);
    return IRQ_HANDLED;
}

// Deferred work can wake a userspace reader, but should not copy to a
// userspace pointer itself.
static void my_work_handler(struct work_struct *work)
{
    struct my_device *dev = container_of(work, struct my_device, work);

    wake_up_interruptible(&dev->read_wait);
}

// A read() file operation runs in the calling process's context.
static ssize_t my_read(struct file *file, char __user *user_buf,
                       size_t count, loff_t *offset)
{
    struct my_device *dev = file->private_data;
    size_t len = dev->pending_data_len;

    if (count > len)
        count = len;
    if (copy_to_user(user_buf, dev->buffer, count))
        return -EFAULT;
    return count;
}

Scenario 3: Race Between ISR and Driver Removal

What happened: Driver was being unloaded while interrupts were still in flight. The ISR dereferenced memory that had been freed during driver removal, causing a use-after-free panic.

Detection: Kernel panic in ISR context with corrupted data structures.

Mitigation:

static int my_driver_remove(struct pci_dev *pdev)
{
    struct my_device *dev = pci_get_drvdata(pdev);

    // Synchronize with any pending interrupts
    // 1. Prevent new interrupts
    disable_irq(pdev->irq);

    // 2. Wait for any in-flight ISRs to complete
    synchronize_irq(pdev->irq);

    // 3. Now safe to free resources
    tasklet_kill(&dev->tlet);
    devm_free_irq(&pdev->dev, pdev->irq, dev);
    pci_set_drvdata(pdev, NULL);

    return 0;
}

Also use reference counting (kref_get/kref_put) to ensure device data isn’t freed while any code (ISR or otherwise) might access it.

Trade-off Table

Mechanism Latency CPU Overhead (idle) Throughput ceiling Complexity
Bare interrupts Lowest (immediate) Zero Limited by IRQ rate Medium
Interrupt + tasklet Low + deferred processing Minimal when idle High (batched) Medium
Threaded IRQ Low + full kernel features Context switch cost High Low
NAPI (poll mode) Higher (polling interval) Zero when idle Very high High
Pure polling Bounded by interval Constant 100% Limited by poll freq Low

Implementation Snippets

Complete Interrupt-Driven Driver Framework

#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/workqueue.h>
#include <linux/timer.h>

#define SHARED_IRQ
#define POLL_INTERVAL (HZ / 10)  // 100ms

struct my_device {
    void __iomem *regs;
    unsigned int irq;
    struct tasklet_struct tlet;
    struct work_struct work;
    struct timer_list poll_timer;
    u32 interrupt_count;
    bool use_polling;  // Fallback when interrupts fail
};

static irqreturn_t my_driver_isr(int irq, void *dev_id)
{
    struct my_device *dev = dev_id;
    u32 status;

    /* Read status - clears interrupt latches in hardware */
    status = readl(dev->regs + INT_STATUS);
    if (!status)
        return IRQ_NONE;

    /* Atomically store status for bottom half */
    dev->interrupt_count++;

    /* For this device, bottom half is tasklet */
    tasklet_schedule(&dev->tlet);

    return IRQ_HANDLED;
}

static void my_tlet_handler(unsigned long data)
{
    struct my_device *dev = (struct my_device *)data;
    u32 status = readl(dev->regs + INT_STATUS);

    /* Process packet arrivals */
    if (status & PKT_AVAILABLE) {
        struct sk_buff *skb = dev_alloc_skb(2048);
        if (skb) {
            /* Transfer data - DMA or MMIO */
            read_memcpy_from_io(skb_put(skb, 2048),
                               dev->regs + RX_BUFFER, 2048);
            netif_rx(skb);
        }
    }
}

static void my_work_handler(struct work_struct *work)
{
    /* For longer operations that can't sleep in tasklet */
    struct my_device *dev = container_of(work, struct my_device, work);

    /* Process configuration changes, etc. */
    msleep(10);  // Safe here
}

/* Polling fallback for environments with broken interrupts */
static void my_poll_timer(struct timer_list *t)
{
    struct my_device *dev = from_timer(dev, t, poll_timer);
    u32 status = readl(dev->regs + INT_STATUS);

    if (status & PKT_AVAILABLE)
        my_tlet_handler((unsigned long)dev);

    if (dev->use_polling)
        mod_timer(&dev->poll_timer, jiffies + POLL_INTERVAL);
}

static int my_driver_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
    struct my_device *dev;
    int ret;

    dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL);
    if (!dev)
        return -ENOMEM;

    pci_set_drvdata(pdev, dev);

    /* Map hardware registers */
    dev->regs = pcim_iomap(pdev, 0, 0);
    if (!dev->regs)
        return -ENOMEM;

    /* Request IRQ - threaded variant for sleeping-capable handler */
    ret = request_threaded_irq(pdev->irq, NULL, my_threaded_isr,
                               IRQF_SHARED, KBUILD_MODNAME, dev);
    if (ret) {
        dev_warn(&pdev->dev, "IRQ %u unavailable, using polling\n", pdev->irq);
        dev->use_polling = true;
        timer_setup(&dev->poll_timer, my_poll_timer, 0);
        mod_timer(&dev->poll_timer, jiffies + POLL_INTERVAL);
    } else {
        dev->irq = pdev->irq;
    }

    /* Initialize tasklet and work */
    tasklet_init(&dev->tlet, my_tlet_handler, (unsigned long)dev);
    INIT_WORK(&dev->work, my_work_handler);

    return 0;
}

static void my_driver_remove(struct pci_dev *pdev)
{
    struct my_device *dev = pci_get_drvdata(pdev);

    if (dev->use_polling) {
        del_timer_sync(&dev->poll_timer);
    } else {
        free_irq(pdev->irq, dev);
    }

    tasklet_kill(&dev->tlet);
    cancel_work_sync(&dev->work);

    pci_set_drvdata(pdev, NULL);
}

static struct pci_device_id my_driver_id[] = {
    { PCI_DEVICE(0x1234, 0x5678) },
    { }
};
MODULE_DEVICE_TABLE(pci, my_driver_id);

static struct pci_driver my_driver = {
    .name = KBUILD_MODNAME,
    .id_table = my_driver_id,
    .probe = my_driver_probe,
    .remove = my_driver_remove,
};
module_pci_driver(my_driver);

Python Model of Interrupt vs Polling

#!/usr/bin/env python3
"""
Toy model for comparing event callbacks with periodic checks. Python threads and callbacks do not model hardware interrupt delivery, Linux driver context, or kernel latency.
"""
import time
import threading
from dataclasses import dataclass
from typing import Callable
import random


@dataclass
class Device:
    """Simulated hardware device with interrupt capability."""
    name: str
    interrupt_callback: Callable[[], None]
    event_interval_ms: float  # How often device generates events

    def __post_init__(self):
        self._running = False
        self._thread = None

    def start(self):
        """Simulate device generating interrupts."""
        self._running = True
        def event_loop():
            while self._running:
                time.sleep(random.uniform(0, self.event_interval_ms * 2) / 1000)
                if self._running and random.random() < 0.7:  # 70% event rate
                    self.interrupt_callback()
        self._thread = threading.Thread(target=event_loop, daemon=True)
        self._thread.start()

    def stop(self):
        self._running = False
        if self._thread:
            self._thread.join(timeout=1.0)


class InterruptDrivenHandler:
    """Handle events immediately via callback."""
    def __init__(self):
        self.events_handled = 0
        self.last_event_time = None

    def handle_interrupt(self):
        self.events_handled += 1
        self.last_event_time = time.time()
        # Simulate minimal ISR work
        self._process_event()

    def _process_event(self):
        pass  # In real ISR, this would be minimal


class PollingHandler:
    """Handle events by periodic checking."""
    def __init__(self, device: Device, poll_interval_ms: float = 100):
        self.device = device
        self.poll_interval = poll_interval_ms / 1000
        self.events_handled = 0
        self.last_poll_time = None
        self._running = False
        self._thread = None
        self._pending = False  # Simulated device register

    def start(self):
        self._running = True
        def poll_loop():
            while self._running:
                self.last_poll_time = time.time()
                # Read device "registers" (check for pending events)
                self._check_device()
                time.sleep(self.poll_interval)
        self._thread = threading.Thread(target=poll_loop, daemon=True)
        self._thread.start()

    def _check_device(self):
        # Simulate reading status register
        if random.random() < 0.7:  # 70% chance of event pending
            self.events_handled += 1

    def stop(self):
        self._running = False
        if self._thread:
            self._thread.join(timeout=1.0)


if __name__ == "__main__":
    print("=== Interrupt vs Polling Simulation ===\n")

    # Interrupt-driven
    handler_int = InterruptDrivenHandler()
    device = Device("UART0", handler_int.handle_interrupt, event_interval_ms=10)
    device.start()
    time.sleep(1.0)
    device.stop()

    print(f"Interrupt-driven: {handler_int.events_handled} events handled")

    # Polling
    handler_poll = PollingHandler(device, poll_interval_ms=50)
    device2 = Device("UART1", lambda: None, event_interval_ms=10)
    device2.start()
    handler_poll.start()
    time.sleep(1.0)
    handler_poll.stop()
    device2.stop()

    print(f"\nPolling (50ms interval): {handler_poll.events_handled} events handled")
    print("  This model does not measure hardware or kernel latency.")

Observability Checklist

Linux Interrupt Metrics

# View all IRQ statistics
cat /proc/interrupts

# Per-CPU interrupt counts
cat /proc/softirqs  # Software interrupt (softirq) handling

# Check interrupt affinity
cat /proc/irq/32/smp_affinity  # Which CPU handles IRQ 32

# Example system change: requires root and a valid, manually managed IRQ/CPU mask.
# Check the device's IRQ and allowed CPUs first; managed IRQs may reject this write.
sudo sh -c 'echo 1 > /proc/irq/42/smp_affinity'

# View interrupt distribution with perf
perf stat -e 'irq:irq_handler_entry' -a sleep 1

Key Metrics to Monitor

Metric Healthy Range Alert Threshold Indicates
/proc/interrupts (per-IRQ delta) Baseline + small variance Sudden 10x increase Interrupt storm
softirq time in top < 5% CPU > 30% CPU ISR deferred work overload
irq_entry perf events < 10,000/s > 100,000/s Excessive interrupts
nmi count delta Stable Increasing Hardware issues (memory errors)

Common Pitfalls / Anti-Patterns

Interrupt Security Concerns

  1. Interrupt Timing Attacks: Observing interrupt timing can leak information. Deterministic scheduling of bottom halves can expose sensitive computation patterns. Consider using hrtimer for high-resolution timing rather than relying on interrupt patterns.

  2. IRQ Routing Attacks: In virtualized environments, a malicious VM could manipulate interrupt routing to cause denial of service against other VMs sharing the same physical CPU. Use IOMMU interrupt remapping and verify APIC configuration.

  3. MSI-X Isolation: PCI MSI/MSI-X messages are handled through platform interrupt hardware. In virtualized or device-assignment setups, interrupt remapping can help keep a device’s messages within its assigned interrupt domain; DMA isolation is a separate IOMMU concern.

  4. Interrupt Descriptor Table (IDT) Attacks: Kernel-level malware can alter interrupt handling. A symbol lookup in /proc/kallsyms does not verify IDT integrity; use secure boot and kernel-integrity controls appropriate to the system.

Coding Anti-Patterns

Anti-pattern Why It’s Bad Correct Approach
Long-running ISR Blocks all interrupts, causes latency spikes Defer to tasklet/workqueue
Blocking in ISR Scheduling while atomic = panic Use non-blocking primitives
Not acknowledging interrupts Spurious interrupts repeat forever Always acknowledge in hardware
No IRQ sharing cleanup Leak resources on driver removal Use free_irq with proper synchronization
Assuming single CPU Race conditions on SMP Use proper locking/synchronization
Disabling interrupts globally Excessive latency for other devices Use per-IRQ masking instead
Not handling interrupt storms Denial of service from device Implement coalescing/irq throttling

Quick Recap Checklist

  • Hardware interrupts allow devices to demand CPU attention asynchronously
  • Hard IRQ handlers run in atomic context—keep them short and never block. Interrupt masking details depend on the architecture and IRQ flow.
  • Bottom halves (tasklets, workqueues, threaded IRQs) defer lengthy processing
  • Tasklets run in softirq context and cannot sleep; workqueues and threaded IRQs run in schedulable kernel-thread context
  • Polling is the alternative—better for high-density events, worse for power/latency
  • Hybrid NAPI model combines interrupts (for idle) with polling (for busy)
  • Always acknowledge hardware interrupts to prevent spurious repeats
  • Use synchronize_irq() before freeing IRQ-related resources
  • Monitor /proc/interrupts and softirqs to detect interrupt storms
  • Interrupt storms usually indicate hardware or driver bugs, not feature

Interview Questions

1. What happens when a hardware interrupt fires? Walk through the complete sequence.

The details vary by architecture and interrupt type. A device may assert a wired interrupt or, for PCI MSI/MSI-X, issue a memory write that platform interrupt hardware routes to a CPU. Architecture-specific entry code then passes the mapped Linux IRQ into the generic IRQ layer, which dispatches the registered handler. The handler checks the device and acknowledges or masks its source as required. It may wake a threaded handler or queue deferred work before returning. On x86 this path uses interrupt vectors and IDT structures; other architectures differ. There is no single latency figure that applies to all hardware and workloads.

2. Why can't you call schedule() or sleep in an interrupt handler?

A hard IRQ handler runs in interrupt context, where it cannot sleep or call schedule(). The interrupted task may be user code, kernel code, or idle, so the handler cannot assume it owns that task's context. Keep the primary handler short, then defer work. A threaded IRQ handler or workqueue runs in schedulable kernel-thread context; softirqs and tasklets remain atomic and cannot sleep. Whether local interrupts are masked during a handler depends on the interrupt flow and architecture.

3. What is the difference between tasklets and workqueues in Linux?

Tasklets defer work through softirq context: they cannot sleep and must stay short. Workqueues run in kernel-thread context and can sleep. A threaded IRQ pairs a short primary handler with a schedulable handler for work tied directly to that interrupt. Use the mechanism that fits the work and its latency needs; a workqueue can also handle tasks that are not tied to a single IRQ event.

4. What is NAPI and when is it used?

NAPI is Linux's networking poll mechanism. In a common receive path, a device interrupt schedules NAPI, and the driver masks the relevant device interrupt while the poll method processes packets within a budget. If work remains, polling continues through the networking softirq path; when the queue is drained, the driver can re-enable interrupts. The exact mapping between queues, NAPI instances, and vectors depends on the device and driver.

5. How do you safely handle a device that might generate spurious interrupts?

Spurious interrupts waste CPU and can indicate hardware problems. Handling strategies: First, always read device status registers at the start of ISR and return IRQ_NONE if there's no real interrupt source—this tells the kernel "this IRQ wasn't for me." Second, implement interrupt coalescing in hardware (waiting for multiple events before asserting interrupt) if the device supports it. Third, for persistent spurious interrupts, Linux has a spurious IRQ handler count—if too many IRQ_NONE returns happen, the kernel will temporarily disable that IRQ line. Fourth, use irqdomain to properly map hardware IRQ numbers to Linux IRQ descriptors. Finally, ensure proper interrupt acknowledgment happens in the correct order (hardware first, then software) to prevent latch-up conditions.

6. What is interrupt coalescing and how does it improve performance for high-speed devices like network cards?

Interrupt coalescing reduces interrupt frequency by waiting for multiple events before asserting an interrupt. Instead of interrupting for every packet, a network card might wait until it has accumulated 16 packets or 128 microseconds have passed since the last interrupt, then fire one combined interrupt. This dramatically reduces CPU overhead from interrupt handling—from thousands of interrupts per second to hundreds. The tradeoff is increased latency: a packet must wait for the coalescing window before being processed. For bulk transfer (file downloads), this latency is unnoticeable. For latency-sensitive applications (high-frequency trading), you tune coalescing aggressively (low thresholds, short timers). Hardware supports this via configurable rx-usecs and rx-max-frames registers. On Linux, the ethtool tool sets coalescing parameters for network drivers.

7. What does the APIC do in multi-core x86 systems?

The APIC is an x86 interrupt-controller system. Local APICs handle CPU-local interrupt delivery, while I/O APICs route many wired device interrupts. MSI/MSI-X uses a message path that is still handled by platform interrupt hardware. Linux's generic IRQ layer supports affinity settings where the controller and IRQ permit them. Other architectures use different interrupt controllers, so APIC behavior should not be generalized to all Linux systems.

8. What is the difference between an edge-triggered and level-triggered interrupt?

For wired interrupts, an edge-triggered source reports a transition, while a level-triggered source remains asserted until the device or controller clears it. The handler and controller configuration must match the device's signaling behavior. MSI/MSI-X are messages rather than electrical edges on a shared IRQ wire, so this distinction does not describe their delivery path. Linux configures trigger types through the IRQ layer when the controller supports the requested type; drivers should follow the device and platform documentation.

9. What is the softirq system in Linux and how does it relate to hardware interrupts?

Softirqs are one Linux mechanism for deferring work from hard IRQ context. They run in atomic context and cannot sleep; tasklets also use softirq processing. Networking uses softirqs to run NAPI poll work, while workqueues and threaded IRQs use kernel threads for schedulable work. Softirq processing may run in the interrupt-return path or in ksoftirqd threads under load; inspect /proc/softirqs to see per-CPU counts.

10. How does MSI (Message Signaled Interrupt) improve interrupt routing compared to wire-based interrupts?

PCI MSI and MSI-X replace a pin assertion with a device write to a programmed address and data value. Platform interrupt hardware routes that message to a CPU; some systems also use interrupt-remapping hardware. MSI supports up to 32 messages, while MSI-X supports up to 2048 independently configurable vectors, subject to device and platform limits. Drivers can associate vectors with queues and request affinity where supported. MSI-X is common for multi-queue devices, but it is not universally required; the device, driver, and platform determine which modes are available. See the Linux kernel's MSI Driver Guide.

11. What is interrupt affinity and how do you set it to optimize performance in a NUMA system?

IRQ affinity restricts which CPUs may handle an interrupt when the IRQ and controller support that setting. On Linux, /proc/irq/<IRQ>/smp_affinity and smp_affinity_list expose affinity for many IRQs. Read /proc/irq/default_smp_affinity to inspect the default mask; reading it does not change the setting. Managed IRQs are allocated and moved by the kernel and cannot be manually changed through those proc files. The irqbalance service may also adjust eligible IRQs. Affinity tuning can help or hurt locality and latency, so check device placement and measure the result rather than assuming one CPU is best. See the kernel's managed IRQ documentation.

12. What is the difference between an interrupt handler and a kernel thread in terms of scheduling and preemption?

A hard IRQ handler runs in atomic interrupt context and cannot sleep; whether local interrupts are masked and how preemption works depend on the architecture and IRQ flow. A threaded IRQ handler runs in a schedulable kernel thread and can sleep when the API and driver state allow it. A workqueue also runs in kernel-thread context and is useful for work that is not tightly tied to one IRQ. Neither mechanism has a universal latency advantage: scheduler load, priority, hardware, and handler work all matter.

13. What is the role of the IRQ descriptor table (`irq_desc`) in Linux interrupt handling?

The Linux IRQ core uses an IRQ descriptor to track an allocated logical IRQ, its flow handler, controller operations, state, and affinity information. Architecture and interrupt-controller code map hardware sources to Linux IRQs; an IRQ number is not necessarily a physical line number. When sharing is supported, the IRQ core can call multiple registered handlers until one claims a wired interrupt. MSI/MSI-X vectors are not shared in this way. See the kernel's generic IRQ documentation.

14. What does `IRQF_ONESHOT` do for a threaded interrupt?

With request_threaded_irq(), IRQF_ONESHOT keeps the interrupt masked while the threaded handler runs. This is useful when the device must not signal another event before the thread finishes. It does not mean the IRQ cannot be shared; sharing depends on the IRQ type, device, and request flags. The primary handler still runs in hard IRQ context and must stay short. The threaded handler runs in schedulable kernel-thread context.

15. What is the interrupt storm problem and how do you diagnose its cause using `/proc/interrupts`?

An interrupt storm is when a device generates interrupts at a rate faster than the system can handle, causing CPU saturation with interrupt processing and preventing useful work. The first diagnostic is `/proc/interrupts`—look at the delta (change) column if you're sampling repeatedly. If an IRQ's count is increasing by thousands per second, you have an interrupt storm. The causes: hardware malfunction (device defective, asserting IRQ line permanently), interrupt coalescing misconfiguration (too low thresholds), software bug causing the interrupt to be raised repeatedly for the same event (handler not acknowledging properly), or a race condition where clearing the interrupt doesn't actually clear the hardware condition. The `spurious` entry in `/proc/interrupts` shows counts of unhandled interrupt calls. Solving requires examining the device's interrupt status register in the ISR to see what condition is causing the repeat, and adjusting hardware coalescing or driver logic accordingly.

16. How does `enable_irq()` and `disable_irq()` work and why must they be called in symmetric pairs?

`disable_irq()` increments a counter and masks the IRQ line at the interrupt controller—each call must have a matching `enable_irq()` to decrement the counter and unmask. The IRQ line only re-enables when the counter reaches zero. This means calling `disable_irq()` twice requires two `enable_irq()` calls to restore. If `disable_irq()` is called from interrupt context, the function waits for any in-flight interrupts to complete before returning, ensuring no handler is running when it returns. The symmetric pair design prevents accidental re-enabling by another piece of code. Common bug: `disable_irq()` in init, `enable_irq()` in cleanup, but cleanup called multiple times causes double-enable. Using `request_threaded_irq()` with `IRQF_ONESHOT` avoids manual enable/disable for most cases. `disable_irq_nosync()` is a non-waiting variant that returns immediately without waiting for in-flight handlers.

17. What is the `IRQF_SHARED` flag and what are the requirements for sharing an interrupt line correctly?

`IRQF_SHARED` allows multiple devices to share one IRQ line—the kernel calls all registered handlers until one claims the interrupt. To share correctly: all devices on the line must support shared interrupts; the handler must check if its device actually raised the interrupt (by reading device status registers) and return `IRQ_NONE` if not; and the handler must acknowledge the interrupt before returning (so the hardware de-asserts the line). If two devices both return `IRQ_HANDLED` without checking, one might be handling the other's interrupt (and vice versa), leading to missed events. Shared interrupts are common when IRQ lines are limited (legacy systems). The request is `request_irq(irq, handler, IRQF_SHARED, name, dev_id)` where `dev_id` is a unique identifier each device passes so the handler can identify which device is reporting.

18. How does the kernel ensure that interrupt handlers can safely access shared data structures with normal kernel code?

Hard IRQ handlers run in atomic context, but that does not make shared data safe by itself. If process context and an interrupt handler access the same data, use synchronization suited to those contexts. A common pattern is `spin_lock_irqsave()` in process context and the matching spinlock in the handler; it saves and restores the local interrupt state while protecting the data. The exact locking rule depends on which contexts access the data and on the architecture's interrupt flow.

19. What is the role of `synchronize_irq()` and why might you call it during driver removal?

`synchronize_irq()` blocks until any interrupt handler currently executing on that IRQ line completes. It is called during driver removal to ensure that no handler is running when resources are freed. If you `free_irq()` without synchronizing, you might free the IRQ descriptor (or device structure) while the ISR is still accessing it—causing a use-after-free crash. The pattern is: `disable_irq()` stops new interrupts, `synchronize_irq()` waits for any in-flight ISR to finish, then you can safely free resources. `synchronize_irq()` is expensive (it can sleep if the handler is slow), so call it only during shutdown sequences where sleeping is acceptable. For faster synchronization, `synchronize_rcu()` is used (for RCU-based synchronization), but that only applies to RCU-protected data, not general ISR completion. In practice, driver removal code calls `free_irq()` which internally calls `synchronize_irq()`.

20. What is the difference between polling and interrupts in the context of high-frequency trading systems and why do they choose polling?

Some latency-sensitive network applications poll because a busy loop can avoid waiting for a scheduled wake-up when traffic is expected continuously. That costs CPU time while idle, and it does not guarantee a particular packet latency. epoll_wait() with a zero timeout checks readiness and returns; it does not itself poll the NIC directly or bypass kernel networking. Systems that need lower latency may use kernel busy-polling options or user-space networking frameworks, depending on the NIC, kernel, and workload. Compare end-to-end latency and CPU use on the target system.

Further Reading

Conclusion

Interrupts and polling give devices two ways to report or expose work. A hard IRQ handler runs in atomic context and should stay short; Linux can defer work to a softirq, threaded IRQ, or workqueue. Polling and interrupt delivery are often combined, as in NAPI, and the right balance depends on the device and workload.

Understanding interrupt handling prepares you for deeper OS topics: the interaction between interrupt context and scheduler, the security implications of IRQ routing in virtualized environments, and the evolution toward message-signaled interrupts that avoid physical pin limitations. These fundamentals also appear in ARM and RISC-V interrupt controllers, embedded real-time operating systems, and hypervisor virtual interrupt delivery.

Interrupt coalescing and NAPI are two examples of batching work around interrupt delivery. Measure their latency and CPU cost on the target system rather than assuming one approach fits every device.

Category

Related Posts

ASLR & Stack Protection

Explore ASLR, PIE, stack canaries, and NX on Linux with GCC, then inspect a harmless C program to see what each mitigation does and where it falls short.

#operating-systems #aslr-stack-protection #computer-science

Assembly Language Basics: Writing Code the CPU Understands

Learn x86-64 Linux assembly with the System V ABI: track registers, assemble and run a small program, debug it in GDB, then compare AArch64.

#operating-systems #assembly-language-basics #computer-science

Boolean Logic & Gates

Understanding AND, OR, NOT gates and how they combine into arithmetic logic units — the building blocks of every processor.

#operating-systems #boolean-logic-gates #computer-science