Kernel vs User Mode & Traps

Ring 0 vs ring 3, privileged instructions, and how a trap/syscall instruction switches to the kernel, runs the handler, and returns — the mechanism behind every I/O operation and memory mapping.

2/5Overview: 20m

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:

  1. User code executes syscall (x86-64) or svc (ARM).
  2. CPU saves minimal state, switches to kernel mode, jumps to a syscall dispatch table entry.
  3. Kernel validates arguments, performs the work, places return value in a register.
  4. sysret/eret restores 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

EventTriggered byTypical handler
SyscallUser instruction (syscall)Kernel syscall table
Page faultMMU (invalid/unmapped address)Demand paging, segfault
Timer interruptHardware clockScheduler preemption
Device interruptNIC, disk, keyboardDriver 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-end

    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, ...).

    15m