Notes
All notes

Memory Management (OS Core #5)

Every process thinks it owns a large, private, contiguous block of memory starting at zero. It does not. The kernel and the MMU translate each access to a physical frame, and most of the time the translation is cached. This post is about that translation, what happens when it fails, and how the kernel decides which page to evict.

Logical and physical addresses

A logical (virtual) address is what the program uses. A physical address is what the RAM chips see. The MMU translates one to the other on every access, using page tables the kernel maintains.

int x = 42;
std::printf("%p\n", (void*)&x);   // a virtual address, not a RAM address

Two processes can print the same virtual address and touch different physical memory. That is the entire basis of isolation: a wild pointer in one process cannot reach another process’s data because the page tables do not map it.

The simplest scheme is base-and-limit: physical = base + virtual, with a limit check. It works for one process at a time, and it fragments badly once processes grow and shrink. Paging fixes both problems.

QQuestionCan two processes share a physical page while having different

virtual addresses for it?

ASolution

Yes. That is shared memory: both page tables map their own virtual page to the same physical frame, and that is why it is the fastest IPC (Ch. 8).

Address translation and paging arithmetic

Paging divides virtual memory into fixed-size pages and physical memory into frames of the same size. A virtual address splits into a page number and an offset:

\[ \text{VA} = (\text{VPN} \times \text{page size}) + \text{offset}, \qquad \text{PA} = (\text{PFN} \times \text{page size}) + \text{offset} \]

With 4 KB pages, the low 12 bits are the offset and never change during translation. For a 32-bit address space, the remaining 20 bits index \(2^{20} = 1{,}048{,}576\) pages.

A single-level page table for that is \(2^{20} \times 4\) bytes = 4 MB per process, and it must be contiguous. That is why real systems use multilevel tables.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum height=0.55cm, font=\scriptsize\ttfamily}]
  \node[c, fill=blue!12, minimum width=2.6cm] (vpn) at (0,0) {VPN (20 bits)};
  \node[c, fill=orange!20, minimum width=1.6cm] (off) at (2.2,0) {offset (12)};
  \node[c, fill=green!18, minimum width=2.2cm] (pfn) at (0,-1.1) {PFN};
  \node[c, fill=orange!20, minimum width=1.6cm] (off2) at (2.2,-1.1) {offset (12)};
  \draw[->, thick] (vpn) -- node[right, font=\tiny] {page table} (pfn);
  \node[font=\scriptsize, anchor=west] at (3.4,0) {virtual address};
  \node[font=\scriptsize, anchor=west] at (3.4,-1.1) {physical address};
\end{tikzpicture}
QQuestionWith 4 KB pages, how many bits of a 48-bit address are the offset?
ASolution

12, because \(2^{12} = 4096\). The remaining 36 bits are the virtual page number.

Contiguous allocation and fragmentation

Before paging, memory was handed out in contiguous chunks. Fixed partitions are simple but waste space inside a partition when a job is smaller than its slot: internal fragmentation. Variable partitions fit the job but leave unusable gaps between allocations: external fragmentation.

Placement policies for variable partitions:

Policy Choose Behaviour
First fit first hole large enough fast, tends to fragment the start
Best fit smallest hole that fits leaves tiny unusable holes
Worst fit largest hole leaves large holes, rarely best in practice

Compaction fixes external fragmentation by moving processes, but only if they can be relocated, and it costs time proportional to memory.

Paging removes external fragmentation entirely: any free frame can hold any page. It introduces internal fragmentation of at most one page per allocation (average half a page, 2 KB with 4 KB pages).

QQuestionWhy does paging eliminate external fragmentation?
ASolution

Pages are fixed-size and can go in any free frame. There are no variable-size holes between allocations, only free frames.

Paging and page tables

A page table maps virtual page numbers to physical frame numbers. Each page table entry (PTE) holds more than the frame number:

Bit Meaning
Present the page is in memory
Frame number where it is
Read/write writable?
User/supervisor accessible from user mode?
Accessed has it been read? (for LRU approximations)
Dirty has it been written? (must be flushed before eviction)
NX executable?

The kernel allocates frames, fills page tables, and updates the bits. Hardware sets accessed and dirty; the kernel clears them to track usage.

QQuestionWhy does the dirty bit matter for page replacement?
ASolution

Only dirty pages need to be written back to disk. A clean page can be dropped immediately, which makes eviction much cheaper.

Multilevel page tables

A 48-bit virtual address with 4 KB pages has a 36-bit VPN. x86-64 splits it into four 9-bit indices, and each level is a 4 KB table with 512 entries:

\[ 9 + 9 + 9 + 9 + 12 = 48 \text{ bits} \]

Translation walks PML4 → PDPT → PD → PT. Each level is allocated only when needed, so a sparse address space costs four pages (16 KB) instead of gigabytes. The cost is up to four memory accesses per translation, which is why the TLB exists.

