Operating Systems Module 1: What an operating system does Lesson 1.3 14 min

User mode, kernel mode and system calls

The CPU’s mode bit, why your program cannot touch devices or other programs’ memory, and the exact trip a system call makes into the kernel and back.

In Lesson 1.2 the timer gave the operating system a way to take the CPU back. But what stops a program from simply switching the timer off? Or reading the disk directly, skipping the file permissions? Or writing over another program’s memory?

The hardware stops it. The CPU has two modes, and your program runs in the one that cannot do any of those things.

One bit decides what is allowed

The CPU keeps a mode bit (on x86 processors it is really a small privilege level, but one bit is enough to think about):

  • In kernel mode, every instruction is allowed. The kernel runs in this mode. It can program the timer, talk to devices, and change which memory each program can see.
  • In user mode, the dangerous instructions are switched off, and only the program’s own memory can be touched. Every program you run, including ones started by an administrator, runs in this mode.

The instructions that only work in kernel mode are called privileged instructions. Here is what happens when a program tries one anyway. hlt tells the processor to stop until the next interrupt: harmless for the kernel, a disaster if any program could do it.

A program tries a privileged instruction

  1. A program tries to stop the CPU The program runs hlt, an instruction that halts the processor. If any program could do this, one program could freeze the whole machine.
    CPU mode
    user
    rax
    –
    rdi
    –
    rsi
    –
    rdx
    –
  2. The CPU checks the mode bit hlt is a privileged instruction. The mode bit says user mode, so the CPU refuses to run it and raises an exception instead.
    CPU mode
    user
    rax
    –
    rdi
    –
    rsi
    –
    rdx
    –
  3. Into the kernel, by force The exception switches the CPU to kernel mode and jumps to the kernel's exception handler. The program had no say in this.
    CPU mode
    kernel
    rax
    –
    rdi
    –
    rsi
    –
    rdx
    –
    Kernel code
    exception handler
  4. The kernel decides A user program broke the rules, so the kernel sends it the signal SIGSEGV. Nothing else on the machine is affected.
    CPU mode
    kernel
    rax
    –
    rdi
    –
    rsi
    –
    rdx
    –
    Kernel code
    send SIGSEGV
  5. The program is killed The program has no handler for SIGSEGV, so the kernel ends it. Your shell reports "Segmentation fault". The kernel itself carries on.
    CPU mode
    kernel
    rax
    –
    rdi
    –
    rsi
    –
    rdx
    –
    Kernel code
    process ended

The program was ended, and only the program. The kernel stayed in control the whole time, and every other program kept running. Try this on Linux and your shell prints Segmentation fault, because the kernel stops the program with the signal SIGSEGV (you will meet signals in Module 4).

So how does a program get anything done?

If user mode cannot touch devices, how does printf ever reach the screen? It asks the kernel, using a system call. A system call is a controlled trip into kernel mode: the program can ask, but the kernel decides what code runs and checks everything first.

Here is write(1, "hi\n", 3) on a 64-bit Linux machine: write 3 bytes to file descriptor 1, the terminal. Watch the mode bit in the middle, and the system call table at the bottom.

write(1, "hi\n", 3), step by step

  1. Arguments go into registers The C library's write function puts the system call number, 1 for write, in rax, and the file descriptor in rdi, the address of the bytes in rsi and the count in rdx.
    CPU mode
    user
    rax
    1
    rdi
    1
    rsi
    → "hi\n"
    rdx
    3
  2. The syscall instruction Then it runs one special instruction: syscall. This is the only door from user mode into the kernel.
    CPU mode
    user
    rax
    1
    rdi
    1
    rsi
    → "hi\n"
    rdx
    3
  3. The mode bit flips The CPU switches to kernel mode and jumps to the kernel's system call entry point. The kernel chose that address when it booted, so a program cannot jump into the middle of the kernel.
    CPU mode
    kernel
    rax
    1
    rdi
    1
    rsi
    → "hi\n"
    rdx
    3
  4. The kernel saves your registers The kernel stores the program's registers, so it can put everything back exactly as it was afterwards.
    CPU mode
    kernel
    rax
    1
    rdi
    1
    rsi
    → "hi\n"
    rdx
    3
    Kernel code
    entry_SYSCALL_64
  5. Look up the system call table rax holds 1. The kernel uses it as an index into its system call table, and entry 1 is ksys_write.
    CPU mode
    kernel
    rax
    1
    rdi
    1
    rsi
    → "hi\n"
    rdx
    3
    Kernel code
    ksys_write
  6. Run ksys_write The kernel checks that the bytes really are in the program's memory and that file descriptor 1 is open, then copies the 3 bytes and passes them to the terminal.
    CPU mode
    kernel
    rax
    1
    rdi
    1
    rsi
    → "hi\n"
    rdx
    3
    Kernel code
    ksys_write
    Returned
    3
  7. The answer goes into rax The kernel puts the result, 3, in rax.
    CPU mode
    kernel
    rax
    3
    rdi
    1
    rsi
    → "hi\n"
    rdx
    3
    Kernel code
    ksys_write
    Returned
    3
  8. Back to user mode The kernel puts the saved registers back (except rax) and runs sysret. The CPU switches to user mode and continues right after the syscall instruction.
    CPU mode
    user
    rax
    3
    rdi
    1
    rsi
    → "hi\n"
    rdx
    3
    Returned
    3
  9. The program carries on write returns 3 to the program, which carries on with its next line.
    CPU mode
    user
    rax
    3
    rdi
    1
    rsi
    → "hi\n"
    rdx
    3
    Returned
    3

