User mode and kernel mode
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Every program on your computer shares one CPU with the kernel, the core of the operating system. What stops a buggy program from wrecking everything? The CPU itself: it runs in user mode or kernel mode, and programs can only cross into the kernel through one guarded gate. Follow three lines of C as one runs freely, one asks the kernel for help with a system call, and one tries to sneak into kernel memory and is stopped. The Software lesson on what an operating system does and the Hardware lesson on interrupts and I/O are good warm-ups, and How Linux boots shows where the kernel first takes charge.
Two kinds of software
A computer runs two kinds of software: your programs, and the kernel, the core of the operating system that is trusted with all the hardware and memory. A wall keeps programs out of the kernel's side, with one guarded gate.
user side your programs (apps, the shell, ...)
limited: must ask for anything risky
kernel side the kernel: core of the operating system
full control of the CPU, memory and devices
the wall built by the CPU itself, not by software
the gate the only way in, chosen by the kernelاقرأ الدرس خطوة بخطوة
Two kinds of software
A computer runs two kinds of software: your programs, and the kernel, the core of the operating system that is trusted with all the hardware and memory. A wall keeps programs out of the kernel's side, with one guarded gate.
user side your programs (apps, the shell, ...) limited: must ask for anything risky kernel side the kernel: core of the operating system full control of the CPU, memory and devices the wall built by the CPU itself, not by software the gate the only way in, chosen by the kernelThe CPU's mode switch
Inside the CPU is a mode setting, at least one bit. In user mode some instructions and some memory are off limits. In kernel mode everything is allowed. The CPU itself checks the mode as it runs each instruction.
mode what it may do user ordinary instructions on its own memory kernel everything off limits in user mode (Berkeley CS162): change the page table pointer, disable interrupts, talk directly to hardware, write kernel memory x86-64 privilege level in CS: 0 = kernel, 3 = user RISC-V S (supervisor) mode and U (user) modeThe kernel goes first
The machine starts in kernel mode, so the kernel can set up: it tells the CPU where the gate leads (the trap table) and marks its own memory kernel-only. Then it switches to user mode and starts your program.
power on CPU in kernel mode kernel sets the trap table: where each trap enters marks its own pages kernel-only (setting the trap table is itself privileged) return-from-trap CPU switches to user mode your program starts at its first lineLine 1: plain work
Plain work needs no permission. In user mode the CPU adds 2 and 3 at full speed and stores 5 in the program's own memory. The kernel is not involved at all.
the whole program (C99, POSIX): #include <unistd.h> int main(void) { volatile int *kernel = (volatile int *)0xffffffff81000000UL; int n; n = 2 + 3; write(1, "hi\n", 3); n = *kernel; return n; } line 1 n = 2 + 3; mode user memory n = 5Line 2: asking the kernel
write() wants the screen, but devices are kernel-only. So it runs a special trap instruction (syscall on x86-64). In one move the CPU switches to kernel mode and jumps through the gate to the entry point the kernel chose.
line 2 write(1, "hi\n", 3); C library loads the request into registers (x86-64 Linux): rax = 1 call number: write rdi = 1 file descriptor: standard output rsi = "hi\n" where the bytes are rdx = 3 how many bytes syscall mode user -> kernel, jump to the kernel entryThe kernel does the job
Now in kernel mode, the kernel checks the request: is file descriptor 1 (standard output) open, and is the text in the program's own memory? It is, so the kernel's driver sends the 3 bytes, h, i and a newline, to the screen.
mode kernel check fd 1 open? yes buffer in the caller's memory? yes (else EFAULT) do driver sends 3 bytes: h i \n screen hiBack to user mode
The kernel puts the answer, 3 bytes written, where the program will look, then runs return-from-trap (sysret on x86-64). In one move the CPU drops back to user mode and the program carries on after the call.
result rax = 3 (write returns the bytes written) sysret mode kernel -> user back to the instruction after syscall write(1, "hi\n", 3) returns 3Line 3: reaching past the wall
Line 3 tries to read kernel memory directly. Those pages are marked kernel-only and the CPU is in user mode, so it refuses the read before any data moves. Nothing in the kernel is read or changed.
line 3 n = *kernel; kernel = 0xffffffff81000000 (x86-64 Linux: inside the kernel text mapping; user space ends at 00007fffffffefff) mode user check page is kernel-only -> refusedThe CPU traps to the kernel
A refused access raises an exception, a page fault. Like a system call, it enters the kernel through the gate in kernel mode. But this time the program did not ask: the hardware sent it.
ways into the kernel (all through the trap table): system call the program asks (line 2) exception the program did wrong (line 3) interrupt a device needs help page fault mode user -> kernel, jump to the fault handlerThe kernel ends the program
The kernel sees that a user program touched memory it may not use, and sends it the signal SIGSEGV, whose default action ends it. The shell reports Segmentation fault. The kernel and every other program keep running.
signal SIGSEGV default action: terminate (and dump core) program ends; its memory is given back shell Segmentation fault kernel fine other programs fineWhy two modes?
Programs run at full speed on the real CPU, yet every risky action goes through one gate the kernel chose at boot. A buggy or hostile program can only hurt itself, not the kernel or the other programs.
the rule as a Python simulation: KERNEL_ONLY = {"screen", "kernel memory"} mode = "kernel" # the machine starts in kernel mode def touch(thing): # the CPU checks every access if mode == "user" and thing in KERNEL_ONLY: raise PermissionError(thing) def syscall(thing): # the only way in: the gate global mode mode = "kernel" # trap touch(thing) print("kernel used the", thing) mode = "user" # return-from-trap mode = "user" # the kernel starts the program touch("user memory") # line 1: fine syscall("screen") # line 2: ask the kernel try: touch("kernel memory") # line 3: refused except PermissionError as e: print("refused:", e) prints: kernel used the screen refused: kernel memory
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01In user mode, what is a program NOT allowed to do?
Plain work on its own memory runs at full speed in user mode. Talking to hardware, changing the page tables or touching kernel memory are privileged: only kernel mode may do them.
02What does a system call's trap instruction (syscall on x86-64) do?
The mode change and the jump happen together, and the destination comes from the trap table the kernel set up at boot. The program cannot pick where it lands, so it cannot skip the kernel's checks.
03A program runs write(1, "hi\n", 3) and it succeeds. What mode is the CPU in when the program carries on with its next line?
When the kernel finishes, it runs a return-from-trap instruction (sysret on x86-64), which drops back to user mode while returning to the program. write returns 3, the number of bytes written.
04Line 3 reads memory that is marked kernel-only. What happens first?
The CPU checks the mode on the access and refuses it before any data moves. The fault is a trap into the kernel, just like a system call, except the program did not ask for it.
05After the fault, what does the kernel do with the program on Linux?
SIGSEGV means an invalid memory reference; its default action is to terminate the process (and dump core). The kernel and the other programs carry on: that is the point of the two modes.
المسرد
- Kernel
- The core of the operating system. It runs in kernel mode and controls the CPU, memory and devices for every program.
- User mode
- The CPU mode programs run in. Ordinary instructions work at full speed, but privileged instructions, devices and kernel memory are off limits.
- Mode bit
- The setting inside the CPU (at least one bit) that says whether it is in user mode or kernel mode. Kernel mode, also called supervisor or privileged mode, allows everything.
- System call
- A request from a program to the kernel, such as write(). It enters the kernel with a trap instruction.
- Trap
- A controlled jump into the kernel that switches the CPU to kernel mode at the same time. System calls, exceptions and interrupts are all traps. Each lands at an entry in the trap table, the list of kernel entry points set at boot.
- File descriptor
- A small number a program uses to name an open file or device. 0 is standard input, 1 is standard output (usually the screen) and 2 is standard error.
- Signal
- A short notice the kernel sends to a program, such as SIGSEGV. Each signal has a default action, and for SIGSEGV that action ends the program.
- Page fault
- The exception the CPU raises when a memory access is not allowed, for example user mode reading kernel-only memory.
الملاحظات والمصادر
- Real CPUs often have more than two levels: x86-64 has four rings (0 to 3) and RISC-V has machine, supervisor and user modes. Operating systems such as Linux use just two for programs and the kernel, so the lesson shows two.
- The card shows the three lines of main() that matter. The whole program declares kernel as a pointer to address 0xffffffff81000000 and is real C99; compiled and run, it prints hi and is then stopped by the kernel.
- The wall and the gate are a picture. In the hardware, the wall is the mode check on instructions and the kernel-only mark on memory pages, and the gate is the trap table: the entry addresses the kernel gave the CPU at boot.
- The register names and the call number 1 for write are for Linux on x86-64; other systems and CPUs use other numbers and registers, but the same idea. Programs normally call write() from the C library, which runs the trap instruction for them.
- On current Linux for x86-64, page-table isolation (KPTI) means most kernel memory is not even mapped while a program runs in user mode, and the kernel may sit at a randomized address (KASLR). Either way, marked kernel-only or not mapped at all, the read is refused with a page fault and the program gets SIGSEGV.
- The words Segmentation fault come from the shell, not the kernel: the kernel only tells the shell which signal ended the program.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 6: Limited Direct Execution
- Berkeley CS162, Lecture 2: Four Fundamental OS Concepts (dual mode operation)
- MIT 6.1810 (2024), lecture notes: System call entry/exit
- Linux man-pages: syscall(2)
- Linux man-pages: write(2)
- Linux man-pages: signal(7)
- Linux kernel documentation: x86-64 memory map
- Linux kernel documentation: x86-64 kernel entry
- Linux source: x86-64 system call table
اختبار يتاح بعد الخطوة الأخيرة.