Technical Notes

MIT 6.S081 Operating System Engineering: Course Notes

· Operating Systemsxv6RISC-VSystems Programming

Originally written between February and May 2022 while studying MIT 6.S081.

Introduction

The Art of Balance

Beyond the usual requirements of performance and stability, an operating system must strike a balance among many competing demands, including:

  • Security (permission systems, access control) vs. sharing vs. programmer freedom
  • Interfaces that are simple, memorable, and easy to use vs. interfaces that are powerful and comprehensive
  • Support for a wide range of hardware, from large servers to small embedded devices

Well-designed operating systems like Unix carefully choose a small set of simple, orthogonal interfaces that tend to compose well, making it easy to accomplish a wide range of tasks. Of course, these interfaces can seem strange when you first encounter them — see below.

fork, exec, wait

In theory, fork copies the entire memory contents of the calling process and returns twice — once in the parent and once in the child.

exec replaces the current process’s memory with the contents of a target program, so it never returns. However, exec preserves the current file-descriptor table.

wait waits for any child process to exit and returns its pid. If there are no children when wait is called, it immediately returns -1 to indicate an error. Unix convention is that exit(0) signals success; for ordinary functions, -1 typically signals an error.

Why separate fork and exec?

The gap between fork and exec makes I/O redirection trivially easy to implement: modify the file-descriptor table after fork but before exec.

At the same time, since fork is almost always followed immediately by exec, fully copying memory only to replace it moments later seems wasteful. The classic optimization is copy-on-write (COW) fork, which eliminates almost all of the obvious overhead by lazily copying memory pages only when they are actually written.

Miscellaneous

  • QEMU is a simulator and Virtual Machine Monitor (VMM) that emulates hardware.
  • A file descriptor corresponds to an entry in the per-process file-descriptor table, where the key is the descriptor number and the value is an inode. This table is inherited across fork.
  • Unix was originally designed for time-sharing among multiple users who interacted through a shell.
  • In RISC-V, the instruction that enters the kernel is ecall. This special instruction transfers control to the kernel, which then inspects the process’s memory and registers to determine what action to take.
  • open returns the smallest unused file-descriptor number. So if you close stdin (fd 0) and then open a file, it will necessarily reuse fd 0, effectively replacing stdin.

OS Organization

Why an OS Is Necessary

If the only goal of an OS were to abstract hardware and make application programming easier, all of its functionality could be provided as a library — and indeed, some embedded systems work exactly that way. This shows that the necessity of an OS in most contexts must be justified on other grounds: isolation and defense.

If OS functionality were just a library, using the hardware directly would be optional. One of the core purposes of an OS is to forcibly isolate user programs from raw hardware (by abstracting it into file operations, etc.), thereby limiting what user programs can do and protecting the system. In most real-world scenarios — where programs are mutually untrusting and malicious or buggy programs may exist — this protection is mandatory. That is the justification for having an OS at all.

OS isolation is not limited to separating hardware from user programs; it also separates one program from another.

Hardware Support

Forced isolation cannot be achieved by software alone. Most hardware architectures provide two foundational isolation mechanisms:

  • Kernel/user mode. RISC-V supports three privilege levels; there is also a machine mode. In RISC-V, kernel mode is called supervisor mode.
  • Virtual memory (via page tables).

Why these two features specifically require hardware support, and why other features don’t, likely involves complex trade-offs.

Hardware supports distinct modes and switching between them. In RISC-V, the ecall instruction transitions from user mode to kernel mode. ecall takes a numeric argument identifying the desired system call; the mapping is defined in kernel/syscall.h, for example:

  • #define SYS_fork 1
  • #define SYS_exit 2
  • #define SYS_exec 7

If a process in user mode (indicated by a hardware bit) attempts to execute a privileged instruction, the instruction is not executed and control is transferred to the OS via a trap.

Monolithic vs. Microkernel

Some terminology:

  • A program running in user mode can only execute user-mode instructions; it is said to be running in user space.
  • A program running in kernel/supervisor mode can execute privileged instructions; it is said to be running in kernel space, i.e., inside the kernel.
  • The kernel is sometimes called the Trusted Computing Base (TCB).

An OS has multiple subsystems (file system, virtual memory, process management, etc.). Whether all of these should run in supervisor mode — whether they should all be part of the kernel — varies by design.

Monolithic kernel: All basic OS functionality runs in the kernel. Advantages: subsystems can easily cooperate and share data, performance is high, and design is simpler (no need to decide what belongs in the kernel). Disadvantage: a large amount of code runs in supervisor mode, raising the probability of bugs; a bug in supervisor mode can be fatal and may require a reboot.

Microkernel: As little code as possible runs in kernel mode. The kernel typically provides only a few modules: IPC (Inter-Process Communication) or message passing; minimal virtual-memory support (perhaps just page-table management); and basic CPU time-sharing. Traditional system calls become message-passing operations:

  1. Shell needs to interact with the file system (e.g., calls exec) → Shell sends an IPC message to the kernel.
  2. Kernel sees the message is for the file system → forwards it.
  3. File system completes its work → replies via IPC with the result.
  4. Kernel forwards the reply to Shell.

Every cross-module interaction now requires two user↔kernel transitions, whereas a monolithic kernel needs only one. This is the main performance drawback of microkernels.

Additionally, tightly coupled subsystems in a monolithic kernel — e.g., file system and virtual memory — can easily share a page cache. In a microkernel, this sharing is harder to achieve, making performance improvements more difficult.


For historical reasons most desktop OSes (and servers running compute-intensive workloads) use monolithic kernels, including most Unix implementations. Microkernels such as Minix, Cell, QNX, and L4 are widely used in embedded systems.

How QEMU Simulates Hardware

QEMU runs a for loop for each simulated CPU core. For each fetched instruction it manipulates variables in its own program rather than real registers.

QEMU is similar to Bochs but faster; it lacks a built-in GDB, so debugging is done via its remote GDB debugging stub.

Starting QEMU:

qemu-system-riscv64 -machine virt -bios none -kernel kernel/kernel -m 128M -smp 3 -nographic -drive file=fs.img,if=none,format=raw,id=x0 -device virtio-blk-device,drive=x0,bus=virtio-mmio-bus.0

Key flags:

  • -machine virt — generic virtual platform (not a specific machine model), includes RAM, a boot ROM, a disk, etc.
  • -kernel — the program to run inside QEMU (here kernel/kernel)
  • -m — VM memory size
  • -smp — number of CPU cores
  • -drive file= — disk image (fs.img)

Page Tables

Address Spaces

An address space is the range and layout of virtual addresses a process can use, including its own text, data, stack, etc. Giving each process its own address space is one way to achieve isolation.

xv6 has two address-space layouts: the kernel address space and the user address space.

Kernel address space → physical memory mapping:

kernel address space

User address space:

user address space

Key points:

  • Free memory maps directly to a contiguous range of physical addresses; all user-process memory lives in this range.
  • Trampoline is a piece of kernel code whose physical address is also reachable via the direct kernel-text mapping.
  • Because kernel text and data are directly mapped to physical addresses, the kernel continues executing correctly after paging is enabled.
  • In xv6, the user stack does not grow; it is fixed at one page.
  • Each user process has a corresponding kernel stack (plus a guard page). xv6 limits NPROC to 64, so 64 kernel stacks are allocated during main.
  • Kernel text is loaded at 0x80000000 by early assembly startup code.
  • Below 0x80000000 are memory-mapped I/O (MMIO) regions, including:
    • PLIC (Platform-Level Interrupt Controller)
    • CLINT (Core Local Interruptor) — used only in M mode; so the maximum user virtual address in xv6 experiments is PLIC, not CLINT
    • UART0 — handles display interaction
    • VIRTIO — handles disk interaction

Address Translation

xv6 uses the Sv39 paging scheme of RISC-V:

Sv39 paging
  • The low 39 bits of a 64-bit virtual address are used.
  • 39 = 9 + 9 + 9 + 12: three levels of page tables plus a 12-bit offset (2^12 = 4096 bytes per page).
  • Each PTE is 8 bytes (64 bits): the top 10 bits are unused, the bottom 10 are flags, and the middle 44 are the PPN (Physical Page Number).
  • Each page table occupies one page: 4096 / 8 = 512 PTEs per page table.
  • After modifying a page table the OS must tell hardware to flush the TLB: sfence_vma.
  • If the U bit is not set, the RISC-V kernel generally cannot access that page. Specifically, whether it can is controlled by the SUM bit in the sstatus register; by default SUM = 0, so access is denied.

The MMU hardware has two main parts: the TLB and the Translation Table Walk hardware.

When paging is enabled and the CPU issues a virtual address (VA):

  1. L1 cache (indexed by VA): each entry stores VA, permissions, and data. On a hit → return data immediately; on a miss →
  2. MMU TLB lookup: on a hit → get PTE directly; on a miss → walk the page table and update the TLB.
  3. L2 cache (indexed by PA): each entry stores PA and data. On a hit → return; on a miss →
  4. Main-memory access.

In xv6, walk() in kernel/vm.c performs the same walk in software. This is needed because PTEs must be installed before paging is enabled (as well as after), and you cannot let hardware walk a not-yet-populated page table without causing a page fault.

Software walks are also needed for copyin/copyout between kernel and user space: you must manually walk the user’s page table to find the physical address rather than simply loading it into satp.

Open Questions

  • Why does the kernel-stack guard page have no physical memory backing, while the user-stack guard page does?
  • In the labs, when should panic be used vs. returning an error value?

Function Calls

RISC-V Overview

RISC-V is the only open-source instruction set architecture (anyone can design boards for it). It originated from a UC Berkeley research project and is used by many companies. SiFive is one hardware vendor based on RISC-V.