Five-level paging (57-bit addresses) adds another level and another 9 bits.

QQuestionWhy is a single-level page table wasteful for a process that uses

only a few megabytes?

ASolution

It must cover the entire virtual address space, so the table is sized by the address space, not by what the process uses. Multilevel tables allocate only the branches that are populated.

The TLB

The translation lookaside buffer caches recent translations. It is small (hundreds to a few thousand entries) and associative; a hit costs about 1 ns, a miss adds a page-table walk.

TLBs are tagged by address space (ASID/PCID on x86). Without tagging, every context switch between processes would flush the TLB. Even with tagging, the kernel must invalidate entries when it changes a mapping, and on multicore that means an IPI to other cores (TLB shootdown), which is expensive.

Coverage matters: with 4 KB pages and 1,500 entries, a TLB covers about 6 MB. Huge pages (2 MB, 1 GB) extend coverage dramatically, which is why databases and JVMs request them.

QQuestionWhy can a TLB miss be cheap but a page fault expensive?
ASolution

A TLB miss only means walking page tables in RAM (nanoseconds to a few microseconds). A page fault means the page is not in memory at all, so the kernel must fetch it from disk (microseconds to milliseconds).

Segmentation

Segmentation divides the address space into variable-length logical segments (code, data, stack) with a base and limit. An address is a pair (segment, offset), checked against the limit.

Segmentation matches how programmers think, and it gives per-segment protection. It also suffers external fragmentation, because segments are variable-sized. x86 combined both: a segment selector chose a descriptor, and the resulting linear address went through paging.

Modern 64-bit systems mostly ignore segmentation and use a flat address space with paging, keeping a few segments for TLS and kernel/user separation.

QQuestionWhat does segmentation provide that paging does not?
ASolution

Logical grouping and per-segment protection with variable sizes. Paging provides fixed-size protection and no logical structure, which is why the two were often combined.

Virtual memory and demand paging

Virtual memory lets a process use more address space than physical RAM by keeping some pages on disk and mapping them on demand. Demand paging loads a page only when it is first touched.

The PTE’s present bit is the switch:

This is why a program can start quickly with a large binary: only the pages it actually executes are loaded. It is also why the first run of a program is slower than later runs, when the page cache is warm.

QQuestionA process has a 1 GB heap but RSS shows 100 MB. How?
ASolution

Virtual memory is reserved, but physical frames are allocated only for pages that are touched. The rest are unmapped or backed by zero pages until first write.

Page faults

A page fault is a CPU exception raised when a translation cannot be completed or the access violates protection. The kernel handler decides what it is:

  1. Minor fault: the page is in memory (page cache, shared page, COW page), just not mapped in this process. Map it and return. Cost ~1 µs.
  2. Major fault: the page must be read from disk or swap. Cost ~100 µs on SSD, milliseconds on a spinning disk.
  3. Invalid access: the address is not in any valid mapping, or the permission is wrong. Deliver SIGSEGV (or SIGBUS).

The handler steps for a major fault:

  1. Find the virtual page and the PTE.
  2. Check the access is legal for the mapping.
  3. Find a free frame (or evict one, Ch. 5).
  4. Read the page from backing store.
  5. Update the PTE: present, frame number, permissions.
  6. Return from the exception; the CPU retries the faulting instruction.
