How computers work

The operating system: who shares out the processor, memory and devices

Hundreds of programs live on a computer at the same time, yet there are only 8–24 processor cores, 16–64 GB of RAM, and a single drive. The operating system divides this hardware among the programs so that each one thinks the computer belongs to it alone, and so that none of them can spoil another’s work. Let’s look at how this works: from processor modes to reading a file.

Open in 3D →

The OS kernel and processor modes

An operating system is not the programs on your desktop; it is, first and foremost, the kernel: a program that runs in the processor’s privileged mode. The processor distinguishes at least two modes in hardware. In x86-64 these are “rings” 0 and 3, in ARM the levels EL1 and EL0, in RISC-V (as in this site’s teaching core) the S and U modes. In kernel mode everything is allowed; in user mode some instructions are forbidden: you cannot change page tables, disable interrupts, access device registers, or halt the processor.

If a user-mode program tries to execute a forbidden instruction or access someone else’s memory, the processor will not execute it but will raise an exception — an emergency jump into the kernel. The kernel will sort things out and most likely terminate the program. It is precisely this hardware separation that makes protection possible: without it, any program could wipe the disk or read passwords from another program’s memory.

The Linux kernel is about 40 million lines of source code, but most of that is drivers for thousands of devices; on any particular computer only a small fraction is running. The Linux and Windows kernels are “monolithic”: file systems, the network stack and drivers run inside the kernel, in a single address space, because that is faster. In microkernel systems (QNX, seL4) the kernel contains only the bare minimum, and drivers are separate processes: more reliable, but every request costs an extra transition.

The kernel does not constantly “run in the background” like a separate program. It gets control in only three cases: a program itself asks it for something (a system call), an exception occurs (division by zero, access to a missing page), or an interrupt arrives from a device or a timer. The rest of the time the processor is executing program code.

See also: The processor core: an educational datapath and a modern core

Processes and threads

A process is a running program together with everything the OS has allocated to it: its own address space (code, data, heap, stacks), open files and network connections, permissions, and an identifier, the PID. A thread is a single line of execution inside a process: a program counter, register values, and its own stack. A process may have one thread or hundreds; all threads of a process see the same memory.

An ordinary desktop computer runs 300–500 processes and several thousand threads — a browser alone launches dozens of processes. At any given moment almost all of them are asleep: waiting for a keystroke, a packet from the network, or a timer to fire. Only a handful of threads actually want the processor, so 8 cores are enough.

What does it mean to “put a thread on a core”? A processor core has a single set of architectural registers: in x86-64 these are 16 general-purpose registers, the program counter, flags, plus the AVX vector registers — from hundreds of bytes to 2–3 KB of state in total. To switch from thread A to thread B, the OS kernel saves A’s registers to memory, into the thread’s structure, and loads B’s registers. If B belongs to another process, the address space must also be switched — the address of B’s page table is written to the CR3 register. This is a context switch.

The switch itself takes 1–5 microseconds, but the real cost is higher: the new thread finds the caches and the TLB filled with someone else’s data and runs more slowly at first. That is why the scheduler does not switch threads too often. In Linux new processes are created with fork (a copy of the current process) and exec (replacing its program with another one); in Windows, with a single CreateProcess call.

The scheduler: who runs next on the core

The OS scheduler decides which of the threads ready to run will execute on each core and for how long. Every thread has a state: running, ready (waiting for a free core) or blocked (waiting for the disk, the network, the keyboard, a timer). The scheduler does not consider blocked threads at all — which is why thousands of sleeping threads cost almost nothing.

To keep one thread from grabbing a core forever, each core has a hardware timer. It regularly raises an interrupt, the OS kernel gets control and decides whether it is time to switch threads. The model on this layer shows the simplest round-robin scheduler: ready programs stand in a queue, each gets a time slice, then goes to the back of the queue. Try changing the time slice: with a large slice, a keystroke in the editor waits until the “project build” finishes its slice; with a small one, the response is quick, but the number of switches grows.