RISC-V distinguishes a Base Integer Instruction Set — which all RISC-V processors must support — from optional Standard Extension Instruction Sets (e.g., single-precision floating point). Processors declare which extensions they support, and compilers use this information.

Calling Convention

RISC-V calling convention
  • ra is typically set to pc + 4 by JAL/JALR at the call site.

Stack Layout

stack frame layout
  • fp holds the top of the current stack frame; the pointer to the previous frame’s top is stored at fp - 16. This is the basis for backtrace. When a function returns, hardware automatically reads Prev. fp and updates fp.

System Calls

Full Flow

  1. User code calls write(int, const void*, int). The three arguments end up in a0, a1, a2.

  2. usys.pl generates usys.S, which contains syscall stubs:

    li a7, SYS_write   # load syscall number into a7
    ecall
    ret
  3. ecall performs four steps:

    1. Enters Supervisor Mode (needed to access control registers; trampoline and TRAPFRAME pages have U = 0).
    2. Disables interrupts.
    3. Saves PC to SEPC.
    4. Loads STVEC into PC; STVEC was previously set to point to uservec in trampoline.S.
  4. uservec does the following:

    1. Swaps a0 and SSCRATCH (SSCRATCH holds the base address of TRAPFRAME). SSCRATCH exists specifically so that, upon trap entry, we have a register-accessible pointer to where we can save all other registers without hardcoding an absolute address.
    2. Saves all registers to TRAPFRAME (except SEPC, which is saved later in C code — the key point is that all general-purpose registers must be saved before entering C, since the compiler may overwrite any of them).
    3. Reads pre-stored values from TRAPFRAME: kernel page-table base address, usertrap() address, etc.
    4. Switches to the kernel page table. Since the trampoline maps at the same address in both user and kernel spaces, execution continues without interruption after the switch.
    5. Jumps to usertrap().
  5. usertrap() in trap.c:

    1. Sets STVEC to kernelvec (in kernelvec.S), since we are now in the kernel and trap handling will differ.
    2. Saves SEPC (written by hardware at trap time) to p->trapframe->epc. This is necessary because if the CPU context-switches to another process that also makes a system call (or an exception occurs), SEPC would be overwritten.
    3. If scause == 8, the trap was caused by a system call:
      1. Check whether the process has been killed.
      2. Increment epc by 4.
      3. Enable interrupts.
      4. Call syscall().
  6. In syscall.c, the core logic is:

    p->trapframe->a0 = syscalls[num]();
  7. The system call return value is now in a0. Control returns to usertrap(), which runs a few more checks and then calls usertrapret().

  8. usertrapret() (symmetric with usertrap()):

    1. Disable interrupts (if STVEC were already pointing back at uservec, an interrupt now would cause problems).
    2. Set STVEC to uservec.
    3. Update the pre-stored values at the top of TRAPFRAME.
    4. Configure SSTATUS for sret: SPP = 0 (return to user mode), SPIE controls interrupt enable.
    5. Write the saved epc to SEPC.
    6. Call fn(TRAPFRAME, MAKE_SATP(p->pagetable)) — i.e., jump to userret with a0 = TRAPFRAME address, a1 = user page-table base.
  9. userret (symmetric with uservec):

    1. Switch back to the user page table.
    2. Restore all registers from TRAPFRAME (including a0, which now holds the syscall return value).
    3. Swap sscratch and a0 — restoring SSCRATCH to the TRAPFRAME address for next time.
    4. Execute sret, which:
      1. Enables interrupts.
      2. Returns to user mode.
      3. Loads SEPC into PC.

The system call is complete. The user program receives the return value in a0; from its perspective, the system call looked like a normal function call.

Notes

Why save registers to TRAPFRAME rather than the stack? Some languages have no stack (making sp invalid); others use non-standard stack formats the kernel cannot parse. As an OS, we cannot assume anything about the layout of user memory.


Real OSes optimize the trap path extensively. For example, memory-mapped file access lets user processes access files directly via virtual addresses without going through syscalls.


myproc() looks up a per-CPU array indexed by the current CPU’s hart ID, which uservec reads from TRAPFRAME and places in the tp register.

Open Questions

  • Why does xv6 save caller-saved registers in the trapframe?
  • Since SEPC can be overwritten by concurrent threads, could it be corrupted even in trampoline code (despite interrupts being off — what about exceptions or other syscalls)?
  • Could we swap sscratch and a0 back at the end of uservec, making the TRAPFRAME argument to fn unnecessary?
  • Why does the kill-check happen where it does?

Page Faults

Dynamism via Page Faults

Virtual-to-physical address mapping provides two main benefits: isolation and abstraction. But page tables also enable dynamism: by writing a page-fault handler, the OS can react to faults at runtime. This enables many classic OS optimizations:

  • Lazy allocation
  • Zero-fill-on-demand
  • Copy-on-write fork
  • Demand paging
  • Memory-mapped files

Hardware Support

When a page fault occurs:

  • SCAUSE is set to:
    • 12: instruction-fetch page fault
    • 13: load page fault
    • 15: store page fault
  • STVAL is set to the faulting virtual address.
  • SEPC is set to the address of the faulting instruction (as with all traps).
  • PTE flags include two RSW bits (reserved for software use by supervisor software).

Lazy Allocation

When a user process calls sbrk to grow the heap, no physical memory or page-table entries are allocated. Only p->sz is updated. Actual allocation happens on the first page fault. Lab note: code paths like unmap must handle pages that have not yet been physically allocated.

Zero-Fill-On-Demand

Compilers represent BSS (uninitialized / zero-initialized globals and statics) in an executable by recording only the size — not the all-zero contents — to keep the file small.

Normally, loading the executable into memory requires allocating pages of zeros for BSS. But since all those pages are identical (all zeros), we can initially map them all to a single read-only physical page of zeros. On the first write, a page fault fires; the handler remaps the faulting page to a fresh writable physical page.

Benefits: less physical memory at startup, faster exec.

Caveats: effectiveness depends on how read-heavy vs. write-heavy BSS actually is; each page fault carries non-trivial overhead (dozens of ld/sw for the trap path).

Copy-On-Write Fork

When fork is followed almost immediately by exec, copying all of the parent’s memory is wasteful. COW fork copies only the page-table structure and marks all parent and child PTEs read-only. On the first write by either side, a fault fires and the actual copy is made.

COW fork requires distinguishing fault reasons. RISC-V’s RSW bits in PTEs help.

Additional details to consider:

  • How does the child find the parent?
  • Does COW handle cascaded forks correctly?
  • If the parent exits before the child, how are shared pages tracked? One approach: per-physical-page reference counts, decrement on release, actually free only when count reaches zero. Where should the count be stored?

Demand Paging

At exec time, allocate no physical pages at all; set V = 0 for all PTEs. On a fault, the OS can even handle OOM by evicting a page — the most common policy is LRU (using the PTE A bit; the OS clears it periodically). Pages with D (dirty) = 0 are preferred for eviction since they need not be written back.

Because this optimization also fires at exec time, its trade-offs are similar to zero-fill-on-demand. Also, since it is a “don’t allocate until accessed” strategy like lazy allocation, the OOM handling applies equally to lazy allocation if implemented with eviction.

In practice, OSes try to keep almost all physical memory in use as buf/cache, so new allocation nearly always requires eviction.

Memory-Mapped Files

Linux provides this via mmap. Typical implementation is lazy: rather than immediately loading the file into memory, the OS records the mapping between a virtual memory region and a file in a VMA (Virtual Memory Area) struct. On a fault within a VMA’s range, the kernel reads that portion of the file into memory.

Synchronization across multiple processes reading/writing the same file is a major concern.

Summary

Most of these optimizations exploit the ability to handle page faults lazily, saving memory and avoiding unnecessary work. The two core patterns are:

  • Don’t-exist-until-accessed: defer allocation until the first access.
  • Read-only sharing: map multiple consumers to the same physical page; copy on write.

These optimizations overlap heavily; in practice you don’t have to implement them as strictly separate mechanisms. The key insight is the lazy principle: what hardware support is strictly necessary, and how do you measure real-world effectiveness?

One more observation: some optimizations eagerly set up page-table entries (e.g., demand paging pre-installs PTEs with V = 0) while others (e.g., lazy allocation) do not. The difference is:

  • Pre-installed PTEs carry per-page flag information (text vs. data vs. stack have different bits in xv6) and let the OS immediately detect invalid addresses.
  • Without pre-installed PTEs, the OS needs alternative bookkeeping to detect invalid accesses.

Since page-table manipulation is already frequent, eagerly allocating the page-table structure (even without the backing physical page) is usually the better trade-off.


Interrupts

This section covers device interrupts (not timer or software interrupts).

Characteristics

Compared to system calls, interrupts have several distinguishing properties:

  • Asynchronous: the interrupt handler has no relationship to the currently running process; system calls operate within the calling process’s context.
  • Concurrency: interrupt generation and CPU execution are concurrent (and different hardware interrupts are concurrent with each other). Interrupt top and bottom halves are also parallel.
  • Programmable devices: most hardware can be configured by writing to it before use.

Hardware

All devices connected to the motherboard send their interrupts to the PLIC (Platform-Level Interrupt Controller). The PLIC routes interrupts to a CPU core; if all cores are busy, the PLIC holds the interrupt. Concretely:

  1. PLIC notifies all CPUs of a pending interrupt.
  2. One CPU claims the interrupt; the PLIC stops sending it to others.
  3. After handling, the CPU notifies the PLIC.
  4. The PLIC discards the interrupt’s state.

The PLIC’s routing logic is programmable — for example, you can configure all cores to be notified but have only one claim.

PLIC

RISC-V provides per-core control registers:

  • SIE (Supervisor Interrupt Enable): E bit for external interrupts, S bit for software interrupts (CPU-to-CPU), T bit for timer interrupts.
  • SSTATUS: a single bit that enables/disables all interrupts.
  • SIP (Supervisor Interrupt Pending): which interrupt type is currently pending.
  • SCAUSE, STVEC: same role as in all traps.