int* p = (int*)mmap(nullptr, 4096, PROT_READ | PROT_WRITE,
                    MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
p[0] = 1;      // first touch: minor fault, zero page mapped

Stack growth is another fault path: the kernel grows the stack mapping when an access lands just below the current stack. A wild pointer far from the stack gets SIGSEGV instead.

QQuestionA program writes to a page that is swapped out. What happens?
ASolution

A major page fault: the kernel allocates a frame, reads the page from swap, updates the PTE, and resumes the instruction. The instruction is retried, not skipped.

Page replacement

When a fault needs a frame and none is free, the kernel evicts a page. The policy decides which one.

Reference string 1 2 3 4 1 2 5 1 2 3 4 5, three frames:

Ref Frames after Fault?
1 1 yes
2 1 2 yes
3 1 2 3 yes
4 2 3 4 yes
1 3 4 1 yes
2 4 1 2 yes
5 1 2 5 yes
1 1 2 5 no
2 1 2 5 no
3 2 5 3 yes
4 5 3 4 yes
5 5 3 4 no

FIFO faults: 9. LRU faults 10 times on this string (LRU is not always better on a short trace); Optimal faults 7.

Belady’s anomaly: for FIFO, adding frames can increase faults. The same string with four frames faults 10 times. LRU and Optimal are stack algorithms and do not suffer from it.

QQuestionWhy does LRU not suffer from Belady’s anomaly?
ASolution

It is a stack algorithm: the set of pages in \(n\) frames is always a subset of the set in \(n+1\) frames. More frames cannot cause an eviction that fewer frames would not also make.

Thrashing and working sets

Thrashing is when the system spends most of its time faulting instead of executing. It happens when the sum of the processes’ working sets exceeds physical memory: every process evicts pages another process is about to use.

The symptom is a page-fault rate near 100% and CPU utilisation that collapses. A naive OS reacts by starting even more processes (CPU looks idle), which makes it worse.

The working set of a process at time \(t\) is the set of pages it referenced in the last \(\Delta\) time units:

\[ W(t, \Delta) = \{\text{pages referenced in } (t-\Delta, t]\} \]

If the total working set of all runnable processes exceeds the available frames, the OS suspends a process (swaps it out) until the pressure drops. The working-set page replacement algorithm uses this idea; WSClock is the practical variant with a clock hand.

QQuestionWhy does adding more processes make thrashing worse?
ASolution

Each process needs a minimum number of frames to avoid constant faulting. More processes split the same frames further, so each one faults more, and the CPU spends its time handling faults instead of running code.

Copy-on-write, protection, and shared memory

Copy-on-write (COW) makes fork cheap: parent and child share pages marked read-only. The first write to a shared page faults, the kernel copies it, and both processes continue with private copies.

pid_t pid = fork();          // page tables copied, pages shared read-only
if (pid == 0) {
    buffer[0] = 1;           // write fault: this page is copied
}

Memory protection lives in the PTE: read/write/execute and user/supervisor bits. A violation raises a fault. mprotect changes the bits, PROT_NONE creates a guard page, and NX prevents executing data.

Shared memory is two page tables pointing at the same frames. It is the fastest IPC because there is no copy and no syscall per access; synchronization is the caller’s problem (Ch. 8).

QQuestionAfter fork, does the child get a full copy of the parent’s memory?
ASolution

Not immediately. The pages are shared read-only and copied lazily on the first write. Programs that fork and immediately exec never copy anything.

Deep: page-table walks, TLB misses, and page faults

These three are constantly confused. They are different events with different costs.

Event What happens Cost Who handles it
TLB hit translation found in cache ~1 ns hardware
TLB miss walk page tables in RAM ~10–100 ns hardware (or kernel, on some ISAs)
Page fault, minor page in memory, map it ~1 µs kernel
Page fault, major page on disk, read it ~100 µs–10 ms kernel + I/O

A TLB miss does not imply a page fault. The page table entry may be present and valid; the walk reads it from memory. A page fault means the PTE says the page is absent (or the access is illegal), so the hardware cannot complete the translation at all.

The TLB’s effective access time:

\[ \text{EMAT} = h\,(t_{\text{TLB}} + t_{\text{mem}}) + (1-h)\,(t_{\text{TLB}} + k\,t_{\text{mem}} + t_{\text{mem}}) \]

where \(h\) is the hit rate and \(k\) is the number of page-table levels. With \(h = 0.99\), \(t_{\text{TLB}} = 1\) ns, \(t_{\text{mem}} = 100\) ns, \(k = 4\):

\[ \text{EMAT} \approx 0.99(101) + 0.01(501) \approx 105 \text{ ns} \]

That is a 5% slowdown from misses alone. With a 90% hit rate it becomes about 141 ns, which is why TLB coverage matters for large working sets.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=1.9cm, minimum height=0.6cm, font=\scriptsize, align=center},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (cpu) at (0,0) {CPU\\virtual addr};
  \node[b, fill=green!18] (tlb) at (2.6,0) {TLB};
  \node[b, fill=orange!15] (pt) at (5.2,0) {page tables\\in RAM};
  \node[b, fill=red!12] (pf) at (7.9,0) {page fault\\handler};
  \draw[a] (cpu) -- (tlb);
  \draw[a] (tlb) -- node[above, font=\tiny] {miss} (pt);
  \draw[a] (pt) -- node[above, font=\tiny] {not present} (pf);
  \draw[a, dashed, green!45!black] (tlb) to[bend left=25] node[above, font=\tiny] {hit: 1 ns} (cpu);
\end{tikzpicture}
QQuestionA workload shows many TLB misses but few page faults. Is the memory

size the problem?

ASolution

Not necessarily. The pages may all be resident, but the working set is larger than the TLB can cover. Huge pages or better locality fix it; adding RAM does not.

Bugs and edge cases

QQuestionmalloc(1 GB) returns a pointer, but the program is killed later

when it writes. Why?

ASolution

Linux overcommits: the allocation succeeds, but physical pages are assigned on first touch. If the system cannot supply them, the OOM killer terminates a process.

Next: Memory Layout and Linking (OS Core #6) — segments, BSS, shared libraries, ASLR.