Real schedulers are smarter. Since 2023 Linux has used EEVDF: it takes into account how much processor time each thread has already received compared with its “fair share,” and runs first the thread that has been shortchanged and whose deadline is closest. The base slice is about 3 ms. A thread that wakes up after a keystroke has used almost nothing, so it gets a core immediately. Windows uses 32 priority levels and temporarily boosts the priority of a thread that has just received the input it was waiting for.

Modern processors add complications. Hybrid chips have fast (P) and efficient (E) cores — the scheduler decides who gets what, using hints from the processor itself. It pays not to bounce threads from core to core: their data has stayed in the L1 and L2 caches of the previous core. On two-socket servers it is important to keep a thread near its memory.

Don’t confuse the OS scheduler with the instruction scheduler inside a processor core (the “Scheduler” block at the Core level). That one works in nanoseconds and decides which of the hundred or so nearest machine instructions of one thread to execute in this clock cycle. The OS scheduler works in milliseconds and chooses whose thread gets the core at all.

See also: The processor core: an educational datapath and a modern core

Virtual memory: each process has its own world of addresses

Every program sees addresses from zero up to a huge number and thinks all the memory is its own. The address a program works with is virtual. On every memory access, the MMU block in the processor core translates it into a physical one — the number of a real cell in the DDR5 modules. Translation is done not byte by byte but in 4 KB pages: the lower 12 bits of the address (the offset within the page) do not change, while the page number is replaced by a physical frame number.

The table mapping pages to frames is maintained by the OS — a separate one for each process. In x86-64 a virtual address has 48 significant bits, i.e. 256 TB, of which the lower 128 TB are for the program and the upper part for the kernel. A flat table for 2³⁶ pages would take up 512 GB, so it is organized as a four-level tree. The 48 bits are split as 9 + 9 + 9 + 9 + 12: each group of 9 bits is the entry number in the table of the next level (512 entries of 8 bytes = exactly one 4 KB page), and the last 12 bits are the offset.

Example: a program reads the address 0x7FFE_1234_5678. The processor takes the physical address of the top-level table from the CR3 register, uses the first 9 bits to find an entry, which contains the address of the next-level table, and so on four times. The last entry holds the frame number and flags: whether the page is present, whether it can be written, whether it is accessible to user mode, whether code can be executed from it (the NX bit), whether it has been accessed and whether it has been modified. The frame number is joined with the offset 0x678 — and that gives the physical address.

Why all this complexity? Isolation: process A’s table simply does not contain process B’s frames, so A can neither read nor corrupt someone else’s memory — there is no address that leads there. Convenience: a program gets contiguous addresses even when the physical frames are scattered. Savings: the same frames holding a library’s code can be mapped into every process. The teaching model on this layer is simplified — a 16-bit address, 16 pages, 4 physical frames — but the translation steps are the same.

MMU and TLB: how address translation avoids slowing everything down

If every memory access required four extra table reads, the computer would run several times slower. So the MMU has a cache of translations — the TLB (Translation Lookaside Buffer). The first-level data TLB has 64–96 entries and answers within a clock cycle; the second level has 2–3 thousand entries. Three thousand 4 KB pages cover 12 MB of memory; programs access memory in “clusters,” so the TLB hit rate is 99% or higher.

On a TLB miss, a hardware “page walker” reads the four levels by itself. Table entries are also cached in L1–L3, and the upper levels additionally in the walker’s own caches, so a miss usually costs tens of clock cycles rather than four trips to DRAM at 80 ns each.

When switching to another process, the old translations in the TLB become invalid. In the past the TLB had to be flushed completely, and the new process started with a cold cache. Today entries are tagged with an address-space number (PCID in x86, ASID in ARM and RISC-V), so translations of different processes coexist — this is also how the teaching model does it.

For programs that work with tens of gigabytes (databases, neural networks, virtual machines), there are huge pages: 2 MB and 1 GB. A single TLB entry covers 512 or 262,144 times more memory, and the table walk is one or two levels shorter. The more memory computers have, the more important huge pages become, as do five-level tables (57-bit addresses, 128 PB), which server processors already support.

