osdev-notes/Rings & Privilege Levels.md
2025-09-25 22:24:58 -04:00

1.7 KiB

Processors have privilege levels that allow them to enforce access to resources. They also have privilege contexts (in the form of paging or segmentation) which detail specifically which resources a process may access, and how it may access them.

Process vs. Kernel

The operating system kernel runs at Ring 0 in x86, meaning it has the most privilege of any software on the system. It can bypass the MMU and write to memory directly, it can execute privileged instructions, and it can modify virtual memory mappings. Everything else runs in rings 1 through 3, though 1 and 2 are seldom used. Processes running in Ring 3 can only access memory via the MMU and virtual memory mappings assigned to that process.

Context Switching

Processes all have unique elements, such as address spaces, stacks, registers, and other things that must be stored and restored. This process is performed by the kernel at a software or hardware defined interval. One thing that makes processes distinct is the memory regions, or "Physical & Virtual Memory#Pages", that are mapped into their address space. These pages are defined in the page tables- cascading sets of tables, where the address of the root table is stored in the CR3 register. Each process might have its own page table root, which is referenced in CR3 upon a context switch.

Interrupts & System Calls

Both interrupts and system calls trigger the CPU to pause execution of the current process or task, and resume execution of the kernel. Interrupts are triggered by hardware, such as peripherals or timers, while system calls are triggered by processes. When the CPU attempts to execute a system call instruction while in unprivileged mode, it causes a return to kernel mode.