本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 3 · 本科三年级
11Virtual 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, 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 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 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 is not translated: a virtual address is a page number and an offset, and its physical address 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 of chapter 9. Pages of one size never fragment physical memory that way: any free frame fits any page.
11.2 Paging and multi-level page tables
RISC-V’s Sv32 mode, for 32-bit processors, uses pages of 4 KiB. A virtual address is a 20-bit virtual page number, split into two 10-bit indices, and a 12-bit offset. The 20-bit page number is translated into a 22-bit physical page number, so a 32-bit processor can address more than 4 GiB of physical memory. Each page table holds entries of four bytes, exactly one page, and the physical page number of the root table is held in the register satp.
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 may be read, written and executed. A page cannot be writable without being readable. The entry’s physical page 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. A, the accessed bit, records that the page 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 and 11.2 implement the tables over a byte array of 1 MiB that plays the physical memory: map installs one page, creating its level-0 table when the first page of a 4 MiB region is mapped; translate walks the tables as the specification describes, printing each step.
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;
}
map. An entry is a frame number shifted left by 10, or-ed with its bits. code/bachelor-3/11-virtual-memory/listings/sv32.cint 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 */
}
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;
}
$ 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
0x40000000 stops at the root. The fetch set the A bit: the code page’s entry has become 0x85b.Why two levels? A one-level table would need an entry for each of the pages, 4 MiB per process, mapped or not. With two, a region of the address 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 counts the cost for three layouts.
"""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")
$ 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
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, the size of its entries. The scattered layout is the worst case: each page brings a table of its own, 4,160 bytes of tables per page of data. With 64-bit addresses the gap grows: RISC-V’s Sv39 uses three levels for a 39-bit address space, and its Sv48 and Sv57 modes four and five. Some processors instead used an inverted page table, one entry per physical frame, searched by hashing the virtual page number: its size follows the physical memory, not the address 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 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 number to page-table entry, 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 and stores the result. The TLB reach is the memory its entries cover at once: the number of entries times the page size. An address-space identifier (ASID) is a number tagging each entry with the address space it belongs to.
With a TLB hit rate , memory access time and a walk of reads on a miss, the average time of an access is
so with two levels and an access costs 2 % more than without translation. The hit rate depends on the order of the accesses. Listing 11.5 simulates a TLB of 16 to 128 entries while a matrix of 4-byte numbers is summed, each row filling exactly one page.
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;
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%
By rows, each page is used 1,024 times in a row: one miss per page, whatever the size. By columns, each access touches the next row, a new page, and the 1,024 pages come back only after all the others: every access misses, even with 128 entries, because the pages in use far exceed the reach, 512 KiB. In strips of 32 rows, the program reuses 32 pages before moving on: a TLB of 32 entries or more holds them all, and one of 16 misses every time. Large pages raise the reach: one megapage entry covers as much as 1,024 small ones.
A context switch changes satp, and with it every translation. Without tags the kernel must flush the whole 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, 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 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, from the file for a page of code or of a mapped file, from the swap area for a page 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, written back to disk first if it is dirty. Which page? The choice is a replacement policy, as for a cache, but page faults cost so much that the kernel can afford to think. LRU, recalled above, applies to pages unchanged.
Definition 11.5 (Optimal replacement, clock algorithm, second-chance bit)
Optimal replacement (OPT) evicts the page 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 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). LRU needs a timestamp on every access, which only the hardware could keep. Clock needs one bit per page, which the hardware sets for free: it is the A bit of the page-table entry. It approximates LRU: a page used since the hand last passed survives one more turn.
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
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
$ 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
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 frames than with . A policy is a stack algorithm if, on every reference string and at every moment, the set of pages it holds with frames is contained in the set it holds with frames.
Theorem 11.7 (Stack algorithms have no anomaly)
A stack algorithm never makes more faults with frames than with , on any reference string.
Proof. A reference that hits with frames finds its page among the pages held with frames, hence, by inclusion, among those held with : it hits there too. So the faults with frames are among the faults with . ∎
LRU is a stack algorithm: with frames it holds the pages most recently used, which are among the most recently used (exercise 11.10 writes the proof in full). OPT is one too. FIFO is not: after 1 2 3 4 1 2 5, FIFO holds with 3 frames and with 4. Stack algorithms 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 , for a window , is the set of pages it used during the last references. Thrashing is the collapse of a system whose processes do not all have their working sets in memory: each evicts pages another will need at once, and the machine spends its time on page faults instead of work.
The second string of Output 11.4 shows the cliff in miniature: a loop over 5 pages 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 is not a better policy but fewer processes: the kernel suspends some until the working sets of the others fit. Peter Denning proposed the 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 between two address spaces, 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: loads read the file, and stores, in a shared mapping, change it.
fork copies the address space of a process; copying every page would make it slow and, when the child replaces its program at once, useless. Linux implements fork with copy on write: what it duplicates is the page tables. Listing 11.8 measures it with the count of minor page faults, the faults served without any disk activity, that getrusage keeps for each process.
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;
}
$ 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
The parent’s 4,097 faults are its 4,096 pages, 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, and each fault copies one page. The parent still reads 1: the child’s writes went to its own copies.
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 are filled from the file on first touch, and a store to a page marks it dirty; the kernel writes dirty pages back to the file, at the latest when msync asks it to.
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;
}
$ 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.
read, holds the stores.The same mechanism loads programs: the kernel maps the program file’s code pages, 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 model in May 1968. Belady, Nelson and Shedler described the anomaly in June 1969, and Mattson, Gecsei, Slutz and Traiger the stack algorithms in 1970.
11.6 Exercises
Exercise 11.1 ★
Split the Sv32 virtual address 0x7ffff123. In the process of Listing 11.3 (root in frame 1, the stack page in frame 6, its level-0 table in frame 7), which two entry addresses does the walk read, and what is the physical address?
Solution
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 , which points to frame 7, then the entry at , a leaf for frame 6. The physical address is 0x06123 (demo_test.c).
Exercise 11.2 ★
A memory access takes 80 ns, a TLB lookup no extra time, and a 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
Solution of Exercise 11.2.
The average is ns: 81.6 ns at 99 % (2 % slower), 80.16 ns at 99.9 %. The slowdown stays under 5 % when %.
Exercise 11.3 ★
Count the faults of LRU with 3 frames on 7 0 1 2 0 3 0 4 2 3.
Solution
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 adds the line translate(root, 0x10001000, 'r', &pa);. Predict what it prints.
Solution
Solution of Exercise 11.4.
VPN[1] is 0x040, as for the data page, so the root entry exists; VPN[0] is 0x001, an entry of the data page’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
Exercise 11.5 ★★
A first version of sv32.c defined its index as below. Loads from the first kilobyte of a mapped page work; a load from 0x10000abc faults although the page 0x10000000 is mapped. Explain, and fix it.
#define VPN(va, i) ((i) == 1 ? (va) >> 22 : ((va) >> 10) & 0x3ff)
Solution
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 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 onto overlapping indices, so it could map one page over another: an index must be built from the page number alone.
Exercise 11.6 ★★
Write clock with a dirty bit: references are (page, 'r' or 'w'); to evict, the hand first looks, over one full turn and changing nothing, for a page neither used nor dirty; failing that, over one more turn, for a page 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 does it evict, and which does plain clock evict?
Solution
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 that is neither used nor dirty; the second clears the three bits and finds none unused; the next first turn finds page 2, unused and clean, and evicts it. Plain clock clears the bits and evicts page 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
Solution of Exercise 11.7.
Let be any policy. We build policies , , , …, where makes the same choices as OPT on the first references and never more faults than ; then is OPT on a string of length , with no more faults than .
Given , suppose that at reference it faults and evicts where OPT evicts ; both were in memory, and ’s next use is not before ’s. evicts and then copies ; their memories differ only by (held by ) against (held by ). While they differ: a reference to a common page hits in both; a reference to a page in neither faults in both, and if evicts , evicts and the memories become equal, otherwise both evict the same page. cannot be referenced before . When is referenced, faults and does not; if evicts the memories are equal, and if it evicts another page , evicts too and loads at once, a load that ’s fault pays for. From then on the two are identical, and has made no more faults.
The load of before it is requested is a prefetch; a policy that prefetches can always be changed into one that loads each page only when requested, with no more faults: postpone each load until the page is requested, and skip it if the page 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 of Sv32 page tables does it need?
Exercise 11.9 ★★
In Listing 11.8, the child first writes every other page, then reads every page, then writes every page. Predict the three counts of minor faults.
Solution
Solution of Exercise 11.9.
2,048 faults for the writes to every other page, each copying a page; none for the reads, since every page is mapped, shared or copied; 2,048 for the second writes, to the pages still shared. cow_test.c runs the same three phases on 1,024 pages and finds 512, 0 and 512 (it allows up to 4 faults more for the program’s own pages).
Exercise 11.10 ★★★
Prove that LRU is a stack algorithm.
Solution
Solution of Exercise 11.10.
Keep the list of the pages 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 frames holds exactly the first pages of the list (all of them, if there are fewer). Before any reference both are empty. Let page be referenced. If is among the first , LRU hits, and moves to the front: the first are the same pages. Otherwise LRU faults; if its frames are full, it evicts the page used least recently among those it holds, the -th of the list, and loads , which goes to the front: LRU now holds and the old first , which are the new first . Hence the pages held with frames, the first of the list, are among the first : LRU is a stack algorithm (test_lru_is_a_stack_algorithm checks the inclusion at every step of 300 random strings).
Exercise 11.11 ★★★
For any , build a reference string on which clock makes about times as many faults as LRU with the same number of frames (you choose it).
Solution
Solution of Exercise 11.11.
Take frames and hot pages , used in order after each new page that is used once: , then for every round , page followed by . LRU holds the hot pages for good, and each new page evicts the previous one, the least recently used: one fault per round. Clock alternates. When a new page arrives and every bit is set, the hand clears all the bits in one turn and evicts the page under it. If that is a hot page, it is about to be used: its fault evicts the next frame, whose bit is now clear, another hot page used soon after, and so on, so the whole round faults, faults. The next round’s new page then evicts the previous new page and the hot pages hit: one fault. Two rounds cost faults under clock against 2 under LRU. Over rounds the counts are and , a ratio that tends to (test_exercise_11_clock_k_times_worse, with and ).
Exercise 11.12 ★★★
Sv39 translates 39-bit virtual addresses with 4 KiB pages through three levels of tables of entries of eight bytes, and also allows 2 MiB megapages and 1 GiB gigapages. Compute the TLB reach of 64 entries with each page size, and the pages of tables needed to map a 1 GiB array aligned on 1 GiB with small pages, with megapages, and with one gigapage. Compare with Sv32 in Output 11.2.
Solution
Solution of Exercise 11.12.
Reach of 64 entries: KiB = 256 KiB; with 2 MiB megapages, 128 MiB; with 1 GiB gigapages, 64 GiB. A table of 512 entries maps KiB = 2 MiB at level 0, MiB = 1 GiB at level 1. The array with small pages: 262,144 entries in 512 level-0 tables, one level-1 table and the root, 514 pages, about 2 MiB, 8 bytes per page mapped. With megapages: 512 leaves in one level-1 table, plus the root, 2 pages. With a gigapage: one leaf in the root, 1 page. Sv32 needed 257 pages for the same array, 4 bytes per page: Sv39 entries are twice as large, the price of a larger address space, and large pages 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.
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
$ 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
Part I — FIFO by hand.
- 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.
- Do the same with 4 frames.
- From which reference on does the 4-frame run hold pages the 3-frame run has evicted, and which references then fault only with 4 frames?
- Clock makes the same counts in Output 11.4. Why does clock behave exactly as FIFO on this string with 3 frames?
- Run OPT by hand with 3 frames: which page does it evict at each fault?
- What is the fewest faults any policy can make on this string, whatever the number of frames, and why?
Part II — The stack property.
- Give FIFO’s pages with 3 and with 4 frames after 1 2 3 4 1 2 5. Is the inclusion of the definition true?
- Give LRU’s pages at the same moment.
- Show that the inclusion at every moment implies that every hit with frames is a hit with .
- Can clock be a stack algorithm? Answer from Output 11.4.
- LRU holds the pages most recently used. Describe FIFO’s pages in the same way, and say why that description depends on .
- 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.
- Why may the search consider only strings in which page first appears after page ?
- The numbers of strings are 1, 2, 5, 15, 52, …: check the first four by listing the strings.
- What is the length of the shortest anomalous string for FIFO with 3 and 4 frames, and how many pages does it use?
- How many anomalous strings of that length are there, and what do they share?
- Some anomalous strings use 6 or 7 pages. What do the extra pages do?
- What does the LRU column show, and why is that no surprise?
- 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.
- Prove Theorem 11.7 from question 9.
- Deduce that LRU never shows the anomaly, using exercise 11.10.
- Why does the search not prove that FIFO has no anomaly with 2 and 3 frames?
- Why does FIFO fail to be a stack algorithm, in one sentence?
- Clock shows the anomaly, yet kernels use clock rather than LRU. Why?
- Sum up: which policies can show the anomaly, how short can an anomalous string be, and why can LRU never show one?
Solution
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: and . 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: references 8, 9 and 12 fault only with 4 frames, 10 and 11 in both. Two extra faults against three.
4. Pages 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 loaded earliest. Clock departs from FIFO only when the hand passes over a set bit and evicts a later page. Here, at every fault, either all the bits are set, so the hand clears them in one turn and evicts the page under it, or the page under the hand has its bit clear: clock evicts the oldest page 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 faults at its first use, whatever the policy, and 5 frames achieve it.
7. with 3 frames, with 4: page 1 is in the first and not in the second, so the inclusion fails.
8. and : included.
9. A reference at time hits with frames when its page is in the set held with frames just before it; that set is contained in the set held with , so the page 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.
11. FIFO holds the pages most recently loaded. But which references load a page depends on : 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’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 frames as the number of references at a distance greater than , for every , in one pass.
13. The policies only compare pages for equality, so renaming the pages one to one changes no fault. Each class of strings equal up to renaming has exactly one member that names its pages 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. No string of length 11 or less is anomalous, with any number of pages.
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 used only once faults in both runs, and FIFO evicts the oldest page 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 and exercise 11.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 strings of length at most 12 in all: a few million steps.
20. By question 9, every hit with frames is a hit with , so the faults with are among the faults with : .
21. LRU is a stack algorithm (exercise 11.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 by when they were loaded, and with more frames some pages are not reloaded, so the order, and with it the pages 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 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, cannot show it: with frames it holds the first pages of a list that does not depend on , so every hit with fewer frames is a hit with more.
本章定义的术语
- Belady’s anomaly, stack algorithm
- Copy on write, memory-mapped file
- Optimal replacement, clock algorithm, second-chance bit
- Page fault, demand paging
- Page, page frame, page table, page-table entry, multi-level page table
- Translation lookaside buffer, TLB reach, address-space identifier
- Virtual memory, address space, virtual and physical addresses
- Working set, thrashing