In Worksheet 8, an invalid memory access caused a page fault. In this worksheet, let's learn how the kernel deliberately uses this mechanism to take back control from a user program. We will see three uses of it, which are lazy allocation, copy-on-write fork() and swapping. Use the self-check at the end to prepare for the quiz on December 2. 英文疲倦?試試看中文版!

On every load, store and instruction fetch, the MMU checks the PTE. If V is 0, or the access needs a permission the PTE does not grant, the MMU stops the instruction, raises a page fault and hands control to the kernel.
The MMU only knows the PTE. But the kernel also keeps its own record of what each process may use:
cat /proc/self/maps.p->sz. Every address below it belongs to the process.With this record, the kernel can decide whether a fault is a bug, or a page that it simply has not set up yet. In the second case, it sets the page up and returns to the same instruction. The instruction runs again and succeeds, so the program never learns that the fault happened.
So a page fault comes in one of three kinds:
The address is in no region, for example a NULL pointer.
A bug. The kernel sends SIGSEGV. (xv6 kills the process.)
The page is mapped, but the PTE forbids this access, for example a store into a page with W = 0.
Usually a bug. But if the kernel cleared W on purpose, it fixes the page and retries.
The address is legal, but the page has no frame yet, or its data is on disk.
The kernel gets a frame, fills it, maps it and retries.
Notice that invalid and not present look the same to the hardware. In both cases the PTE has V = 0, because the PTE has only one bit for two different meanings. Only the kernel's own record can tell them apart. (On x86, this bit is called P, for present.)
Try to classify each of these page faults:
A fault can also be cheap or expensive, depending on whether the kernel must wait for the disk:
To see the difference, I mapped a 512 MB file into memory and read one byte from every page, twice. The first time, the file was not in the page cache, so every page came from the SSD. The second time, the file was already in the page cache:
| reading one byte from every page of a 512 MB file | time |
|---|---|
| first time: every page comes from the SSD (major faults) | 0.32 s |
| second time: every page is already in RAM (minor faults) | 0.02–0.03 s |
You feel the same difference when an app starts slowly right after boot, but quickly the second time.
On my machine, this line returns in 4 microseconds:
char *p = malloc(8UL << 30); // 8 GiB
That is far too fast to allocate 8 GiB, and indeed, the process still uses only about 1 MB of RAM afterwards. To find out when the memory does get allocated, I wrote to the first 1 GiB with memset(). That took 0.31 s and caused 262,231 minor faults, almost exactly one per 4 KiB page (1 GiB / 4 KiB = 262,144). So the kernel did not allocate memory when the program asked. It allocated each page at its first touch. This is lazy allocation. Because of it, a program that asks for a lot but uses little pays only for what it uses.
xv6 offers both styles in sys_sbrk():
sbrk(n) is eager: it allocates and maps every frame at once, in growproc().sbrklazy(n) is lazy: it only raises p->sz, the size of the process.// kernel/sysproc.c, sys_sbrk() 50 if (t == SBRK_EAGER || n < 0) { 51 if (growproc(n) < 0) { // kalloc() + mappages() for every page 52 return -1; 53 } 54 } else { ... 62 myproc()->sz += n; // the lazy branch: only the size grows 63 }
Since the lazy branch maps nothing, the first touch of such a page causes a page fault. The CPU then enters the kernel in usertrap(), and two registers tell the kernel what happened:
scause says what kind of access failed: 13 for a load, 15 for a store.stval holds the virtual address that failed.So usertrap() passes load and store page faults to vmfault(), together with the failing address. If vmfault() returns 0, it kills the process:
// kernel/trap.c, usertrap() 71 } else if ((r_scause() == 15 || r_scause() == 13) && 72 vmfault(p->pagetable, p->sz, r_stval(), 73 (r_scause() == 13) ? 1 : 0) != 0) { 74 // page fault on lazily-allocated page 75 } else { ... 78 setkilled(p);
If vmfault() succeeds, usertrap() returns to the program at the address saved in a third register, sepc. It holds the address of the instruction that failed, so the same instruction runs again, and this time it succeeds.
sbrklazy() for three pages and stores into one of them. Follow p->sz, the page table and the free frames while usertrap() and vmfault() handle the fault line by line. At the end, A touches an address it never asked for.
With lazy allocation, a program finds out there is no more memory only when it touches a page. Linux takes this risk on purpose. It overcommits: it lets processes ask for more memory in total than RAM and swap together. This usually works, because most programs never touch most of what they ask for.
So malloc() almost never returns NULL on Linux. Running out of memory shows up later, at a page fault.
fork() must give the child a copy of the parent's whole address space. xv6 does this literally, in uvmcopy(): for every page of the parent, it allocates a new frame and copies 4096 bytes.
// kernel/vm.c, uvmcopy(): called by fork() for every page of the parent 311 pa = PTE2PA(*pte); 312 flags = PTE_FLAGS(*pte); 313 if ((mem = kalloc()) == 0) // a new frame for the child 314 goto err; 315 memmove(mem, (char *)pa, PGSIZE); // copy 4096 bytes 316 if (mappages(new, i, PGSIZE, (uint64)mem, flags) != 0) {
For a process with 1 GiB of memory, that means 262,144 frames to allocate and 1 GiB to copy, before the child runs a single instruction. Most of this work is wasted, because a shell's child calls exec() right away and throws the copy away.
Linux avoids the copy. On my machine, fork() of a process with 1 GiB of memory takes only about 7 ms, because the child gets the parent's pages without copying them. A page is copied only when one of the two processes writes to it. To see this, I let the child write to part of its memory and counted its page faults:
after fork() of a 1 GiB process, the child writes… | page faults in the child | time for the writes |
|---|---|---|
| nothing | 0 | 0 ms |
| one byte in each page of 10% of the memory | 26,215 | 29 ms |
| one byte in each page of all of it | 262,144 | 275 ms |
So the copying did not disappear. It moved to the first write of each page, one fault at a time. But now the child pays only for the pages it writes, and a child that calls exec() pays almost nothing. This is copy-on-write (COW).
Copy-on-write is a protection fault that the kernel plans. At fork(), the kernel does three things:
After that, loads work as usual, because R is still set. But the first store to a shared page faults. The kernel then copies that one page, gives the writer its own frame with W = 1, and runs the store again.
fork(): two page tables, one set of frames. The writable pages lost W in both tables and carry the copy-on-write mark C. Nothing has been copied yet.Before you open the walkthrough, think about two questions that every copy-on-write kernel must answer:
fork(), the kernel clears W in the parent's PTEs. But the parent's TLB may still hold the old entries with W = 1, and with them the parent could keep writing into the shared frame. So the kernel must run sfence.vma, and it must do so again after each copy.exec(), unmapping a page only decrements its frame's reference count. A frame returns to the free list only when its count reaches 0. Otherwise the kernel would free a frame that the other process still uses.fork() still copies the page table. For 1 GiB of 4 KiB pages, the child's page table needs 262,144 PTEs of 8 bytes, that is 2 MiB of entries. The kernel also updates the reference counts of 262,144 frames. So even with copy-on-write, setting up the page table of a new process still takes time: about 7 ms on my machine.xv6 does not implement copy-on-write, so its uvmcopy() copies every page. Lab 2's pgprotect() changes W on a range of pages, which is the kind of operation a copy-on-write kernel needs. But Lab 2 does not build copy-on-write.
Redis is a popular database that keeps all its data in memory, so it can answer a lookup in microseconds. Instagram, for example, used Redis to remember which user posted each of its hundreds of millions of photos.
So a single Redis process often holds many gigabytes. Because RAM is lost when the machine powers off, Redis regularly saves a snapshot of its data to disk. To save it without stopping, it calls fork(). Then the child writes the snapshot while the parent keeps serving clients.
Sources: Instagram Engineering · Redis latency documentation · Redis administration · Redis FAQ

