User Mode & Kernel Mode
If any program could talk to the disk controller, change the page tables or switch off interrupts, one buggy app could wipe your disk or freeze the machine. Operating systems prevent this with help from the CPU itself: the processor has (at least) two privilege levels, and only the kernel runs at the high one.
Protection rings
x86 processors define four rings, numbered 0 (most privileged) to 3 (least). Linux and Windows use only two of them:
+-----------------------------------+
| ring 3: user mode | apps, shells, services,
| +---------------------------+ | libraries (libc, ntdll.dll)
| | ring 2 / ring 1 (unused) | |
| | +-------------------+ | |
| | | ring 0: kernel | | | Linux kernel + modules,
| | | mode | | | ntoskrnl.exe + drivers + HAL
| | +-------------------+ | |
| +---------------------------+ |
+-----------------------------------+
below ring 0: hypervisor ("ring -1": Hyper-V, KVM) firmware/SMM ("ring -2")ARM CPUs (phones, Apple Silicon, many servers) use exception levels instead: EL0 for user code, EL1 for the kernel, EL2 for a hypervisor and EL3 for secure firmware. The idea is the same.
| User mode (ring 3 / EL0) | Kernel mode (ring 0 / EL1) | |
|---|---|---|
| Who runs there | applications, most services | kernel, drivers |
| Memory it can touch | only its own process's user pages | all memory, including the kernel's |
Privileged instructions (hlt, cli, in/out, loading page tables) |
trap to the kernel | allowed |
| Effect of a crash | the process dies | the whole system halts (panic / blue screen) |
Windows names the two modes the same way (user mode and kernel mode); Task Manager and Performance Monitor call
time spent in the kernel privileged time, while Linux's top and time call it sys (system) time.
The CPU enforces it
The current privilege level is stored in the CPU (the low two bits of the CS register on x86). When user-mode code
executes a privileged instruction, the CPU does not obey: it raises a general protection fault, which jumps into
the kernel. The kernel sees that a user program misbehaved and kills it: on Linux with the signal SIGSEGV, on
Windows with the exception STATUS_PRIVILEGED_INSTRUCTION (0xC0000096).
This tiny x86-64 program tries to run hlt (halt the CPU), which only ring 0 may execute. It runs as a normal Linux
process on Compiler Explorer:
section .data
msg: db "about to execute HLT in user mode", 10
len equ $ - msg
section .text
global _start
_start:
mov rax, 1 ; write(1, msg, len)
mov rdi, 1
mov rsi, msg
mov rdx, len
syscall
hlt ; privileged: the CPU traps to the kernel
mov rax, 60 ; exit(0) - never reached
xor rdi, rdi
syscallabout to execute HLT in user mode
Program terminated with signal SIGSEGV (11)
The first line is printed through a legitimate system call; the hlt never halts anything, because the kernel
terminates the process instead.
The kernel enforces policy too
Privileged instructions are blocked by hardware. Privileged operations (setting the clock, changing the host name, raising your priority, reading kernel memory) are blocked by the kernel, which checks your identity and capabilities when you ask for them through a system call. As an ordinary user on Linux:
date -s "2030-01-01" > /dev/null
hostname newname
nice -n -5 true
cat /proc/kcore > /dev/null
echo "still running as UID $(id -u), nothing was changed"date: cannot set date: Operation not permitted
hostname: sethostname: Operation not permitted
nice: cannot set niceness: Permission denied
cat: /proc/kcore: Permission denied
still running as UID 1000, nothing was changed
Each tool asked the kernel nicely, and the kernel answered "Operation not permitted" (EPERM) or "Permission
denied" (EACCES). Only root, or a process holding the right capability such as CAP_SYS_TIME, may do these.
On Windows the equivalent checks look at the access token of the process and its privileges
(SeSystemtimePrivilege, SeShutdownPrivilege, ...), and UAC keeps even administrators running with a filtered
token until they elevate (sample output):
C:\Users\ada>whoami /priv
PRIVILEGES INFORMATION
----------------------
Privilege Name Description State
============================= ==================================== ========
SeShutdownPrivilege Shut down the system Disabled
SeChangeNotifyPrivilege Bypass traverse checking Enabled
SeUndockPrivilege Remove computer from docking station Disabled
SeIncreaseWorkingSetPrivilege Increase a process working set Disabled
SeTimeZonePrivilege Change the time zone DisabledHow the CPU switches modes
There are only a few doors into kernel mode, and the kernel controls all of them:
- System calls: a deliberate request (
syscallon x86-64,svcon ARM). See System Calls. - Exceptions: the current instruction went wrong: a page fault, a division by zero, a privileged instruction.
- Hardware interrupts: a device needs attention (a key was pressed, a packet arrived, the timer fired).
On each entry the CPU saves the user registers, switches to the thread's kernel stack and jumps to an address the
kernel registered at boot. The return path (sysret/iret) drops back to ring 3. The timer interrupt is what lets
the scheduler take the CPU away from a program that never makes a system call.
Windows adds a finer level inside kernel mode, the IRQL (interrupt request level): code running at a high IRQL
(for example DISPATCH_LEVEL) may not touch pageable memory, which is why a driver bug often shows up as the stop code
IRQL_NOT_LESS_OR_EQUAL.
A CPU with a mode bit, simulated
PRIVILEGED = {"hlt", "cli", "load_page_table", "out"}
class CPU:
def __init__(self):
self.mode = "kernel" # the CPU starts in kernel mode at boot
def execute(self, instr):
if instr in PRIVILEGED and self.mode == "user":
print(f" [{self.mode:6}] {instr:16} -> #GP fault, trap to kernel")
self.mode = "kernel"
print(f" [{self.mode:6}] kernel: kill the offending process")
return False
if instr == "syscall":
print(f" [{self.mode:6}] {instr:16} -> enter kernel mode")
self.mode = "kernel"
print(f" [{self.mode:6}] do the work, then sysret")
self.mode = "user"
return True
print(f" [{self.mode:6}] {instr:16} ok")
return True
cpu = CPU()
print("boot:")
for i in ["load_page_table", "cli"]:
cpu.execute(i)
cpu.mode = "user"
print("user program:")
for i in ["add", "syscall", "mov", "hlt", "add"]:
if not cpu.execute(i):
breakboot:
[kernel] load_page_table ok
[kernel] cli ok
user program:
[user ] add ok
[user ] syscall -> enter kernel mode
[kernel] do the work, then sysret
[user ] mov ok
[user ] hlt -> #GP fault, trap to kernel
[kernel] kernel: kill the offending process
The cost of crossing the boundary is real (saving registers, switching stacks, and on CPUs vulnerable to Meltdown, switching page tables too), which is why programs buffer I/O instead of making one system call per byte.
Learn more: System Calls · Kernel Designs · Windows Users, UAC & ACLs
Test yourself
Which x86 rings do Linux and Windows actually use?
- 0 and 1
- 0 and 3
- 1 and 2
- All four
A user-mode program on Linux executes hlt. What happens?
- The CPU halts
- The instruction is silently ignored
- The CPU raises a fault and the kernel kills the process (SIGSEGV)
- The kernel asks for the root password
Which of these does NOT switch the CPU into kernel mode?
- A system call
- A page fault
- A timer interrupt
- Calling a function in the same program