Configuring interrupt handling requires configuring the device, the PLIC, and the CPU — three layers.

Drivers

A driver is the OS code that manages a device. In practice, driver code can be larger than the kernel itself.

Most drivers split into two parts:

  • Bottom half: the interrupt handler. When an interrupt fires and a CPU claims it, the CPU calls the interrupt handler. The handler runs independently of the current process.

  • Top half: the calling interface. For UART (Universal Asynchronous Receiver/Transmitter), this is mainly uartputc(), uartgetc(), etc.

    UART: A UART chip sends data bit-by-bit over a serial line. In QEMU the emulated UART is connected to another emulated UART, which connects to the emulated display (a real terminal).

Typically drivers use an internal buffer shared between the top and bottom halves, decoupling the two.

Drivers program hardware via memory-mapped I/O: device address ranges are assigned by the board manufacturer. For example, the UART device in our QEMU board maps to 0x10000000–0x10001000:

UART MMIO

Within that range, the specific registers are defined by the UART model. QEMU simulates a 16550 UART:

16550 UART registers

THR is the transmit holding register. After each write, the UART transmits the byte and then fires an interrupt indicating it is ready for the next one; writing before the interrupt causes data corruption. (Hardware may buffer internally, but keep this in mind.)

Initialization Flow

  1. entry.S runs in machine mode, jumps to start.c. By writing 0xffff to medeleg and mideleg, it delegates all exceptions and interrupts to supervisor mode. Then it sets SIE so this CPU accepts external, software, and timer interrupts. Finally, it initializes the timer.

    By default in RISC-V all traps are handled in machine mode; they can be re-delegated via MRET. The delegation registers (medeleg, mideleg) allow lower privilege levels to handle specific trap types directly for performance.

  2. start.c uses mret to enter main.c. The first call is consoleinit(), which includes:

    1. uartinit(): configures the UART chip — disables interrupts, sets baud rate, sets 8-bit character length, resets and configures FIFO, re-enables interrupts. After this the UART can generate interrupts, but since PLIC is not yet configured, the CPU cannot see them.

    2. Sets up devsw[CONSOLE]:

      devsw[CONSOLE].read  = consoleread;
      devsw[CONSOLE].write = consolewrite;
  3. main calls plicinit() after a few other inits. The PLIC is MMIO at 0xC000_0000; writing to it configures the PLIC to accept UART0 and VIRTIO interrupts.

  4. plicinithart() runs on every CPU core, declaring interest in UART and VIRTIO interrupts and setting equal priority for all cores. Core 0 runs plicinit(); every core runs plicinithart(). The main function uses an if/else to separate per-CPU-0 and per-core work.

  5. Finally, scheduler() at the end of main calls intr_on(), which sets the SSTATUS interrupt enable bit.

Top-Half Flow (Shell prints $ )

  1. main calls userinit(), which execs the first user process user/init.c. init.c opens the console and duplicates its fd to create fds 0, 1, 2.

  2. init forks and execs Shell. Shell calls fprintf() to write $ to fd 2, ultimately reaching sys_write(), which processes one character at a time, calls filewrite().

  3. filewrite() checks the file type. Since the console was created with mknod, it is FD_DEVICE; for device files, it calls the device’s write function via devsw[f->major].write, which is consolewrite().

  4. consolewrite() copies the argument in with either_copyin(), then calls uartputc().

  5. uart.c maintains a circular buffer (buf, read pointer, write pointer) in a producer-consumer model. uartputc() checks whether the buffer is full (sleeps if so), writes the character to the buffer, then calls uartstart().

  6. uartstart() (called by both top and bottom halves) drives the device: while the buffer is non-empty and the UART’s THR is not full, it writes a character to the THR (via the MMIO address mapped to the physical register).

  7. sys_write returns. The UART hardware sends the character asynchronously and then fires an interrupt when done.

Bottom-Half Flow

  1. An interrupt fires; the PLIC routes it to a CPU. If that CPU has SIE.E set, the CPU enters the trap handler (similar to ecall: saves PC, disables interrupts, etc.).

  2. The trap handler calls devintr(), which identifies this as a hardware interrupt and calls plic_claim(). The claiming CPU reads the interrupt number from a PLIC register (this read atomically claims the interrupt in hardware) and then calls the appropriate bottom-half handler — here, uartintr().

  3. uartintr() is called either because new input arrived or because the previous output completed (room for more). It first loops to drain any input, then calls uartstart() to send the next buffered output character. Top and bottom halves are decoupled.

Input handling follows a similar pattern and is omitted here.

Polling

As interrupt handling becomes more complex, a very fast device can overwhelm the CPU. For example, a 1 Gbps NIC receiving maximum small packets can fire 1.5 million interrupts/second — one every microsecond.

Solutions:

  • More work in hardware to reduce CPU load.
  • Polling: for a slow device, interrupts are efficient; for a fast device, polling is better. Carefully designed drivers (like Linux’s NAPI interface for network cards) switch dynamically between the two.

Locks

Multi-Core Background

Why locks? After roughly year 2000, CPU clock frequencies plateaued, capping single-thread performance. Moore’s Law transistor counts kept increasing, but the gains went into more cores. To exploit this hardware, multi-threaded programming became mandatory. Locks are the most common tool for ensuring correctness in multi-threaded programs.

Race Conditions

A race condition is defined as: a memory location concurrently accessed by two or more threads where at least one access is a write.

When should you lock? A rough answer: whenever a race condition could occur — i.e., when a data structure might be read and written by multiple threads. But this rule is imperfect:

  • Sometimes too coarse: even printf, which shares no data, needs a lock to avoid interleaved output.
  • Sometimes too fine: sometimes a lock should be associated with an operation, not a data structure.

Invariants

From an invariant perspective, a lock exists to preserve invariants. For example, a linked list’s invariant includes “the head pointer points to the first node.” During a head-insert operation, this invariant is momentarily violated. A lock prevents the outside world from observing this inconsistent state.

Deadlock

To prevent deadlocks, related locks must be acquired in a consistent order. If two functions both use locks A and B, one must not acquire A first while the other acquires B first. This simple rule quickly becomes complex, with two unfortunate consequences:

  • Finer-grained locks improve performance (ignoring lock overhead itself) but are harder to audit for potential deadlocks.
  • More importantly, this breaks ideal modularity: we’d prefer a function to hide its internal locks, but ordering requirements force callers to know what locks a function holds.

The mathematical rule is simple, which is why deadlock-detection tools exist.

Development Practice

In practice, the common workflow is: start with coarse-grained locks, verify the multi-threaded code is correct and performance is adequate. If it is, there may be no need to refine. If not, incrementally fine-grain.

Spinlock Implementation

The most common spinlock implementation relies on a hardware-provided atomic test-and-set instruction.

In RISC-V, this is amoswap (atomic memory swap): takes address, register r1, and register r2; atomically swaps the value at address with r1, storing the old value in r2.

Implementation approaches for hardware atomicity:

  • Shared memory controller: locks the address, lets one processor execute a few instructions, then unlocks.
  • Shared bus: a bus arbiter executes multiple memory ops atomically.
  • Cached: the cache coherence protocol ensures only one writer holds the cache line; that processor locks the cache line for the two operations.

xv6 acquire:

push_off();  // disable interrupts; uses a counter since locks can nest
if (holding(lk))
    panic("acquire");  // not re-entrant

// on RISC-V this typically compiles to amoswap
while (__sync_lock_test_and_set(&lk->locked, 1) != 0)
    ;
// memory barrier: prevents reordering across this point
__sync_synchronize();
lk->cpu = mycpu();

Notes:

  • Interrupts must be disabled because concurrency isn’t only between CPUs — it’s also between an interrupt handler and normal code on the same CPU. If a lock is held when an interrupt fires and the interrupt handler tries to acquire the same lock, you get a deadlock.
  • __sync_synchronize() prevents the compiler or CPU from reordering instructions across this barrier (e.g., hoisting critical-section code before acquire). The same barrier appears in release.
  • acquire is per-CPU: the subject that acquires a lock is a CPU, not a process.

Lock-Free Programming

More elegant solutions exist for avoiding race conditions without locks — these are called lock-free programs — but they are considerably harder to write.

The lock-free idea: do your work in a temporary location, then atomically commit to the visible state; retry if the commit fails.

For example, kalloc/kfree use a freelist. A lock-free approach might give each CPU its own list, only sharing with others when a CPU’s own list runs out.


Thread (Process) Scheduling

In xv6, a process is the same as a thread (no multi-threaded processes), so the terms are interchangeable below.

Why Multiple Threads?

  • Hardware is trending toward more cores; you need multiple threads to utilize them.
  • Computers genuinely run multiple tasks simultaneously (listening to music while browsing the web).
  • Multi-threading can simplify program structure (e.g., the sieve of Eratosthenes pipeline).

Two types of parallelism:

  • Running on multiple CPUs simultaneously.
  • Time-sharing one CPU among multiple threads.

Other approaches exist (event-driven programming, state machines), but threads are generally the most convenient, programmer-friendly, and widely applicable method.

Design and Architecture

Switching from one thread and starting another is called scheduling. xv6 creates one scheduler per CPU.

Implementation challenges:

  • Preemptive scheduling: in a system where user programs may be malicious, you cannot rely on them voluntarily yielding. A timer interrupt is used to forcibly reclaim control.
  • Transparent context switching: saving and restoring state so each thread believes it has exclusive use of the CPU.
  • Concurrency safety: multiple CPUs running schedulers simultaneously; locks must be designed carefully.

In xv6 (and most OSes), a timer interrupt fires to give the kernel control (pre-emptive), then the kernel voluntarily transfers control on behalf of the running thread (cooperative within the kernel). The flow: timer interrupt → usertrap() → yield() → sched().