In October 2016, the security researcher Phil Oester found attackers using a Linux bug that nobody had known about. With it, an ordinary user could become root, the user who may do anything on the machine. "Any user can become root in < 5 seconds in my testing, very reliably," he reported.
The bug had been in Linux since 2007, so it sat in almost every Linux server, and in every Android phone too. A year later, researchers found it inside more than 1,200 malicious Android apps, disguised as games and adult apps, which used it to take over the phone.
Where was the bug? In the kernel's copy-on-write code. That is why it was named Dirty COW.
/proc/self/mem. This should change only the process's private copy.The lesson: "copy the page, then remap it" is easy to say, but the kernel must make sure that nothing can slip in between the two steps.
Sources: NVD, CVE-2016-5195 · CERT/CC VU#243144 · Security Affairs on Phil Oester and ZNIU · Trend Micro, ZNIU · NowSecure
In Week 1, we created a big matrix of zeros with np.zeros in Colab. Reading it was fast, but filling it with 1 was slow. Now you can explain why. I repeated the demo with a 1 GiB array and timed each line:
a = np.zeros(1 << 27) # 2^27 floats of 8 bytes = 1 GiB of zeros a.sum() # read every element a.sum() # read every element again a[:] = 1 # write every element a[:] = 2 # write every element again
| line | time | minor faults | RAM in use (RSS) |
|---|---|---|---|
a = np.zeros(1 << 27) | 0 ms | 3 | +0 |
a.sum() | 97 ms | 262,144 | +0 |
a.sum() again | 14 ms | 0 | +0 |
a[:] = 1 | 238 ms | 262,144 | +1 GiB |
a[:] = 2 | 70 ms | 0 | +0 |
Each line changes the page table in a different way:
np.zeros only makes a promise. This is lazy allocation, so no PTE and no frame exist yet, and the line takes no time.a.sum() faults on every page. But a read only needs to see zeros. So the kernel maps every page to the same zero page, one shared frame full of zeros, read-only. No new frame is used, so RSS stays the same. The second a.sum() faults nowhere and takes 14 ms, which is the real cost of reading 1 GiB.a[:] = 1 faults on every page again, because every page maps the zero page with W = 0. Each of these is a copy-on-write fault. The kernel allocates a frame, fills it with zeros, maps it writable and runs the store again. So RSS grows by 1 GiB and the line takes three times as long as the second write, which faults nowhere.I measured on Linux with NumPy's request for 2 MiB huge pages turned off (NUMPY_MADVISE_HUGEPAGE=0), so that every 4 KiB page faults on its own.
Lazy allocation and copy-on-write let processes use more memory than the machine has, as long as they do not touch it all. Sooner or later, though, a page fault needs a frame and no frame is free. Then the kernel must take a frame away from some other page. What happens to that page's data depends on its kind:
mmap(). Their data already exists on disk.
After the eviction, the kernel sets V = 0 in the PTE and flushes the TLB. Linux even writes the page's swap location into the PTE itself, because the MMU ignores all other bits when V = 0. So the next access to the page faults, and the kernel fixes it with a major fault: it reads the page back from disk and retries.
Which page should the kernel evict? A good choice is a page that has not been used for a while. To find one, kernels work like the CLOCK algorithm of Worksheet 7, with one used bit per page. Two bits of the PTE help:
Eviction only helps if the evicted pages stay unused for a while. If the processes keep using more pages than fit in RAM, every eviction is soon followed by a major fault for the same page. Then the machine spends its time moving pages between RAM and disk instead of running programs. This is thrashing: the mouse cursor still moves, but nothing else responds.
Phones and laptops often compress pages instead of writing them to disk. A compressed page stays in RAM but takes much less space, so getting it back costs a decompression instead of a disk read. macOS has done this since Mavericks (2013), and Windows 10 keeps a "compression store". Android says that it "uses compressed swap (ZRAM) to keep background apps in memory".
Sources: Apple, OS X Mavericks · Android developers
Sometimes nothing more can be evicted, because swap is full (or there is none) and every page is in use. Then a page fault needs a frame, and there is none. The program at that fault did nothing wrong, and the kernel cannot return an error from a store instruction. So Linux's OOM killer (out of memory) picks a process and kills it with SIGKILL, to get its frames back.
Check each item that you can do without looking at the worksheet. The quiz on December 2 covers these topics. (Progress is stored only in this browser.)
cat-right.png (Freepik and ChatGPT). The pictures this week were generated with Google Gemini from that art.fork() test.