Operating-System Kernels

the trap mechanism (traps, exceptions, interrupts)

Normally the CPU just runs your instructions one after another. But three kinds of events can interrupt this flow and force the CPU to drop what it is doing, switch into the kernel's privileged mode, and jump to a kernel handler. Collectively these are the trap mechanism - the hardware's universal doorbell into the kernel. They are the reason the kernel ever gets to run at all: most of the time the CPU is executing user code, and only a trap brings control back into the operating system.

There are three flavors, and the distinction matters. A trap (often called a software interrupt) is deliberate and synchronous: your program executes a special instruction on purpose to ask the kernel for service - this is how a system call enters the kernel. An exception (or fault) is also synchronous but unplanned: an instruction did something the CPU cannot complete, like dividing by zero, accessing an unmapped page (a page fault), or executing an illegal instruction; the CPU stops at that instruction and jumps to a handler, which may fix things up (a page fault can load the missing page and retry) or kill the offending program. An interrupt proper is asynchronous and external: a device - a network card, a disk, the timer - raises a signal that has nothing to do with the current instruction, saying 'I need attention now.' The CPU finishes the current instruction, then jumps to that device's handler.

The key mental model: in every case the hardware automatically saves enough state (at least the program counter), elevates privilege, and uses a table to find the right kernel handler to jump to. This single mechanism underpins system calls, virtual memory (page faults), the preemptive scheduler (the timer interrupt), and all device I/O. A common confusion is to lump them together: traps and exceptions are synchronous (caused by the running instruction, reproducible at that point), while hardware interrupts are asynchronous (caused by the outside world, arriving at unpredictable moments) - and that difference shapes everything about how each is handled.

trap: 'syscall' instruction -> kernel (deliberate). exception: mov eax, [unmapped_addr] -> page fault -> kernel handler may load page + retry. interrupt: NIC asserts IRQ -> CPU finishes current instr, then jumps to the NIC handler.

Three doorbells into the kernel: deliberate (trap), unplanned-but-synchronous (exception), and external-asynchronous (interrupt).

Do not equate 'interrupt' with all three. Traps/exceptions are synchronous (the running instruction triggers them and they recur at that instruction), while a hardware interrupt is asynchronous and unrelated to whatever instruction happened to be executing - which is why an interrupt handler must not assume anything about the interrupted code's context.

Also called
interrupts and exceptionstrap/fault/interrupt陷阱、例外與中斷