The xv6 context switch goes through an intermediate scheduler thread:

  1. User process kernel thread → (via swtch) → scheduler thread.
  2. Scheduler thread → (via swtch) → next user process’s kernel thread.
context switch

Detailed Flow

  1. Timer interrupt → usertrap() → yield(). yield acquires the current process’s lock, changes state RUNNING → RUNNABLE, calls sched():

    void yield(void) {
        struct proc *p = myproc();
        acquire(&p->lock);
        p->state = RUNNABLE;
        sched();
        release(&p->lock);
    }
  2. sched() runs sanity checks, then calls swtch(&p->context, &mycpu()->context).

  3. swtch saves callee-saved registers, sp, and ra to the old context, restores them from the new context, then executes ret, which jumps to the ra stored in the new context — i.e., the swtch call site inside scheduler():

    // round-robin scheduler
    for (p = proc; p < &proc[NPROC]; p++) {
        acquire(&p->lock);
        // ...
        if (p->state == RUNNABLE) {
            p->state = RUNNING;
            c->proc = p;
            swtch(&c->context, &p->context);  // returns here
            c->proc = 0;
        }
        release(&p->lock);
        // ...
    }

    scheduler() never returns; every CPU enters it at the end of main() and loops forever.

  4. After swtch returns to scheduler, c->proc is cleared to 0.

  5. Locks: yield() acquires p->lock at entry and releases it on exit; scheduler() acquires p->lock before the switch and releases it afterward. These lock operations are cross-matched: scheduler acquires → switches into process → process (via yield) releases on the way back. This ensures atomicity of the state transition.

    An additional constraint: when switching threads, you must not hold any lock other than the process’s own lock. Consider a single-core system where P1 holds uart_tx_lock and then the scheduler switches to P2. If P2 tries to acquire uart_tx_lock, it spins forever — and since acquire disables interrupts, no timer interrupt can fire to switch back to P1. Deadlock. (The same analysis applies on multi-core systems.)

First Invocation

The scenario above covers most cases. But what happens when a process runs for the very first time?

  1. allocproc() sets up a new process:

    p->context.ra = (uint64)forkret;   // swtch into this process → start at forkret
    p->context.sp = p->kstack + PGSIZE; // sp = top of kernel stack
  2. userinit() allocates pages for initcode, sets trapframe->epc = 0, trapframe->sp = PGSIZE, and marks the process RUNNABLE.

  3. When scheduler picks this process and calls swtch, execution lands in forkret.

  4. forkret releases the scheduler’s lock. On the first call, it also initializes the file system. Then it calls usertrapret() — not as a real return from user space, but to enter user space for the very first time. usertrapret restores pc and sp from the trapframe (epc = 0 for the first process, or the parent’s post-fork instruction for forked children) and enters user mode. Faking a return is a common OS technique.

Design Notes

Why isn’t PC saved/restored during context switching? swtch is just a C function call. When swtch executes ret, it returns to the address in ra — no need to explicitly save/restore PC. This is also why only callee-saved registers are in the context: the C compiler handles caller-saved registers by pushing them to the stack before the call.

Why a separate context from trapframe? trapframe saves the registers of the user program; context saves the registers of a kernel thread. The two sets of state are different.

Where is the context stored?

  • Each user process has a corresponding kernel thread; its context lives in the proc struct.
  • Each scheduler thread has its own context but no associated process; its context lives in the cpu struct.

Terminology: “Context switch” usually means switching from one (kernel) thread to the scheduler, though it can also mean a full user-process switch or even a user/kernel mode transition.


Sleep & Wakeup

Coordination

Some scenarios require waiting for a specific event or synchronizing between threads:

  • Reading from a pipe when no data is available.
  • I/O completion (e.g., waiting for a disk read to finish).
  • A process calling wait() for a child to exit.

Busy-waiting wastes the CPU when the event may take a long time. Coordination mechanisms let a thread yield the CPU and resume when the event occurs. Unix-style sleep & wakeup is the implementation we focus on.

Interface Design

Both sleep and wakeup need a channel to identify what to wait for / what to wake:

void sleep(void *chan)   // broken_sleep
void wakeup(void *chan)

The channel is just a number; sleep and wakeup don’t care what it represents:

void sleep(void *chan) {
    p->chan = chan;
    p->state = SLEEPING;
}
void wakeup(void *chan) {
    for (p = proc; p < &proc[NPROC]; p++)
        if (p->state == SLEEPING && p->chan == chan)
            p->state = RUNNABLE;
}

The Lost-Wakeup Problem

Consider this usage (omitting process locks):

int done;
uartwrite(buf):
    for each c in buf
        while not done
            sleep(&tx_chan);
        send(c);
        done = 0;
uartintr():
    done = 1;
    wakeup(&tx_chan);

The race: uartwrite checks done (false), decides to sleep, but has not yet changed state to SLEEPING. An interrupt fires, uartintr sets done = 1 and calls wakeup — but the process isn’t SLEEPING yet, so wakeup misses it. uartwrite then goes to sleep and never wakes up. This is the lost-wakeup problem.

We cannot release the condition lock after sleep or before sleep; the only solution is to pass the lock into sleep and let it release the lock atomically. The lock passed in is the condition lock — the lock protecting the condition checked in the while loop.

Additionally, sleep must call sched(), which requires holding the process lock. Acquiring the process lock must happen before releasing the condition lock; otherwise a wakeup could slip in between.

Correct Implementation

The correct sequence for sleep:

  1. Hold the condition lock.
  2. Check the condition in a while loop; not satisfied → call sleep.
  3. sleep acquires the process lock.
  4. sleep releases the condition lock.
  5. sleep sets state to SLEEPING, records chan, switches threads.
  6. sleep (on wakeup) releases the process lock.
  7. sleep (on wakeup) re-acquires the condition lock.
  8. Return from sleep; release the condition lock.

And for wakeup:

  1. Hold the condition lock.
  2. Modify the condition.
  3. wakeup scans all processes:
    1. Acquire the process lock.
    2. If state is SLEEPING and chan matches → set state to RUNNABLE.
    3. Release the process lock.
  4. Release the condition lock.

The lock acquisition order is always condition lock then process lock, so no deadlock.

void sleep(void *chan, struct spinlock *lk) {
    struct proc *p = myproc();
    if (lk != &p->lock) {
        acquire(&p->lock);
        release(lk);
    }
    p->chan = chan;
    p->state = SLEEPING;
    sched();
    p->chan = 0;
    if (lk != &p->lock) {
        release(&p->lock);
        acquire(lk);
    }
}

Other Coordination Primitives

Sleep & wakeup is general but has a minor wart: callers must expose the condition lock to the sleep interface, even though logically sleep shouldn’t need to know the condition. Semaphores avoid this by using a dedicated counter, but are less general. Java’s equivalent is Object.wait() / Object.notify().

exit

A process that wants to exit still holds resources needed to execute exit itself, so it cannot clean itself up entirely. The solution: let the parent clean up. Key code (simplified):

void exit(int status) {
    // wake init in case parent has already exited
    acquire(&initproc->lock);
    wakeup1(initproc);
    release(&initproc->lock);

    acquire(&p->lock);
    struct proc *original_parent = p->parent;
    release(&p->lock);

    acquire(&original_parent->lock);
    acquire(&p->lock);
    reparent(p);         // re-parent children to init
    wakeup1(original_parent);
    p->xstate = status;
    p->state = ZOMBIE;
    release(&original_parent->lock);
    sched();             // never returns
}

And wait:

int wait(uint64 addr) {
    acquire(&p->lock);
    for (;;) {
        for (np = proc; np < &proc[NPROC]; np++) {
            if (np->parent == p) {
                acquire(&np->lock);
                if (np->state == ZOMBIE) {
                    freeproc(np);
                    release(&np->lock);
                    release(&p->lock);
                    return pid;
                }
                release(&np->lock);
            }
        }
        sleep(p, &p->lock);
    }
}

Notable details in exit:

  1. Why wake init? And why is it unsafe to hold another process’s lock when holding initproc->lock?
  2. Recording original_parent guards against a race where the parent also calls exit and reassigns p->parent to init, which would cause us to hold init’s lock unexpectedly.
  3. Lock ordering: parent’s lock before child’s lock. This is why wait reads np->parent without a lock — the parent field can only be written by the parent while holding the parent’s lock, so a racing write while we hold the parent’s lock is impossible.

If a parent exits without calling wait, its zombie children are re-parented to init, which calls wait in a loop. True permanent zombies are impossible in xv6.

kill

kill sets the target process’s killed flag to 1; if the target is SLEEPING, it sets the state to RUNNABLE. The process checks killed at safe points (beginning of each system call in usertrap, and at the end of usertrap) and calls exit voluntarily. Since these checks happen in the kernel (not user code), a malicious process cannot avoid being killed.


File System

Architecture

The file-system API we implement is a classic hierarchical-path-name API, but it is not the only way to build a storage system. Databases are another (their API is quite different). Modern databases generally sit on top of file systems; early databases often built their own FS directly on raw disks.

The classic layered file-system architecture:

  • Disk (bottom)
  • Buffer cache (block cache): block is the unit of FS disk operations; block cache caches blocks in memory
  • Logging layer: for crash safety
  • Inode cache: per-inode synchronization
  • Inode: implements read/write
  • File names and file descriptors (top)

Hardware and Drivers

Terminology:

  • Sector: the smallest unit the disk drive can read/write (historically 512 bytes).
  • Block: the OS-level unit, defined by the file system. In xv6, one block = 1024 bytes = 2 sectors. (Note: “block” and “sector” are sometimes used interchangeably; pay attention to context.)

Disk drivers use standard protocols such as PCIe or SATA. From the FS’s perspective, the driver API is simple: provide a block number and say read or write.

