Two modes, one CPU
Modern CPUs run in at least two privilege levels: kernel mode (ring 0 — full hardware access) and user mode (ring 3 — restricted). Privileged instructions — manipulating page tables, disabling interrupts, accessing I/O ports — trap if executed from user mode. This is how the OS enforces isolation without trusting application code.
How a trap works
A trap (or exception) transfers control to a kernel handler:
- User code executes
syscall(x86-64) orsvc(ARM). - CPU saves minimal state, switches to kernel mode, jumps to a syscall dispatch table entry.
- Kernel validates arguments, performs the work, places return value in a register.
sysret/eretrestores user mode and resumes after the syscall instruction.
The same machinery handles page faults, divide-by-zero, and hardware interrupts — only the handler differs.
Traps vs interrupts vs exceptions
| Event | Triggered by | Typical handler |
|---|---|---|
| Syscall | User instruction (syscall) | Kernel syscall table |
| Page fault | MMU (invalid/unmapped address) | Demand paging, segfault |
| Timer interrupt | Hardware clock | Scheduler preemption |
| Device interrupt | NIC, disk, keyboard | Driver bottom-half |
Senior-level signal
High syscall rates are a performance smell — every trap flushes pipeline state and may invalidate TLB entries. Tools like perf stat -e syscalls:sys_enter_* and Brendan Gregg's syscall heat maps reveal when you're paying kernel tax for chatty I/O (e.g., write per log line instead of buffering).
Where this goes next
The Process Abstraction & API covers what the kernel actually manages once inside a trap — fork, exec, and the lifecycle that turns syscalls into running programs.
Further Reading
Hands-On Tasks (Optional)
Low-setup exercises on your local machine. No autograding — the goal is to build intuition, not pass a test.
- Trace a write() syscall end-to-end15m
Run `strace -f -e trace=write echo hello 2>&1`. Identify the write syscall, its file descriptor, and return value. Understand that printf ultimately becomes write(1, ...).