Act VI · One Machine, Many Programs
Part 32 of 61Virtual Memory
How does every program get a huge private memory when the machine has only one, and a finite one?
Two PebbleOS processes store their pid at the same virtual address, 0x405004, and each reads back its own: the two stores went to different physical addresses. The part builds the machinery behind that. Base and bounds and segments relocate and protect but fragment memory; paging cuts both spaces into equal pages, and the page table becomes a radix tree that the hardware walks and the TLB caches, measured on this machine as a staircase. Because memory is finite some page must leave: Belady's OPT is proved optimal by an exchange argument, FIFO on Belady's string faults 9 times with 3 frames and 10 with 4, and LRU's stack property rules that anomaly out. Working sets and thrashing follow on the Job's trace. The part then turns from scarcity to what a level of indirection buys: copy-on-write fork, the zero page and mmap, the kernel mapped into every address space, buddy and slab allocators, trap-and-emulate virtual machines with the 24-reference nested walk, and containers. It ends with PebbleOS gaining an MMU: 46 more kernel instructions, a store into code killed with exit -15, and the Job's pipeline running unchanged under demand paging.
What you need. Binary and hexadecimal arithmetic; pointers in C. The caches of Part 9 and the process of Part 31 are assumed.
- Mathematics, ideas and history
- paging, multi-level tables, the TLB, Belady's OPT and anomaly, working sets, copy-on-write, hypervisors, nested paging, containers
- What we build or compute
- Pebble's MMU; page replacement on real traces
What you will be able to do
Degree
- Split a virtual address into table indices and offset, walk a two-level page table by hand, and say which PTE bit stops which access.
- Replay a reference string through FIFO, LRU and OPT, count the faults, and exhibit Belady's anomaly.
- Compute an effective access time from a fault rate, and explain copy-on-write fork.
Graduate
- Prove that OPT is optimal by an exchange argument and that LRU has the stack property, and compute a whole LRU miss curve from stack distances.
- Compute the size of flat and multi-level page tables and the reach of a TLB, and count the memory references of a nested walk.
- State the Popek-Goldberg condition and explain how trap-and-emulate runs an unmodified guest.
Research
- Explain why translation reach has fallen behind memory size, and compare direct segments, range TLBs, transparent huge pages and Midgard as answers.
- State the open problems of page placement across CXL memory tiers and of TLB shootdown cost.
Industry
- Choose between a virtual machine and a container for isolation, naming what each shares with the host and the attacks that crossed each boundary.
- Diagnose a slowdown as TLB misses, page faults or thrashing from counters, and decide when huge pages help.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 27 min · Graduate 43 min · Research 48 min · Industry 30 min.
- 0Two programs, one addressDegree1 min
- 1Protection and relocationDegree2 min
- 2Base and bounds, and segmentsDegree2 min
- 3PagingDegree2 min
- 4Multi-level page tablesDegree2 min
- 5The TLBDegree2 min
- 6Page faultsDegree3 min
- 7Which page to evictDegree5 min
- 8Working sets and thrashingGraduate4 min
- 9Copy-on-write, zero pages and mmapDegree2 min
- 10The kernel's own mappingGraduate2 min
- 11Kernel allocatorsGraduate3 min
- 12Virtual machinesGraduate4 min
- 13ContainersIndustry3 min
- 14PebbleOS gains virtual memoryDegree4 min
- 15Frontier: translation reach and memory tiersResearch4 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
Two programs, one addressDegree1 min
Two copies of the same program run on our machine. Each stores its process number at the same address, hexadecimal four oh five, oh oh four. Then each steps aside, so the other can store its number at that very address. Then each reads the address back. Process one finds one, and process two finds two. They used the same address, and two different bytes of memory. Every address a program uses is virtual. The hardware translates it, on every load, store and instruction fetch, through a table the kernel keeps for that process. This part builds that translation into Pebble, and asks what it costs and what it buys.
1Protection and relocationDegree2 min
In Part 31, PebbleOS gave each process its own region of physical memory. The tokenizer was compiled to run at one mebibyte and the job at two, and each program worked only there. That caused four problems. Relocation: a program runs only where it was linked, so a second copy needs a second compile, and fork, which copies a process, is impossible. Protection: the bounds guard one contiguous range, so two processes cannot share a library, and code cannot be read-only. Size: a program can never be bigger than its region. And fragmentation, which the next chapter shows. The fix for all four is the same: give each process its own virtual addresses, and have the hardware translate every one.
The idea came from Manchester. The Atlas computer had a small fast core memory, and a drum six times larger and far slower. Its designers let programs address one large memory, and had the machine move fixed-size pages of five hundred and twelve words between core and drum, automatically, as they were needed. Each page of core had a register holding the number of the page it currently held. An address whose page matched one of them ran at full speed; otherwise the machine trapped and fetched the page. Tom Kilburn and his colleagues called it a one-level storage system, in 1962. Every phone, laptop and server since works the same way, with RAM and flash in place of core and drum.
2Base and bounds, and segmentsDegree2 min
The simplest translation adds a base. The process uses addresses from zero. The hardware first checks each one against a bound, and faults if it is too big. Then it adds the base, the physical address where the kernel put this process. Two registers, one addition and one comparison, and the process can be loaded anywhere, and cannot touch anything outside its range. Part 31 had the bounds; adding the base gives relocation too. Segments generalise it: a separate base and bound for the code, the data, the heap and the stack, so each can grow on its own, and code can be shared. The Burroughs B5000 had segments in 1961, and Intel's 8086 in 1978. Modern x86 processors have all but abandoned them, for a reason the next picture shows.
The trouble with segments is that they come in every size. We simulated a thousand and twenty-four units of memory, with segments of random sizes arriving and leaving, each placed in the first hole big enough. Here is the memory at the end: live segments in colour, holes outlined in red. The first refusal came early: a request for ninety units, when a hundred and thirty-eight were free, but split among eight holes, the largest sixty-three. Over the whole run, two hundred and forty-seven requests were refused. This is the problem of malloc from Part 11, now inside the kernel. Memory can be compacted by moving segments together, but every process must stop while it is copied. The way out is to make every piece the same size. Then any free piece fits any request. That piece is a page.
3PagingDegree2 min
Paging cuts memory into pieces of one size, four kibibytes in our machine, and translates each piece separately. Here is the address from the start of this part, in binary. The low twelve bits are the offset within the page, and pass through untouched. The high twenty bits are the virtual page number, and that is what gets translated. Our hardware splits the page number again, into two ten-bit indexes, for the two levels of table you will see in a moment. And because every frame of physical memory is the same size, any free frame can hold any page. Fragmentation between pieces is gone; at most part of the last page of each region is wasted.
Each entry in a page table is one word. The top twenty bits name the physical frame. The low bits are flags. Valid means the page is mapped at all. Read, write and execute say what may be done with it, so code can be execute-only and data never executed. User says whether a user-mode program may touch it. And two bits are set by the hardware itself: accessed, on every use, and dirty, on every write. The kernel reads them back. Accessed tells it which pages are in use, which chapter seven needs; dirty tells it which pages must be written to disk before their frame is reused.
Now the walk itself, done in hardware on every access that misses the cache of chapter five. The control register p-t-b-r holds the physical address of the current process's first-level table. The first ten bits of the address pick an entry there, which points to a second-level table. The next ten bits pick an entry in that, which names the frame. Add the offset, and that is the physical address. The two processes use the same indexes, but their tables, built by the kernel, point to different frames, so the same address holds one in one process and two in the other. Entry zero of every first-level table is the same: it maps the kernel, as chapter ten explains.
4Multi-level page tablesDegree2 min
Why two levels? A flat table, one entry for each of the million pages in a thirty-two-bit address space, would need four mebibytes per process, almost all of it saying not mapped. Instead the table is a tree. The first level has a thousand and twenty-four entries, each covering four mebibytes. In our processes only two are used: entry zero maps the kernel with one large page, and entry one points to the process's second-level table. That table has entries for the pages actually mapped. Each level resolves ten bits of the page number, like the tries of Part 21. An empty first-level entry covers four mebibytes with no second-level table at all. So our process needs eight kibibytes of table instead of four mebibytes. The price is a memory read per level on every translation.
Real machines go deeper. For our thirty-two-bit addresses, a flat table would be four mebibytes. For x86-64's forty-eight bits, five hundred and twelve gibibytes, per process. So x86-64 uses four levels of nine bits each, with five hundred and twelve eight-byte entries in each four-kibibyte table. Since 2019, servers can use five levels, for fifty-seven-bit addresses, so a miss in the translation cache can cost five memory reads before the real one. Some designs invert the table instead, with one entry per physical frame, found by hashing the virtual page number; PowerPC and Itanium did this.
5The TLBDegree2 min
The translation lookaside buffer. A walk costs two extra memory reads in our machine, and up to five on a modern one, for every single access. The fix is a small cache of recent translations, the translation lookaside buffer, which IBM's 360 model 67 had in 1967. We ran the Job as two processes under paged PebbleOS, with TLBs of different sizes. With four entries, three and a half percent of accesses miss and need a walk. With eight, under one percent. With sixteen, one access in eleven thousand: the working set of both programs fits. But every context switch writes a new page-table root, and our hardware then flushes the TLB. Switching every five hundred instructions, the misses rise eightfold. Tag each entry with the address space it belongs to, an address-space identifier, and the entries survive the switch: forty-three misses instead of five hundred and eight. Real processors have two levels of TLB, with tags, which x86 calls process-context identifiers.
On this machine we can watch the TLB from outside. A program follows a chain of pointers through more and more pages, touching one cache line in each, and we time each step. Up to sixty-four pages, each step takes under two nanoseconds: every translation is in the first-level TLB. Past sixty-four, the time jumps: the second-level TLB is slower. Far past it, the steps climb as walks begin, and the caches themselves fill. At sixty-five thousand pages, a step takes about a hundred nanoseconds. Now repeat with two-mebibyte pages. The program touches exactly the same cache lines, but each TLB entry now covers five hundred and twelve times more memory, and the step falls to under sixty nanoseconds. That is why databases and virtual machines ask for huge pages, and why Linux builds them automatically where it can.
6Page faultsDegree3 min
What happens when a program touches a page that is not mapped? It executes a store. The TLB has no entry, so the hardware walks the table, and finds the entry not valid. It traps, with cause fifteen and the address in t-val. The kernel checks that the address lies inside the process's memory, and takes a free frame. It fills the frame: with zeros for a new page of heap or stack, or with data read from the disk. It writes the entry, and returns with e-ret to the very same store, which now succeeds. The faulting instruction never happened, so it can simply happen again. This is demand paging: map nothing until it is touched. PebbleOS now does it. A program that touches sixteen new pages of heap takes sixteen faults, each about three thousand three hundred kernel instructions, nearly all of them writing the zeros.
When memory is full, a fault must first free a frame, and the page in it has to go somewhere. The dirty bit from chapter three decides where. A clean page, unchanged since it was read from a file, can simply be dropped: if it is needed again, it is read again. A dirty page must be written out first, and a page of heap or stack has no file at all, so it goes to swap space, a partition or file set aside for exactly this. That doubles the cost of the fault. On the Job's trace, with eight frames under LRU, forty-four percent of evictions are dirty. So kernels do not wait for the fault. A page-out daemon, kswapd in Linux, writes dirty pages back in the background, in batches, and keeps a pool of free frames ready, so that a fault only has to read.
How much does a fault cost? On this machine, touching a page that is already mapped takes twenty-five nanoseconds. The first touch of a brand-new page, a fault plus zeroing four kibibytes, takes almost two microseconds. A fault that must read from storage is far worse: around a hundred microseconds from flash, and eight milliseconds from a spinning disk. So the average cost of a memory access depends on how often it faults. With a disk, one fault in a thousand accesses makes memory eighty times slower. Even one in a million adds eight percent. A system that pages to disk is usable only while faults are rarer than one in a million, which is why running out of memory feels like falling off a cliff.
7Which page to evictDegree5 min
When memory is full and a fault needs a frame, some page must go. Which one? László Belady showed in 1966 that the best choice is the page whose next use lies farthest in the future. Here it is on the reference string Belady used, with three frames: seven faults, and no policy can do better. The proof is an exchange, like the one for shortest-first scheduling in Part 31. Suppose some schedule, at a fault, evicts a page f, where the optimum would evict e, so f is needed again before e. Change it to evict e, and then copy the old schedule. When f is next requested, the new schedule either hits, or pays the single fault the old one would have paid anyway. So the new schedule is never worse, and agrees with the optimum one step longer. But this optimum needs to know the future. It is a yardstick, not a policy. Real policies guess the future from the past.
The simplest guess is first in, first out: evict the page that was loaded longest ago. Here is the reference string Belady used, with three frames. Each column is one reference; the red dots are faults. Nine faults. Now give FIFO a fourth frame. Ten faults. More memory, more faults. Belady, Nelson and Shedler published this in 1969, and it shocked people, because it means buying memory can make a machine slower. It is rare: we found two such strings in twenty thousand random ones. But it can happen, and some policies cannot do it at all.
A better guess: the past predicts the future. Evict the page used least recently. On Belady's string, least recently used is worse than FIFO at three frames, but never shows the anomaly. The reason is the inclusion property. With k frames, LRU holds exactly the k pages used most recently; with k plus one, the k plus one most recent, which include them. So any reference that hits with k frames also hits with more, and adding memory can never add faults. Algorithms with this property are called stack algorithms, and OPT is one too. We checked five thousand random strings: no anomalies for LRU.
How far from the optimum can LRU be? Take four pages used in a cycle, with three frames. LRU always evicts exactly the page that comes next, so it faults on every single reference. The optimum, knowing the future, faults only once in every three. Over a hundred and twenty references: a hundred and twenty faults against forty-two. With k frames, an adversary can make any deterministic policy fault about k times as often as the optimum. Sleator and Tarjan proved in 1985 that this is the worst: LRU, and FIFO too, are within a factor k of the optimum, and no deterministic policy can promise better. More usefully, give LRU k frames and the optimum only h: the factor falls to k over k minus h plus one, under two when LRU has twice the memory. On the Job's real trace it is better still. With twice the memory, LRU does not merely come within a factor of two. It beats the optimum outright. Real programs are not adversaries.
True LRU would reorder a list on every memory access, far too often for hardware or software. The practical approximation is CLOCK. Each frame keeps the accessed bit the hardware sets. On a fault, a hand sweeps around the frames. A frame whose bit is set gets a second chance: the bit is cleared and the hand moves on. The first frame found with its bit clear is evicted. Nothing happens on ordinary accesses, only on faults. Real kernels refine the idea, and newer policies, 2Q, ARC and LIRS, also defend against a single scan flushing everything useful, as the next chapter shows.
8Working sets and thrashingGraduate4 min
How do the policies compare on a real program? We recorded every memory reference of the Job on a sixteen-kilobyte passage, a hundred and twenty thousand of them, to thirty-nine pages of one kibibyte, and replayed them through each policy at every memory size. With eight frames, the optimum takes twelve thousand faults, LRU twenty-three thousand, and FIFO twenty-nine thousand. LRU sits between the optimum and FIFO, with CLOCK close behind it. And because LRU is a stack algorithm, its whole curve comes from a single pass over the trace, by recording how deep each page is in the recency stack when it is used again: Mattson and his colleagues' trick from 1970, which caches are still sized with. With forty frames everything fits, and only the first touches fault.
Here is that trick worked by hand, on eight references. Keep the pages in a stack, most recently used on top. For each reference, find how deep its page is: that depth is its stack distance. A page never seen before has distance infinity. Then move it to the top. Page b is found at depth two, a at depth three, c at depth four. Now the key fact. LRU with k frames holds exactly the top k pages of this stack, so a reference hits precisely when its distance is at most k. Count the distances greater than k, and you have LRU's misses: eight with one frame, seven with two, five with three, four with four. One pass gives every memory size at once. That is how the whole LRU curve came from a single pass over the Job's trace, and how cache sizes are still chosen.
LRU has a famous weakness. Here is a trace like a database's: twenty hot pages used over and over, and then a scan through sixty pages, used once, again and again. With thirty-two frames, LRU faults on almost every reference, and so does CLOCK. Each scan pushes the hot pages out just before they are needed again, because the scanned pages are more recent. The adaptive replacement cache, ARC, keeps two lists, pages seen once and pages seen twice, and moves the boundary between them as it learns. LIRS ranks pages by the distance between their last two uses, so a page used once never displaces a page used often. Both do far better, and LIRS approaches the optimum.
Peter Denning gave the idea that ties this together. A program's working set at time t is the set of pages it used in the last tau references. Here it is along the Job's trace, for three windows: in any hundred references the Job uses about nine pages, over longer ones it reaches all thirty-nine. Denning's rule for a time-shared machine: keep each running process's working set in memory, and if they do not all fit, run fewer processes.
Break that rule and you get thrashing. We simulated processes sharing sixty-four frames, each with a working set of twenty pages, and each sometimes waiting for ordinary input or output. With more processes, the processor fills the waits with other work, up to half busy with three. But four working sets of twenty do not fit in sixty-four frames. Now every process faults, each fault waits for the one disk, and utilisation falls. At eight processes the processor is almost idle, and the disk never stops: the machine is all paging. Operating systems in the sixties learned to respond by taking whole processes out of memory; Linux, when memory is truly exhausted, kills one.
9Copy-on-write, zero pages and mmapDegree2 min
Fork promises the child a copy of all the parent's memory. Virtual memory lets it keep that promise without copying. Fork copies only the page tables, so both processes point at the same frames, and it marks every page read-only in both. Reading costs nothing. When either process writes a page, the write faults. The kernel sees a page that is shared, not truly read-only, copies it into a fresh frame, maps the copy writable for the writer, and lets the write go ahead. Only pages that are actually written are ever copied. A fork followed at once by exec, the shell's pattern, copies almost nothing. The Mach kernel made this standard in the late nineteen-eighties.
On this machine: a parent using two hundred and fifty-six mebibytes forks in under six milliseconds, because only the tables are copied. Then the child writes one byte in every page. Each first write takes three microseconds: a fault, and a copy of four kibibytes. A second write to the same page takes twenty-six nanoseconds, an ordinary store. Part 31's fork with a gibibyte took thirty-three milliseconds, all of it tables. And a child that writes all its memory still pays for the copy in the end, one fault at a time.
The same machinery, mapping and faulting, serves three more purposes. Memory a process has asked for but never written reads as zeros from one shared frame of zeros, and the first write gives it a private page. m-map puts a file's pages into the address space, so reading the file is just a load; the pages come from the kernel's cache of the disk. Shared libraries, the libc of Part 11, are mapped read-only into every process from the same frames, so a hundred processes hold one copy. The price is that a load from a mapped file can, invisibly, wait for the disk.
10The kernel's own mappingGraduate2 min
Where does the kernel itself live? In every process's address space. The same kernel pages appear in every page table, marked supervisor-only: user mode cannot touch them, but they are always there. So a trap needs no change of page table: the kernel's code and data are already mapped. In our PebbleOS it is entry zero of every first-level table, a single four-mebibyte page. A user program that reads it faults and is killed. And because the process's pages are mapped too, the kernel can copy a process's buffers using the very addresses the process passed it.
In 2018 that arrangement broke. Meltdown, which Part 8 previewed: on many Intel processors, a user-mode load from a kernel address did fault, but only after the out-of-order core had already used the data speculatively. The data leaked through the cache, so the supervisor bit alone no longer kept the kernel secret. The fix was kernel page-table isolation. Each process gets two tables: in user mode almost none of the kernel is mapped, just the few pages that handle the entry. Every system call and interrupt must now switch tables. With address-space tags the switch is cheap; without them, it flushes the TLB each time, and some workloads slowed by a third. This machine's processor reports itself not affected, because newer chips fixed the flaw in hardware, and Linux skips the isolation here.
11Kernel allocatorsGraduate3 min
How the kernel allocates memory for itself. The kernel needs memory too: for page tables, process control blocks, network buffers. It takes it in physical frames, and the classic allocator for frames is the buddy system, from Knowlton in 1965. Memory is kept in blocks whose sizes are powers of two. A request for three pages rounds up to four. There is no free block of four, so the sixteen splits into two eights, and one eight into two fours. The first four is handed out; its halves' partners stay on the free lists. Each block's partner, its buddy, is found by flipping one bit of its address. So freeing is quick: if the buddy is free too, merge, and try again one size up. Fragmentation can never leave two free buddies side by side.
Run it under random traffic: a thousand and twenty-four pages, three thousand steps, each one allocating between one and thirty pages or freeing an earlier block. Blocks split five hundred and eighty-three times and merged five hundred and seventeen times. Not one request was refused: there was always a free block of at least a quarter of the pool, usually half. Chapter two's segments, in the same size of pool, refused two hundred and forty-seven. The price is waste inside the blocks: five pages occupy a block of eight. Linux uses exactly this for physical frames, with eleven sizes, from one page to a thousand and twenty-four, and you can read the free lists in proc buddy-info.
And here are this machine's own free lists, read just now from proc buddy-info. Each bar is one order: single pages on the left, four-mebibyte blocks on the right. There are almost six gibibytes free. Nearly half of it is in the largest blocks, ready to be split for any request, or to become huge pages. And there are only eight free single pages: freed pages almost always find their buddy and merge. On a busy machine that has run for weeks, the high orders run dry. Then a request for a huge page has to wait for compaction: the kernel moves pages around, updating their mappings, to rebuild large free blocks.
But most of what a kernel allocates is small: a socket, an open file, a process control block of a hundred bytes or so. A page each would be absurd. Jeff Bonwick's slab allocator, written for SunOS in 1994, keeps a cache for each kind of object. Each cache carves pages into slots of exactly that size: fifty-six objects of seventy-two bytes in one page. Ten thousand such objects take forty-one megabytes at a page each, and under three quarters of a megabyte in slabs. And Bonwick's second idea: a freed object goes back to its slab still initialised, so the next allocation of that type can skip setting it up. Linux's allocator, called SLUB, descends from it; slab-top shows its caches on any Linux machine.
12Virtual machinesGraduate4 min
Virtual memory gives each process a private memory. The same trick, applied to the whole machine, gives each operating system a private computer. IBM's VM three-seventy did it in 1972. Run the guest kernel, unmodified, in user mode, under a small hypervisor that alone has the real privilege. Whenever the guest kernel does something privileged, such as writing a control register, it traps. The hypervisor performs the operation on a copy of the registers it keeps for that guest, and returns. Popek and Goldberg made the condition precise in 1974. Call an instruction sensitive if it reads or changes the machine's mode, its control state or its devices. Call it privileged if it traps in user mode. If every sensitive instruction is privileged, trap-and-emulate works. Pebble passes: all four privileged instructions, and every touch of the device page, trap in user mode. And when a guest's own process makes a system call, the hypervisor reflects it: it saves the program counter and sets the cause in the guest's virtual registers, as the hardware would, and jumps to the guest kernel.
We built that hypervisor for Pebble, and ran Part 31's kernel under it without changing one instruction. Two processes printing letters: the guest kernel exited to the hypervisor almost six hundred times, mostly to read and write control registers during its context switches. The output is identical to the native run, and so is the number of instructions the guest executed: the guest cannot tell. The Job's pipeline tells a different story. It moves four thousand six hundred bytes through the console device, and almost every exit is a device access, one per byte. That is why real hypervisors offer paravirtual devices, as Xen did in 2003 and virtio does today: the guest knows it is virtual and hands over a whole buffer with a single exit.
The x86, the processor in most computers, failed Popek and Goldberg's test. Robin and Irvine later counted seventeen sensitive instructions that do not trap. One, pop-flags, run in user mode, silently ignores the bit that turns interrupts off, so a guest kernel cannot even tell that it failed. VMware's answer, in 1999, was binary translation: rewrite the guest kernel's code as it runs, replacing the troublesome instructions, while letting user code run directly. Xen's answer, in 2003, was to modify the guest kernel to call the hypervisor openly. Then Intel and AMD added a new mode beneath the kernel, and x86 passed the test. Surprisingly, Adams and Agesen measured the first hardware version as slower than VMware's software, because every exit was so expensive.
Memory needs virtualising too. The guest kernel builds page tables from what it thinks are physical addresses; the hypervisor has its own table from those to the real ones. Modern hardware walks both. Each guest table entry lives at a guest-physical address, so before the hardware can read it, it must walk the host's four levels to find it, and only then read it. Four guest levels times five references, plus four more to translate the final address: twenty-four memory references for one TLB miss, where a native walk takes four. In general, n plus one times m plus one, minus one. Before this hardware existed, hypervisors kept shadow page tables, combining the two, and had to catch every change the guest made to its own tables. Nested paging, from AMD in 2007 and Intel in 2008, ended that, at the price of the two-dimensional walk, which is why huge pages matter even more inside virtual machines.
13ContainersIndustry3 min
A virtual machine is one way to give a program its own world. Each guest brings its own kernel, running on a hypervisor. A container is the other way. There is one kernel, and it simply shows different groups of processes different views: their own process numbers, their own files, their own network and users. A container starts in milliseconds and carries no second kernel. But all the containers on a machine trust the same kernel, and that is the price we will come back to.
On Linux the views are called namespaces. Here is one made on this machine, without any special privilege: a new user namespace and a new process namespace, and a shell inside them. The shell believes it is process number one, and that it is root, user zero. Ask it for the list of processes and it sees three: itself and the two commands it just ran. Outside, this machine is running eighty-two. There are eight kinds of namespace: processes, the file tree, the network, user ids, and four smaller ones. The second ingredient is control groups, which limit how much of each resource a group of processes may use: processor time, memory, the number of processes, and so on. Add a file tree to run in, and you have a container. Docker, in 2013, put the three together in a form everyone could use.
Side by side. A virtual machine boots a kernel, in seconds; a container starts a process, in milliseconds. Each virtual machine holds a whole guest kernel in memory; containers share one kernel and its cache of the disk. But a virtual machine's only door to the host is the hypervisor and its few kinds of exit. A container's door is the whole Linux system call interface, some four hundred and fifty calls. So a single kernel bug can break out of every container. In 2016, Dirty COW, a race in exactly the copy-on-write code of chapter nine, let any process write to files it could only read. The industry's answer is a middle ground: Google's gVisor puts a second kernel in user space, and Amazon's Firecracker builds virtual machines small enough to boot in about a hundred and twenty-five milliseconds. Amazon's serverless functions each run in one.
14PebbleOS gains virtual memoryDegree4 min
Our own machine has had all of this since chapter three. Here is what it took. The hardware: a memory-management unit for Pebble, with the two-level walk, a sixteen-entry TLB, and three new kinds of fault. The boot loader builds one page table per process, with the kernel's superpage in entry zero, the code pages readable and executable, and the data pages readable and writable. The context switch gains two instructions, to load and write the page-table base register, which also flushes the TLB. And the trap handler gains this: a page fault at an address inside the process's range, on a page not yet mapped, gets a fresh frame, zeroed, mapped, and the instruction runs again. Any other fault kills the process, as it did in Part 31. In all, forty-six instructions: the kernel grew from two hundred and eighty-four to three hundred and thirty.
Here is the whole page table of the hook's first process, read out of our machine. The library's code, then three pages of buffers for input and output, then the program's own code, and its data page, holding the cell from the hook. Then two hundred and forty-nine pages that were never mapped, and at the very top, the stack. The bits tell the story. Code is readable and executable, never writable; data is writable, never executable; every page is marked for user mode; and the hardware has set accessed and dirty as the program ran. The output buffer is dirty because the program printed. Seven pages of the two hundred and fifty-six are mapped: twenty-eight kibibytes of memory for a one-mebibyte address space. And the stack sits a whole mebibyte above the code, with nothing in between to pay for: room for both to grow.
Now four processes on one machine. One prints eight letters A. One stores a zero over its own first instruction. Its code page is mapped, but not writable: a store fault, cause fifteen, and the kernel kills it. One loads from an address beyond its memory: a load fault, cause thirteen, killed. And one walks up its heap, touching sixteen new pages. It takes sixteen page faults, each served with a zeroed frame, and prints a G. The console shows only the survivors' output. A write to code is a protection fault; a wild load is outside the process altogether. In both cases the hardware only reports, the kernel decides, and the other processes never notice.
Finally, the pipeline that has run through this series: the tokenizer feeding the Job, as two processes, now each in its own address space. Without paging, Part 31's kernel ran it in five hundred and fifty-eight thousand instructions. Paged, with every page mapped at boot, it takes just twelve more. Paged with zero pages on demand, it takes seven page faults and twenty-two thousand more instructions. The output is identical, byte for byte. So translation itself is almost free: two instructions for the table register at each switch, and the TLB hides the rest. A demand fault costs about three thousand instructions, nearly all of them zeroing. What demand paging buys is memory: the two processes need twenty-four frames instead of a hundred and forty-six, because most of the Job's hash table is never touched.
15Frontier: translation reach and memory tiersResearch4 min
The first frontier is reach: how much memory the TLB can translate without walking. A first-level data TLB of sixty-four entries, with four-kibibyte pages, covers two hundred and fifty-six kibibytes, less than this machine's second-level cache. The second-level TLB, with fifteen hundred entries, covers six mebibytes. A laptop has sixteen gibibytes; a large server, four tebibytes, a million times the reach. Huge pages multiply the reach by five hundred and twelve, or by a quarter of a million. On chapter five's staircase, a pointer chase over two hundred and fifty-six mebibytes took forty percent less time with two-mebibyte pages. But a huge page wastes memory when only a little of it is used, and it needs two mebibytes of contiguous physical frames, which a busy machine's buddy allocator may not have.
Research attacks reach from several sides. Direct segments, in 2013: give a big server's heap one base-and-bounds register, beside ordinary paging. Redundant memory mappings: a small TLB of ranges, each covering a large contiguous extent. Ingens and HawkEye: policies for when the kernel should promote small pages to huge ones, fairly between processes and without bloating memory. Midgard: let the caches work in an intermediate address space, and translate only on the way to memory. And Mosaic pages, in 2023: restrict each page to a few possible frames, chosen by hashing, so one entry can describe several pages. Notice chapter two's segments returning: a large contiguous range is cheap to translate.
The second frontier is that memory is no longer one thing. Beside the DRAM on the processor's own channels, servers can now attach more memory over CXL, a protocol on the PCI Express link, at two or three times the latency. Beyond that, the disk. So the operating system faces chapter seven's question again, with a new twist: not which page to evict, but which pages deserve the fast tier. And it is nearly blind. The kernel learns about use only from the accessed bits, and to read them fresh it must clear them and flush the TLBs of every core. Meta's TPP, in 2023, demotes cold pages to the slow tier and promotes pages that fault there often; it is now part of Linux. Processors can also sample memory accesses in hardware. How accurately, and how cheaply, the kernel can find hot pages that way is an open question.
The third frontier is the foundations. Page tables are themselves memory. The hardware walker reads them with ordinary loads, while the kernel on another core may be changing them, so translation inherits all the difficulties of Part 10's weak memory models. Only in 2022 did Ben Simner and colleagues publish a precise model of how virtual memory behaves on Arm processors, tested against the hardware and agreed with Arm's architects. Changing a mapping means interrupting every core that might have it cached, a TLB shootdown, which costs microseconds each time and limits how fast many-core systems can remap memory. And verified kernels such as seL4 prove their page-table code correct, against a model of the MMU that must itself be trusted.
Six open problems. What should replace the four-level radix tree when memories are measured in terabytes? When should the kernel form huge pages, and when break them, trading TLB misses against wasted memory and the cost of compaction? How can it find the hot pages for tiered memory, with bounded overhead and provable accuracy? How much can a learned predictor improve on LRU, while keeping a guarantee when the predictions are wrong? How can TLB shootdowns scale to hundreds of cores? And can a hypervisor with nested paging be verified, on a processor with a weak memory model? This part's research problem takes a small, computable case of the second.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. Address translation, from Atlas to the four-level radix tree, and a TLB that makes it nearly free. Page faults, demand paging, and Belady's optimum, his anomaly, and the stack property that rules it out for LRU. Working sets, thrashing, copy-on-write, and the allocators the kernel uses for itself. Virtual machines, from Popek and Goldberg to the nested walk, and containers. And PebbleOS, with an MMU, running every process at the same addresses.
Where this comes back. In Part 33, threads share one address space, which brings races, and the TLB shootdowns we just met. Part 34 adds a disk to PebbleOS, with a page cache and memory-mapped files. Part 35's databases keep their own buffer pool, with their own replacement policy. Part 45 builds the cloud from microVMs and containers. Part 48 meets LRU again, as caches in front of services. And Part 55 attacks memory safety, and the address-space randomisation that defends it.
In practice. Look before you tune: the smaps file of a process, vmstat, and perf's count of TLB misses. Databases and Java virtual machines usually want explicit huge pages, and transparent huge pages can cause latency spikes while the kernel compacts memory. When a process vanishes, the out-of-memory killer's reasons are in the kernel log; put limits on control groups rather than relying on swap. A large process's fork copies its page tables, so spawn helpers early, or use posix-spawn. And remember that containers share one kernel: untrusted code belongs in a virtual machine.
Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: give PebbleOS a copy-on-write fork. The last, marked with a star, is a research problem: deciding, with hindsight, which regions deserve huge pages within a budget of wasted memory, the offline version of the question Ingens and HawkEye answer by heuristics.
Next time, Part 33: Concurrency. Two threads each add one to a counter, and the count goes up by one. Peterson's lock, proved correct, and then broken by the hardware's reordering; locks, semaphores, monitors and deadlock; and the theory of memory models and of which atomic operations can build which. Threads share everything this part worked to keep apart. Part 33, Concurrency.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. In Part 33 threads share one address space, which brings races and TLB shootdowns. Part 34 adds a disk to PebbleOS with a page cache and memory-mapped files, and Part 35's databases keep their own buffer pool. Part 45 builds the cloud from microVMs and containers, Part 48 meets LRU again as caches in front of services, and Part 55 attacks memory safety and address-space randomisation.
Key results
The part's results in one place, for revision.
Try it
Lab 32 · Which page to evict: Belady's anomaly and the stack property
Count page faults on Belady's reference string with 1 to 5 frames under FIFO, LRU and OPT; search random strings for the anomaly; then check on a trace with locality that LRU never gets worse with more frames, that one pass of stack distances gives its whole miss curve, and that OPT is never beaten.
python -m videos.cs.labs 32
needs numpy, scipy, matplotlib · download lab32.py ·
source on GitHubBelady's string, FIFO faults at 1..5 frames 12 12 9 10 5
Belady's string, LRU faults at 1..5 frames 12 12 10 8 5
Belady's string, OPT faults at 1..5 frames 12 9 7 6 5
random strings where FIFO(5) > FIFO(4) 2 of 20,000 (the film, seed 0: 2)
of 1,500 random strings, LRU or OPT worse with more frames 0 (the stack property: 0)
LRU miss curve, 24 sizes one pass of stack distances = 24 simulations: True
locality trace, faults with 8 frames FIFO 797 LRU 453 OPT 313
4 pages in a cycle, 3 frames, 120 references LRU 120 OPT 42 (the film: 120 and 42)
FIFO can fault more with more memory; LRU and OPT cannot, because the pages held with k frames are always a subset of those held with k + 1, and that same fact gives every LRU size in one pass.
The code (96 lines; it asserts its own result)
"""Lab 32: replay reference strings through FIFO, LRU and OPT, and find Belady's anomaly."""
from videos.coursekit import labs # noqa: I001 (first, so the library imports without manim)
import random
import numpy as np
from explainer.cs.os import paging as P
TITLE = "Which page to evict: Belady's anomaly and the stack property"
GOAL = ("Count page faults on Belady's reference string with 1 to 5 frames under FIFO, LRU and OPT; search random "
"strings for the anomaly; then check on a trace with locality that LRU never gets worse with more "
"frames, that one pass of stack distances gives its whole miss curve, and that OPT is never beaten.")
TASKS = [
"Add 'clock' and 'arc' to the right panel. Which one tracks LRU, and where does either beat it?",
"Search strings of length 12 over 5 pages going from 3 to 4 frames (P.anomalies(12, 5, 3, rng)). Do you find any?",
"Set the hot-set probability to 0.5 and to 0.99. How does the knee of the miss curve move, and why?",
]
BELADY = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
POLICIES = (("fifo", labs.RED), ("lru", labs.BLUE), ("opt", labs.GREEN))
def locality_trace(rng, n=4000, pages=40, hot=6, p_hot=0.9, phase=400):
"""A hot set of `hot` pages that moves every `phase` references; the other references go anywhere."""
out, base = [], 0
for i in range(n):
if i % phase == 0:
base = int(rng.integers(0, pages))
out.append((base + int(rng.integers(0, hot))) % pages if rng.random() < p_hot else int(rng.integers(0, pages)))
return out
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. Belady's string (Chapter 7)
sizes = [1, 2, 3, 4, 5]
table = {p: P.curve(BELADY, sizes, p) for p, _ in POLICIES}
for p, _ in POLICIES:
lab.row(f"Belady's string, {p.upper()} faults at 1..5 frames", " ".join(str(f) for f in table[p]))
assert (table["fifo"][2], table["fifo"][3]) == (9, 10), "FIFO: 9 faults with 3 frames, 10 with 4"
assert all(a >= b for a, b in zip(table["lru"], table["lru"][1:])), "LRU has no anomaly"
# 2. how rare the anomaly is, and that LRU and OPT never show it
found = P.anomalies(20, 6, 4, random.Random(seed + 6), trials=20000) # length 20, 6 pages, 4 against 5 frames
lab.row("random strings where FIFO(5) > FIFO(4)", f"{len(found)} of 20,000 (the film, seed 0: 2)")
assert all(P.faults(s, 5, "lru") <= P.faults(s, 4, "lru") for s, _, _ in found)
worse = 0
for _ in range(1500):
s = [int(x) for x in rng.integers(0, 6, 20)]
fifo, lru, opt = (P.curve(s, range(1, 7), p) for p in ("fifo", "lru", "opt"))
worse += any(b > a for a, b in zip(lru, lru[1:])) or any(b > a for a, b in zip(opt, opt[1:]))
assert all(o <= min(f, r) for o, f, r in zip(opt, fifo, lru)), "OPT is never beaten"
lab.row("of 1,500 random strings, LRU or OPT worse with more frames", f"{worse} (the stack property: 0)")
assert worse == 0
# 3. Mattson's one pass against a simulation at every size, on a trace with locality
trace = locality_trace(rng)
ks = list(range(1, 25))
one_pass = P.lru_curve(trace, ks)
direct = P.curve(trace, ks, "lru")
lab.row("LRU miss curve, 24 sizes", f"one pass of stack distances = 24 simulations: {one_pass == direct}")
assert one_pass == direct
curves = {"fifo": P.curve(trace, ks, "fifo"), "lru": direct, "opt": P.curve(trace, ks, "opt")}
lab.row("locality trace, faults with 8 frames", " ".join(f"{p.upper()} {curves[p][7]:,}" for p, _ in POLICIES))
assert all(o <= min(f, r) for o, f, r in zip(curves["opt"], curves["fifo"], curves["lru"]))
# 4. Sleator and Tarjan: LRU with k frames against OPT with h, and the cyclic worst case
cyc = [i % 4 for i in range(120)]
lab.row("4 pages in a cycle, 3 frames, 120 references", f"LRU {P.faults(cyc, 3, 'lru')} OPT {P.faults(cyc, 3, 'opt')}"
" (the film: 120 and 42)")
assert P.faults(cyc, 3, "lru") == 120 and P.faults(cyc, 3, "opt") == 42
for h in (2, 4, 8):
k = 2 * h
assert curves["lru"][k - 1] <= k / (k - h + 1) * curves["opt"][h - 1] + h, "the competitive bound"
lab.note = ("FIFO can fault more with more memory; LRU and OPT cannot, because the pages held with k frames "
"are always a subset of those held with k + 1, and that same fact gives every LRU size in one pass.")
fig, ax = labs.figure(2, size=(11, 4.2))
for p, c in POLICIES:
ax[0].plot(sizes, table[p], "o-", color=c, label=p.upper())
ax[0].annotate("more memory,\nmore faults", (4, 10), (4.15, 11.2), color=labs.RED, fontsize=9,
arrowprops=dict(arrowstyle="->", color=labs.RED))
ax[0].set(title="Belady's string 1 2 3 4 1 2 5 1 2 3 4 5", xlabel="frames", ylabel="page faults", xticks=sizes,
ylim=(4, 12.6))
ax[0].legend()
for p, c in POLICIES:
ax[1].plot(ks, curves[p], color=c, label=p.upper())
ax[1].plot(ks[::2], one_pass[::2], "o", color=labs.GOLD, ms=4, label="LRU from stack distances")
ax[1].set(title="4,000 references with a moving hot set of 6 pages", xlabel="frames", ylabel="page faults",
yscale="log")
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Add 'clock' and 'arc' to the right panel. Which one tracks LRU, and where does either beat it?
- Search strings of length 12 over 5 pages going from 3 to 4 frames (P.anomalies(12, 5, 3, rng)). Do you find any?
- Set the hot-set probability to 0.5 and to 0.99. How does the knee of the miss curve move, and why?
Problems, with solutions
Try each problem before opening its solution.
-
OPT is optimal. Prove by an exchange argument that Belady's OPT (on a fault, evict the page whose next use is farthest in the future) minimises the number of faults.
Solution
Let S be any schedule that agrees with OPT on the first j requests. We build S′ that agrees with OPT on the first j + 1 requests and has no more misses than S. If request j + 1 hits, or S and OPT evict the same page, take S′ = S. Otherwise the request misses, S evicts f and OPT evicts e, so by OPT's choice f is requested again before e. Let S′ evict e, and from then on copy S. The two memories differ only in that S′ holds f where S holds e, until the first request y at which one of these happens:
- y is neither e nor f, and S evicts e. Then S′ evicts f, and the memories are equal at the same cost.
- y = f (this must come before any request for e). S′ hits; S misses and evicts some page x. If x = e, the memories are now equal and S′ has one miss fewer. Otherwise S′ evicts x and loads e, which costs it one miss, as S paid one; the memories are equal.
A request for e cannot come first, since f is requested before e. In every case S′ has no more misses than S, and agrees with OPT on j + 1 requests. (S′ may load a page that was not requested, but any such schedule can be rewritten to load pages only on demand without adding misses.) By induction on j, OPT has no more misses than any schedule. This is the farthest-in-future argument of Belady (1966), in the form of Kleinberg and Tardos's Algorithm Design, §4.3.
-
LRU's stack property. Prove that LRU has the stack property, so it has no anomaly; show that FIFO's three- and four-frame memories are not nested on Belady's string.
Solution
With k frames, after any prefix of the requests, LRU holds exactly the k distinct pages most recently used (fewer if fewer have been used): it evicts the least recent, and keeps every other. The k most recent are among the k + 1 most recent, so M_k(t) ⊆ M_{k+1}(t) at every time t. A hit with k frames is therefore a hit with k + 1, and faults can only fall as frames are added. This is Mattson's inclusion property, and it is what lets one pass of stack distances give LRU's whole miss curve.
FIFO, on 1 2 3 4 1 2 5 1 2 3 4 5: after the seventh request (5), three frames hold {1, 2, 5} and four frames hold {2, 3, 4, 5}. Page 1 is in the smaller memory and not the larger, so the next request (1) hits with three frames and faults with four. In all, FIFO faults 9 times with three frames and 10 with four.
-
The nested walk. Derive (n + 1)(m + 1) − 1 for the nested walk, and the count when a walk cache holds every upper level of both tables.
Solution
A guest walk reads n guest entries. Each lives at a guest-physical address, which the hardware must translate through the host's m levels (m references) before reading it (1 reference): m + 1 references per guest level. The guest walk ends with the guest-physical address of the data, which needs one more host walk of m references. So n(m + 1) + m = nm + n + m = (n + 1)(m + 1) − 1; for 4 and 4, 24. The grid picture: n + 1 rows (n guest entries and the data) times m + 1 columns (m host entries and the read), less the final read of the data itself, which is not part of translation.
With a cache of every non-leaf entry of both tables, and of the host translations of the guest's table pages (AMD's nested TLB), a miss reads only the guest's leaf entry (1 reference, its host address already known) and then the host's leaf entry for the data's guest-physical page (1 reference): 2, against 1 for a native walk with a walk cache. Real walk caches are small, so measured nested misses fall between these bounds (Bhargava et al., 2008).
-
Buddy waste. Show that a buddy block is always more than half used, and find the expected waste for request sizes uniform on 1..2^k.
Solution
A request of s pages, 2^{j−1} < s ≤ 2^j, gets a block of 2^j, and s > 2^{j−1} = 2^j/2; for s = 1, the block is exactly 1. So every block is more than half used (or full). For s uniform on 1..2^k: the sizes in (2^{j−1}, 2^j] waste 2^j − s, which runs from 2^{j−1} − 1 down to 0, an average of (2^{j−1} − 1)/2 over 2^{j−1} sizes. Summing, the total waste is ½ ∑_{j=1}^{k} (4^{j−1} − 2^{j−1}) = ½[(4^k − 1)/3 − (2^k − 1)], so the expected waste is about 2^k/6 pages. The expected request is (2^k + 1)/2, so a block's expected size is about 2^k · 2/3, and the waste is about a quarter of the memory allocated (a third of what was asked for). For k = 10, exactly 170.2 pages wasted on average, 24.9% of what is allocated.
-
Build: a copy-on-write fork for PebbleOS. Share frames read-only, copy on the store fault, and count the copies.
Solution
- Add
sys_fork: take a free PCB, copy the parent's registers and set the child'sa0to 0; take a root and an L2 frame; copy the root's two entries (the kernel's superpage and the pointer to the new L2). - Copy the parent's L2 entries into the child's L2, clearing W in both and setting a software bit COW (bit 8, the RSW field Pebble's MMU ignores) on every entry that was writable. Keep a reference count per frame, in a kernel array indexed by frame number, and increment it for each shared frame.
- Write the parent's
ptbragain, to flush its stale writable translations from the TLB. - In
pfault: a store fault (cause 15) on a valid entry with COW set is not a protection error. If the frame's count is 1, set W, clear COW and retry. Otherwise take a frame, copy 4 KiB, map it W in this process, decrement the old frame's count, count the copy (ncow), and retry. - Test: a parent fills 16 pages, forks, and the child writes 4 of them. The child sees the parent's data, each
process sees its own writes, and
ncow= 4. For fork followed at once by exit,ncow= 0, except for the stack page the call itself writes.
- Add
-
★ Research: offline huge-page promotion. Given a trace, a TLB of k entries and a budget of wasted frames, choose the aligned regions to promote to huge pages. Is it NP-hard? How close is greedy on the Job's trace?
Where to start.
- The model. A region is promoted whole: it costs (region size − pages of it the trace touches) wasted frames, and
all its pages share one TLB entry. The objective is the number of misses of an LRU TLB with k entries on the
trace of entries (each reference mapped to its region if promoted, else to its page). Measure it with
explainer/cs/os/paging.faults(trace, k, "lru"). Scale the Job's 1 KiB-page trace fromcompute._job_traceto regions of 4 or 16 pages, since its address space is only 1 MiB. - Sanity checks. If k is at least the number of entries, only compulsory misses remain, and promotion helps by merging them. With OPT as the TLB's policy instead of LRU, is the problem easier?
- Hardness. The gains are not additive (promoting two regions can help more or less than the sum). If they were, the problem would be a knapsack, weakly NP-hard and solved by dynamic programming in pseudo-polynomial time. Try a reduction from a strongly NP-hard problem through the LRU interaction, for example from a packing problem in which promoted regions must keep the working set under k.
- Algorithms. Greedy by marginal misses saved per wasted frame; compare it with exhaustive search on small instances and with an integer program. A submodularity check (are the marginal gains diminishing?) would give greedy a (1 − 1/e)-style guarantee if it holds, and a counterexample if it does not.
- Literature. Navarro et al., "Practical, transparent operating system support for superpages" (OSDI 2002); Kwon et al., Ingens (OSDI 2016); Panwar et al., HawkEye (ASPLOS 2019); Ram et al., Trident (ISCA 2021).
Deployed systems promote by heuristics. A hardness result, or an algorithm with a provable ratio, for the offline problem would tell them how far from optimal they can be.
- The model. A region is promoted whole: it costs (region size − pages of it the trace touches) wasted frames, and
all its pages share one TLB entry. The objective is the number of misses of an LRU TLB with k entries on the
trace of entries (each reference mapped to its region if promoted, else to its page). Measure it with
Notes and sources
Glossary
虚拟内存 virtual memory · 地址空间 address space · 虚拟地址 virtual address · 物理地址 physical address · 地址翻译 address translation · 重定位 relocation · 基址与界限 base and bounds · 段 segment · 外部碎片 external fragmentation · 内部碎片 internal fragmentation · 页 page · 页框 frame · 页号 page number · 页内偏移 offset · 页表 page table · 页表项 page-table entry · 有效位 valid bit · 访问位 accessed bit · 脏位 dirty bit · 多级页表 multi-level page table · 页表遍历 page-table walk · 超级页 superpage · 大页 huge page · 倒排页表 inverted page table · 快表 TLB · 地址空间标识 ASID · TLB 覆盖范围 TLB reach · TLB 击落 TLB shootdown · 缺页 page fault · 按需调页 demand paging · 交换 swapping · 有效访问时间 effective access time · 页面置换 page replacement · Belady 异常 Belady's anomaly · 栈性质 stack property · 栈距离 stack distance · 时钟算法 CLOCK · 工作集 working set · 抖动 thrashing · 写时复制 copy-on-write · 零页 zero page · 内存映射文件 memory-mapped file · 共享库 shared library · 内核页表隔离 KPTI · 伙伴系统 buddy system · slab 分配器 slab allocator · 虚拟机 virtual machine · 虚拟机监控器 hypervisor · 陷入并模拟 trap and emulate · 敏感指令 sensitive instruction · 二进制翻译 binary translation · 半虚拟化 paravirtualization · 影子页表 shadow page table · 嵌套页表 nested paging · 容器 container · 命名空间 namespace · 控制组 cgroup · 内存分层 memory tiering
Sources
Canon. Books:
- Arpaci-Dusseau & Arpaci-Dusseau, Operating Systems: Three Easy Pieces (OSTEP, v1.10, 2023), virtualisation of memory;
- Tanenbaum & Bos, Modern Operating Systems (5th ed., 2023), ch. 3;
- Gorman, Understanding the Linux Virtual Memory Manager (2004);
- Bhattacharjee & Lustig, Architectural and Operating System Support for Virtual Memory (2017);
- Smith & Nair, Virtual Machines: Versatile Platforms for Systems and Processes (2005).
Papers:
- History: Kilburn, Edwards, Lanigan & Sumner, "One-Level Storage System" (1962); Denning, "Virtual Memory" (Computing Surveys, 1970).
- Replacement:
- Belady, "A study of replacement algorithms for a virtual-storage computer" (1966); Belady, Nelson & Shedler, "An anomaly in space-time characteristics of certain programs" (1969);
- Mattson, Gecsei, Slutz & Traiger, "Evaluation techniques for storage hierarchies" (1970);
- Denning, "The working set model for program behavior" (1968); Carr & Hennessy, WSClock (1981);
- Sleator & Tarjan, "Amortized efficiency of list update and paging rules" (CACM 1985); Fiat et al., "Competitive paging algorithms" (1991);
- Johnson & Shasha, 2Q (1994); Jiang & Zhang, LIRS (2002); Megiddo & Modha, ARC (2003).
- Allocators: Knowlton, "A fast storage allocator" (1965); Bonwick, "The Slab Allocator" (USENIX 1994).
- The kernel's mapping: Lipp et al., "Meltdown" (USENIX Security 2018); Gruss et al., KAISER (2017).
- Virtualisation:
- Popek & Goldberg, "Formal requirements for virtualizable third generation architectures" (CACM 1974);
- Robin & Irvine, "Analysis of the Intel Pentium's ability to support a secure virtual machine monitor" (2000);
- Bugnion et al., "Bringing virtualization to the x86 architecture with the original VMware Workstation" (TOCS 2012); Barham et al., "Xen and the art of virtualization" (SOSP 2003);
- Adams & Agesen, "A comparison of software and hardware techniques for x86 virtualization" (ASPLOS 2006);
- Bhargava, Serebrin, Spadini & Manne, "Accelerating two-dimensional page walks for virtualized systems" (ASPLOS 2008).
- Containers: Kerrisk, "Namespaces in operation" (LWN, 2013); Agache et al., Firecracker (NSDI 2020); Young et al., "The true cost of containing: a gVisor case study" (HotCloud 2019).
- Frontier:
- Basu, Gandhi, Chang, Hill & Swift, "Efficient virtual memory for big memory servers" (ISCA 2013); Karakostas et al., "Redundant memory mappings" (ISCA 2015);
- Kwon et al., Ingens (OSDI 2016); Panwar et al., HawkEye (ASPLOS 2019); Gupta et al., Midgard (ISCA 2021); Gosakan et al., "Mosaic pages" (ASPLOS 2023);
- Maruf et al., "TPP: transparent page placement for CXL-enabled tiered memory" (ASPLOS 2023);
- Simner et al., "Relaxed virtual memory in Armv8-A" (ESOP 2022); Kumar et al., LATR (ASPLOS 2018).
About this partfrom its README
Part 32 of a sixty-one-part course in computer science (see the series plan and the syllabus), and the second part of Act VI, One Machine, Many Programs. Every program believes it owns a huge, private, contiguous memory, and none of them does. Address translation keeps up the illusion with a radix tree that the hardware walks and the TLB caches. Memory is finite, so some page must leave; Belady showed which page is optimal, and that adding memory can make things worse. The same machinery gives copy-on-write fork, shared libraries, virtual machines and containers. Pebble gains an MMU, and PebbleOS runs every process at the same virtual addresses.
The instruments are in explainer/cs/os/ (tested in tests/test_cs32_vm.py):
mmu.py, Pebble's MMU:- an Sv32-like two-level walk (10 + 10 + 12 bits), 4 MiB superpages, and the PTE bits V, R, W, X, U, A, D;
- the
ptbrcontrol register (CSR 9); faults 12 (fetch), 13 (load) and 15 (store) with the address intval; - an LRU TLB of any size, flushed on every write of
ptbrunless address-space tags are on; - counts of hits, misses, walks, memory references per walk, flushes and faults;
vmos.py, PebbleOS with paging:- the boot loader builds a table per process: the kernel's supervisor-only superpage in L1 entry 0, and the process at virtual 4–5 MiB through its own L2 table, code R+X, data R+W;
- the kernel (46 more instructions, 330 in all) switches
ptbrwith the process and serves demand-zero faults; every other fault kills only the offender; - Part 13's compiler gains
target="vm", which page-aligns the data;
virt.py, trap and emulate: Part 31's PebbleOS, unmodified, as a guest in user mode. The hypervisor keeps the guest's virtual mode and control registers, emulatescsrr,csrw,eret,haltand device accesses, and reflects the guest processes' traps;exitscounts its work by kind;paging.py: replacement (OPT, FIFO, LRU, CLOCK, 2Q, ARC, LIRS, random) over any trace; Mattson's stack distances and LRU's whole miss curve in one pass; a Belady-anomaly search; Denning's working set; a thrashing simulator; a buddy allocator and a slab allocator.
The simplified MMU rejects write-without-read PTE encodings and superpage physical bases that are not 4 MiB aligned. With zero resident frames, every reference faults under every replacement policy. Buddy allocation requires a positive page count. The slab example models occupancy only: allocation returns a slab index, not an object address; it tracks free slots without storing object bytes or running constructors.
Measured on this machine (videos/cs/cs32/compute.py compiles and runs a small C program):
- a pointer chase over 1 to 131,072 pages, with 4 KiB pages and with 2 MiB huge pages: the TLB staircase;
- the first touch of a page (a fault) against a mapped page;
forkwith 256 MiB resident, and the child's first and second write to each page;- a new PID and user namespace with
unshare; this process's namespaces and cgroup controllers; - whether this processor is affected by Meltdown.
Chapter notes
- Hook. Two processes store their pid at the same virtual address,
0x405004, and read it back: one sees 1, the other 2. The two physical addresses,0x109004and0x110004. - 1. Protection and relocation.
- What Part 31's PebbleOS could not do: a program linked for one address, a fixed region each, no sharing, nothing larger than memory.
- Atlas (Manchester, 1962): the one-level store, 512-word pages, a drum behind core.
- 2. Base and bounds, and segments.
- Base and bounds, and segment tables.
- First fit over 1,024 units: the first refusal wants 90 units with 138 free in 8 holes, the largest 63; 247 refusals in 4,000 steps. External fragmentation, and Part 11's malloc.
- 3. Paging.
- The address split, animated: L1 index 1, L2 index 5, offset 4.
- The PTE's bits, and who sets each one. The walk of
0x405004in both processes' tables.
- 4. Multi-level page tables.
- The radix tree: one process needs 8 KiB of tables instead of a 4 MiB flat array.
- Flat tables for 32, 48 and 57 bits: 4 MiB, 512 GiB, 256 TiB. x86-64's 9 + 9 + 9 + 9 + 12 and five levels. Inverted and hashed tables.
- 5. The TLB.
- The Job's pipeline under paged PebbleOS: 4 entries miss 3.58% of the time, 8 miss 0.80%, 16 miss 0.009% (63 misses in 712,311 accesses).
- With a switch every 500 instructions, 16 entries: 508 misses flushing, 151 with ASIDs.
- The staircase on this machine: 1.9 ns per access over 64 pages, 4.4 ns over 128, 97 ns over 65,536 pages with 4 KiB pages and 58 ns with 2 MiB pages.
- 6. Page faults.
- A fault end to end; demand paging.
- Where an evicted page goes: clean pages are dropped, dirty ones written to swap. Under LRU with 8 frames, 10,242
of the Job's 23,077 evictions (44%) are dirty;
kswapd. - On this machine: 1,732 ns for a first touch against 25 ns for a mapped page. The effective access time: one fault per million accesses to a disk costs 8%.
- 7. Which page to evict.
- Belady's OPT and its exchange argument.
- Belady's string: FIFO faults 9 times with 3 frames and 10 with 4. Random strings with the anomaly: 2 of 20,000 (length 20 over 6 pages, 4 against 5 frames).
- LRU's stack property, proved; no anomaly in 5,000 random strings.
- How bad can LRU be: 4 pages in a cycle with 3 frames, 120 faults in 120 references against OPT's 42. Sleator and Tarjan (1985): k/(k − h + 1). On the Job's trace, LRU with 2h frames beats OPT with h for h = 2, 4, 8, 16.
- CLOCK's hand.
- 8. Working sets and thrashing.
- The Job's 120,412 references to 39 pages of 1 KiB through every policy; at 8 frames OPT 12,474, LRU 23,085, FIFO 29,363 faults.
- Mattson's stack distances worked by hand on
abcbadca: distances ∞ ∞ ∞ 2 3 ∞ 4 3, so LRU misses 8, 7, 5, 4 with 1 to 4 frames. - A hot set with scans: LRU is flushed, and LIRS and ARC resist.
- Denning's working set along the trace. Thrashing: utilisation peaks at 0.51 with 3 processes and falls to 0.001 at 8.
- 9. Copy-on-write, zero pages and mmap.
- fork without copying, animated.
- On this machine: fork with 256 MiB takes 5.8 ms; the child's first write to a page 3.1 µs, the second 26 ns.
- The zero page,
mmapand shared libraries.
- 10. The kernel's own mapping.
- The kernel in every address space, supervisor-only; a user read of it exits −13.
- Meltdown (2018) and KPTI. This machine: "Not affected".
- 11. Kernel allocators.
- The buddy system: 3 pages from 16 leave free blocks of 4 (at 4) and 8 (at 8).
- Random traffic over 1,024 pages: 583 splits, 517 merges, no refusals, against segments' 247.
- This machine's
/proc/buddyinfo: 5.7 GiB free, 47% of it in 4 MiB blocks, 8 single pages; compaction. - Slab: 10,000 objects of 72 bytes in 0.73 MB instead of 40.96 MB.
- 12. Virtual machines.
- Popek and Goldberg (1974): trap and emulate.
- Part 31's PebbleOS as a guest: identical output and identical guest instruction counts (14,987 and 558,092). The letter-printers make 594 exits, mostly control registers; the pipeline makes 5,127, of which 4,810 are the device: paravirtual devices.
- x86's 17 sensitive unprivileged instructions, binary translation, Xen, VT-x.
- The nested walk: (n + 1)(m + 1) − 1 = 24 references; shadow page tables.
- 13. Containers.
- One kernel, different views: inside
unshare, the shell is pid 1 and uid 0, and sees 3 processes of the host's 82. Eight namespaces, the cgroup controllers. - VMs against containers; Dirty COW (2016); gVisor and Firecracker.
- One kernel, different views: inside
- 14. PebbleOS gains virtual memory.
- What changed: the MMU, the boot loader, two instructions per switch and the fault handler; 284 → 330 kernel instructions.
- One process's page table, read out: 7 of 256 pages mapped (28 KiB), code R X, data R W, A and D set by the MMU.
- Four processes:
goodprints eight A's;codewritedies with exit −15 andwildwith −13;growertakes 16 page faults and prints G. The console:AAAAAAAAG. - The Job's pipeline: 558,092 instructions unpaged, 558,104 paged with everything mapped (146 frames), 580,365 with zero pages on demand (7 faults, 24 frames). The output is identical.
- 15. Frontier: translation reach and memory tiers.
- TLB reach (64 × 4 KiB = 256 KiB; 1,536 × 1 GiB = 1.5 TiB) against 16 GiB and 4 TiB memories.
- Direct segments, range TLBs, Ingens and HawkEye, Midgard, Mosaic pages.
- CXL memory tiers and TPP; relaxed virtual memory on Armv8-A; TLB shootdowns. Open problems. Outro.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- The problem: protection and relocation; Atlas (1962) invents paging.
- Base and bounds; segmentation; external fragmentation (callback to Part 11).
- Paging: VPN | offset split, animated; PTE bits (valid, protection, dirty, accessed).
- Multi-level page tables as a radix-tree walk (x86-64 four and five levels); inverted and hashed tables.
- The TLB, a cache for translations (callback to Part 9): reach, ASIDs, huge pages. The TLB-miss staircase is measured on this machine.
- Page faults: demand paging and swapping; effective access time (why one fault per million accesses matters).
- Replacement:
- Belady's OPT is optimal (exchange argument);
- FIFO and Belady's anomaly (a computed example where more frames give more faults);
- LRU and the stack property, which rules out the anomaly (proved);
- CLOCK and WSClock; 2Q, ARC, LIRS.
- Working sets (Denning 1968) and thrashing; the Job's trace replayed through every policy, with miss curves against frames.
- Copy-on-write fork; zero pages; mmap; shared libraries (callback to Part 11).
- The kernel's own mapping; KPTI after Meltdown (callback to Part 8).
- Kernel allocators: buddy and slab (Bonwick 1994).
- Virtualization:
- Popek–Goldberg (1974) and trap-and-emulate;
- x86's non-virtualizable instructions and VMware's binary translation (1999);
- VT-x and nested paging's 2D walk (up to 24 memory references, derived);
- Xen's paravirtualization.
- Containers: namespaces and cgroups; isolation without a second kernel, and what it costs in security.
- PebbleOS gains virtual memory: two processes at the same virtual address, isolated, and a protection fault caught. Outro.
Computed: page-table walks on Pebble's MMU; Belady's anomaly; OPT, LRU, FIFO, CLOCK and ARC curves on real traces; the TLB staircase on this machine; the nested-walk count. Visuals: address bits walking down a radix tree; frames shuffling to disk and back; the anomaly curve rising; the CLOCK hand sweeping. In practice: hypervisors (KVM, Xen), containers (Docker, cgroups, namespaces), huge pages for databases, OOM debugging. Reading: OSTEP (virtualization of memory); Tanenbaum & Bos ch. 3; Denning 1970; Belady 1966; Belady, Nelson & Shedler 1969; Mattson et al. 1970; Kilburn et al. 1962; Bonwick 1994; Popek & Goldberg 1974; Adams & Agesen 2006; Bhargava et al. 2008; Gorman, Understanding the Linux Virtual Memory Manager.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
OPT 最优。 用交换论证证明:Belady 的 OPT(缺页时换出下一次使用最远的页)使缺页次数最少。
解答
设任意调度 S 在前 j 个请求上与 OPT 一致。构造 S′,使它在前 j + 1 个请求上与 OPT 一致且缺页不多于 S。若第 j + 1 个 请求命中,或 S 与 OPT 换出同一页,令 S′ = S。否则 S 换出 f,OPT 换出 e,由 OPT 的选择,f 在 e 之前会再被请求。令 S′ 换出 e, 此后照搬 S。两者的内存只差在:S′ 持有 f 处 S 持有 e,直到第一个出现下列情况之一的请求 y:
- y 既非 e 也非 f,而 S 换出 e:S′ 换出 f,两者内存相同,代价相同。
- y = f(它必在对 e 的任何请求之前):S′ 命中;S 缺页并换出某页 x。若 x = e,内存已相同,S′ 少一次缺页;否则 S′ 换出 x 并装入 e,付出一次缺页,与 S 相同,内存相同。
对 e 的请求不可能先出现,因为 f 先于 e 被请求。每种情况下 S′ 的缺页都不多于 S,且在 j + 1 个请求上与 OPT 一致。(S′ 可能装入 未被请求的页,但任何这样的调度都能改写为只按需装入而不增加缺页。)对 j 归纳,OPT 的缺页不多于任何调度。这是 Belady(1966) 的“最远未来”论证,写法取自 Kleinberg 与 Tardos《算法设计》§4.3。
-
LRU 的栈性质。 证明 LRU 有栈性质,因此没有异常;并说明 FIFO 在 Belady 串上三帧与四帧的内存不嵌套。
解答
k 帧时,在请求的任意前缀之后,LRU 恰好持有最近使用过的 k 个不同页:它换出最久未用的,保留其余。最近的 k 个包含于 最近的 k + 1 个之中,所以每一时刻 M_k(t) ⊆ M_{k+1}(t)。k 帧时的命中在 k + 1 帧时也命中,缺页只会随帧数增加而减少。这就是 Mattson 的包含性质,也正是它让一遍栈距离就能给出 LRU 的整条缺页曲线。FIFO 在 1 2 3 4 1 2 5 1 2 3 4 5 上:第七个请求(5) 之后,三帧持有 {1, 2, 5},四帧持有 {2, 3, 4, 5}。页 1 在小内存中而不在大内存中,于是下一个请求(1)三帧命中、四帧缺页。FIFO 共缺页:三帧 9 次,四帧 10 次。
-
嵌套页表遍历。 推导嵌套遍历的 (n + 1)(m + 1) − 1,以及遍历缓存持有两张表所有上层时的次数。
解答
客户机遍历读 n 个客户机表项;每个都位于一个客户机物理地址上,硬件必须先经主机的 m 级翻译(m 次访存)再读它(1 次): 每个客户机层级 m + 1 次。遍历最后得到数据的客户机物理地址,还需一次 m 次访存的主机遍历。共 n(m + 1) + m = (n + 1)(m + 1) − 1; 4 与 4 时为 24。网格图:n + 1 行(n 个客户机表项和数据)乘 m + 1 列(m 个主机表项和读取),减去不属于翻译的那次数据读取。 若缓存了两张表的所有非叶表项,以及客户机页表页的主机翻译(AMD 的嵌套 TLB),一次缺失只需读客户机叶表项(1 次,其主机地址已知), 再读数据所在客户机物理页的主机叶表项(1 次):共 2 次,而带遍历缓存的原生遍历为 1 次。实际的遍历缓存很小,实测的嵌套缺失介于 两界之间(Bhargava 等,2008)。
-
伙伴系统的浪费。 证明伙伴块总是用了一半以上,并求请求大小在 1..2^k 上均匀分布时的期望浪费。
解答
大小 s 满足 2^{j−1} < s ≤ 2^j 的请求得到 2^j 的块,而 s > 2^j/2;s = 1 时块恰为 1。所以每块用了一半以上(或全满)。 s 在 1..2^k 上均匀时,(2^{j−1}, 2^j] 中的大小浪费 2^j − s,从 2^{j−1} − 1 降到 0,在 2^{j−1} 个大小上平均 (2^{j−1} − 1)/2。 求和得总浪费 ½[(4^k − 1)/3 − (2^k − 1)],期望浪费约 2^k/6 页。期望请求为 (2^k + 1)/2,块的期望大小约 2^k · 2/3,浪费约为 已分配内存的四分之一(所请求量的三分之一)。k = 10 时,平均恰浪费 170.2 页,占已分配的 24.9%。
-
动手:给 PebbleOS 加写时复制的 fork。 只读共享页框,在写缺页时复制,并统计复制次数。
解答
加
sys_fork:取空闲 PCB,复制父进程寄存器并把子进程的a0设为 0;取一个根页框和一个 L2 页框,写入根表的两项 (内核超级页和指向新 L2 的指针)。把父进程的 L2 表项复制到子进程,两边都清除 W,并在原本可写的表项上置软件位 COW(第 8 位, Pebble 的 MMU 忽略的 RSW 字段)。为每个页框维护引用计数(内核中按页框号索引的数组),共享的页框各加一。重写父进程的ptbr, 冲掉 TLB 中过时的可写翻译。在pfault中:对有效且置了 COW 的表项的写缺页(原因 15)不是保护错误。若页框计数为 1,置 W、清 COW 并重试;否则取新页框、复制 4 KiB、在本进程中以 W 映射、旧页框计数减一、复制计数ncow加一,然后重试。测试:父进程写满 16 页, fork,子进程写其中 4 页;子进程看到父进程的数据,各自看到自己的写,ncow= 4。fork 后立即 exit 时ncow= 0,只有调用本身 写到的栈页除外。 -
★ 研究:离线大页提升。 给定访问序列、k 项的 TLB 和浪费页框的预算,选择要提升为大页的对齐区域。它是 NP 难的吗?贪心在 Job 的序列上离最优多远?
从哪里开始。 模型:区域整体提升,浪费(区域大小 − 序列触及的页数)个页框,区域内所有页共用一个 TLB 项;目标是 k 项 LRU TLB 在表项序列上的缺失数(每次访问若所在区域已提升则映射到区域,否则映射到页),用
explainer/cs/os/paging.faults(trace, k, "lru")测量。Job 的地址空间只有 1 MiB,把compute._job_trace的 1 KiB 页序列缩放到 4 或 16 页的区域。检查:若 k 不小于表项数,只剩 强制缺失,提升靠合并它们起作用;若 TLB 用 OPT 而不是 LRU,问题会更容易吗?难度:收益不可加(提升两个区域的效果可能大于或小于 两者之和);若可加,问题就是背包,弱 NP 难,可用伪多项式动态规划求解。试着通过 LRU 的相互作用从强 NP 难问题归约,例如提升的 区域必须使工作集保持在 k 以下的装箱问题。算法:按每个浪费页框节省的缺失数贪心;在小实例上与穷举和整数规划比较。检验次模性 (边际收益是否递减):若成立,贪心有 (1 − 1/e) 式的保证;若不成立,给出反例。文献:Navarro 等(OSDI 2002);Kwon 等,Ingens (OSDI 2016);Panwar 等,HawkEye(ASPLOS 2019);Ram 等,Trident(ISCA 2021)。实际系统靠启发式提升;离线问题的难度结果,或 有可证比率的算法,能告诉它们离最优有多远。
Build the film
python -m videos.cs.cs32.compute # the part's numbers, into .cache/cs32
python tools/build.py cs32 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs32 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs32. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs32.compute # every number in the part (about five minutes)
python tools/build.py cs32 -q l # a 480p preview
python tools/build.py cs32 # 1080p