SSD random access: ~0.1–1 ms. HDD random access: ~10 ms.

Disk Layout

The FS must organize all data structures on disk so the file system can be reconstructed after a reboot. xv6’s layout:

  • Block 0: boot sector (or unused). In xv6, QEMU loads the kernel directly via -kernel, so block 0 is unused.
  • Block 1: super block — contains file-system metadata (e.g., log size).
  • Blocks 2–31: log area.
  • Blocks 32–44: inode area. Each inode is 64 bytes; 16 inodes per block.
  • Block 45: bitmap block — tracks which data blocks are free. Bitmap, inode, and log blocks are collectively “metadata blocks.”
  • Beyond: data blocks — store file and directory contents.
disk layout

On-Disk Inode Structure

Each 64-byte disk inode contains:

  • type: file, directory, or other type; also indicates whether the inode is free.
  • nlink: number of directory entries pointing to this inode.
  • size: bytes of file data.
  • 12 direct block numbers: point to the first 12 data blocks.
  • 1 indirect block number: points to a block containing 256 block numbers.

Maximum file size in xv6: 12 × 1024 + 256 × 1024 = 268 × 1024 bytes.

Directories store directory entries (dirent), each 16 bytes:

  • 2 bytes: inode number of the file or subdirectory.
  • 14 bytes: name.

The root inode has a fixed inode number (1 in xv6).

Path lookup: starting from the root, scan each directory’s data blocks to find the matching dirent, follow its inode, and repeat.

QEMU

make qemu compiles mkfs/mkfs.c into mkfs/mkfs, which generates fs.img containing the initial file system. QEMU uses fs.img via -drive file=fs.img.

create Flow

  1. sys_open() with O_CREATE calls create().
  2. create() calls nameiparent() → returns the parent directory inode dp and the new filename name.
  3. dirlookup() confirms name does not already exist in dp.
  4. ialloc() allocates a new inode (simple linear scan):
    1. Use super-block metadata to find the inode range; iterate.
    2. bread() fetches the block (efficient due to buf cache). bget() searches the cache; on miss, evicts an unreferenced block and returns it. bread checks the valid flag; if not set (evicted block), it calls virtio_disk_rw() to read from disk.
    3. Check type == 0 (free inode), clear the dinode, write type.
    4. log_write(): records this write in the log and calls bpin() to pin the buffer (increment refcnt) so it is not evicted before the transaction commits.
    5. Release the buffer lock.
    6. iget(): analogous to bget, looks up or allocates an in-memory inode with valid = 0 (returns without reading the disk, and without a lock).
  5. Acquire the inode lock; write major, minor, nlink; call iupdate() to persist changes.
  6. If a directory, create . and .. entries.
  7. Write the new dirent into the parent directory.

Sleep Locks

Both buf and inode use sleeplock rather than spinlock:

struct sleeplock {
    uint locked;
    struct spinlock lk;  // protects the sleeplock's state
    char *name;
    int pid;
};

Reason: spinlock busy-waits and disables interrupts. For buf and inode, disk I/O (which relies on interrupts for completion) may be required. Holding a spinlock with interrupts disabled while waiting for an interrupt-driven I/O operation on a single-CPU system would deadlock. sleeplock uses sleep/wakeup and does not disable interrupts. The program can still guarantee no interrupt-driven corruption because all disk interaction goes through bread, the only entry point that touches disk data.

acquiresleep():

void acquiresleep(struct sleeplock *lk) {
    acquire(&lk->lk);
    while (lk->locked) {
        sleep(lk, &lk->lk);
    }
    lk->locked = 1;
    lk->pid = myproc()->pid;
    release(&lk->lk);
}

brelse() calls releasesleep() and implements LRU: moves the buf to the bcache.head.next position (most-recently-used).

Logging: Principles

Crash safety does not require preserving all recent writes; a crash that loses the last few bytes of a write is acceptable. What is not acceptable is leaving the system in an internally inconsistent state — e.g., an inode allocated but not linked into any directory.

The logging mechanism (borrowed from database transaction logs) guarantees:

  • Atomic system calls: file-system calls are all-or-nothing.
  • Fast recovery: no need to scan the entire FS on reboot (unlike scavengers, which check every inode and bitmap block).
  • Efficiency (in implementations like Linux ext3).

Steps:

  1. Log write: when updating the FS, write to the log rather than the FS itself; record which FS block each log block corresponds to.
  2. Commit: when a file-system operation (possibly spanning multiple log writes) completes, write the count of log blocks to the log header. This single write is the atomic commit point.
  3. Install log: copy log blocks to their actual FS positions.
  4. Clean log: set the count in the log header to zero.

On reboot, if the header count > 0, redo the install step. Install is idempotent — repeating it causes no harm.

Two invariants:

  • Write-ahead rule: all writes must be in the log before the commit record.
  • Freeing rule: a transaction may not be removed from the log until all its writes are in the FS.

The commit’s atomicity comes from the fact that writing the header is a single-block (sector) write; disk hardware guarantees single-sector writes are atomic.

Logging: Implementation

xv6 log structure on disk (30 blocks total):

  • Header block: n (number of valid log blocks) + n block numbers.
log layout

In memory:

struct logheader {
    int n;
    int block[LOGSIZE]; // LOGSIZE = 3 * 10; one call can write at most 10 blocks
};

struct log {
    struct spinlock lock;
    int start, size;
    int outstanding; // number of FS syscalls in progress
    int committing;
    int dev;
    struct logheader lh;
};

Transactions are delimited by begin_op() / end_op():

void begin_op(void) {
    acquire(&log.lock);
    while (1) {
        if (log.committing) {
            sleep(&log, &log.lock);
        } else if (log.lh.n + (log.outstanding + 1) * MAXOPBLOCKS > LOGSIZE) {
            sleep(&log, &log.lock);
        } else {
            log.outstanding += 1;
            release(&log.lock);
            break;
        }
    }
}

When code needs to modify a block, the sequence is:

bp = bread(...)
// modify bp->data[]
log_write(bp)
brelse(bp)

log_write(): if the block is already in the log header (log absorption), no-op; otherwise, increment n, record the block number, and bpin the buffer.

end_op() decrements outstanding; if it reaches 0, calls commit():

static void commit() {
    if (log.lh.n > 0) {
        write_log();       // write blocks to log area on disk
        write_head();      // the real commit: write n to the log header
        install_trans(0);  // write blocks to their FS positions
        log.lh.n = 0;
        write_head();      // clear the log
    }
}

Recovery

  1. The first time any process runs it goes through forkret(), which calls fsinit(ROOTDEV) once (guarded by a static int). fsinit must run in a process context because disk reads need sleep.
  2. fsinit reads the super block and calls initlog(), which initializes the in-memory log struct and calls recover_from_log().
  3. recover_from_log() reads the log header from disk, loads n and the block-number array into memory, then (if n > 0) calls install_trans, completing any interrupted transaction.

bpin() / bunpin()

bget() can evict any buffer with refcnt == 0. All writes belong to a transaction; bwrite is always called by the logging layer. Therefore the logging layer must pin buffers (via bpin, which increments refcnt) to prevent eviction until the transaction commits. bunpin is called only in install_trans (for non-recovery use).

Concurrency Details

The log area is limited (30 blocks), leading to subtle constraints:

  • The number of pinned buffers can reach 30, so bcache must have at least 30 entries.
  • Large operations like filewrite are broken into loops of multiple sub-operations.
  • begin_op checks that the space reserved for all in-progress transactions plus this new one will not overflow the log. end_op with outstanding == 0 commits all accumulated transactions together — this is called group commit.

Inode Cache

The inode cache mirrors the buffer cache: a large icache with a single lock, and an array of per-inode entries each with their own lock.

The key difference: iget() returns an inode without a lock (unlike bread, which returns a locked buffer). This is necessary because multiple processes must be able to hold references to the same file simultaneously (e.g., for pathname lookup).

Rules:

  • Reading/writing an inode requires calling ilock() first (may do a disk read if valid == 0) and iunlock() when done.
  • Inodes are write-through: modifications to the disk inode portion must be followed by iupdate(), which calls log_write().

Real-World Considerations

  • xv6 directory lookup is O(n) linear scan; production systems use on-disk balanced trees.
  • Multi-disk file systems: RAID in hardware, or software-defined in modern systems.
  • Dynamic add/remove of disks.
  • Snapshots and incremental backups.
  • Most production OSes abstract many resource types as files, with a per-file function-pointer table dispatching operations to inode-type-specific implementations.

ext3

FS below refers to the non-log disk region.

xv6’s Performance Problem

xv6 logging forces every system call to wait for the entire transaction — all writes to the log, header update, install to FS, and log clear — before returning. Other system calls must wait during commit() because begin_op checks committing. Each system call is synchronous with its disk writes.

Additionally, xv6 writes every block twice (to the log and then to FS). ext3 can partially optimize this.

ext3 Data Structures

On-disk log:

  • Super block: global log info — offset (start of the first uncommitted transaction) and sequence number.
  • Transactions (multiple), each containing:
    • Descriptor block: block count, block numbers, sequence number.
    • Data blocks: the actual updated data.
    • Commit block: written after all data is in the log; contains the sequence number.

The log area (excluding the super block) is a circular buffer.

In memory, an open transaction contains:

  • Its sequence number.
  • Pointers to in-memory (block-cache) blocks it has modified.
  • Handles for each system call participating in it.

At any moment there is at most one open transaction in memory, though multiple committed transactions may be awaiting install to the FS.

How ext3 Improves Performance

