Mechanics and Implementation of CPU Interrupt Handling
Interrupts enable concurrent execution of multiple programs, improving system throughput. Concurrency reflects accumulated work within a unit time, while parallelism means tasks run simultaneously. With interrupts, simultaneous use of keyboard and mouse becomes possible.
Operating systems operate reactively, driven by events signaled via interrupts. Hardware generates external interrupts—also called maskable interrupts—through INTR and NMI pins. INTR handles non-critical events, optionally ignored via the IF flag in EFLAGS or per-device masking. NMI denotes critical faults and cannot be masked.
Interrupt handling can be split: a top half for urgent processing and a bottom half for deferrable tasks. For example, network packet reception runs in the top half; packet parsing may be deferred.
Each interrupt maps to a vector number used as an index into the Interrupt Descriptor Table (IDT). The CPU fetches the handler address from the corresponding descriptor. Non-maskable exceptions often share a fixed vector range.
Internal interrupts divide into software-triggered and exception types. Software interrupts include:
int imm8: system callsint3: breakpoint for debugginginto: overflow trap if OF=1, vector 4bound: array bounds check, vector 5ud2: undefined instruction, vector 6
Exceptions have three severities: Fault (recoverable), Trap (deliberate stop), Abort (unrecoverable). Some push an error code onto the stack after EIP.
Vector numbers span 0–255. The IDT links each vector to a gate descriptor containing the handler’s segment selector and offset. Vector assignment sources differ: CPU-defined for exceptions/NMI, programmable interrupt controller (PIC) for external maskable interrupts, and software for int n.
Interrupt Descriptor Table
In protected mode, IDT stores gate descriptors. Types include:
- Task gate: holds TSS selector, rarely used in modern OSes (type 0101)
- Interrupt gate: segment selector and offset; clears IF to block nesting (type 1110)
- Trap gate: like interrupt gate but preserves IF for nested handling (type 1111)
- Call gate: enables user→kernel transitions, accessed via
call/jmp, resides in GDT/LDT (type 1100)
IDT base and limit reside in IDTR. Unlike GDT, IDT allows slot 0 usage. The P bit should be 0 during setup to indicate absent handler.
Handling Procedure and Protection
Upon interrupt receipt, the CPU locates the gate by vector × 8 + IDT_base. Privilege checks ensure CPL ≤ gate DPL and CPL ≥ target segment DPL. If checks pass, CS:EIP are loaded with handler address. For interrupt gates, IF is cleared to prevent nesting; trap gates allow nesting.
Return uses iret, restoring CS, EIP, EFLAGS, and conditionally SS:ESP when privilege changes. cli disables maskable interrupts; sti re-enables them. On entry, NT and TF flags are reset; NT indicates task nesting.
Stack Behavior on Interrupt
For inter-privilege interrupts, the processor switches stacks: temporary old SS:ESP are saved, new SS:ESP come from TSS, then EFLAGS, CS:EIP, and optional error code are pushed. Same-privilege pushes only EFLAGS, CS:EIP. Manual adjustment is needed if an error code is present.
Error codes encode source: EXT (NMI or external), IDT (IDT vs GDT/LDT), TI (LDT vs GDT). Only vectors 0–31 push error codes.
Programmable Interrupt Controller 8259A
The 8259A manages up to 8 maskable interrupt inputs, expandable via master/slave cascading to 64 sources. It performs priority arbitration and sends the chosen vector to the CPU.
Registers:
- IMR: mask bits (1 = disabled)
- ISR: tracks active interrupts
- IRR: pending interrupts
Priority: lower IRQ number wins. After selection, ISR bit set, IRR bit cleared. Vector number = base + IRQ. The CPU indexes IDT with this vector.
EOI command resets ISR bit. In manual EOI mode, the handler must issue EOI to 8259A.
Programming involves Initialization Command Words (ICW1–ICW4) and Operation Command Words (OCW1–OCW3):
- ICW1: edge/level trigger, cascade, ICW4 needed
- ICW2: base vector number
- ICW3: master/slave linkage map
- ICW4: mode settings (8086 mode, auto EOI, buffering)
- OCW1: interrupt mask
- OCW2: EOI, rotation, priority control
- OCW3: special mask, poll mode
Port mapping: ICW1/OCW2/OCW3 → even ports (0x20 master, 0xA0 slave); ICW2–ICW4/OCW1 → odd ports (0x21 master, 0xA1 slave).
Writing an Interrupt Handler
Setup stages:
- Assembly macro defines entry stubs performing minimal context save, sending EOI, invoking C handler, and returning.
%macro VEC_ENTRY 2
section .text
vec_%1_entry:
%2
pusha
mov al, 0x20
out 0xA0, al
out 0x20, al
push %1
call [handler_table + %1*4]
jmp vec_exit
section .data
dd vec_%1_entry
%endmacro
- Construct IDT entries using a gate descriptor structure: low/high offset, selector, attributes.
struct gate {
uint16_t offset_lo;
uint16_t selector;
uint8_t zero;
uint8_t attr;
uint16_t offset_hi;
};
static void build_gate(struct gate *g, uint8_t attr, void (*handler)(void)) {
g->offset_lo = (uint32_t)handler & 0xFFFF;
g->selector = K_CODE_SEL;
g->zero = 0;
g->attr = attr;
g->offset_hi = ((uint32_t)handler >> 16) & 0xFFFF;
}
- Initialize 8259A:
void pic_setup(void) {
outb(M_CTRL, 0x11);
outb(M_DATA, 0x20);
outb(M_DATA, 0x04);
outb(M_DATA, 0x01);
outb(S_CTRL, 0x11);
outb(S_DATA, 0x28);
outb(S_DATA, 0x02);
outb(S_DATA, 0x01);
outb(M_DATA, 0xFE); // enable IRQ0
outb(S_DATA, 0xFF);
}
-
Load IDT with
lidt. -
Provide generic C handlers indexed by vector, allowing specific registration later.
Timer 8253 Programming
System timing relies on internal (nanosecond-scale, from crystal oscillator) and external clocks (millisecond/second scale). Precise interavls use hardware timers like 8253.
8253 provides three independent counters (ports 0x40–0x42), each with a 16-bit count register, control logic, and output latch. Clock (CLK), gate (GATE), and output (OUT) pins manage operation.
Control word at port 0x43 sets counter, access mode, and operating mode. Common modes: periodic (mode 2) or square wave (mode 3).
To raise timer interrupt frequency to 100 Hz:
- Use counter 0, mode 2
- Compute initial count = 1193180 / 100 ≈ 11932
void set_freq(uint8_t port, uint8_t counter, uint8_t rw_mode, uint8_t mode, uint16_t val) {
outb(0x43, (counter << 6) | (rw_mode << 4) | (mode << 1));
outb(port, val & 0xFF);
outb(port, (val >> 8) & 0xFF);
}
void init_timer() {
set_freq(0x40, 0, 3, 2, 11932);
}
Integration involves calling init_timer() during system boot, enabling IRQ0 at 100 Hz.