Lesson 6 · Operating Systems

Interrupts in OS

An interrupt is a signal that makes the CPU stop what it is doing, run a handler in the kernel, and then resume. It is how devices, timers and errors get the operating system's attention without being polled.

Interrupts in OS concept diagramA user program runs until the keyboard raises IRQ1. The program is paused, shown as a dashed gap. The CPU saves the program counter 0x102 and the flags, looks up vector 0x21 in the vector table to find kbd_isr, runs the interrupt service routine, which sends end-of-interrupt, and iret restores the context so the program resumes at 0x102.an interrupt pauses the program between two instructions, then resumes ituser programpausedresumes at 0x102keyboardraises IRQ1save contextPC 0x102, flagsvector 0x21IVT → kbd_isrrun the ISRread key, send EOIpushiretkernel mode from the save to the iret; user mode on both sides
1

Stop, Handle, Resume

  1. Fetch – the CPU fetches the next instruction.
  2. Execute – it executes the instruction completely.
  3. Check – it checks the interrupt request line; if nothing is pending, go back to fetch.
  4. Handle – if an interrupt is pending and enabled, save the context and run its ISR, then continue.

An interrupt is a signal to the CPU that an event needs immediate attention. When it arrives, the CPU suspends the program it is running, saves enough state to continue it later, and jumps to a kernel function called the interrupt service routine (ISR) or interrupt handler. When the ISR finishes, the CPU restores the saved state and the program continues as if nothing had happened.

Interrupts are how an operating system reacts to the outside world. A key press, a finished disk transfer, an arriving network packet and the timer that drives CPU scheduling all reach the kernel as interrupts. Without them, the CPU would have to keep asking each device whether it needs anything, which is called polling. Modern operating systems are interrupt driven: when nothing is happening, the CPU idles until the next interrupt.

  • Interrupt: an event that diverts the CPU to a handler
  • ISR: the kernel routine that services one kind of interrupt
  • The interrupted program resumes at the exact instruction it would have run next
2

Types of Interrupts

Interrupts are classified by where they come from, and the first split is between hardware and software interrupts. Hardware interrupts arrive from devices on interrupt request (IRQ) lines, asynchronously: they can occur between any two instructions. Software interrupts are raised deliberately by an instruction, such as int 0x80 or syscall, and are how programs make system calls. Exceptions are raised by the CPU itself when an instruction cannot complete normally.

Hardware interrupts are further split by whether they can be ignored. A maskable interrupt can be disabled temporarily by the kernel; a non-maskable interrupt (NMI) cannot, and is reserved for events such as hardware memory errors and watchdog timers.

Kinds of interrupts
TypeSourceTimingExamples
Hardware, maskablea device via an IRQ lineasynchronouskeyboard, disk, network card, timer
Hardware, non-maskable (NMI)critical hardwareasynchronousmemory parity error, watchdog timer
Software interrupt (trap)an instruction in the programsynchronoussystem calls: int 0x80, syscall, svc
Exception: faultthe CPU; the instruction is retriedsynchronouspage fault, segment not present
Exception: trapthe CPU; execution continues after itsynchronousbreakpoint, overflow
Exception: abortthe CPU; the process cannot continuesynchronousdouble fault, machine check
  • Asynchronous: unrelated to the current instruction
  • Synchronous: caused by the current instruction
  • A page fault is a fault: after the handler loads the page, the instruction runs again
3

How an Interrupt Is Handled

  1. Request – the device signals the interrupt controller, which raises the CPU's interrupt line.
  2. Finish the instruction – the CPU completes the current instruction; interrupts are recognised only between instructions.
  3. Acknowledge – the CPU acknowledges, and the controller supplies a vector number.
  4. Save context – the hardware pushes the program counter and flags onto the kernel stack and switches to kernel mode.
  5. Look up the handler – the vector number indexes the interrupt vector table to find the ISR's address.
  6. Run the ISR – it saves any registers it uses, services the device, and sends an end-of-interrupt (EOI) to the controller.
  7. Return – the iret instruction restores the flags and program counter, returning to user mode if the program was there.

Interrupt handling is shared between the hardware and the operating system. The hardware does the part that must be atomic, saving the minimum state and switching into the kernel; the ISR does the device-specific work. The same sequence, summarised in the diagram, applies to every interrupt.

  • The hardware saves only what it must; the ISR saves the registers it uses
  • EOI tells the controller the interrupt is done, so it can deliver the next one
  • If the interrupt made a higher-priority process ready, the kernel may context switch before returning
Key reference

Terms, operations, and practical uses