By default ext3 creates a new transaction every 5 seconds, batching all system calls within that window. A kernel thread writes committed transactions to the log; another writes from the log to the FS. Benefits:

  • Async system calls: programs return immediately; I/O happens in the background.
  • I/O concurrency: CPU and disk can work simultaneously.
  • Amortization: the fixed overhead of descriptor and commit blocks is shared across many calls; disk head seek time is amortized.
  • Write absorption: multiple writes to the same block within a transaction collapse into one.
  • Disk scheduling: sending 1000 write requests at once lets the driver sort them by track position, far more efficient than 1000 separate writes.
  • Transaction concurrency: one open, several committing, several installing. System calls don’t wait for earlier transactions.

The main complexity introduced: when the current open transaction commits, ext3 copies all modified blocks in memory (the transaction works on its own copies going forward). Copy-on-write avoids unnecessary copies.

fsync

For applications that need synchronous guarantees (databases, word processors), Unix provides fsync(fd), which forces all data related to that file descriptor to disk before returning.

Transaction API

start() marks the beginning of a file-system call and returns a handle. Any block the call reads or writes is registered with get(handle, ...). stop(handle) marks the end. When all handles in a transaction have called stop, the transaction can commit.

Commit Flow

Every 5 seconds:

  1. Block new file-system calls (they wait for the new transaction).
  2. Wait for all in-progress calls in the current transaction to call stop.
  3. End the current transaction; copy modified blocks (COW).
  4. Open a new transaction; wake waiting calls.
  5. Write the descriptor block to disk.
  6. Write data blocks.
  7. Write the commit block.

Why must steps 1–2 complete before opening a new transaction? Consider: T1 contains an in-progress create(x) that hasn’t yet allocated an inode. ext3 opens T2. An unlink(y) in T2 frees an inode. create(x) uses that inode. T1 commits; T2 crashes before committing. On recovery, T1’s changes are replayed but T2’s are not — two files share the same inode. T2’s atomicity is violated because one of its effects (the inode free) survived while its commit did not.

This is the classic cross-transaction dependency problem from database theory: T1 used data modified by T2 but committed before T2 — if T2 rolls back, T1’s state is corrupt.

Recovery Flow

  1. Read the super block; find the log start.
  2. Scan forward: stop when a commit block is not followed by a descriptor block, or a descriptor block is not followed by matching data and a commit block.
  3. Re-apply all valid transactions to the FS; clear them from the log.

Two disambiguation problems:

  • Distinguishing block types: descriptor and commit blocks start with a 32-bit magic number. If a data block happens to start with the magic number, its first 4 bytes are replaced with zeros in the log and a flag is set in the descriptor block; on install the zeros are replaced with the magic number.
  • Identifying the correct commit block: each block carries a transaction sequence number; stale blocks from a previous rotation of the circular log have a lower sequence number.

Further Optimizations

  • Can the commit block be merged into the descriptor block?
  • ext4 writes data and commit blocks together for better disk scheduling, and uses a checksum in the commit block to detect partial writes.
  • ext3 data modes (configurable in Linux):
    • Journaled: file content also goes through the log.
    • Ordered (default): only metadata (inodes, directory blocks) go through the log; file content is written directly to the FS, but always before the metadata commit. This avoids seeing stale file content via a new inode.
    • Writeback: no ordering guarantee; fastest but risks stale content visibility.

User Programs and Virtual Memory

Virtual Memory Primitives

This 1991 paper argues that just as the kernel uses VM and page faults (for COW, etc.), user programs should have the same power: controlling page accessibility and registering custom handlers. The authors survey several applications and identify these OS-level primitives:

  • TRAP: handle page faults in user space (register a handler with the OS).
  • PROT1: reduce the accessibility of one page (e.g., set to read-only or no-access).
  • PROTN: reduce the accessibility of N pages at once (amortizes TLB flush overhead — a significant cost).
  • UNPROT: increase accessibility of one page.
  • DIRTY: return a list of pages dirtied since the last call.
  • MAP2: map multiple virtual addresses to the same physical address.

Unix Interfaces

Modern OSes (including Unix-family) provide these primitives:

  • TRAP: sigaction() + SIGSEGV.
  • PROT1, PROTN, UNPROT: all via mprotect().
  • DIRTY: no direct interface; see Linux pagemap documentation.
  • MAP2: multiple calls to mmap().

mmap() is the most important VM-related system call:

void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);

Arguments:

  1. addr: desired virtual address (NULL = let the OS choose); actual address returned.
  2. length: size of the mapping.
  3. prot: PROT_EXEC, PROT_READ, PROT_WRITE, PROT_NONE.
  4. flags: MAP_PRIVATE (writes don’t propagate to file on disk), MAP_ANONYMOUS (no backing file — allocates anonymous memory; similar to sbrk but more flexible and POSIX-standard).
  5. fd: file descriptor.
  6. offset: start offset within the file.

munmap(): removes a mapping.

mprotect(): changes permissions on a virtual memory range; addr must be page-aligned, and the change applies to all pages covered by [addr, addr+len).

sigaction(): registers a handler for a signal (e.g., SIGSEGV for page faults):

int sigaction(int signum, const struct sigaction *restrict act, struct sigaction *restrict oldact);

Implementation

How does the OS know what file a virtual region maps to? The OS creates a VMA (Virtual Memory Area) object for each contiguous mapped region. Pages within a VMA share the same permissions and are backed by the same object (file or anonymous memory). In Linux (linux/mm.h, vm_area_struct):

unsigned long vm_start;           /* inclusive */
unsigned long vm_end;             /* exclusive */
pgprot_t      vm_page_prot;       /* access permissions */
unsigned long vm_flags;
struct vm_operations_struct *vm_ops;
unsigned long vm_pgoff;           /* offset within file */
struct file  *vm_file;            /* mapped file, if any */
// ...

VMAs provide the metadata needed to handle page faults correctly; a single PTE cannot carry enough information.

How does the OS hand page-fault handling to a user handler? The overall approach (the same as xv6’s sigalarm lab):

  1. Page fault → enter kernel.
  2. Upcall to user space; run the handler.
  3. Handler calls mprotect() to change PTE permissions.
  4. Handler returns to kernel.
  5. Kernel returns to the original user process.

Security: the handler runs in the same user address space, so the worst it can do is crash its own process.

Applications

  • Memoization / cached tables: map a virtual address space for lookup results; on the first access (page fault), mmap a page, compute all results for that page, and cache. On OOM, munmap one page and mmap another.

  • SVM (Shared Virtual Memory): build a large virtual shared memory across machines. Pages not in local memory are initially inaccessible; on fault, fetch the page from the remote machine and invalidate all other copies.

  • Concurrent checkpointing: mark all pages read-only, start a background checkpoint thread copying pages. If the main program writes a page first (fault), the handler copies it immediately. This enables concurrent checkpoint without pausing the program. Incremental checkpointing uses DIRTY to copy only changed pages.

  • Persistent storage, extended addressability, data-compression paging.

  • Concurrent GC (garbage collection):

    • Basic copying GC: split heap into from-space and to-space; pause, forward all reachable objects to to-space, free from-space.
    • Baker’s real-time incremental GC: forward roots, then mark from-space inaccessible. Each object access checks if it’s in from-space; if so, forward it. Allocations forward a few objects each time. Problems: per-access check overhead; no natural place for a background GC thread.
    • VM-based concurrent GC: after forwarding roots, set all occupied from-space pages inaccessible (unscanned). On fault, the handler scans all reachable objects on that page and forwards them, then marks the page accessible. A background GC thread can concurrently scan unscanned pages (the user thread has no permission to access them). Concurrency requires a global lock around scan() calls. See Baker’s implementation.
    • Generational GC: young objects die soon; young objects tend to point to old objects. GC should run frequently on the young generation. The hard part: finding old-to-young pointers. Solution: set old generation to read-only; on write fault, record the dirty page. At GC time, check dirty pages for young-generation pointers. (DIRTY makes this even simpler.)

The pattern is consistent: use page faults for any situation where a background thread must run concurrently with the main thread but must not interfere with data the background thread is working on.


Microkernel

No source code explored for this section; consult “Operating Systems: Design and Implementation” and Minix source.

Monolithic Kernels and Their Problems

xv6 models Unix, a monolithic kernel. The core idea: the OS should provide powerful abstractions, so it includes VM, process scheduling, system calls, signals, interrupts, hardware drivers, file system, etc. Benefits:

  • Abstraction and portability: high-level abstractions hide hardware complexity.
  • Resource management: the OS has global visibility over all hardware and processes.
  • Subsystem cooperation: all subsystems are in one program; sharing data is simple.
  • Security: strict isolation between user programs and hardware.

But problems stem from the fundamental issue: because the OS does everything, if a new need arises the OS must handle it; the user is powerless if it doesn’t.

  • Growing code base → more bugs; formal correctness proofs are infeasible. Embedded systems often don’t need all this functionality.
  • User programs are severely constrained by OS design decisions (e.g., wait only on your own children).
  • Extensibility: all subsystems are in one program; replacing or customizing one is hard.
  • Tightly coupled subsystems may mean low modularity; large codebases are aesthetically unsatisfying.

Linux and others have responded: loadable kernel modules, IPC-like subsystems in macOS, hybrid kernels (Windows).

Microkernels and Their Challenges

A microkernel implements only threads and IPC; everything else runs as user-space servers. It is essentially a client-server architecture, with user processes as clients and FS/VM/driver processes as servers.

This reflects a clean answer to the question from the start of the course: what must an OS do? Isolate mutually untrusting programs. So even a microkernel needs address spaces and threads.

Additional advantages:

  • A crashed server can be restarted without rebooting.
  • Multiple OSes can run as services on top of one microkernel.

Challenges:

  • What is the minimal kernel API?
  • IPC is on the critical path for everything; performance is critical.
  • Separated services have fewer opportunities for cross-component optimization (e.g., shared page cache).
  • Can a monolithic OS (Linux) be ported to run on a microkernel without a full rewrite?

L4 Microkernel

