ENع
←User and kernel mode
Lesson 01 · The kernel and system calls

User mode and kernel mode

12 min11 steps5 questionsBeginner
About this lesson

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.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 1 · Interactive
01 / 11

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
Loading figure…
or ← →
Read the lesson step by step
  1. 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
  2. The 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) mode
  3. The 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 line
  4. Line 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 = 5
  5. Line 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 entry
  6. The 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   hi
  7. Back 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 3
  8. Line 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 -> refused
  9. The 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 handler
  10. The 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   fine
  11. Why 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

Quiz Unlocks after the last step.