Core vocabulary

  • InterruptA signal that diverts the CPU to a kernel handler and later resumes the program.
  • ISRInterrupt service routine: the handler for one interrupt source.
  • IRQInterrupt request line from a device to the interrupt controller.
  • NMINon-maskable interrupt, for critical hardware events.

Mechanisms

  • Vector table (IVT / IDT)Maps each vector number to its handler's address.
  • EOIEnd-of-interrupt: tells the controller the ISR has finished.
  • iretRestores the saved flags and program counter to resume the interrupted code.
  • Bottom halfDeferred interrupt work run later with interrupts enabled.
Implementation

Nested and pending interrupts on a priority controller

DEVICES = {0: ("timer", 0x20, 2), 1: ("keyboard", 0x21, 4), 14: ("disk", 0x2E, 3)}  # IRQ -> (device, vector, ISR ticks)
# A lower IRQ number means a higher priority, as on the x86 8259 controller.
ARRIVALS = {2: 1, 4: 0, 5: 14}  # tick -> IRQ line raised at that tick
USER_PRIORITY = 99  # user code can be interrupted by any IRQ


def simulate(ticks):
    pending, raised_at = set(), {}
    stack = []  # saved contexts: (name, priority, pc or ticks left)
    current = ("user", USER_PRIORITY, 0x100)
    timeline = []
    for t in range(ticks):
        if t in ARRIVALS:
            irq = ARRIVALS[t]
            pending.add(irq)
            raised_at[irq] = t
            print(f"t={t:>2}: IRQ{irq} raised by {DEVICES[irq][0]}")
        # Between instructions the CPU accepts the most urgent pending request,
        # but only if it outranks whatever is running now.
        if pending and min(pending) < current[1]:
            irq = min(pending)
            pending.remove(irq)
            name, vector, length = DEVICES[irq]
            stack.append(current)
            wait = t - raised_at[irq]
            print(f"t={t:>2}: save {current[0]}, vector 0x{vector:X}", end="")
            print(f" -> {name} ISR, waited {wait}")
            current = (name, irq, length)
        name, priority, state = current
        timeline.append(name)
        if name == "user":
            current = (name, priority, state + 1)  # next instruction
        elif state == 1:  # last tick of the ISR: acknowledge, then iret
            current = stack.pop()
            where = f" at pc 0x{current[2]:X}" if current[0] == "user" else ""
            print(f"t={t + 1:>2}: {name} ISR done, iret -> {current[0]}{where}")
        else:
            current = (name, priority, state - 1)
    return timeline


timeline = simulate(13)
print("timeline:", " ".join(name[0].upper() for name in timeline))
print("ticks of user code:", timeline.count("user"))
#include <cctype>
#include <cstdio>
#include <map>
#include <set>
#include <string>
#include <vector>
using namespace std;

struct Device {
    string name;
    int vector, length;  // ISR length in ticks
};

// A lower IRQ number means a higher priority, as on the x86 8259 controller.
const map<int, Device> DEVICES = {
    {0, {"timer", 0x20, 2}},
    {1, {"keyboard", 0x21, 4}},
    {14, {"disk", 0x2E, 3}},
};
const map<int, int> ARRIVALS = {{2, 1}, {4, 0}, {5, 14}};  // tick -> IRQ line raised at that tick
const int USER_PRIORITY = 99;                              // user code can be interrupted by any IRQ

struct Context {
    string name;
    int priority;
    int state;  // user: program counter; ISR: ticks left
};

vector<string> simulate(int ticks) {
    set<int> pending;
    map<int, int> raisedAt;
    vector<Context> stack;  // saved contexts
    Context current{"user", USER_PRIORITY, 0x100};
    vector<string> timeline;
    for (int t = 0; t < ticks; t++) {
        auto a = ARRIVALS.find(t);
        if (a != ARRIVALS.end()) {
            pending.insert(a->second);
            raisedAt[a->second] = t;
            printf("t=%2d: IRQ%d raised by %s\n", t, a->second, DEVICES.at(a->second).name.c_str());
        }
        // Between instructions the CPU accepts the most urgent pending request,
        // but only if it outranks whatever is running now.
        if (!pending.empty() && *pending.begin() < current.priority) {
            int irq = *pending.begin();
            pending.erase(pending.begin());
            const Device& d = DEVICES.at(irq);
            stack.push_back(current);
            printf("t=%2d: save %s, vector 0x%X -> %s ISR, waited %d\n", t, current.name.c_str(), d.vector,
                   d.name.c_str(), t - raisedAt[irq]);
            current = {d.name, irq, d.length};
        }
        timeline.push_back(current.name);
        if (current.name == "user") {
            current.state++;  // next instruction
        } else if (current.state == 1) {  // last tick of the ISR: acknowledge, then iret
            string done = current.name;
            current = stack.back();
            stack.pop_back();
            printf("t=%2d: %s ISR done, iret -> %s", t + 1, done.c_str(), current.name.c_str());
            if (current.name == "user") printf(" at pc 0x%X", current.state);
            printf("\n");
        } else {
            current.state--;
        }
    }
    return timeline;
}