Notable microkernels: QNX (Blackberry QNX in phones and automotive systems), L4 (widely used in embedded systems, RF control in phones). As of 1997, L4 had:

  • 4 abstractions: threads, address spaces, IPC, and tasks.
  • 7 system calls.
  • 13,000 lines of code.

An address space is a set of address mappings; a thread is an execution abstraction associated with an address space, a UID, a page-fault handler, and an exception handler; a task is a set of threads sharing an address space.

The 7 system calls provide:

  • threadcreate: create a task or thread.
  • IPC: send, recv, and many variants.
  • mapping: map a physical page into your own or another task’s address space. Mapping into your own address space is like mmap; mapping into another’s requires permission. This enables fork:
    1. threadcreate for a new task.
    2. IPC message mapping parent’s memory into the new task.
    3. IPC Start message to the new task with PC and SP.
  • Register as another task’s pager (page-fault handler): L4 packages page faults as IPC messages to the pager. A shared pager effectively provides memory management as a service.
  • Hardware access: privileged tasks can map hardware registers into their address space, providing a driver foundation.
  • Interrupt handling: L4 packages interrupts as IPC messages to interested tasks, also for drivers.

L4 scheduling is similar to xv6 (not discussed further).

Slow IPC

A naive IPC implementation (like Unix pipes):

  1. P1 calls send(P2_UID, msg_ptr).
  2. Kernel copies message to a kernel buffer, records it as from P1.
  3. P1 returns.
  4. P2 calls recv; kernel copies the buffered message to P2’s memory and returns P1’s UID.

For a typical request-response cycle (two IPC transactions):

  • 4 system calls = 8 mode switches, each involving a TLB flush.
  • 4 data copies.
  • On single-core: at least 2 context switches = 4 full context switches.

This was the original L4 IPC implementation, and its terrible performance caused many researchers to dismiss microkernels.

Fast IPC

Jochen Liedtke’s 1993 paper “Improving IPC by Kernel Design” introduced several optimizations. The core change: synchronous instead of asynchronous mode.

  1. P2 (a server) is already waiting in recv.
  2. P1 calls send → enters kernel.
  3. Kernel copies P1’s data directly into P2’s memory.
  4. Immediately starts P2 running (P2 returns from its recv), skipping the scheduler.

Additional optimizations:

  • Zero-copy via registers: for small messages (tens of bytes), use registers instead of memory — no copy at all.
  • Page mapping: for large messages, include a mapping in the IPC message — no copy at all.
  • RPC optimization: replace two pairs of send/recv with one call() (P1 sends and waits for reply) and one sendrecv() (P2 replies to one call and waits for the next).

Combined, these optimizations yielded a 20× speedup.

Linux as a Service

The microkernel community has long wanted to compete with monolithic kernels in all domains. Two obstacles:

  • Reimplementing all monolithic functionality as microkernel services is enormous work.
  • Compatibility with the vast body of Linux/Unix software.

A practical solution: run a monolithic OS (Linux) as one large service on top of L4. Most of Linux runs unchanged, except it can no longer directly modify page tables. Each Linux process runs as a separate L4 task. A library translates Linux system calls (fork, exec, read, write) into RPC calls to the Linux task. L4 handles scheduling of all tasks; the Linux task still runs kernel threads internally for handling its own system calls, but it can no longer schedule user processes directly.

Under the AIM Multiuser Benchmark, L4-Linux was only a few percent slower than native Linux.


Virtual Machines

Overview

A Virtual Machine (VM) emulates a complete physical machine and can run an OS with applications. Multiple VMs share one physical machine, managed by a Virtual Machine Monitor (VMM, also called hypervisor), which sits directly on hardware (or as a loadable kernel module on a host OS). In either case we assume the VMM has full privilege.

VMM diagram

Three main uses:

  • Multi-tenancy: cloud services (sharing one physical machine among many users).
  • Kernel development: convenient debugging environment.
  • Advanced features: checkpoint, migrate, monitor.

Why we study VMs:

  • Cloud computing (ECS, etc.) requires understanding how VMs isolate untrusted guest OSes.
  • VMs offer a different abstraction from processes; studying VM memory allocation and scheduling gives new insight into OS design.
  • VMs are influencing OS and hardware design: e.g., Intel VT-X; RISC-V guarantees that any privileged instruction in user mode triggers a trap.

Implementation approaches:

  • Full software emulation: simulate registers as variables. Highly portable; extremely slow (every guest instruction becomes multiple host instructions).
  • Direct execution with trap-and-emulate: run most instructions directly; trap on privileged ones. Fast, but requires careful handling.
  • Hardware support (VT-X / SVM): trap-and-emulate still has overhead from frequent traps; Intel VT-X adds hardware to run privileged instructions at near-native speed.

Trap-and-Emulate

  • All guests run in user mode from the VMM’s perspective. Any privileged instruction traps to the VMM, which reads the cause and emulates the instruction by updating in-memory virtual control registers.
  • To track guest privilege level: when the guest executes sret, set its virtual mode to user; on ecall, set to kernel.
  • Each VM has its own set of virtual state in VMM memory, analogous to how an OS maintains per-CPU/per-process state.
  • Before returning from a trap, write the virtual SEPC to physical SEPC, so sret jumps to the correct guest instruction (or to the guest’s trap handler for ecall).
  • Shadow page tables: the VMM cannot use the guest’s page table (guest physical addresses are not the same as host physical addresses; isolation must be maintained). The VMM maintains a guest-physical → host-physical mapping. For each guest page table, it builds a shadow page table mapping guest-virtual → host-physical. When the guest modifies SATP (CR3 on x86), the VMM installs the shadow page table instead.
  • Guest direct PTE modifications don’t trap immediately. But sfence.vma is a privileged instruction, so the VMM can intercept it and rebuild the shadow page table.
  • Device emulation: three options:
    • Trap on MMIO access: set shadow PTEs for device MMIO pages to invalid; accesses fault to the VMM, which emulates the device (e.g., disk reads become reads from an image file). Fully transparent to the guest; very slow.
    • Paravirtualized devices: guest knows it’s in a VM; writes I/O commands to a shared memory queue; VMM processes them asynchronously. Fewer traps; decoupled I/O.
    • Pass-through: modern NICs support partitioning into multiple sub-NICs; each guest interacts directly with its sub-NIC at near-native speed.

VT-X

VT-X eliminates trap overhead by providing an extra set of control registers per CPU, allowing privileged instructions to execute at hardware speed in the guest:

  • Intel calls host mode root mode and guest mode non-root mode.
  • The VMM creates a VMCS (Virtual Machine Control Structure) in memory, fills in configuration and initial register values, and invokes a special instruction:
    • VMLAUNCH: root → non-root; creates a new VM from a VMCS pointer.
    • VMCALL: non-root → root; guest-to-VMM trap.
    • VMRESUME: root → non-root; return from VMM to guest.
  • Device interrupts (especially timer) default to trapping to the VMM, enabling multi-VM scheduling.
  • EPT (Extended Page Table): the VMM sets up an EPT for each VM. The MMU automatically performs two-level translation: guest-virtual → guest-physical (via guest page table) → host-physical (via EPT).

Dune

Dune is a research project that allows ordinary Linux processes to use privileged instructions directly (without system calls) by leveraging VT-X. A Dune process is like a VM with its own guest supervisor mode and guest user mode. Use cases include sandboxing untrusted apps/plugins in a browser.

Another use case: GC. During concurrent GC, the program may modify already-scanned objects. With Dune, the GC can check PTE dirty bits directly using ordinary load/store instructions — instead of the slow /proc/pid/pagemap approach available in normal Linux.


Networking

Background

  • Every layer’s packet (except the application layer) carries a type/protocol field to indicate which module should handle the payload.
  • MAC address: first 24 bits = manufacturer ID, last 24 bits = per-device ID.
  • In Linux, tcpdump inspects packets of any type.
  • Ethernet is a LAN communication protocol.
  • ARP packets are encapsulated directly in Ethernet frames; the ARP payload also contains source and destination MAC addresses (because ARP does not depend on the underlying protocol header).
  • The OS socket layer maintains a table mapping sockets to file descriptors, and per-socket queues. UDP/TCP use incoming packet fields to find the right socket and enqueue the payload.

Packet Processing Flow

Although the protocol stack appears synchronous, the implementation uses multiple concurrent actor threads. Resource contention between them can cause the livelock problem discussed below.

  1. NIC receives a frame, validates it, identifies it as an IP packet → fires an rx interrupt.
  2. The rx interrupt handler copies the packet into a memory queue.
  3. An IP processing thread reads the queue and decides: a. Deliver to UDP, then to a socket queue; an application reads it later. b. Forward: place the packet in the tx queue for an egress NIC. The NIC fires a tx interrupt when the previous packet is sent; the tx interrupt handler sends the next packet.

Actors present: rx interrupt handler, tx interrupt handler, IP processing thread, application threads.

DMA

Copying packets from NIC to memory in the rx interrupt handler is CPU-intensive. Modern NICs (e.g., Intel E1000) use DMA via ring buffers:

  1. The NIC driver allocates a packet buffer in memory and an array of packet pointers (the ring — a circular queue).
  2. The driver tells the NIC the ring’s address.
  3. When a packet arrives, the NIC uses DMA to copy it into the buffer at the ring head and advances the head.
  4. The IP processing thread reads from the ring.

Details (buffer full handling, how the thread knows a buffer is ready) are straightforward to implement. Cache coherence between DMA and CPU caches is a subtlety.

Modern NICs also support:

  • Multi-queue: multiple rx/tx rings; packets are distributed by rule (useful for VMs).
  • Hardware checksumming and other protocol offloads.

Receiving Livelock

router throughput graph

The graph shows router throughput (y) vs. input rate (x):

  • Linear rise: CPU handles every packet immediately; throughput equals input rate.
  • Plateau around 5000 pps: CPU bottleneck (10 Mbps network supports ~10–15 kpps; software processes ~5000 pps max).
  • Performance drops beyond the peak: this is receiving livelock.

