ENع
←Traps and interrupts
Lesson 03 · The kernel and system calls

Traps, exceptions and the interrupt table

13 min11 steps5 questionsBeginner
About this lesson

A program can be stopped mid-run in three ways: it asks the kernel for help (a system call), one of its instructions goes wrong (an exception), or a device needs attention (an interrupt). Every one of them goes through the same numbered table that the kernel fills at boot. Follow three lines of C as a missing page is fixed and the line retried, a timer interrupt slips in and out unnoticed, and a divide by zero ends the program. It builds on User mode and kernel mode and System calls: crossing into the kernel; the Hardware lesson on interrupts and I/O shows the device side.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 3 · Interactive
01 / 11

Three ways in

Three kinds of event stop a program and run the kernel: a system call (the program asks), an exception (an instruction goes wrong) and an interrupt (a device needs attention). All three are traps: controlled jumps into kernel mode.

event         who causes it            when
system call   the program asks         when it chooses
exception     the instruction now      at that instruction
              (divide by zero, bad address, ...)
interrupt     a device (timer, disk)   any moment

all three: a trap into the kernel, in kernel mode
Loading figure…
or ← →
Read the lesson step by step
  1. Three ways in

    Three kinds of event stop a program and run the kernel: a system call (the program asks), an exception (an instruction goes wrong) and an interrupt (a device needs attention). All three are traps: controlled jumps into kernel mode.

    event         who causes it            when
    system call   the program asks         when it chooses
    exception     the instruction now      at that instruction
                  (divide by zero, bad address, ...)
    interrupt     a device (timer, disk)   any moment
    
    all three: a trap into the kernel, in kernel mode
  2. The interrupt table

    At boot the kernel fills the interrupt table: 256 numbered rows on x86-64, each pointing to a kernel handler. The CPU fixes rows 0 to 31 for exceptions and other CPU events; the rest serve devices and the kernel. Only the kernel can set it.

    x86-64: the Interrupt Descriptor Table, 256 rows
    
    row    handler (Linux)                  set by
    0      divide error                     CPU (fixed)
    14     page fault                       CPU (fixed)
    128    legacy system call (int 0x80)    Linux
    236    local timer                      Linux
    
    rows 0..31    exceptions and other CPU events (2 = NMI)
    rows 32..255  devices and the kernel's own use
    then:  load_idt  tells the CPU where the table is
           (only possible in kernel mode)
  3. What the CPU does

    Every trap runs the same four moves, in hardware: find the event's number, save the program's place (its instruction address and flags), switch to kernel mode, and jump to the handler in that row. The program never picks where it lands.

    on any trap, the CPU itself:
      1  gets the number      (14 = page fault, ...)
      2  saves the place      instruction address, flags
                              (onto the kernel stack, on x86)
      3  mode user -> kernel
      4  jumps to table[number]
    
    return-from-trap undoes 2 and 3
  4. Line 1: a missing page

    Line 1 writes into a big array. To save work, the kernel gives an array page real memory only when it is first used. This page has none yet, so the CPU raises exception 14, a page fault, and switches to kernel mode.

    the whole program (C99):
    
    #include <stdio.h>
    
    static volatile char big[1000000]; /* 1 MB of zeros, no memory yet */
    
    int main(void) {
        volatile long i = 0;
        volatile int zero = 0;
        int n;
        big[500000] = 1;
        while (i < 1e8) i++;
        n = 10 / zero;
        printf("%d\n", n);          /* never reached on x86-64 */
        return 0;
    }
    
    line 1   big[500000] = 1;
    page     belongs to big[], but has no memory yet
    CPU      page fault   number 14
    saves    the address of THIS instruction
    mode     user -> kernel, jump to table[14]
  5. The kernel fixes it

    Row 14 sends the CPU to the kernel's page-fault handler. It checks the address: it belongs to the program's array, so the fault is fine. It takes a free page of memory, fills it with zeros and maps it into the program.

    handler  page fault (row 14)
    check    is the address part of the program?   yes: big[]
    do       take a free page
             fill it with zeros   (never leak old data)
             map it into the program's page table
    this trick is called demand zeroing
  6. Retry the same line

    Return-from-trap goes back to the same instruction, not the next one. The CPU runs the write again, and now it works: big[500000] becomes 1. The program never knew. A fault the kernel can fix is retried.

    return   mode kernel -> user
             to the saved address: line 1 again
    retry    big[500000] = 1;   works this time
    
    fault  (page fault, divide error)  saved place = that instruction
    system call, interrupt             saved place = the next one
  7. Line 2: a timer interrupt

    Line 2 just counts up. Meanwhile the timer the kernel set at boot fires, every few milliseconds. This is an interrupt: it comes from a device, not from the instruction running now, so it can arrive at any moment.

    line 2   while (i < 1e8) i++;
             about a hundred million steps: long enough
             for the timer to fire many times
    timer    set by the kernel at boot
             fires every few milliseconds
    kind     interrupt: asynchronous, from outside the program
  8. The tick handler

    The CPU pauses the loop, saves its place, switches to kernel mode and looks up row 236, the local timer on Linux. The handler counts the tick and may pick another program. Then it returns and the loop carries on.

    CPU      saves the place in the loop
             mode user -> kernel, jump to table[236]
    handler  local timer (Linux x86-64: vector 0xec = 236)
             count a tick; maybe switch programs
    return   mode kernel -> user, back into the loop
    program  sees nothing: the trap is transparent
  9. Line 3: divide by zero

    Line 3 divides 10 by zero. There is no answer, so the CPU's divide instruction raises exception 0, a divide error. As with every trap, the CPU saves the program's place, switches to kernel mode and jumps through row 0.

    line 3   n = 10 / zero;
    CPU      divide instruction, divisor 0: no answer
    raises   divide error   number 0
    saves    the address of this instruction
    mode     user -> kernel, jump to table[0]
  10. A fault it cannot fix

    The handler has nothing to fix: no page to add, no answer to find, and retrying would fail again. So the kernel sends the program the signal SIGFPE, whose default action ends it. The shell prints Floating point exception.

    handler  divide error (row 0)
    fix?     no   (retrying would fault again)
    signal   SIGFPE   "Erroneous arithmetic operation"
             default action: terminate (and dump core)
    shell    Floating point exception
    kernel   fine        other programs   fine
  11. One table for everything

    One table, filled by the kernel at boot, decides where every event goes. Exceptions come from the instruction running now; interrupts come from devices at any moment. Fixable faults are retried; fatal ones end only the program that caused them.

    dispatch as a Python simulation:
    
    def divide():     print("row 0:   send SIGFPE"); return "kill"
    def page_fault(): print("row 14:  map a zero page"); return "retry"
    def timer():      print("row 236: count a tick"); return "resume"
    
    table = {0: divide, 14: page_fault, 236: timer}   # filled at boot
    
    for vector in [14, 236, 0]:      # events while ./prog runs
        action = table[vector]()     # the CPU jumps through the row
        if action == "kill":
            print("program ends")
            break
    
    prints:
    row 14:  map a zero page
    row 236: count a tick
    row 0:   send SIGFPE
    program ends

Quiz Unlocks after the last step.