int main() {
    vector<string> timeline = simulate(13);
    int user = 0;
    printf("timeline:");
    for (const string& name : timeline) {
        printf(" %c", toupper(name[0]));
        user += name == "user";
    }
    printf("\nticks of user code: %d\n", user);
    return 0;
}
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

public class Main {
    record Device(String name, int vector, int length) {} // ISR length in ticks

    record Context(String name, int priority, int state) {} // user: program counter; ISR: ticks left

    // A lower IRQ number means a higher priority, as on the x86 8259 controller.
    static final Map<Integer, Device> DEVICES = Map.of(
            0, new Device("timer", 0x20, 2),
            1, new Device("keyboard", 0x21, 4),
            14, new Device("disk", 0x2E, 3));
    static final Map<Integer, Integer> ARRIVALS = Map.of(2, 1, 4, 0, 5, 14); // tick -> IRQ line raised
    static final int USER_PRIORITY = 99; // user code can be interrupted by any IRQ

    static List<String> simulate(int ticks) {
        TreeSet<Integer> pending = new TreeSet<>();
        Map<Integer, Integer> raisedAt = new HashMap<>();
        Deque<Context> stack = new ArrayDeque<>(); // saved contexts
        Context current = new Context("user", USER_PRIORITY, 0x100);
        List<String> timeline = new ArrayList<>();
        for (int t = 0; t < ticks; t++) {
            Integer raised = ARRIVALS.get(t);
            if (raised != null) {
                pending.add(raised);
                raisedAt.put(raised, t);
                System.out.printf("t=%2d: IRQ%d raised by %s%n", t, raised, DEVICES.get(raised).name());
            }
            // Between instructions the CPU accepts the most urgent pending request,
            // but only if it outranks whatever is running now.
            if (!pending.isEmpty() && pending.first() < current.priority()) {
                int irq = pending.pollFirst();
                Device d = DEVICES.get(irq);
                stack.push(current);
                System.out.printf("t=%2d: save %s, vector 0x%X -> %s ISR, waited %d%n",
                        t, current.name(), d.vector(), d.name(), t - raisedAt.get(irq));
                current = new Context(d.name(), irq, d.length());
            }
            timeline.add(current.name());
            if (current.name().equals("user")) {
                current = new Context("user", current.priority(), current.state() + 1); // next instruction
            } else if (current.state() == 1) { // last tick of the ISR: acknowledge, then iret
                String done = current.name();
                current = stack.pop();
                String where = current.name().equals("user")
                        ? String.format(" at pc 0x%X", current.state())
                        : "";
                System.out.printf("t=%2d: %s ISR done, iret -> %s%s%n", t + 1, done, current.name(), where);
            } else {
                current = new Context(current.name(), current.priority(), current.state() - 1);
            }
        }
        return timeline;
    }

    public static void main(String[] args) {
        List<String> timeline = simulate(13);
        StringBuilder line = new StringBuilder("timeline:");
        int user = 0;
        for (String name : timeline) {
            line.append(' ').append(Character.toUpperCase(name.charAt(0)));
            if (name.equals("user")) user++;
        }
        System.out.println(line);
        System.out.printf("ticks of user code: %d%n", user);
    }
}
Watch it run

Step through it

Running on IRQ1 keyboard at t = 2 (ISR 4 ticks), IRQ0 timer at t = 4 (2 ticks), IRQ14 disk at t = 5 (3 ticks)

CPUuser programuser modepc 0x100interrupt controllerlinerequestin serviceIRQ0timerIRQ1kbdIRQ14diskinterrupt vector table0x20→ timer_isr0x21→ kbd_isr0x2E→ disk_isrkernel stackemptyhandling an interrupt1. device raises an IRQ line2. CPU finishes the current instruction3. save PC and flags, enter kernel mode4. look up the vector, run the ISR5. ISR sends EOI, iret restores contextCPU timeline012345678910111213
Step 1

t = 0: a user program runs, no requests pending

The CPU executes a user program in user mode, one instruction per tick, starting at address 0x100. No device needs attention, so every request bit in the interrupt controller is clear. The program has no idea interrupts exist.

Output
1 / 11
4

Interrupt Vector Table and Interrupt Controller