See also: Cache: why the processor doesn’t wait for memory

Page faults, swap and “Segmentation fault”

An entry in the page table can be marked “not present.” Accessing such a page raises an exception — a page fault — and the kernel decides what to do. This is not necessarily an error; it is the main mechanism by which memory works. When a program asks for 1 GB of memory, the OS does not allocate a single frame — it only marks the range as allowed. A frame is allocated when the program first touches the page. This is lazy, on-demand allocation.

Programs are loaded the same way: an executable file is not read in its entirety but mapped into memory, and code pages are brought in from disk on first access. The fork call creates a copy of a process instantly: both copies receive the same frames marked “read-only,” and real copying happens only when someone writes (copy-on-write). Faults handled without the disk cost about a microsecond; those that read from an SSD, tens of microseconds; from a hard disk, milliseconds.

If there are no free frames, the OS picks a page that has not been accessed for a long time (approximately following the LRU algorithm, using the “accessed” bits in the page tables) and evicts it. An unmodified code page can simply be forgotten — it is in the file. Modified data is first written to the page file (swap). Windows and macOS also compress rarely used pages right in memory. When memory is catastrophically short, the system spends all its time shuffling pages — this is called thrashing, and the computer “grinds to a halt.” In that case Linux can forcibly kill the most memory-hungry process (the OOM killer).

But if a program accesses an address that has not been allocated at all, or writes to a code page, that is a real error. The processor raises an exception, the kernel sees that the page should not be accessible, and sends the process the SIGSEGV signal: “Segmentation fault” in Linux or “access violation” in Windows. Most often this is a null pointer dereference: the page at address 0 is deliberately left unmapped so that such errors are caught immediately.

The file system: files on top of blocks

To the OS, a drive is simply an array of 4 KB blocks numbered from zero to hundreds of millions. It has no files or folders. A file system (ext4, NTFS, APFS, Btrfs) is a data structure written into those same blocks: where each file is located, what it is called, who owns it, when it was modified.

In ext4 each file is described by an index node (inode) of 256 bytes: permissions, size, timestamps, and a list of extents — contiguous ranges of blocks (one extent describes up to 128 MB). A folder is a special file that stores “name → inode number” pairs. To open /home/user/notes.txt, the kernel reads the root folder, finds home in it, reads that, finds user, and so on. In NTFS a similar role is played by the Master File Table (MFT) with 1 KB records.

The most dangerous situation for a file system is a power loss in the middle of a change: for example, a data block has already been allocated but this has not yet been recorded in the table. So ext4 and NTFS keep a journal: first they briefly write down what they are going to change, then they change it. After a crash it is enough to replay or roll back the unfinished journal entries instead of checking the whole disk for hours. Databases use the same technique — it is covered in the “Databases” layer.

Between a program and the disk there is almost always the page cache: all free RAM is used to hold recently read blocks and blocks not yet written. That is why a program starts faster the second time, and why Linux always seems to have little “free memory” — it isn’t lost; it works as cache and is handed to programs instantly. Writes also go to the cache first; data reaches the disk seconds later, and is guaranteed to be there only after an fsync call. Beneath the file system, an SSD has one more layer — the controller’s FTL table, which translates block numbers into physical NAND pages.

See also: Storage: SSDs and hard drives

Drivers, interrupts and DMA

A driver is the part of the kernel that speaks the language of a particular device. PCIe devices open register windows (BARs) to the processor: a write to such an address is not a write to memory but a command to the device. The NVMe driver, for example, creates command queues in RAM: the standard allows up to 65,535 queues of 65,536 commands each, usually one pair per processor core so that cores do not get in each other’s way.

Let’s walk through a read() call, as in this layer’s diagram. The driver places a 64-byte command “read block N into memory at address X” into the submission queue and writes the number of the last command into the SSD’s “doorbell” register. The program’s thread goes to sleep, and the processor core moves on to other work. The SSD controller reads the command from memory, reads the NAND page (about 50 µs), and writes the data into RAM by itself over the PCIe bus. This is DMA — direct memory access: the processor takes no part in the copying.