Receiving livelock: each arriving packet triggers an interrupt; each interrupt requires CPU time to copy the packet to memory. Under high load, interrupts arrive so fast that the CPU never gets to run the IP processing thread. Throughput collapses.

Livelock is a general phenomenon. It occurs whenever two concurrent related threads (often a producer and a consumer) have unequal priority, causing one to starve the other and reducing overall throughput. It is called livelock (not deadlock) because the system can potentially recover on its own.

Why doesn’t UART or disk I/O suffer from livelock? Because their interrupt handler and the processing of that interrupt are synchronous — each interrupt is fully handled before the next. The network uses a separate processing thread, enabling the producer-consumer decoupling that creates livelock risk (though the decoupling has benefits for bursty traffic).

Solution

Disable the NIC’s interrupts when the first interrupt fires (rather than copying the packet in the handler), and wake the IP processing thread. The IP processing thread runs in a loop, pulling up to a quota (e.g., 5 packets) per iteration and processing them. When the NIC is empty, re-enable interrupts and sleep.

Under high load: NIC and CPU run fully concurrently (NIC receives, CPU pulls from the ring — effectively polling). Under low load: the interrupt-driven wake-up pattern dominates. The system automatically switches modes.

The quota is critical: without it, the processing thread could spin copying packets indefinitely while never processing them, worsening livelock.

Linux’s NAPI uses this approach.


Meltdown

Overview

Meltdown is a micro-architectural attack described in a 2018 paper that exploits CPU implementation details to break OS isolation and read kernel memory from user space. It relies on:

  1. (At the time) Most OSes map the kernel page table into every user process’s address space for fast system calls.
  2. Speculative execution.
  3. Cache timing.

Meltdown has been patched in most OSes and CPUs, but studying it shows how difficult it is to fully verify the correctness of increasingly complex CPUs, and that similar vulnerabilities may remain undiscovered.

Speculative Execution

Speculative execution is a micro-architectural feature (not documented in the architecture specification):

r0 = <something>           // 1
r1 = valid                 // 2 — load from memory (hundreds of cycles)
if (r1 == 1) {             // 3
    r2 = *r0               // 4
    r3 = r2 + 1            // 5
} else {
    r3 = 0
}
  1. The load at line 2 takes many cycles; the CPU continues executing rather than waiting — this is out-of-order / speculative execution.
  2. At line 3, valid is not yet available → branch prediction: the CPU guesses (e.g., predicts the if branch) and executes lines 4–5 speculatively.
  3. If the prediction was wrong, the CPU rolls back the speculative results via register renaming and other mechanisms.

Key detail: if r0 is a virtual address with a valid PTE but insufficient permissions, the CPU does not raise the page fault immediately during speculative execution. It waits until the instruction is retired (its outcome is final). “Retired” means:

  • An instruction is retired when it is confirmed to execute and its effects are made architecturally visible, or when it is confirmed not to execute (rolled back).
  • Instructions retire in order, so a later instruction cannot retire before an earlier one.

Therefore, at line 4, the CPU performs the load (even to a privileged address) and places the value in a temporary (renamed) register — it doesn’t raise the page fault yet because the branch at line 3 hasn’t retired. Furthermore, Intel CPUs (at the time) did not check PTE permissions before loading during speculative execution; AMD did check, and thus were not vulnerable to Meltdown.

Flush and Reload

Micro-architecture features are supposed to be transparent, but are not perfectly so: we can detect whether data is in cache by measuring access time. The flush-and-reload technique:

  1. Flush address x from all caches (clflush on x86, or by reading enough other data to evict it).
  2. Call f().
  3. Record time (rdtsc — reads the CPU cycle counter).
  4. Load from address x.
  5. Record time again.
  6. If the elapsed time is small (e.g., < 50 cycles), x was in cache → f() must have accessed x.

The Meltdown Attack

// flush
clflush buf[0]
clflush buf[4096]
// expensive instruction to trigger speculative execution and delay retirement
<divide, etc.>
// Meltdown core
r1 = <target kernel virtual address>
r2 = *r1         // load: possible violation, but not yet retired → no page fault yet
r2 = r2 & 1      // extract lowest bit of the secret byte
r2 = r2 * 4096   // multiply by page size (> one cache line) to separate the two options
r3 = buf[r2]     // load buf[0] or buf[4096] into cache depending on the secret bit
// eventually: retired — page fault from "r2 = *r1" is raised
<handle page fault>  // register a SIGSEGV handler; continue execution
// reload
a = rdtsc
r0 = buf[0]
b = rdtsc
r1 = buf[4096]
c = rdtsc
// if b-a < c-b, buf[0] was cached → the secret bit is 0; otherwise it's 1

Due to the complexity of modern CPUs and OSes, the attack succeeds with a relatively low probability. In some scenarios the throughput is only about 10 bytes/second.

Fixes

Software fix: stop mapping the kernel page table into user processes. This is called KAISER (in Linux: KPTI, Kernel Page Table Isolation). System calls now require a page-table switch, but Intel’s PCID (Process Context Identifiers, similar to RISC-V ASID) avoids flushing the TLB on the switch, keeping the performance penalty to about 5%.

Hardware fix: Intel modified the CPU to check PTE permissions before performing the speculative load.

With a hardware fix in place, the software fix is unnecessary. Linux can query which hardware fixes are present and skip KPTI accordingly.


RCU (Read-Copy-Update)

Modern computer performance depends on multi-core parallelism. But many operations share kernel data structures, so they are not fully concurrent. We explore this with a singly linked list example.

Read-Write Locks

A simple improvement over spinlocks: read-write locks. API: r_lock/r_unlock, w_lock/w_unlock. The internal counter n:

  • n == 0: unlocked.
  • n == -1: one writer holds the write lock.
  • n > 0: n readers hold the read lock.

Acquiring the read lock:

r_lock(l):
    while 1:
        x = l->n
        if x < 0:
            continue
        if CAS(&l->n, x, x + 1):
            return

Acquiring the write lock:

w_lock(l):
    while 1:
        if CAS(&l->n, 0, -1):
            return

(CAS = Compare-And-Swap, similar to test-and-set.)

Problem 1: writer starvation — a continuous stream of readers can block writers indefinitely (addressable with additional mechanisms).

Problem 2: cache contention — multiple CPUs trying to increment n simultaneously all load n into their caches. Only one succeeds at CAS; the winner must then invalidate n in every other CPU’s cache, forcing them to re-read from memory before retrying. With m CPUs, the cost of all acquiring the read lock is O(m²).

The root cause: “parallel reads” still require a write to shared memory. We want reads to truly not write any shared state.

RCU

Assume one writer (protected by a spinlock) and multiple readers. Without any synchronization, problems include:

  1. In-place update to a struct field: readers see a half-old/half-new value.
  2. Insert a new node: if the head pointer is updated before the new node’s next is set, readers crash.
  3. Delete a node: a reader currently traversing it may access freed memory.

RCU’s core techniques:

  • Never update in place. To update node E2 in Head → E1 → E2 → E3: copy E2 to E2’, update E2’, set E2’→next = E3, then commit with one atomic write: E1→next = E2’. Readers see either E2 or E2’ — never a partial state. This limits RCU to data structures that support an atomic commit-write (e.g., singly linked lists; doubly linked lists don’t work directly).

  • Memory barriers ensure the data writes precede the commit write:

    e = alloc()
    e->val = xxx
    e->next = E3
    // barrier
    E1->next = e  // commit write
  • Deferred reclamation. After commit, old E2 may still be in use by readers. RCU imposes two constraints:

    • Readers must not hold a pointer to RCU-protected data across a thread switch (cannot hold a reference while yielding the CPU).
    • Writers wait until every CPU has gone through at least one thread switch before freeing E2 — at that point, no reader can still hold a reference. Simplest implementation: briefly run the writer thread on each CPU; each execution constitutes a thread switch.

Linux RCU API

For readers:

  • rcu_read_lock(): set a per-CPU flag disabling voluntary scheduling (not interrupts). Per-CPU state avoids shared writes.
  • rcu_read_unlock(): re-enable scheduling.
  • rcu_dereference(p): marks the pointer dereference as RCU-protected; on most architectures, compiles to nothing.

For writers:

  • synchronize_rcu(): wait until every CPU has had at least one thread switch (blocking).
  • call_rcu(fn, x): register a callback fn(x); returns immediately. RCU internally tracks per-CPU thread switches and calls fn(x) once the grace period has elapsed.
  • rcu_assign_pointer(pa, p): inserts a memory barrier to ensure the commit write comes last.

Example read:

rcu_read_lock()
e = head
while (e) {
    e = rcu_dereference(e)
    look at e->x ...
    e = e->next
}
rcu_read_unlock()

Example insert:

acquire(lock)
old = head
e = alloc()
e->x = ...
e->next = head->next
rcu_assign_pointer(&head, e)
release(lock)
synchronize_rcu()
free(old)

Summary

RCU achieves high-concurrency reads by not requiring any shared write during reads, and enables writer-reader concurrency by deferring reclamation until a grace period — after all current readers have passed a safe point.

RCU is a major success in Linux and a significant contributor to its scalability. But it is not a silver bullet:

  • Requires data-structure support for atomic commit writes.
  • Readers cannot yield/sleep while holding an RCU reference.
  • Makes writes slower.
  • Does not guarantee all readers see the new value immediately after a write.
  • Requires frequent thread switches and the ability to observe them.

Other synchronization primitives exist (e.g., sequence locks allow in-place updates without reader locks, but are more complex and more restrictive). Some mechanisms perform better under high load, worse under low load. In distributed systems, the complexity grows further. Synchronization is a vast and ongoing field of research.