Those 9 steps are the same for every system call. Only the number and the kernel function change:

  1. The program puts a system call number in a register (rax) and the arguments in others.
  2. It runs the syscall instruction. This is the only door into the kernel, and it always leads to the same entry point, which the kernel chose when it booted.
  3. The CPU flips to kernel mode. The kernel saves the program’s registers, looks up the number in its system call table, and runs that function.
  4. The result goes back in rax, the registers are restored, the CPU flips back to user mode, and the program carries on.

Press Try it and pick other calls. getpid asks for the process’s ID. read puts the program to sleep until you type something. exit goes in and never comes back. And “write with a bad pointer” shows what happens when a program passes an address that is not its own.

The same call, three ways

You do not have to go through printf. This C program prints hi three times: through the C library’s printf, through the library’s thin write wrapper, and by making the system call directly with syscall(SYS_write, ...). SYS_write is the number 1 you saw in rax.

three_ways.c
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>

int main(void) {
    printf("hi\n");                      /* the C library formats, then calls write */
    fflush(stdout);                      /* make printf send its bytes now */
    write(1, "hi\n", 3);                 /* the library's wrapper for the system call */
    syscall(SYS_write, 1, "hi\n", 3);    /* the system call itself, by number */
    printf("SYS_write is %d\n", SYS_write);
    return 0;
}

Output (one run)

hi
hi
hi
SYS_write is 1

All three end up in the same kernel function. fflush is there because printf collects text in a buffer and sends it later, often in one bigger write. That buffering is one reason programs use the library instead of calling the kernel for every character: system calls are not free.

A bad pointer does not crash the kernel

The kernel never trusts a program’s arguments. Here the program asks to write 3 bytes from address 16, which is not memory it owns:

bad_pointer.c
#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/syscall.h>

int main(void) {
    long r = syscall(SYS_write, 1, (char *)16, 3);
    printf("returned %ld, errno %d (%s)\n", r, errno, strerror(errno));
    return 0;
}

Output (one run)

returned -1, errno 14 (Bad address)

The kernel checked the address, refused, and reported the error EFAULT (number 14, “Bad address”). The C library turned that into a return value of -1 and set errno, the variable where C keeps the last error. Nothing crashed: not the kernel, and not even this program.

Why system calls cost more than function calls

A normal function call is a jump and a return. A system call also has to switch modes, save and restore registers, check every argument and copy data between the program’s memory and the kernel’s. On top of that, modern kernels take extra steps on each entry to defend against attacks on the CPU itself. So a system call costs far more than a function call. That is why libraries buffer output, and why reading a file 1 byte at a time is so much slower than reading 4096 bytes at once.

In the real world

On Linux, strace shows every system call a program makes, with its arguments and its result. For a hello-world program in C, the end of the output looks like this (trimmed):

Terminal
$ strace ./hello
execve("./hello", ["./hello"], ...) = 0
...
write(1, "hi\n", 3)                     = 3
exit_group(0)                           = ?
+++ exited with 0 +++

The write line is the same call you stepped through above, and = 3 is the value that came back in rax. Windows has the same split: programs call functions in ntdll.dll, which use the syscall instruction to enter the Windows kernel. The numbers in its table are different, and they change between Windows versions, which is why Windows programs always go through the library. :::

Quick check

Quick check

  1. What does the CPU's mode bit protect?
  2. A program passes a pointer to memory it does not own to write. What happens?
  3. Why does a system call cost more than a normal function call?
  4. How does a program tell the kernel which system call it wants?

Recap

  • The CPU has a mode bit. Kernel mode can do anything; user mode cannot run privileged instructions or touch other programs’ memory.
  • A program that tries a privileged instruction causes an exception, and the kernel ends it.
  • A system call is the controlled way in: a number in rax, arguments in registers, the syscall instruction, a lookup in the system call table, and back.
  • The kernel checks every argument. Errors come back as negative numbers, which C turns into -1 and errno.
  • System calls cost much more than function calls, so libraries buffer.

Next: the kernel decides everything, but someone has to start the kernel. What happens between the power button and your login screen.

Your progress is saved in this browser. Sign in to keep it on every device. Free, no password.

Join the discussion