Skip to content
systemcoding.dev
Kernels

What Is an Interrupt and How CPUs Handle Them

An interrupt makes the CPU pause its program, run a handler and resume. Learn what the CPU saves, how it finds the handler, and what Linux does next.

7 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Linux, C and GNU logos.

When you press a key, your editor does not poll the keyboard a million times a second asking whether anything happened. The keyboard controller taps the CPU on the shoulder, the CPU stops what it was doing, runs a small piece of kernel code that reads the key, and goes back to the editor as if nothing had occurred. That tap is an interrupt, and it is the mechanism behind every disk read, network packet, timer tick and keystroke on your machine. This post explains what the CPU does when one arrives, step by step, with x86-64 as the example and Linux 6.12 as the operating system on top.

The problem interrupts solve

A processor executes instructions one after another. Devices are slower and unpredictable: a disk takes milliseconds, a network packet arrives when it arrives. There are two ways for the CPU to learn that a device needs attention.

The first is polling: the CPU checks a status register in a loop. It is simple, and it wastes the CPU on checking, since most of the time the answer is "nothing yet". The second is the interrupt: the device signals the CPU, and the CPU reacts only when there is something to react to. Polling still has a place for devices that are always busy, but interrupts are the default for everything else.

An interrupt is therefore a hardware signal that forces the CPU to switch from the current program to a handler, a function chosen by the operating system for that kind of event, and then return.

Three kinds of events that look alike

CPU documentation separates events that are easy to confuse.

KindCauseExampleTiming
InterruptOutside the CPU, from a device or timerA network card has a packetAsynchronous, any time
ExceptionInside the CPU, caused by an instructionDivision by zero, a page faultSynchronous, at that instruction
Software interruptA deliberate instructionThe int 0x80 instruction, syscallSynchronous, on purpose

Linux handles all of them through the same machinery, a table of handler addresses, but they differ in whether they are predictable. When people say "interrupt" without qualification they mean the first row: an asynchronous signal from hardware.

What the CPU does, step by step

Take an x86-64 CPU running a user program when a network card raises an interrupt.

  1. The device pulls a wire or sends a message to the interrupt controller. The controller decides which CPU gets it and passes a number, the vector, between 0 and 255. Vectors 0 to 31 are reserved for CPU exceptions; Linux uses 32 and up for external interrupts.

  2. The CPU finishes the instruction it is on. It never stops in the middle of one.

  3. It checks whether interrupts are currently allowed. A flag in the RFLAGS register, IF, decides this. If it is clear, the interrupt waits.

  4. It saves just enough state to resume later: the instruction pointer RIP, the code segment, RFLAGS, the stack pointer and the stack segment. These are pushed onto a stack. If the interrupt arrived while the CPU was in user mode, it first switches to a kernel stack, since the user stack cannot be trusted.

  5. It looks up the vector in the interrupt descriptor table (IDT), a table of 256 entries whose address is held in the IDTR register. The entry gives the address of the handler's first instruction.

  6. It clears IF, so a second interrupt does not pile on top, and jumps to the handler.

  7. The handler runs. When it is done, it executes iretq, which pops the saved registers and resumes the interrupted code at the exact instruction it left.

The key property is that the interrupted program does not know. Its registers are intact on return, and apart from lost time, it cannot tell the interruption happened.

What Linux does with the jump

The IDT entry does not point directly at your driver's function. It points at a small assembly stub in the kernel, for example the entry for vector 0x21, which saves the rest of the general-purpose registers into a pt_regs structure and then calls a C function, common_interrupt(). That function looks up which Linux interrupt number is mapped to this vector and calls the generic interrupt layer in kernel/irq/.

From there the kernel does the following:

  1. The generic layer calls the flow handler for this interrupt, which acknowledges the interrupt controller.

  2. It then runs each handler function registered for this interrupt, the ones drivers installed with request_irq().

  3. If they report the interrupt handled, it signals end-of-interrupt to the controller and returns.

  4. On the way out, if the interrupt marked deferred work such as a softirq as pending, the kernel runs that before returning to the program.

Here is the chain for a keyboard press, in function names you can find in the source:

