CSE Roadmap

Core tier · about 3 hours · 8 parts

Part 2 of 8 · 2 min read

Two modes

Think of a bank with a public hall and a locked vault. Customers work in the hall. Only staff may enter the vault, and only through a guarded door. If every customer could enter the vault, the bank could not promise safety.

In plain words: A processor has at least two modes, kept in one bit. In user mode it may not run privileged instructions, which control devices, memory protection and interrupts. In kernel mode it may run anything. The kernel always runs in kernel mode and ordinary programs run in user mode, so a program cannot take over the machine.

A processor works the same way. It has at least two modes, kept in a bit inside the processor:

  • User mode is for ordinary programs. Some instructions are forbidden here.
  • Kernel mode is for the operating system's core, the kernel. All instructions are allowed. Other names for it are supervisor mode and privileged mode.

The forbidden instructions are privileged instructions. They include instructions that control devices, change the timer, manage interrupts, and change the mode itself. If a program in user mode tries one, the hardware refuses to run it and passes control to the OS.

The kernel is the part of the OS that always runs in kernel mode. It manages processes, memory, files and devices. Other software, such as a shell or a text editor, runs in user mode and asks the kernel for help.

Some processors have more than two modes. Intel processors define four protection rings. Ring 0 plays the part of kernel mode and ring 3 the part of user mode, while rings 1 and 2 see little use. A processor that supports virtual machines often adds a mode for the program that manages them (Level 11).

The life of an instruction stream looks like this. The machine starts in kernel mode. When the OS hands the processor to a user program, the mode is switched to user mode. When the program makes a system call, or an interrupt or trap happens, control returns to the OS and the mode switches back to kernel mode.

Privileged instruction

A privileged instruction is a processor instruction that the hardware allows only in kernel mode, because it can affect the whole machine: for example, changing memory protection, disabling interrupts or talking directly to a device. Executing one in user mode causes a trap instead of running it.

Example: the instruction that turns off interrupts. If a program in user mode tried it, the processor would trap to the OS instead of running it.

Check yourself: 1. Which mode can run every instruction? 2. What happens if a user program tries a privileged instruction? 3. In the bank analogy, what is the guarded door?