How Intel Interrupts Work: A Practical Guide
In this article
Interrupts on Intel CPUs are signals that pause the current code, save state, and jump to a predefined handler, allowing the processor to respond to hardware or software events instantly.
What You'll Need
- A computer with an Intel processor (any modern x86 or x86‑64 CPU)
- A text editor or IDE capable of editing assembly or C source files
- A compiler/assembler such as GCC, NASM, or MASM
- Basic knowledge of the Intel architecture (protected mode, registers, and memory layout)
- Optional: A debugger like GDB or WinDbg for stepping through interrupt handling code
Step‑By‑Step
- Understand the two main interrupt sources. Intel CPUs handle hardware interrupts generated by external devices (timer, keyboard, network card) and software interrupts invoked by the INT instruction or exceptions (divide‑by‑zero, page fault). Both types use the same mechanism: the CPU looks up an entry in the Interrupt Descriptor Table (IDT) and transfers control to the address stored there.
- Locate or create the IDT. In real‑mode the IDT is a 256‑entry table of 4‑byte descriptors; in protected mode each entry is an 8‑byte descriptor containing the segment selector, offset, type, and privilege level. Allocate a block of memory (e.g., 0x1000 bytes aligned on a 16‑byte boundary) and fill each entry with a pointer to a stub routine that eventually calls your real handler.
- Load the IDT with the lidt instruction. Write assembly similar to:
lidt [idt_pointer]
whereidt_pointeris a 6‑byte structure: first two bytes = size‑1, next four bytes = linear address of the table. This tells the CPU where to find the descriptors. - Write a simple interrupt service routine (ISR). An ISR must preserve the processor state: push all general‑purpose registers, segment registers if needed, and the flags register. Then execute the handling code, and finally restore the state and execute
iretto return. Example in NASM:global isr_timer isr_timer: pushad push ds push es ; handler code here (e.g., increment a tick counter) pop es pop ds popad iret - Map the ISR to an IDT entry. For IRQ0 (system timer) the vector is usually 0x20 after remapping the PIC. Fill the corresponding descriptor with the selector of your code segment (usually 0x08) and the offset of
isr_timer. Set the type attribute to 0x8E (present, interrupt gate, DPL=0). - Remap the legacy PIC (if you are using it). The 8259 PIC maps IRQ0‑IRQ7 to vectors 0x08‑0x0F, which conflict with CPU exceptions. Send initialization commands to ports 0x20 and 0xA0 to move IRQ0‑IRQ15 to 0x20‑0x2F. This step is optional on systems that already use the APIC, but many tutorials still cover it for completeness.
- Enable interrupts globally. After the IDT is loaded and the PIC is configured, clear the interrupt‑disable flag with the
stiinstruction. Untilstiis executed, the CPU will ignore external IRQs. - Test the handler. Write a small program that increments a global counter in the timer ISR. After a few seconds, read the counter from main code to verify that the interrupt fired at the expected rate (approximately 119 Hz on a legacy PIT).
- Handle software interrupts. Use the
int ninstruction to invoke a handler you placed in the IDT. For system calls on Linux, the kernel sets up a specific vector (e.g., 0x80 on 32‑bit). In your own OS you can define custom vectors for privileged services. - Deal with privilege levels. If a user‑mode program needs to trigger an interrupt, set the descriptor's DPL (Descriptor Privilege Level) to 3. The CPU will then allow
intfrom CPL 3 code. Hardware IRQs always arrive at CPL 0, so the handler must run in kernel mode. - Implement nested interrupt handling. By default the CPU disables further maskable interrupts when an ISR starts. To allow higher‑priority IRQs, clear the IF flag inside the ISR after saving it, or use the
pushf / popfsequence to temporarily re‑enable interrupts. Be careful to avoid infinite recursion. - Clean up and document. Comment each IDT entry, keep a table of which device uses which vector, and store the original PIC masks so you can restore them on shutdown. Proper documentation prevents hard‑to‑track bugs later.
Common Mistakes
- Forgetting to preserve registers. An ISR that clobbers a register used by the interrupted code will cause unpredictable crashes.
- Loading an IDT with an incorrect size or address. The
lidtoperand must point to a 6‑byte structure; a typo will make the CPU fetch garbage descriptors. - Using the wrong descriptor type. A task gate (type 0x85) will cause a task‑switch instead of a simple jump, breaking simple OS kernels.
- Leaving the PIC un‑remapped. Vectors 0x08‑0x0F clash with CPU exceptions, leading to mysterious “divide‑by‑zero” or “general protection” faults when a device raises an IRQ.
- Enabling interrupts before the stack is set up for kernel mode. If the ISR executes
iretand the stack pointer is invalid, the CPU will triple‑fault and reset.
Tips
- Start with the timer interrupt; it is the simplest hardware source and provides a visible heartbeat for debugging.
- Use the
pushfd / popfdpair to save and restore the flags register instead of manually saving the IF flag. - When writing in C, declare the ISR with the
__attribute__((interrupt))qualifier (GCC) – the compiler will generate the correct prologue/epilogue. - Keep the IDT in read‑only memory after it is loaded to prevent accidental overwrites.
- On modern CPUs prefer the Advanced Programmable Interrupt Controller (APIC) over the legacy PIC; the APIC provides more vectors and better performance.
Troubleshooting
If the system freezes after you issue sti, try the following checks in order:
- Reboot and temporarily replace your ISR with a simple routine that only executes
iret. If the crash disappears, the problem lies in the handler code. - Verify the IDT entry for the vector that caused the fault. Use a debugger to read the descriptor bytes; they should match the expected selector and offset.
- Check that the segment selector in the descriptor points to a valid code segment with the correct privilege level (usually 0x08 for the kernel code segment).
- Make sure the stack pointer (ESP/RSP) points to a writable region when the ISR runs. A stack overflow will corrupt the return address and cause a triple fault.
- If using the PIC, confirm that the remap commands were sent to the correct ports (0x20/0x21 for master, 0xA0/0xA1 for slave) and that the masks were restored after initialization.
- Enable CPU logging (e.g., via QEMU’s
-d intflag) to see which vector caused the exception. - As a last resort, clear the IF flag with
cliand step through the code in a debugger to locate the exact instruction that triggers the fault.
Frequently Asked Questions
What is the difference between an interrupt gate and a trap gate?
An interrupt gate clears the IF flag automatically, preventing other maskable interrupts from occurring while the handler runs. A trap gate leaves IF unchanged, allowing nested interrupts. Use interrupt gates for most hardware IRQs.
Can I use the same ISR for multiple IRQ lines?
Yes, you can point several IDT entries to the same routine, but the ISR must be able to read the interrupt vector (often passed in the stack or via the int instruction) to differentiate the source.
Do modern Intel CPUs still use the legacy PIC?
Physical hardware may still include a PIC for compatibility, but operating systems typically switch to the APIC or x2APIC because they provide 256 vectors and advanced features like interrupt priority and load balancing.
How do I disable a specific hardware interrupt?
Write to the PIC’s interrupt mask registers (port 0x21 for the master, 0xA1 for the slave) to set the mask bit corresponding to the IRQ line you want to ignore.
Why does my ISR receive a different stack layout when compiled with GCC?
When you use the interrupt attribute, GCC passes an extra error code on the stack for exceptions that push one. Adjust your handler signature accordingly (e.g., void handler(struct interrupt_frame *frame)).
Is it safe to call C library functions from an ISR?
Generally no. Most C library functions are not re‑entrant and may rely on interrupts being enabled. Stick to simple, deterministic code inside an ISR.