The interrupt vector table (IVT) is an array of handler addresses indexed by vector number. On x86 in protected mode it is the Interrupt Descriptor Table (IDT), with 256 entries: vectors 0 to 31 are reserved for CPU exceptions (0 is divide error, 14 is page fault), and the rest are for hardware interrupts and system calls. The kernel fills in the table at boot, so every interrupt goes straight to the right handler without searching.

Devices do not connect to the CPU directly. An interrupt controller collects their IRQ lines, decides which request to deliver, and tells the CPU its vector. The classic 8259 PIC handled 8 lines (two cascaded gave 15) with fixed priorities; modern systems use the APIC, which routes interrupts to any of many cores, and MSI, where a PCIe device raises an interrupt by writing to a special memory address instead of using a wire.

x86 vectors with the legacy PIC remapped to start at 32, a common setup
VectorSourceHandler
0divide by zeroexception handler, usually kills the process
14 (0x0E)page faultloads the page or reports a segmentation fault
32 (0x20)timer, IRQ0updates time, triggers the scheduler
33 (0x21)keyboard, IRQ1reads the scan code into a buffer
46 (0x2E)primary disk, IRQ14completes the pending I/O request
128 (0x80)int 0x80 instructionLinux's legacy system call entry
  • IVT / IDT: vector number → handler address
  • Interrupt controller: many IRQ lines in, one prioritised request to the CPU
  • APIC and MSI spread interrupts across cores in multiprocessor systems
5

Interrupt Priority, Masking, and Nested Interrupts

When several interrupts are pending, the controller delivers the one with the highest priority first; on the 8259, IRQ0 (the timer) beats IRQ1 (the keyboard), which beats IRQ14 (the disk). While an ISR runs, interrupts of equal or lower priority are held back, and those of higher priority may interrupt the handler itself. That is a nested interrupt, and the tracer shows the timer nesting inside the keyboard handler while the disk waits.

The kernel can also disable (mask) interrupts for short critical sections, with cli and sti on x86. A disabled interrupt is not lost; its request stays pending until interrupts are enabled again. Masking must be brief, because every tick it lasts adds to the latency of every device. It also only works on one CPU, which is why multiprocessor kernels combine it with spinlocks.

  • Masking one IRQ line – holds back only that device, for example while its own ISR runs or while it is reconfigured
  • Disabling all (cli) – no maskable interrupt gets through until sti; only for a few instructions
  • NMI – ignores every mask, which is why watchdogs and profilers use it
  • Cost of nesting – each level pushes another saved context, so the kernel stack must be sized for the deepest nest
6

Polling vs Interrupts

With polling, the CPU repeatedly reads a device's status register to see whether it is ready. With interrupts, the device tells the CPU when it is ready. Polling wastes CPU time when events are rare, but it has no per-event overhead, so it wins when events are extremely frequent.

That is why high-speed network drivers combine the two. Linux's NAPI takes an interrupt for the first packet, then switches that device to polling while packets keep arriving, and goes back to interrupts when the traffic stops. It avoids an interrupt storm, where the CPU does nothing but enter and leave handlers.

Polling against interrupt-driven I/O
AspectPollingInterrupts
Who initiatesthe CPU asks the devicethe device signals the CPU
CPU use while waitingbusy: every check costs cyclesfree for other work
Cost per eventlow: a register readhigher: save, vector, ISR, restore
Response timeup to one polling intervalimmediate, subject to priority
Best forvery fast or very frequent eventsslow or unpredictable events
  • Rare events: interrupts
  • Continuous high-rate events: polling, or interrupts with coalescing
  • Bulk data: DMA plus one interrupt per completed transfer
7

Top Half, Bottom Half, and Interrupt Latency

Interrupt latency is the time from a device raising an interrupt to its ISR starting. It is made up of finishing the current instruction, any time interrupts were disabled, and any higher-priority handlers that run first; the disk in the tracer waited 3 ticks this way. Real-time systems bound it, because a missed interrupt can mean a missed deadline.

To keep latency low, operating systems split interrupt handling in two. The top half, the ISR itself, runs with its interrupt masked and does only the urgent part: acknowledge the device, copy the data, schedule the rest. The bottom half runs later with interrupts enabled and does the slow work, such as processing a network packet through the protocol stack. Linux uses softirqs, tasklets and workqueues for bottom halves; Windows uses deferred procedure calls (DPCs).

  • Top half: minimal, fast, interrupts masked
  • Bottom half: deferred, interruptible, does the heavy work
  • Latency = instruction completion + masked time + higher-priority handlers
  • See Real-Time Operating Systems for bounded latency