Operating System · CS3423 · Fall 2026

Worksheet 9

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. 英文疲倦?試試看中文版!

中文版
The brown-and-white cat and the orange cat type on two laptops; thin glowing lines run from both laptops to one shared grid of slate-blue squares floating between them. The yellow cat points at one orange square that is splitting into two.

Part 1Page Fault On Purpose

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:

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:

Invalid address

The address is in no region, for example a NULL pointer.

A bug. The kernel sends SIGSEGV. (xv6 kills the process.)

Protection fault

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.

Not present

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:

Minor and major 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 filetime
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.

Part 2Lazy Allocation

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():

// 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:

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.

🐾
Walkthrough 1: Lazy allocation in xv6. Process A calls 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.
Open walkthrough 1 ▶ 11 steps · use ← → keys · press E for the explanation

Overcommit: promising more than you have

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.

Part 3Copy-on-write fork

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 childtime for the writes
nothing00 ms
one byte in each page of 10% of the memory26,21529 ms
one byte in each page of all of it262,144275 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).

How it works

Copy-on-write is a protection fault that the kernel plans. At fork(), the kernel does three things:

  1. It builds the child's page table with the same frames as the parent's.
  2. For every writable page, it clears W in both page tables and sets the copy-on-write mark C. (This is xv6's implementation. Linux works differently.)
  3. For every frame, it counts how many page tables map it. This is the frame's reference count.

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.

the parent's page table physical RAM the child's page table page 0R Xcode: read-only anyway page 1R W Cdata page 2R W Cheap page 0R X page 1R W C page 2R W C frame 30refs 2 frame 37refs 2 frame 46refs 2
Right after a copy-on-write 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:

🐾
Walkthrough 2: xv6's copy-on-write fork
Open walkthrough 2 ▶ 12 steps · use ← → keys · press E for the explanation

Tricky details

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.

Fun to know (optional)
Redis saves its database by forking

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

Fun to know (optional)
Dirty COW: any user becomes root in five seconds
Logo: a cow drawn in Android green with brown patches and the Android robot head, its tongue out, above the words THE DIRTY COW DROID.
Image: NowSecure, 2016.

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.

How the attack worked
  1. The attacker maps a file that it may only read, such as a system password file, as a private copy-on-write mapping.
  2. One thread keeps writing into that mapping through /proc/self/mem. This should change only the process's private copy.
  3. Another thread keeps telling the kernel to throw that private copy away.
  4. With the right timing, the kernel's write lands in the original page, the one that belongs to the file. So the read-only file changes, and the attacker can make itself root.

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

Part 4The Zero Page

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
linetimeminor faultsRAM in use (RSS)
a = np.zeros(1 << 27)0 ms3+0
a.sum()97 ms262,144+0
a.sum() again14 ms0+0
a[:] = 1238 ms262,144+1 GiB
a[:] = 270 ms0+0

Each line changes the page table in a different way:

  1. np.zeros only makes a promise. This is lazy allocation, so no PTE and no frame exist yet, and the line takes no time.
  2. The first 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.
  3. The first 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.
after np.zeros after a.sum() after a[:] = 1 page 0page 1page 2page 3 no entryno entryno entryno entry … 262,144 pages in all page 0page 1page 2page 3 RRRR zeropage page 0page 1page 2page 3 R WR WR WR W 1.0 1.0 …1.0 1.0 …1.0 1.0 …1.0 1.0 … RSS +0RSS +0, one shared frameRSS +1 GiB, one frame per page
Four of the array's 262,144 pages. Reading maps them all to the one zero page. Writing gives each page a frame of its own.

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.

Part 5When RAM runs out

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:

RAMdisk file-backed, cleanD = 0 file-backed, dirtyD = 1 anonymousheap, stack, COW copies the file already holds the clean data swap area just drop it, nothing to write ✕ write back to the file, then drop write to swap, then drop Afterwards the PTE has V = 0. The next access is a major fault that reads the page back from disk.
When the kernel needs a frame, the cost depends on the page: nothing for a clean file page, one disk write for a dirty file page or an anonymous page.

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.

Optional: compressed memory, swap without the disk

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

The OOM killer

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.

Self-checkLearning goals

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.)

Reset checklist

AttributionCredits