---
title: "Virtual Memory"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 11
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 11 — Virtual Memory

Every process on a laptop believes it owns the whole memory, from address 0 upwards, and two processes can both store at address `0x10000000` without disturbing each other. Neither is true of the hardware: there is one physical memory, shared by all of them and by the kernel. This chapter builds the translation that makes the belief hold, the [page tables](#def-b3-virtual-memory-paging), walks it in C exactly as a RISC-V processor walks it, measures the cache that makes it fast, and then uses it for more than isolation: running programs larger than the memory, sharing [pages](#def-b3-virtual-memory-paging) between processes until one of them writes, and reading files with ordinary loads and stores. Along the way it meets one of the strangest facts of systems, a policy that faults more when given more memory, and proves which policies cannot.

**You already know.**

In the Year 2 volume a cache keeps copies of recently used blocks of memory close to the processor, and is fast because programs have locality: they reuse what they used recently, and use what lies next to it. When a cache is full, a replacement policy chooses the block to evict; the least recently used (LRU) policy evicts the block unused for longest. A process is created by `fork`, which makes a copy of the calling process.

## 11.1 Address spaces

**Definition 11.1 (Virtual memory, address space, virtual and physical addresses).**

*Virtual memory* gives each process its own *address space*, the set of addresses it can use, and translates each address it issues, a *virtual address*, into a *physical address*, a location in the memory chips, by a mapping the kernel controls and the processor applies on every access.

The translation does three jobs at once. It isolates: a process can only reach the physical memory its mapping includes, so it cannot read or damage another’s. It relocates: every program can be linked to run at the same addresses, wherever its memory really is. And it lets the kernel lie usefully: an address may be mapped to nothing yet, and get memory only when it is first used, or be mapped to the same physical memory as an address of another process.

**Definition 11.2 (Page, page frame, page table, page-table entry, multi-level page table).**

*Paging* divides the [virtual address](#def-b3-virtual-memory-space) space into *pages*, blocks of a fixed size, and the physical memory into *page frames* of the same size. A *page table* maps each virtual page number to a frame number; its entries, *page-table entries*, also carry permission bits (readable, writable, executable, accessible from user mode) and a valid bit. A *multi-level page table* is a tree of small tables: the high bits of the page number index the root, whose entry points to a table indexed by the next bits, and so on.

The offset within a [page](#def-b3-virtual-memory-paging) is not translated: a [virtual address](#def-b3-virtual-memory-space) is a [page](#def-b3-virtual-memory-paging) number and an offset, and its [physical address](#def-b3-virtual-memory-space) is the frame number and the same offset. An older scheme, *segmentation*, translated variable-sized segments (code, data, stack) by adding a base and checking a limit; it needs no tables, but the segments must each find a contiguous hole in physical memory, with the [external fragmentation](https://one-course.com/books/computer-science/5/en/chapter/9-memory-management-and-garbage-collection#def-b3-garbage-collection-fragmentation) of chapter [9](https://one-course.com/books/computer-science/5/en/chapter/9-memory-management-and-garbage-collection#ch-b3-garbage-collection). [Pages](#def-b3-virtual-memory-paging) of one size never fragment physical memory that way: any free frame fits any [page](#def-b3-virtual-memory-paging).

![Two address spaces over one physical memory. Each page of a process maps to any free frame; the two copies of the same program share the frame of its code, which neither can write; pages that are not mapped use no memory at all.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-virtual-memory/fig-e7d71ed311a2.svg)

*Two [address spaces](#def-b3-virtual-memory-space) over one physical memory. Each [page](#def-b3-virtual-memory-paging) of a process maps to any free frame; the two copies of the same program share the frame of its code, which neither can write; [pages](#def-b3-virtual-memory-paging) that are not mapped use no memory at all.*

## 11.2 Paging and multi-level page tables

RISC-V’s Sv32 mode, for 32-bit processors, uses [pages](#def-b3-virtual-memory-paging) of 4 KiB. A [virtual address](#def-b3-virtual-memory-space) is a 20-bit virtual [page](#def-b3-virtual-memory-paging) number, split into two 10-bit indices, and a 12-bit offset. The 20-bit [page](#def-b3-virtual-memory-paging) number is translated into a 22-bit physical [page](#def-b3-virtual-memory-paging) number, so a 32-bit processor can address more than 4 GiB of physical memory. Each [page table](#def-b3-virtual-memory-paging) holds $2^{10}$ entries of four bytes, exactly one [page](#def-b3-virtual-memory-paging), and the physical [page](#def-b3-virtual-memory-paging) number of the root table is held in the register `satp`.

![An Sv32 translation. satp locates the root table; VPN(1) selects one of its 1,024 entries, which points to a level-0 table; VPN(0) selects the entry there, a leaf, which holds the frame and the permissions; the offset selects the byte in the frame. Two memory reads before every access the program makes.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-virtual-memory/fig-60fd7b78a444.svg)

*An Sv32 translation. `satp` locates the root table; VPN[1] selects one of its 1,024 entries, which points to a level-0 table; VPN[0] selects the entry there, a leaf, which holds the frame and the permissions; the offset selects the byte in the frame. Two memory reads before every access the program makes.*

An entry is valid when its bit V is set. If its bits R, W and X are all 0, it points to the next level; otherwise it is a leaf, and they say whether the [page](#def-b3-virtual-memory-paging) may be read, written and executed. A [page](#def-b3-virtual-memory-paging) cannot be writable without being readable. The entry’s physical [page](#def-b3-virtual-memory-paging) number fills its top 22 bits; below it come two bits left to software, then D, A, G, U, X, W, R and V. U allows access from user mode, and G marks a mapping present in every [address space](#def-b3-virtual-memory-space). A, the *accessed* bit, records that the [page](#def-b3-virtual-memory-paging) has been used since A was last cleared, and D, the *dirty* bit, that it has been written. A leaf may also appear at the root, mapping a whole 4 MiB *megapage* at once.

Listings [11.1](#lst-b3-virtual-memory-map) and [11.2](#lst-b3-virtual-memory-walk) implement the tables over a byte array of 1 MiB that plays the physical memory: `map` installs one [page](#def-b3-virtual-memory-paging), creating its level-0 table when the first [page](#def-b3-virtual-memory-paging) of a 4 MiB region is mapped; `translate` walks the tables as the specification describes, printing each step.

```c
static uint32_t *pte_at(uint32_t addr) { return (uint32_t *)(mem + addr); }

#ifndef VPN
#define VPN(va, i) ((i) == 1 ? (va) >> 22 : ((va) >> 12) & 0x3ff)
#endif

void map(uint32_t root, uint32_t va, uint32_t frame, uint32_t flags)
{
    uint32_t *pte = pte_at(root * PAGE + VPN(va, 1) * 4);
    if (!(*pte & PTE_V))                               /* no level-0 table yet */
        *pte = alloc_frame() << 10 | PTE_V;            /* a pointer: R = W = X = 0 */
    uint32_t table = *pte >> 10;
    *pte_at(table * PAGE + VPN(va, 0) * 4) = frame << 10 | flags | PTE_V;
}
```

***Listing 11.1.** The indices and `map`. An entry is a frame number shifted left by 10, or-ed with its bits. code/bachelor-3/11-virtual-memory/listings/sv32.c*

```c
int translate(uint32_t root, uint32_t va, char access, uint32_t *pa)
{
    uint32_t a = root * PAGE;
    if (trace)
        printf("%-5s va 0x%08x: vpn1 0x%03x  vpn0 0x%03x  offset 0x%03x\n",
               access == 'r' ? "load" : access == 'w' ? "store" : "fetch",
               va, VPN(va, 1), VPN(va, 0), va & 0xfff);
    for (int i = 1; i >= 0; i--) {
        uint32_t addr = a + VPN(va, i) * 4, pte = *pte_at(addr);
        fault_level = i;
        if (trace)
            printf("  level %d: pte at 0x%05x = 0x%08x", i, addr, pte);
        if (!(pte & PTE_V) || (!(pte & PTE_R) && (pte & PTE_W))) {
            if (trace) printf("  -> not valid: page fault\n");
            return PAGE_FAULT;
        }
        if (!(pte & (PTE_R | PTE_X))) {                /* a pointer to the next level */
            a = (pte >> 10) * PAGE;
            if (trace) printf("  -> table in frame %u\n", pte >> 10);
            continue;
        }
        if (i == 1) {                                  /* a 4 MiB megapage: not used here */
            if (trace) printf("  -> megapage: not supported\n");
            return PAGE_FAULT;
        }
        uint32_t need = access == 'r' ? PTE_R : access == 'w' ? PTE_W : PTE_X;
        if (trace)
            printf("  -> leaf, frame %u, %c%c%c\n", pte >> 10, pte & PTE_R ? 'R' : '-',
                   pte & PTE_W ? 'W' : '-', pte & PTE_X ? 'X' : '-');
        if (!(pte & need)) {
            if (trace) printf("  not allowed: page fault\n");
            return PAGE_FAULT;
        }
        *pte_at(addr) = pte | PTE_A | (access == 'w' ? PTE_D : 0);  /* accessed, dirty */
        *pa = (pte >> 10) * PAGE + (va & 0xfff);
        if (trace) printf("  pa 0x%05x\n", *pa);
        return OK;
    }
    return PAGE_FAULT;                         /* a pointer at level 0: page fault too */
}
```

***Listing 11.2.** The walk. A missing entry or a forbidden access is a [page fault](#def-b3-virtual-memory-fault); a successful access sets A, and D for a store. code/bachelor-3/11-virtual-memory/listings/sv32.c*

```c
int main(void)
{
    uint32_t root = alloc_frame();                     /* the root table: frame 1 */
    map(root, 0x00010000, alloc_frame(), PTE_R | PTE_X | PTE_U);   /* code  */
    map(root, 0x10000000, alloc_frame(), PTE_R | PTE_W | PTE_U);   /* data  */
    map(root, 0x7ffff000, alloc_frame(), PTE_R | PTE_W | PTE_U);   /* stack */
    printf("root table in frame %u; %u frames in use\n\n", root, next_frame - 1);

    trace = 1;
    uint32_t pa;
    translate(root, 0x10000abc, 'r', &pa);             /* a load from the data page */
    translate(root, 0x00010004, 'x', &pa);             /* an instruction fetch */
    translate(root, 0x00010004, 'w', &pa);             /* a store into the code */
    translate(root, 0x40000000, 'r', &pa);             /* nothing mapped there */
    return 0;
}
```

***Listing 11.3.** A process of three [pages](#def-b3-virtual-memory-paging), and four accesses. code/bachelor-3/11-virtual-memory/listings/sv32_demo.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o sv32_demo sv32_demo.c sv32.c -lm && ./sv32_demo
root table in frame 1; 7 frames in use

load  va 0x10000abc: vpn1 0x040  vpn0 0x000  offset 0xabc
  level 1: pte at 0x01100 = 0x00001401  -> table in frame 5
  level 0: pte at 0x05000 = 0x00001017  -> leaf, frame 4, RW-
  pa 0x04abc
fetch va 0x00010004: vpn1 0x000  vpn0 0x010  offset 0x004
  level 1: pte at 0x01000 = 0x00000c01  -> table in frame 3
  level 0: pte at 0x03040 = 0x0000081b  -> leaf, frame 2, R-X
  pa 0x02004
store va 0x00010004: vpn1 0x000  vpn0 0x010  offset 0x004
  level 1: pte at 0x01000 = 0x00000c01  -> table in frame 3
  level 0: pte at 0x03040 = 0x0000085b  -> leaf, frame 2, R-X
  not allowed: page fault
load  va 0x40000000: vpn1 0x100  vpn0 0x000  offset 0x000
  level 1: pte at 0x01400 = 0x00000000  -> not valid: page fault
```

***Output 11.1.** Three translations and two faults. The store into the code [page](#def-b3-virtual-memory-paging) fails on the permissions, after a walk that succeeded; the load at `0x40000000` stops at the root. The fetch set the A bit: the code [page](#def-b3-virtual-memory-paging)’s entry has become `0x85b`.*

Why two levels? A one-level table would need an entry for each of the $2^{20}$ [pages](#def-b3-virtual-memory-paging), 4 MiB per process, mapped or not. With two, a region of the [address space](#def-b3-virtual-memory-space) that is not used costs one empty entry in the root, and level-0 tables exist only for the 4 MiB regions that hold something. [Output 11.2](#out-b3-virtual-memory-size) counts the cost for three layouts.

```python
"""table_size.py -- how much memory Sv32 page tables take for a few layouts of an
address space, against a one-level table with an entry for each of the 2**20 pages."""

PAGE, MB = 4096, 1 << 20


def pages(regions):  # regions: (start address, length in bytes)
    return {va // PAGE for start, n in regions for va in range(start, start + n, PAGE)}


def table_bytes(regions):
    used = pages(regions)
    level0 = {vpn >> 10 for vpn in used}  # one level-0 table per 4 MiB touched
    return len(used), len(level0), (1 + len(level0)) * PAGE


LAYOUTS = {
    "small program": [(0x00010000, 200 * 1024), (0x10000000, 2 * MB),
                      (0x40000000, MB), (0x80000000 - 128 * 1024, 128 * 1024)],
    "1 GiB array": [(0x10000000, 1024 * MB)],
    "64 scattered pages": [(k * 4 * MB, PAGE) for k in range(64)],
}
ONE_LEVEL = 2**20 * 4  # 2**20 entries of 4 bytes

print(f"{'layout':<20}{'pages':>8}{'tables':>8}{'table bytes':>13}{'per page':>10}")
for name, regions in LAYOUTS.items():
    n, t, size = table_bytes(regions)
    print(f"{name:<20}{n:>8}{t + 1:>8}{size:>13,}{size / n:>10.1f}")
print(f"one-level table: {ONE_LEVEL:,} bytes, whatever the layout")
```

***Listing 11.4.** Page-table memory for three layouts: a small program, a large array, and [pages](#def-b3-virtual-memory-paging) scattered one per 4 MiB. code/bachelor-3/11-virtual-memory/listings/table_size.py*

```
$ python table_size.py
layout                 pages  tables  table bytes  per page
small program            850       5       20,480      24.1
1 GiB array           262144     257    1,052,672       4.0
64 scattered pages        64      65      266,240    4160.0
one-level table: 4,194,304 bytes, whatever the layout
```

***Output 11.2.** Tables, counting the root, and their bytes, in total and per mapped [page](#def-b3-virtual-memory-paging).*

The small program, with code, heap, libraries and stack far apart, needs five tables, 20 KiB, against the 4 MiB of one level. A large dense array costs 4 bytes per [page](#def-b3-virtual-memory-paging), the size of its entries. The scattered layout is the worst case: each [page](#def-b3-virtual-memory-paging) brings a table of its own, 4,160 bytes of tables per [page](#def-b3-virtual-memory-paging) of data. With 64-bit addresses the gap grows: RISC-V’s Sv39 uses three levels for a 39-bit [address space](#def-b3-virtual-memory-space), and its Sv48 and Sv57 modes four and five. Some processors instead used an *inverted* [page table](#def-b3-virtual-memory-paging), one entry per physical frame, searched by hashing the virtual [page](#def-b3-virtual-memory-paging) number: its size follows the physical memory, not the [address space](#def-b3-virtual-memory-space), but sharing a frame between two processes becomes awkward.

## 11.3 The translation cache

Two extra memory reads on every access would make a program that reads memory at every step up to three times slower. Programs have locality, and the same few [pages](#def-b3-virtual-memory-paging) are translated again and again; the processor keeps the recent translations in a small cache.

**Definition 11.3 (Translation lookaside buffer, TLB reach, address-space identifier).**

A *translation lookaside buffer* (TLB) is a cache of recent translations, from virtual [page](#def-b3-virtual-memory-paging) number to [page-table entry](#def-b3-virtual-memory-paging), searched on every access. On a hit the access uses the cached translation; on a miss the processor (or, on some processors, the kernel) walks the [page table](#def-b3-virtual-memory-paging) and stores the result. The *TLB reach* is the memory its entries cover at once: the number of entries times the [page](#def-b3-virtual-memory-paging) size. An *address-space identifier* (ASID) is a number tagging each entry with the [address space](#def-b3-virtual-memory-space) it belongs to.

With a [TLB](#def-b3-virtual-memory-tlb) hit rate $h$, memory access time $m$ and a walk of $L$ reads on a miss, the average time of an access is

$$
m + (1 - h)\, L\, m,
$$

so with two levels and $h = 0.99$ an access costs 2 % more than without translation. The hit rate depends on the order of the accesses. [Listing 11.5](#lst-b3-virtual-memory-tlb) simulates a [TLB](#def-b3-virtual-memory-tlb) of 16 to 128 entries while a $1{,}024 \times 1{,}024$ matrix of 4-byte numbers is summed, each row filling exactly one [page](#def-b3-virtual-memory-paging).

```c

static void access_page(unsigned page, int size)
{
    int victim = 0;
    clock_now++;
    for (int e = 0; e < size; e++) {
        if (used[e] && tag[e] == page) {               /* hit */
            used[e] = clock_now;
            hits++;
            return;
        }
        if (used[e] < used[victim]) victim = e;        /* least recently used */
    }
    misses++;                                          /* walk the page table, refill */
    tag[victim] = page;
    used[victim] = clock_now;
```

***Listing 11.5.** A fully associative [TLB](#def-b3-virtual-memory-tlb) with LRU replacement: `access_page` hits or refills one entry. code/bachelor-3/11-virtual-memory/listings/tlb.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o tlb tlb.c -lm && ./tlb
TLB entries          16       32       64      128
reach (KiB)          64      128      256      512
rows             99.90%   99.90%   99.90%   99.90%
columns           0.00%    0.00%    0.00%    0.00%
strips of 32      0.00%   99.90%   99.90%   99.90%
```

***Output 11.3.** [TLB](#def-b3-virtual-memory-tlb) hit rates for three orders of the same sum, by number of entries.*

By rows, each [page](#def-b3-virtual-memory-paging) is used 1,024 times in a row: one miss per [page](#def-b3-virtual-memory-paging), whatever the size. By columns, each access touches the next row, a new [page](#def-b3-virtual-memory-paging), and the 1,024 [pages](#def-b3-virtual-memory-paging) come back only after all the others: every access misses, even with 128 entries, because the [pages](#def-b3-virtual-memory-paging) in use far exceed the reach, 512 KiB. In strips of 32 rows, the program reuses 32 [pages](#def-b3-virtual-memory-paging) before moving on: a [TLB](#def-b3-virtual-memory-tlb) of 32 entries or more holds them all, and one of 16 misses every time. Large [pages](#def-b3-virtual-memory-paging) raise the reach: one megapage entry covers as much as 1,024 small ones.

A [context switch](https://one-course.com/books/computer-science/5/en/chapter/10-the-kernel-and-cpu-scheduling#def-b3-kernel-and-scheduling-switch) changes `satp`, and with it every translation. Without tags the kernel must flush the whole [TLB](#def-b3-virtual-memory-tlb), and the next process starts with misses. With an ASID, kept in `satp` beside the root table and up to 9 bits wide in Sv32, entries of several processes coexist. When the kernel changes a [page table](#def-b3-virtual-memory-paging), it must also tell the processor: on RISC-V the instruction `sfence.vma` invalidates cached translations, for one address or all, one ASID or all.

## 11.4 Demand paging and page replacement

**Definition 11.4 (Page fault, demand paging).**

A *page fault* is the exception the processor raises when a translation fails: no valid entry, or an access the entry does not allow. With *demand paging*, the kernel maps a [page](#def-b3-virtual-memory-paging) only when the program first touches it: the fault is the request.

The kernel’s fault handler takes the faulting address from a register the trap filled, `stval` on RISC-V, finds which region of the process it belongs to, and decides. An address in no region is an error: the process receives a signal, usually fatal, the familiar segmentation fault. Otherwise the handler finds a free frame, fills it (with zeros for a new heap or stack [page](#def-b3-virtual-memory-paging), from the file for a [page](#def-b3-virtual-memory-paging) of code or of a mapped file, from the swap area for a [page](#def-b3-virtual-memory-paging) evicted earlier), writes the entry, and returns to the faulting instruction, which runs again and succeeds. A fault that needs no disk is a *minor* fault; one that must wait for the disk is a *major* fault, and costs milliseconds instead of microseconds.

When no frame is free, one must be taken from some [page](#def-b3-virtual-memory-paging), written back to disk first if it is dirty. Which [page](#def-b3-virtual-memory-paging)? The choice is a replacement policy, as for a cache, but [page faults](#def-b3-virtual-memory-fault) cost so much that the kernel can afford to think. LRU, recalled above, applies to [pages](#def-b3-virtual-memory-paging) unchanged.

**Definition 11.5 (Optimal replacement, clock algorithm, second-chance bit).**

*Optimal replacement* (OPT) evicts the [page](#def-b3-virtual-memory-paging) whose next use lies furthest in the future. The *clock algorithm* keeps the frames in a circle with a hand; each frame has a *second-chance bit*, set when its [page](#def-b3-virtual-memory-paging) is used. To evict, the hand advances: a frame with the bit set has it cleared and is passed over; the first frame with the bit clear is evicted.

OPT needs the future, so no kernel can run it; it is the yardstick that others are measured against, and it is optimal (exercise [11.7](#exo-b3-virtual-memory-7)). LRU needs a timestamp on every access, which only the hardware could keep. Clock needs one bit per [page](#def-b3-virtual-memory-paging), which the hardware sets for free: it is the A bit of the [page-table entry](#def-b3-virtual-memory-paging). It approximates LRU: a [page](#def-b3-virtual-memory-paging) used since the hand last passed survives one more turn.

```python
def fifo(refs, frames):
    resident, faults = [], 0
    for p in refs:
        if p not in resident:
            faults += 1
            if len(resident) == frames:
                resident.pop(0)  # the page that came in first
            resident.append(p)
    return faults


def lru(refs, frames):
    resident, faults = OrderedDict(), 0  # least recently used first
    for p in refs:
        if p in resident:
            resident.move_to_end(p)
            continue
        faults += 1
        if len(resident) == frames:
            resident.popitem(last=False)
        resident[p] = True
    return faults

```

***Listing 11.6.** FIFO evicts the [page](#def-b3-virtual-memory-paging) loaded first; LRU the [page](#def-b3-virtual-memory-paging) used least recently. code/bachelor-3/11-virtual-memory/listings/replace.py*

```python
def clock(refs, frames):
    page, ref, hand, faults = [None] * frames, [0] * frames, 0, 0
    for p in refs:
        if p in page:
            ref[page.index(p)] = 1  # the hardware sets the referenced bit
            continue
        faults += 1
        while ref[hand]:  # a second chance: clear the bit, move on
            ref[hand], hand = 0, (hand + 1) % frames
        page[hand], ref[hand], hand = p, 1, (hand + 1) % frames
    return faults


def opt(refs, frames):
    resident, faults = set(), 0
    for t, p in enumerate(refs):
        if p in resident:
            continue
        faults += 1
        if len(resident) == frames:  # evict the page needed furthest in the future
            later = refs[t + 1:]
            next_use = {q: later.index(q) if q in later else len(later)
                        for q in resident}
            resident.remove(max(resident, key=next_use.get))
        resident.add(p)
    return faults
```

***Listing 11.7.** Clock and OPT. code/bachelor-3/11-virtual-memory/listings/replace.py*

```
$ python replace.py
Belady's string: 1 2 3 4 1 2 5 1 2 3 4 5
frames    1   2   3   4   5
FIFO     12  12   9  10   5
LRU      12  12  10   8   5
clock    12  12   9  10   5
OPT      12   9   7   6   5
a loop over 5 pages, 3 times: 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
frames    1   2   3   4   5
FIFO     15  15  15  15   5
LRU      15  15  15  15   5
clock    15  15  15  15   5
OPT      15  12   9   7   5
```

***Output 11.4.** Faults of each policy with 1 to 5 frames, on two reference strings.*

The first string is the one L. A. Belady, R. A. Nelson and G. S. Shedler published in 1969. FIFO faults 9 times with 3 frames and 10 times with 4. More memory, more faults.

**Definition 11.6 (Belady’s anomaly, stack algorithm).**

*Belady’s anomaly* is a reference string on which a policy makes more faults with $f + 1$ frames than with $f$. A policy is a *stack algorithm* if, on every reference string and at every moment, the set of [pages](#def-b3-virtual-memory-paging) it holds with $f$ frames is contained in the set it holds with $f + 1$ frames.

![Faults on Belady’s string 1 2 3 4 1 2 5 1 2 3 4 5, from . LRU and OPT never fault more with more frames; FIFO, and clock with it, fault once more with 4 frames than with 3.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-virtual-memory/fig-aa50a762e44c.svg)

*Faults on Belady’s string 1 2 3 4 1 2 5 1 2 3 4 5, from [Output 11.4](#out-b3-virtual-memory-replace). LRU and OPT never fault more with more frames; FIFO, and clock with it, fault once more with 4 frames than with 3.*

**Theorem 11.7 (Stack algorithms have no anomaly).**

A [stack algorithm](#def-b3-virtual-memory-belady) never makes more faults with $f + 1$ frames than with $f$, on any reference string.

**Proof.** A reference that hits with $f$ frames finds its [page](#def-b3-virtual-memory-paging) among the [pages](#def-b3-virtual-memory-paging) held with $f$ frames, hence, by inclusion, among those held with $f + 1$: it hits there too. So the faults with $f + 1$ frames are among the faults with $f$. ∎

LRU is a [stack algorithm](#def-b3-virtual-memory-belady): with $f$ frames it holds the $f$ [pages](#def-b3-virtual-memory-paging) most recently used, which are among the $f + 1$ most recently used (exercise [11.10](#exo-b3-virtual-memory-10) writes the proof in full). OPT is one too. FIFO is not: after 1 2 3 4 1 2 5, FIFO holds $\{1, 2, 5\}$ with 3 frames and $\{2, 3, 4, 5\}$ with 4. [Stack algorithms](#def-b3-virtual-memory-belady) were defined by R. L. Mattson, J. Gecsei, D. R. Slutz and I. L. Traiger in 1970, in a paper on evaluating storage hierarchies.

**Definition 11.8 (Working set, thrashing).**

The *working set* of a process at time $t$, for a window $\Delta$, is the set of [pages](#def-b3-virtual-memory-paging) it used during the last $\Delta$ references. *Thrashing* is the collapse of a system whose processes do not all have their working sets in memory: each evicts [pages](#def-b3-virtual-memory-paging) another will need at once, and the machine spends its time on [page faults](#def-b3-virtual-memory-fault) instead of work.

The second string of [Output 11.4](#out-b3-virtual-memory-replace) shows the cliff in miniature: a loop over 5 [pages](#def-b3-virtual-memory-paging) faults on every reference with 4 frames or fewer, under FIFO, LRU and clock alike, and faults only 5 times once 5 frames hold the loop. The remedy for [thrashing](#def-b3-virtual-memory-working-set) is not a better policy but fewer processes: the kernel suspends some until the [working sets](#def-b3-virtual-memory-working-set) of the others fit. Peter Denning proposed the [working set](#def-b3-virtual-memory-working-set) model in 1968.

## 11.5 Copy on write and memory-mapped files

**Definition 11.9 (Copy on write, memory-mapped file).**

*Copy on write* shares a [page](#def-b3-virtual-memory-paging) between two [address spaces](#def-b3-virtual-memory-space), mapped read-only in both, and copies it only when one of them writes, in the page-fault handler. A *memory-mapped file* is a file whose bytes are mapped into an [address space](#def-b3-virtual-memory-space): loads read the file, and stores, in a shared mapping, change it.

`fork` copies the [address space](#def-b3-virtual-memory-space) of a process; copying every [page](#def-b3-virtual-memory-paging) would make it slow and, when the child replaces its program at once, useless. Linux implements `fork` with [copy on write](#def-b3-virtual-memory-cow): what it duplicates is the [page tables](#def-b3-virtual-memory-paging). [Listing 11.8](#lst-b3-virtual-memory-cow) measures it with the count of minor [page faults](#def-b3-virtual-memory-fault), the faults served without any disk activity, that `getrusage` keeps for each process.

```c
int main(void)
{
    char *buf = mmap(NULL, PAGES * 4096L, PROT_READ | PROT_WRITE,
                     MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    madvise(buf, PAGES * 4096L, MADV_NOHUGEPAGE);      /* 4 KiB pages only */
    long f0 = faults();
    memset(buf, 1, PAGES * 4096L);                     /* the parent touches every page */
    report("parent, first touch of every page:", f0);
    fflush(stdout);
    if (fork() == 0) {
        volatile long sum = 0;
        long f = faults();
        for (long i = 0; i < PAGES; i++) sum += buf[i * 4096];
        report("child, reads every page:", f);
        f = faults();
        for (long i = 0; i < PAGES; i++) buf[i * 4096] = 2;
        report("child, writes every page:", f);
        f = faults();
        for (long i = 0; i < PAGES; i++) buf[i * 4096] = 3;
        report("child, writes every page again:", f);
        return 0;
    }
    wait(NULL);
    printf("parent, after the child: buf[0] = %d, %d pages of %d bytes\n", buf[0], PAGES, 4096);
    return 0;
}
```

***Listing 11.8.** A parent touches 4,096 [pages](#def-b3-virtual-memory-paging), forks, and the child reads them, writes them, and writes them again. code/bachelor-3/11-virtual-memory/listings/cow.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o cow cow.c -lm && ./cow
parent, first touch of every page:  4097 faults
child, reads every page:               0 faults
child, writes every page:           4096 faults
child, writes every page again:        0 faults
parent, after the child: buf[0] = 1, 4096 pages of 4096 bytes
```

***Output 11.5.** Minor [page faults](#def-b3-virtual-memory-fault) on the laptop. The first touch of a [page faults](#def-b3-virtual-memory-fault) once, [demand paging](#def-b3-virtual-memory-fault); reading a shared [page](#def-b3-virtual-memory-paging) costs nothing; the first write to each [page](#def-b3-virtual-memory-paging) copies it; the second write costs nothing.*

The parent’s 4,097 faults are its 4,096 [pages](#def-b3-virtual-memory-paging), each mapped on first touch, and one more elsewhere in the program. The child’s reads fault zero times: `fork` copied the entries, which still point at the parent’s frames. Its writes fault once per [page](#def-b3-virtual-memory-paging), and each fault copies one [page](#def-b3-virtual-memory-paging). The parent still reads 1: the child’s writes went to its own copies.

![Copy on write, for one page. After fork both entries point to the same frame, read-only. The child’s store faults; the handler copies the frame, points the child’s entry at the copy, writable, and the store runs again. The parent’s entry stays read-only: its next store faults too, and the handler, finding the frame no longer shared, makes the entry writable without copying.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-virtual-memory/fig-431924999776.svg)

*[Copy on write](#def-b3-virtual-memory-cow), for one [page](#def-b3-virtual-memory-paging). After `fork` both entries point to the same frame, read-only. The child’s store faults; the handler copies the frame, points the child’s entry at the copy, writable, and the store runs again. The parent’s entry stays read-only: its next store faults too, and the handler, finding the frame no longer shared, makes the entry writable without copying.*

A shared mapping of a file turns the file into memory: `mmap` returns an address, the [pages](#def-b3-virtual-memory-paging) are filled from the file on first touch, and a store to a [page](#def-b3-virtual-memory-paging) marks it dirty; the kernel writes dirty [pages](#def-b3-virtual-memory-paging) back to the file, at the latest when `msync` asks it to.

```c
int main(void)
{
    const char *text = "the print shop opens at nine.\nthe queue forms at ten.\n";
    size_t len = strlen(text);
    int fd = open("notes.txt", O_RDWR | O_CREAT | O_TRUNC, 0644);
    if (write(fd, text, len) != (ssize_t)len) return 1;   /* an ordinary file */

    char *p = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    close(fd);                                         /* the mapping keeps the file */
    for (size_t i = 0; i < len; i++)                   /* capitalise each sentence */
        if (i == 0 || p[i - 1] == '\n')
            p[i] = (char)toupper((unsigned char)p[i]);
    memcpy(strstr(p, "nine"), "8:45", 4);              /* no write(): just stores */
    msync(p, len, MS_SYNC);
    munmap(p, len);

    char back[128] = {0};
    fd = open("notes.txt", O_RDONLY);
    ssize_t n = read(fd, back, sizeof back - 1);
    close(fd);
    printf("read back %zd bytes:\n%s", n, back);
    return 0;
}
```

***Listing 11.9.** A file edited in place by stores to memory. code/bachelor-3/11-virtual-memory/listings/mmap_file.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o mmap_file mmap_file.c -lm && ./mmap_file
read back 54 bytes:
The print shop opens at 8:45.
The queue forms at ten.
```

***Output 11.6.** The file, read back with `read`, holds the stores.*

The same mechanism loads programs: the kernel maps the program file’s code [pages](#def-b3-virtual-memory-paging), and they come from disk only when executed; and two processes that map the same library share its frames.

**History — Paging.**

L. A. Belady published a study of replacement algorithms for a virtual-storage computer in 1966. Peter Denning published the [working set](#def-b3-virtual-memory-working-set) model in May 1968. Belady, Nelson and Shedler described the anomaly in June 1969, and Mattson, Gecsei, Slutz and Traiger the [stack algorithms](#def-b3-virtual-memory-belady) in 1970.

## 11.6 Exercises

**Exercise 11.1 ★.**

Split the Sv32 [virtual address](#def-b3-virtual-memory-space) `0x7ffff123`. In the process of [Listing 11.3](#lst-b3-virtual-memory-demo) (root in frame 1, the stack [page](#def-b3-virtual-memory-paging) in frame 6, its level-0 table in frame 7), which two entry addresses does the walk read, and what is the [physical address](#def-b3-virtual-memory-space)?

**Solution of Exercise 11.1.**

In binary, `0x7ffff123` is `0111111111 1111111111 000100100011`: VPN[1] = `0x1ff`, VPN[0] = `0x3ff`, offset `0x123`. The walk reads the root entry at $\mathtt{0x1000} + \mathtt{0x1ff} \times 4 = \mathtt{0x17fc}$, which points to frame 7, then the entry at $\mathtt{0x7000} + \mathtt{0x3ff} \times 4 = \mathtt{0x7ffc}$, a leaf for frame 6. The [physical address](#def-b3-virtual-memory-space) is `0x06123` (`demo_test.c`).

**Exercise 11.2 ★.**

A memory access takes 80 ns, a [TLB](#def-b3-virtual-memory-tlb) lookup no extra time, and a [TLB](#def-b3-virtual-memory-tlb) miss a walk of two memory reads. What is the average access time with a hit rate of 99 %, and of 99.9 %? Which hit rate keeps the slowdown under 5 %?

**Solution of Exercise 11.2.**

The average is $80 + (1 - h) \times 2 \times 80$ ns: 81.6 ns at 99 % (2 % slower), 80.16 ns at 99.9 %. The slowdown $(1 - h) \times 160 / 80 = 2(1 - h)$ stays under 5 % when $h \ge 97.5$ %.

**Exercise 11.3 ★.**

Count the faults of LRU with 3 frames on 7 0 1 2 0 3 0 4 2 3.

**Solution of Exercise 11.3.**

7, 0, 1 fault and fill the frames; 2 faults and evicts 7; 0 hits; 3 evicts 1; 0 hits; 4 evicts 2; 2 evicts 3; 3 evicts 0, leaving 4, 2, 3. Eight faults (`test_exercise_3_lru_by_hand`).

**Exercise 11.4 ★.**

[Listing 11.3](#lst-b3-virtual-memory-demo) adds the line `translate(root, 0x10001000, 'r', &pa);`. Predict what it prints.

**Solution of Exercise 11.4.**

VPN[1] is `0x040`, as for the data [page](#def-b3-virtual-memory-paging), so the root entry exists; VPN[0] is `0x001`, an entry of the data [page](#def-b3-virtual-memory-paging)’s table that was never written:

```
$ gcc -std=c17 -O2 -Wall -Wextra -o sv32_ex4 sv32_ex4.c sv32.c -lm && ./sv32_ex4
load  va 0x10001000: vpn1 0x040  vpn0 0x001  offset 0x000
  level 1: pte at 0x01100 = 0x00001401  -> table in frame 5
  level 0: pte at 0x05004 = 0x00000000  -> not valid: page fault
```

***Output 11.8.** Exercise 4: the walk stops at level 0.*

**Exercise 11.5 ★★.**

A first version of `sv32.c` defined its index as below. Loads from the first kilobyte of a mapped [page](#def-b3-virtual-memory-paging) work; a load from `0x10000abc` faults although the [page](#def-b3-virtual-memory-paging) `0x10000000` is mapped. Explain, and fix it.

```cpp
#define VPN(va, i) ((i) == 1 ? (va) >> 22 : ((va) >> 10) & 0x3ff)
```

***Listing 11.10.** The index as first written. code/bachelor-3/11-virtual-memory/exercises/ex5_vpn_bug.h*

**Solution of Exercise 11.5.**

`(va >> 10) & 0x3ff` takes bits 19 to 10: the low eight bits of VPN[0] and the top two bits of the offset. `map` stored the [page](#def-b3-virtual-memory-paging) `0x10000000`, whose offset is 0, at index 0. A load at offset below `0x400` has bits 11 and 10 clear, finds index 0 and works; at `0x10000abc` they are `10`, the index is 2, an empty entry, and the walk faults at level 0 (`vpn_bug_test.c`). The right index is `((va) >> 12) & 0x3ff`. The bug also folds four [pages](#def-b3-virtual-memory-paging) onto overlapping indices, so it could map one [page](#def-b3-virtual-memory-paging) over another: an index must be built from the [page](#def-b3-virtual-memory-paging) number alone.

**Exercise 11.6 ★★.**

Write clock with a dirty bit: references are ([page](#def-b3-virtual-memory-paging), `'r'` or `'w'`); to evict, the hand first looks, over one full turn and changing nothing, for a [page](#def-b3-virtual-memory-paging) neither used nor dirty; failing that, over one more turn, for a [page](#def-b3-virtual-memory-paging) not used, clearing the bits it passes; and repeats. Count the faults and the write-backs. On (1, w), (2, r), (3, r), (4, r) with 3 frames, which [page](#def-b3-virtual-memory-paging) does it evict, and which does plain clock evict?

**Solution of Exercise 11.6.**

`exercises/ex6_clock_dirty.py`. On the example the three frames hold 1 (written), 2 and 3, all used. The first turn finds no [page](#def-b3-virtual-memory-paging) that is neither used nor dirty; the second clears the three bits and finds none unused; the next first turn finds [page](#def-b3-virtual-memory-paging) 2, unused and clean, and evicts it. Plain clock clears the bits and evicts [page](#def-b3-virtual-memory-paging) 1, the first under the hand, which is dirty and must be written back: `test_exercise_6_clock_with_dirty_bit` gets (4, 0) and (4, 1). On random strings the test also checks that the faults are never fewer than OPT’s.

**Exercise 11.7 ★★.**

Prove that OPT makes the fewest possible faults on every reference string, for every number of frames.

**Solution of Exercise 11.7.**

Let $A$ be any policy. We build policies $A_0 = A$, $A_1$, $A_2$, …, where $A_k$ makes the same choices as OPT on the first $k$ references and never more faults than $A_{k-1}$; then $A_n$ is OPT on a string of length $n$, with no more faults than $A$.

Given $A_k$, suppose that at reference $k + 1$ it faults and evicts $y$ where OPT evicts $x$; both were in memory, and $x$’s next use is not before $y$’s. $A_{k+1}$ evicts $x$ and then copies $A_k$; their memories differ only by $y$ (held by $A_{k+1}$) against $x$ (held by $A_k$). While they differ: a reference to a common [page](#def-b3-virtual-memory-paging) hits in both; a reference to a [page](#def-b3-virtual-memory-paging) in neither faults in both, and if $A_k$ evicts $x$, $A_{k+1}$ evicts $y$ and the memories become equal, otherwise both evict the same [page](#def-b3-virtual-memory-paging). $x$ cannot be referenced before $y$. When $y$ is referenced, $A_k$ faults and $A_{k+1}$ does not; if $A_k$ evicts $x$ the memories are equal, and if it evicts another [page](#def-b3-virtual-memory-paging) $v$, $A_{k+1}$ evicts $v$ too and loads $x$ at once, a load that $A_k$’s fault pays for. From then on the two are identical, and $A_{k+1}$ has made no more faults.

The load of $x$ before it is requested is a *prefetch*; a policy that prefetches can always be changed into one that loads each [page](#def-b3-virtual-memory-paging) only when requested, with no more faults: postpone each load until the [page](#def-b3-virtual-memory-paging) is requested, and skip it if the [page](#def-b3-virtual-memory-paging) is evicted first. `test_opt_is_never_beaten` compares OPT with FIFO, LRU and clock on 300 random strings.

**Exercise 11.8 ★★.**

A process has 64 KiB of code at `0x00400000`, 8 MiB of heap at `0x20000000`, and 64 KiB of stack just below `0x80000000`. How many [pages](#def-b3-virtual-memory-paging) of Sv32 [page tables](#def-b3-virtual-memory-paging) does it need?

**Solution of Exercise 11.8.**

The code is in the 4 MiB region 1 (`0x00400000 >> 22`); the heap covers regions `0x80` and `0x81`, since 8 MiB is two regions; the stack is in region `0x1ff`. Four level-0 tables and the root: 5 [pages](#def-b3-virtual-memory-paging), 20 KiB, for $16 + 2{,}048 + 16$ [pages](#def-b3-virtual-memory-paging) of data (`test_exercise_8_table_pages`).

**Exercise 11.9 ★★.**

In [Listing 11.8](#lst-b3-virtual-memory-cow), the child first writes every other [page](#def-b3-virtual-memory-paging), then reads every [page](#def-b3-virtual-memory-paging), then writes every [page](#def-b3-virtual-memory-paging). Predict the three counts of minor faults.

**Solution of Exercise 11.9.**

2,048 faults for the writes to every other [page](#def-b3-virtual-memory-paging), each copying a [page](#def-b3-virtual-memory-paging); none for the reads, since every [page](#def-b3-virtual-memory-paging) is mapped, shared or copied; 2,048 for the second writes, to the [pages](#def-b3-virtual-memory-paging) still shared. `cow_test.c` runs the same three phases on 1,024 [pages](#def-b3-virtual-memory-paging) and finds 512, 0 and 512 (it allows up to 4 faults more for the program’s own [pages](#def-b3-virtual-memory-paging)).

**Exercise 11.10 ★★★.**

Prove that LRU is a [stack algorithm](#def-b3-virtual-memory-belady).

**Solution of Exercise 11.10.**

Keep the list of the [pages](#def-b3-virtual-memory-paging) referenced so far, ordered by last use, most recent first; it does not depend on the number of frames. We show by induction on the references that LRU with $f$ frames holds exactly the first $f$ [pages](#def-b3-virtual-memory-paging) of the list (all of them, if there are fewer). Before any reference both are empty. Let [page](#def-b3-virtual-memory-paging) $p$ be referenced. If $p$ is among the first $f$, LRU hits, and $p$ moves to the front: the first $f$ are the same [pages](#def-b3-virtual-memory-paging). Otherwise LRU faults; if its frames are full, it evicts the [page](#def-b3-virtual-memory-paging) used least recently among those it holds, the $f$-th of the list, and loads $p$, which goes to the front: LRU now holds $p$ and the old first $f - 1$, which are the new first $f$. Hence the [pages](#def-b3-virtual-memory-paging) held with $f$ frames, the first $f$ of the list, are among the first $f + 1$: LRU is a [stack algorithm](#def-b3-virtual-memory-belady) (`test_lru_is_a_stack_algorithm` checks the inclusion at every step of 300 random strings).

**Exercise 11.11 ★★★.**

For any $k$, build a reference string on which clock makes about $k$ times as many faults as LRU with the same number of frames (you choose it).

**Solution of Exercise 11.11.**

Take $f = 2k - 1$ frames and $f - 1$ hot [pages](#def-b3-virtual-memory-paging) $1, \dots, f - 1$, used in order after each new [page](#def-b3-virtual-memory-paging) that is used once: $1, \dots, f - 1$, then for every round $r$, [page](#def-b3-virtual-memory-paging) $100 + r$ followed by $1, \dots, f - 1$. LRU holds the hot [pages](#def-b3-virtual-memory-paging) for good, and each new [page](#def-b3-virtual-memory-paging) evicts the previous one, the least recently used: one fault per round. Clock alternates. When a new [page](#def-b3-virtual-memory-paging) arrives and every bit is set, the hand clears all the bits in one turn and evicts the [page](#def-b3-virtual-memory-paging) under it. If that is a hot [page](#def-b3-virtual-memory-paging), it is about to be used: its fault evicts the next frame, whose bit is now clear, another hot [page](#def-b3-virtual-memory-paging) used soon after, and so on, so the whole round faults, $f$ faults. The next round’s new [page](#def-b3-virtual-memory-paging) then evicts the previous new [page](#def-b3-virtual-memory-paging) and the hot [pages](#def-b3-virtual-memory-paging) hit: one fault. Two rounds cost $f + 1 = 2k$ faults under clock against 2 under LRU. Over $R$ rounds the counts are $2k - 2 + kR$ and $2k - 2 + R$, a ratio that tends to $k$ (`test_exercise_11_clock_k_times_worse`, with $R = 200$ and $k = 2, 3, 5$).

**Exercise 11.12 ★★★.**

Sv39 translates 39-bit virtual addresses with 4 KiB [pages](#def-b3-virtual-memory-paging) through three levels of tables of $2^9$ entries of eight bytes, and also allows 2 MiB megapages and 1 GiB gigapages. Compute the [TLB reach](#def-b3-virtual-memory-tlb) of 64 entries with each [page](#def-b3-virtual-memory-paging) size, and the [pages](#def-b3-virtual-memory-paging) of tables needed to map a 1 GiB array aligned on 1 GiB with small [pages](#def-b3-virtual-memory-paging), with megapages, and with one gigapage. Compare with Sv32 in [Output 11.2](#out-b3-virtual-memory-size).

**Solution of Exercise 11.12.**

Reach of 64 entries: $64 \times 4$ KiB = 256 KiB; with 2 MiB megapages, 128 MiB; with 1 GiB gigapages, 64 GiB. A table of 512 entries maps $512 \times 4$ KiB = 2 MiB at level 0, $512 \times 2$ MiB = 1 GiB at level 1. The array with small [pages](#def-b3-virtual-memory-paging): 262,144 entries in 512 level-0 tables, one level-1 table and the root, 514 [pages](#def-b3-virtual-memory-paging), about 2 MiB, 8 bytes per [page](#def-b3-virtual-memory-paging) mapped. With megapages: 512 leaves in one level-1 table, plus the root, 2 [pages](#def-b3-virtual-memory-paging). With a gigapage: one leaf in the root, 1 [page](#def-b3-virtual-memory-paging). Sv32 needed 257 [pages](#def-b3-virtual-memory-paging) for the same array, 4 bytes per [page](#def-b3-virtual-memory-paging): Sv39 entries are twice as large, the price of a larger [address space](#def-b3-virtual-memory-space), and large [pages](#def-b3-virtual-memory-paging) remove nearly all of it.

## 11.7 Weekend problem

**Problem 11.1.**

Weekend problem — Belady’s anomaly

More memory should never hurt. This problem checks the claim on FIFO by hand, defines what makes a policy safe, searches every short reference string for counterexamples, and proves that the safe policies are safe.

```python
def fifo_step(state, p, frames):  # state: (pages in arrival order, faults)
    pages, faults = state
    if p in pages:
        return state
    return (pages + (p,))[-frames:], faults + 1


def lru_step(state, p, frames):  # state: (pages, least recent first; faults)
    pages, faults = state
    rest = tuple(q for q in pages if q != p)
    return (rest + (p,))[-frames:], faults + (len(rest) == len(pages))


def search(n):
    """Strings of length n up to renaming: page k+1 first appears after page k."""
    found = {"strings": 0, "FIFO": [], "LRU": []}

    def extend(s, used, f3, f4, l3, l4):
        if len(s) == n:
            found["strings"] += 1
            if f4[1] > f3[1]:
                found["FIFO"].append(" ".join(map(str, s)))
            if l4[1] > l3[1]:
                found["LRU"].append(" ".join(map(str, s)))
            return
        for p in range(1, used + 2):  # an old page, or the next new one
            extend(s + [p], max(used, p), fifo_step(f3, p, 3), fifo_step(f4, p, 4),
                   lru_step(l3, p, 3), lru_step(l4, p, 4))

    empty = ((), 0)
    extend([], 0, empty, empty, empty, empty)
    return found

```

***Listing 11.11.** Every string up to renaming, extended one reference at a time, with the state of FIFO and LRU with 3 and with 4 frames carried along. code/bachelor-3/11-virtual-memory/listings/belady_search.py*

```
$ python belady_search.py
length  1:         1 strings, anomalous under FIFO 0, under LRU 0
length  2:         2 strings, anomalous under FIFO 0, under LRU 0
length  3:         5 strings, anomalous under FIFO 0, under LRU 0
length  4:        15 strings, anomalous under FIFO 0, under LRU 0
length  5:        52 strings, anomalous under FIFO 0, under LRU 0
length  6:       203 strings, anomalous under FIFO 0, under LRU 0
length  7:       877 strings, anomalous under FIFO 0, under LRU 0
length  8:     4,140 strings, anomalous under FIFO 0, under LRU 0
length  9:    21,147 strings, anomalous under FIFO 0, under LRU 0
length 10:   115,975 strings, anomalous under FIFO 0, under LRU 0
length 11:   678,570 strings, anomalous under FIFO 0, under LRU 0
length 12: 4,213,597 strings, anomalous under FIFO 8, under LRU 0
  1 2 3 4 1 2 5 1 2 3 4 5
  1 2 3 4 1 2 5 1 2 3 6 5
  1 2 3 4 1 2 5 1 2 6 3 5
  1 2 3 4 1 2 5 1 2 6 4 5
  1 2 3 4 1 2 5 1 2 6 7 5
  1 2 3 4 1 2 5 1 6 2 3 5
  1 2 3 4 1 2 5 1 6 2 4 5
  1 2 3 4 1 2 5 1 6 2 7 5
```

***Output 11.7.** The search, lengths 1 to 12, and the anomalous strings found.*

**Part I — FIFO by hand.**

1. Run FIFO with 3 frames on 1 2 3 4 1 2 5 1 2 3 4 5, writing the frames after each reference. Count the faults.
2. Do the same with 4 frames.
3. From which reference on does the 4-frame run hold [pages](#def-b3-virtual-memory-paging) the 3-frame run has evicted, and which references then fault only with 4 frames?
4. Clock makes the same counts in [Output 11.4](#out-b3-virtual-memory-replace) . Why does clock behave exactly as FIFO on this string with 3 frames?
5. Run OPT by hand with 3 frames: which [page](#def-b3-virtual-memory-paging) does it evict at each fault?
6. What is the fewest faults any policy can make on this string, whatever the number of frames, and why?

**Part II — The stack property.**

7. Give FIFO’s [pages](#def-b3-virtual-memory-paging) with 3 and with 4 frames after 1 2 3 4 1 2 5. Is the inclusion of the definition true?
8. Give LRU’s [pages](#def-b3-virtual-memory-paging) at the same moment.
9. Show that the inclusion at every moment implies that every hit with $f$ frames is a hit with $f + 1$ .
10. Can clock be a [stack algorithm](#def-b3-virtual-memory-belady) ? Answer from [Output 11.4](#out-b3-virtual-memory-replace) .
11. LRU holds the $f$ [pages](#def-b3-virtual-memory-paging) most recently used. Describe FIFO’s [pages](#def-b3-virtual-memory-paging) in the same way, and say why that description depends on $f$ .
12. Explain how a single pass over a string can then give LRU’s faults for every number of frames at once.

**Part III — The search.**

13. Why may the search consider only strings in which [page](#def-b3-virtual-memory-paging) $k + 1$ first appears after [page](#def-b3-virtual-memory-paging) $k$ ?
14. The numbers of strings are 1, 2, 5, 15, 52, …: check the first four by listing the strings.
15. What is the length of the shortest anomalous string for FIFO with 3 and 4 frames, and how many [pages](#def-b3-virtual-memory-paging) does it use?
16. How many anomalous strings of that length are there, and what do they share?
17. Some anomalous strings use 6 or 7 [pages](#def-b3-virtual-memory-paging) . What do the extra [pages](#def-b3-virtual-memory-paging) do?
18. What does the LRU column show, and why is that no surprise?
19. The count of strings grows faster than any power of a fixed base. Why can the search still afford length 12?

**Part IV — The proof.**

20. Prove [Theorem 11.7](#thm-b3-virtual-memory-stack) from question 9.
21. Deduce that LRU never shows the anomaly, using exercise [11.10](#exo-b3-virtual-memory-10) .
22. Why does the search not prove that FIFO has no anomaly with 2 and 3 frames?
23. Why does FIFO fail to be a [stack algorithm](#def-b3-virtual-memory-belady) , in one sentence?
24. Clock shows the anomaly, yet kernels use clock rather than LRU. Why?
25. Sum up: which policies can show the anomaly, how short can an anomalous string be, and why can LRU never show one?

**Solution of Problem 11.1.**

**1.** Oldest first: 1 [1]; 2 [1 2]; 3 [1 2 3]; 4 [2 3 4]; 1 [3 4 1]; 2 [4 1 2]; 5 [1 2 5]; 1 and 2 hit; 3 [2 5 3]; 4 [5 3 4]; 5 hits. Nine faults.

**2.** 1, 2, 3, 4 fault [1 2 3 4]; 1 and 2 hit; 5 [2 3 4 5]; 1 [3 4 5 1]; 2 [4 5 1 2]; 3 [5 1 2 3]; 4 [1 2 3 4]; 5 [2 3 4 5]. Ten faults.

**3.** After the seventh reference neither memory contains the other: $\{1, 2, 5\}$ and $\{2, 3, 4, 5\}$. The 3-frame run had paid for that position with two faults of its own (references 5 and 6, which hit with 4 frames), and it now has the right [pages](#def-b3-virtual-memory-paging): references 8, 9 and 12 fault only with 4 frames, 10 and 11 in both. Two extra faults against three.

**4.** [Pages](#def-b3-virtual-memory-paging) enter the circle in the order they are loaded, and the hand moves round in that order, so the frame under the hand holds the [page](#def-b3-virtual-memory-paging) loaded earliest. Clock departs from FIFO only when the hand passes over a set bit and evicts a later [page](#def-b3-virtual-memory-paging). Here, at every fault, either all the bits are set, so the hand clears them in one turn and evicts the [page](#def-b3-virtual-memory-paging) under it, or the [page](#def-b3-virtual-memory-paging) under the hand has its bit clear: clock evicts the oldest [page](#def-b3-virtual-memory-paging) each time.

**5.** 1, 2, 3 fault. 4 evicts 3 (next used at reference 10, after 1 and 2). 1 and 2 hit. 5 evicts 4 (used at 11, after 1 and 2). 1 and 2 hit. 3 evicts 1 or 2, never used again. 4 evicts the other of them, or 3. 5 hits. Seven faults.

**6.** Five: each of the five [pages](#def-b3-virtual-memory-paging) faults at its first use, whatever the policy, and 5 frames achieve it.

**7.** $\{1, 2, 5\}$ with 3 frames, $\{2, 3, 4, 5\}$ with 4: [page](#def-b3-virtual-memory-paging) 1 is in the first and not in the second, so the inclusion fails.

**8.** $\{1, 2, 5\}$ and $\{1, 2, 4, 5\}$: included.

**9.** A reference at time $t$ hits with $f$ frames when its [page](#def-b3-virtual-memory-paging) is in the set held with $f$ frames just before it; that set is contained in the set held with $f + 1$, so the [page](#def-b3-virtual-memory-paging) is there too.

**10.** No: on Belady’s string clock faults 9 times with 3 frames and 10 with 4, which question 9 rules out for a [stack algorithm](#def-b3-virtual-memory-belady).

**11.** FIFO holds the $f$ [pages](#def-b3-virtual-memory-paging) most recently *loaded*. But which references load a [page](#def-b3-virtual-memory-paging) depends on $f$: with 4 frames, the references to 1 and 2 at 5 and 6 hit and load nothing, so 1 and 2 count as old, while with 3 frames they are reloaded and count as young.

**12.** Keep LRU’s list. At each reference, the [page](#def-b3-virtual-memory-paging)’s position in the list, its distance, says at once for which numbers of frames it hits: those at least the distance. Counting the references at each distance, with first uses at distance infinity, gives the faults with $f$ frames as the number of references at a distance greater than $f$, for every $f$, in one pass.

**13.** The policies only compare [pages](#def-b3-virtual-memory-paging) for equality, so renaming the [pages](#def-b3-virtual-memory-paging) one to one changes no fault. Each class of strings equal up to renaming has exactly one member that names its [pages](#def-b3-virtual-memory-paging) 1, 2, 3, … in order of first use.

**14.** Length 1: 1. Length 2: 11, 12. Length 3: 111, 112, 121, 122, 123. Length 4: 1111, 1112, 1121, 1122, 1123, 1211, 1212, 1213, 1221, 1222, 1223, 1231, 1232, 1233, 1234: fifteen.

**15.** Twelve references, and Belady’s string, the first one found, uses five [pages](#def-b3-virtual-memory-paging). No string of length 11 or less is anomalous, with any number of [pages](#def-b3-virtual-memory-paging).

**16.** Eight. All begin with 1 2 3 4 1 2 5 1 and end with 5; they differ only in references 9 to 11.

**17.** A [page](#def-b3-virtual-memory-paging) used only once faults in both runs, and FIFO evicts the oldest [page](#def-b3-virtual-memory-paging) whatever arrives: it acts as a filler that ages both queues, as a reference to 3 or 4 does at those places.

**18.** No anomaly under LRU at any length, as [Theorem 11.7](#thm-b3-virtual-memory-stack) and exercise [11.10](#exo-b3-virtual-memory-10) require.

**19.** The strings form a tree, each extending its prefix by one reference, and the search carries the four memories along the tree, so each string costs one step from its prefix. There are $1 + 2 + 5 + \dots + 4{,}213{,}597 = 5{,}034{,}584$ strings of length at most 12 in all: a few million steps.

**20.** By question 9, every hit with $f$ frames is a hit with $f + 1$, so the faults with $f + 1$ are among the faults with $f$: $\mathit{faults}(f + 1) \le \mathit{faults}(f)$.

**21.** LRU is a [stack algorithm](#def-b3-virtual-memory-belady) (exercise [11.10](#exo-b3-virtual-memory-10)), so question 20 applies: on every string, more frames never mean more faults.

**22.** It only compares 3 frames with 4, and only up to length 12. An exhaustive search can find a counterexample but proves nothing beyond the cases it covers.

**23.** FIFO orders [pages](#def-b3-virtual-memory-paging) by when they were loaded, and with more frames some [pages](#def-b3-virtual-memory-paging) are not reloaded, so the order, and with it the [pages](#def-b3-virtual-memory-paging) held, differ between the two runs.

**24.** LRU must update its order on every memory access, which no kernel can do; clock needs only the A bit, which the hardware sets for free, and work at fault time. On programs with locality, the [pages](#def-b3-virtual-memory-paging) in use have their bits set and survive, as under LRU; the anomaly needs strings that defeat the bit, like Belady’s.

**25.** FIFO and clock show the anomaly; the shortest anomalous string for 3 against 4 frames has 12 references, and there are eight of that length up to renaming, Belady’s among them. LRU, and every [stack algorithm](#def-b3-virtual-memory-belady), cannot show it: with $f$ frames it holds the first $f$ [pages](#def-b3-virtual-memory-paging) of a list that does not depend on $f$, so every hit with fewer frames is a hit with more.