When the data is in place, the SSD writes a 16-byte report into the completion queue and sends an MSI-X interrupt — a special memory write that the interrupt controller turns into a signal to the right core. The processor core finishes its current instruction, saves a minimum of state, and jumps to the handler via the interrupt vector table (x86 has 256 of them). The handler must be very short: mark the request as completed, wake the thread, and defer the rest of the work.

DMA is powerful and dangerous: a device can write anywhere in memory. That is why an IOMMU sits between devices and memory — the same idea as the MMU, but for devices: each device has its own table of permitted addresses. Drivers are the main source of kernel crashes, because a bug in kernel code brings down the whole system. So Windows has moved some drivers (for printers, many USB devices, and part of the graphics work) to user mode, and when a graphics driver fails it can restart it without bringing down the system.

System calls: the door from a program into the kernel

A program cannot open a file or send a packet by itself: these actions require privileged instructions. It asks the kernel through a system call. In Linux on x86-64 it looks like this: the call number goes into the RAX register (0 — read, 1 — write, 2 — open; there are more than 400 in total), the arguments go into RDI, RSI, RDX, R10, R8, R9, and the syscall instruction is executed. With a single instruction the processor switches to kernel mode and jumps to a predefined entry address.

The kernel checks everything it has received: is this descriptor number really open in this process? Does the buffer really belong to the program and is it writable? The kernel never trusts arguments coming from user mode — otherwise a system call could be used to make the kernel read someone else’s memory. The result is returned in RAX, and the sysret instruction returns the processor to user mode.

The round trip itself costs about 100 ns, and with protections against the Meltdown and Spectre vulnerabilities, up to several hundred. That is hundreds of times more expensive than an ordinary function call, so libraries try to batch small operations: printf accumulates text in a buffer and calls write once for many lines. Some calls, such as “what time is it,” the kernel handles without any transition at all, via the vDSO — a small piece of kernel code mapped into the process’s memory.

Programmers usually don’t write syscall themselves: it is invoked by the standard library (libc in Linux, kernel32 and ntdll in Windows) or by the language runtime. But every path — print in Python, fetch in JavaScript, writing to a file in Java — ends at one of these few hundred doors. For servers performing millions of operations there is io_uring: the program places requests in a queue in memory shared with the kernel and collects the results without a system call for each operation.

See also: Languages and runtimes: how program text becomes processor instructions

Communication between processes

Processes are isolated, but they need to communicate: the command “ls | grep txt” feeds the output of one program into the input of another, and a browser passes data between dozens of its processes. All interaction goes through the kernel — it is the only one that sees everyone’s memory.

A pipe is a buffer inside the kernel, 64 KB by default in Linux. One process writes to it with the write system call, the other reads with read. If the buffer is empty, the reader goes to sleep; if it is full, the writer does. In this way a pipe evens out the speeds of the programs by itself. Sockets work similarly, except that they can connect processes on different computers — this is the foundation of the network layer.

Shared memory is the fastest method. The kernel maps the same physical frames into the address spaces of two processes, and from then on they read and write without system calls, at the speed of ordinary memory. The price is synchronization: the processes have to agree on who writes when. For this there are mutexes and semaphores; in Linux they are built on futex — as long as there is no contention, a lock is taken with a single atomic processor instruction without entering the kernel, and only on contention does a thread ask the kernel to put it to sleep.

A signal is a short notification without data: “terminate” (SIGTERM), “interrupt” (SIGINT — that’s Ctrl+C), “your child process has finished.” The kernel marks the signal on the receiving process and, the next time that process gets the processor, calls its handler first. You can watch all of this step by step in the “Pipes and signals” tab of the OS model.

Open in 3D →

All articles

Overviews

Logic: from transistor to arithmetic

Processor

Computer

Servers and data centers

Networks and the internet

Software