Text
keyboard controller raises IRQ 1
  -> IDT vector 0x21
    -> asm stub saves registers
      -> common_interrupt()
        -> handle_irq() / generic_handle_irq_desc()
          -> handle_edge_irq()
            -> i8042_interrupt()     (the driver's handler)
            -> ack the controller
  -> irqentry_exit(): run pending softirqs, maybe reschedule
  -> iretq: back to the user program

The names after the first few differ with hardware, but the shape is the same on every architecture Linux supports. ARM64 uses a vector table entry instead of an IDT and a GIC instead of the APIC; the steps match.

Seeing interrupts on your machine

Linux counts them. /proc/interrupts has one row per interrupt line and one column per CPU:

Shell
cat /proc/interrupts | head -5
Text
           CPU0       CPU1       CPU2       CPU3
  0:         10          0          0          0  IR-IO-APIC    2-edge      timer
  1:          0       2143          0          0  IR-IO-APIC    1-edge      i8042
  8:          0          0          0          1  IR-IO-APIC    8-edge      rtc0
  9:          0          0        412          0  IR-IO-APIC    9-fasteoi   acpi

Row 1 is the PS/2 keyboard controller (i8042). Its count, 2143 on CPU1, goes up each time you press or release a key on a PS/2 keyboard. The name in the last column is the string the driver passed when it registered. Rows and numbers differ per machine. The total since boot is also in /proc/stat, on the line starting with intr.

To watch it live, run watch -n1 'grep -E "i8042|eth0" /proc/interrupts' and press keys or generate network traffic; the matching counts climb.

Why handlers must be short

Look again at step 6: the CPU cleared IF, so no other interrupt can preempt the handler on that CPU, and in Linux the interrupt line itself is usually masked while its handler runs. While the handler runs, nothing else on that CPU makes progress. Every microsecond spent there is a microsecond when the CPU cannot run your program, serve other devices or respond to the timer. A handler that does too much makes the whole machine stutter, loses packets on a busy network card and delays input.

So the kernel splits interrupt work into two parts. The top half is the handler: it reads the device's status, tells the device to stop signaling, and records what happened. The bottom half does the long work later, with interrupts enabled again, in softirqs, tasklets, workqueues or threads. Packet parsing, file system updates and scheduling all happen in bottom halves. The next posts on this site go through each of them.

Masking and priority

A CPU can be told not to take interrupts for a while. Kernel code does this in two ways. It can disable interrupts on the current CPU, with local_irq_disable(), which executes the cli instruction and clears IF; this is what protects short critical sections that share data with a handler. Or it can mask a particular device at the interrupt controller with disable_irq(), leaving other devices and CPUs unaffected. Interrupt disabling should be as short as possible; a long stretch with interrupts off delays every timer tick and device, and Linux has a tracer (irqsoff) just to find the longest such stretches.

Some interrupts cannot be masked. The non-maskable interrupt (NMI) is used for hardware errors and by the kernel's own watchdog and profiling, and it ignores IF. Code in an NMI handler lives under severe restrictions because it can interrupt anything, including the code that disabled other interrupts.

A tiny example: a handler registered by a module

A kernel module can register a handler for an interrupt line. This one only counts interrupts, and it shows the three parts every handler has: a registration, a function with a fixed signature, and a return value:

irqcount.cc
#include <linux/module.h>
#include <linux/interrupt.h>

static int irq_line = 1;	/* the PS/2 keyboard on many PCs */
module_param(irq_line, int, 0444);

static atomic_t hits = ATOMIC_INIT(0);

static irqreturn_t count_handler(int irq, void *dev_id)
{
	atomic_inc(&hits);
	return IRQ_NONE;	/* we do not own this device */
}

static int __init irqcount_init(void)
{
	return request_irq(irq_line, count_handler, IRQF_SHARED,
			   "irqcount", &hits);
}

static void __exit irqcount_exit(void)
{
	free_irq(irq_line, &hits);
	pr_info("irqcount: saw %d interrupts on irq %d\n",
		atomic_read(&hits), irq_line);
}

module_init(irqcount_init);
module_exit(irqcount_exit);
MODULE_LICENSE("GPL");

It returns IRQ_NONE because it did not service the device, which is correct for an observer that shares the line with the real driver, and it passes IRQF_SHARED so registration succeeds alongside that driver. After pressing 12 keys (24 interrupts, one for each press and each release) and removing the module, the log shows:

Text
irqcount: saw 24 interrupts on irq 1

The exact count depends on what you press. On a system where the keyboard is USB, line 1 may not exist or never fire, and request_irq can fail with -EBUSY if the owner did not allow sharing.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.