Interrupt Handling
Hardware inputs run million times slower than the cpu can do instructions. (e.g. you press keyboard keys in milliseconds, 3.2GHz CPU does instructions 3.2 Million times in one millisecond)
So CPU cannot wait and listen until you press key, this is why it uses Interrupt concept. An Interrupt signal is an Asynchronous signal sent to CPU via a dedicated bus.
Types of interrupts
Mainly 2 types,
- Hardware Interrupt (Asynchronous): Triggered by external physical devices (e.g., disk drive done, network packet arrived, timer clock tick). Can occur at any arbitrary CPU instruction.
- Software Trap / Exception (Synchronous): Triggered internally by the currently executing program instruction (e.g.,
syscall, division by zero, page fault).
The Interrupt Handling Lifecycle
When a device fires an interrupt, the hardware and kernel process it in a strict, deterministic sequence:
Signal Assertion (IRQ):
Hardware Layer.
The peripheral device asserts an Interrupt Request (IRQ) signal line connected to an Interrupt Controller (such as an x86 APIC).
CPU Interrupt Check & Context Save:
CPU Hardware.
At the end of the current instruction execution cycle, the CPU detects the IRQ signal. It automatically pauses the current program, saves the Program Counter (PC) and CPU flags onto the kernel stack, and switches from User Mode to Kernel Mode.
Interrupt Vector Lookup:
CPU & Hardware.
The Interrupt Controller delivers an Interrupt Vector Number (an integer index) to the CPU. The CPU uses this number to look up the target memory address in the Interrupt Descriptor Table (IDT) or Interrupt Vector Table (IVT).
Execute Interrupt Service Routine (ISR):
Device Driver.
The CPU jumps to the memory address of the driver's Interrupt Service Routine (ISR). The ISR executes privileged code to read data out of hardware device registers into system RAM.
Acknowledge & Return (IRET):
Kernel to CPU.
The ISR sends an Acknowledge (EOI - End of Interrupt) signal back to the interrupt controller, restores the saved program context registers, and issues an IRET (Interrupt Return) instruction to resume execution of the paused user process.
Direct Memory Access (DMA)
For high-speed devices (like NVMe SSDs, 10Gb E Network Cards, and GPUs), transferring data byte-by-byte through the CPU using interrupts would still overload the processor.
Operating systems use Direct Memory Access (DMA):
- The driver tells the DMA controller: "Copy 10 MB from disk address X directly into RAM address Y without involving the CPU."
- The DMA engine manages the bus and writes data directly to RAM.
- Once the entire multi-megabyte transfer completes, the DMA engine fires a single hardware interrupt to notify the driver.