Traps, exceptions and the interrupt table
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
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.
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اقرأ الدرس خطوة بخطوة
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 modeThe 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)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 3Line 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]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 zeroingRetry 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 oneLine 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 programThe 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 transparentLine 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]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 fineOne 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
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01Which of these is an interrupt rather than an exception?
Exceptions are caused by the instruction running right now. An interrupt comes from a device, such as the timer, and can arrive at any moment, whatever the program is doing.
02Who decides which handler runs for event number 14?
The kernel fills the table while it is in kernel mode at boot, and setting the table is privileged. The CPU looks up the row by number, so the program can never choose where in the kernel it lands.
03After the kernel maps a fresh zeroed page for big[500000], where does the program continue?
For a fault the CPU saves the address of the faulting instruction itself, so return-from-trap runs it again. This time the page is there and the write works.
04Why does the divide error end the program, when the page fault did not?
The page-fault handler could fix the cause (add the page). The divide-error handler cannot, so the kernel sends SIGFPE, whose default action terminates the program. The kernel and other programs keep running.
05On x86-64, how many rows does the interrupt table have, and which ones does the CPU itself number?
The table has 256 rows. Rows 0 to 31 are the CPU's own exceptions (0 is divide error, 14 is page fault). The kernel uses the rest for devices and its own needs; Linux puts its local timer at 236.
المسرد
- Trap
- Any controlled jump from a program into the kernel that switches the CPU to kernel mode. System calls, exceptions and interrupts are all traps.
- Exception
- A trap caused by the instruction running now, such as a divide by zero or a page fault. It happens at the same instruction every time the program runs the same way.
- Interrupt
- A trap caused by a device, such as the timer or a disk. It can arrive at any moment and has nothing to do with the instruction running.
- Interrupt table
- A list of numbered rows, each holding the address of a kernel handler. On x86-64 it is called the Interrupt Descriptor Table and has 256 rows.
- Handler
- The piece of kernel code a row of the interrupt table points to. It deals with one kind of event and then returns or ends the program.
- Page fault
- Exception 14 on x86-64: the CPU could not use a page of memory. If the page belongs to the program the kernel can fix it and the instruction is retried.
- Return-from-trap
- The instruction the kernel runs to go back to the program: it restores the saved place and switches the CPU back to user mode.
- SIGFPE
- The signal Linux sends after an arithmetic error such as an integer divide by zero. Its default action ends the program.
الملاحظات والمصادر
- The figure shows 4 of the table's 256 rows. Rows 0 (divide error) and 14 (page fault) are numbered by the CPU itself; rows 128 (int 0x80) and 236 (local timer) are the numbers Linux chooses on x86-64. On RISC-V, xv6 uses no table of rows: every trap enters at one address (stvec, in direct mode) and the CPU puts the cause number in scause.
- Row 128 is the old int 0x80 way to make a system call. 64-bit programs on Linux use the faster syscall instruction, which enters at a separate address the kernel also sets at boot. Both are traps into kernel mode.
- In C, dividing an int by zero is undefined behaviour. On x86-64 the compiled divide instruction raises the divide error shown here. On 64-bit ARM, integer division by zero gives 0 and nothing traps, so the program would carry on.
- Giving a page memory only on first use is demand zeroing. The page is filled with zeros so a program can never read what another program left there.
- SIGFPE is named after floating point, but on Linux it also reports integer divide errors. The words Floating point exception come from the shell, not the kernel.
- How often the timer fires depends on the kernel: Linux is commonly built for 250 or 1000 ticks per second, and can skip ticks on idle CPUs.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 6: Limited Direct Execution (trap table, timer interrupt)
- Operating Systems: Three Easy Pieces, ch. 21: Beyond Physical Memory: Mechanisms (page faults, retrying the instruction)
- Operating Systems: Three Easy Pieces, ch. 23: Complete Virtual Memory Systems (demand zeroing)
- Berkeley CS162, Lecture 3 (Interrupt Vector; syscall, interrupt, trap or exception)
- MIT 6.1810, xv6: a simple, Unix-like teaching operating system (RISC-V), ch. 4: Traps and system calls
- Linux kernel documentation: x86-64 kernel entry
- Linux source: x86 interrupt vector numbers (irq_vectors.h)
- Linux source: x86 trap numbers (trapnr.h)
- Linux source: x86 IDT setup (idt.c)
- Linux man-pages: signal(7)
اختبار يتاح بعد الخطوة الأخيرة.