16. A look through xv6
Why this layer exists
Chapter 13 gave ember spawn and no fork, and said why: fork needs a second address space, and ember has one page table. It named the cure in one clause, per-process page tables with copy-on-write (chapter 14’s term), and left it. xv6 is the kernel that has the per-process tables, in a teaching Unix small enough to read whole. At the pinned commit its fork copies every page of the parent. This chapter makes that fork cheap, and reads the kernel’s trap, page-table and allocator code while doing it.
It is one extension, not a port of ember to xv6’s structure and not a tour of xv6. The extension is the one chapter 13 postponed. It touches the three places where a page’s meaning changes hands: the allocator, which has to know when a page is free; the page table, which has to say that a page is shared; and the trap handler, which has to turn a store to a shared page into a private one.
Mechanism
Every block headed xv6-riscv 06aad25 is copied from a checkout of https://github.com/mit-pdos/xv6-riscv at that commit, by line range. Blocks headed + 0001-cow-fork.patch are hunks of labs/ch16/patches/0001-cow-fork.patch, the lab’s one patch, and labs/ch16/build.sh applies it to that checkout. At this commit the kernel functions that implement system calls carry a k prefix (kfork, kexit, kwait, kexec), so the fork system call is kfork in the kernel, and the call that sleeps is pause. The xv6 book (rev4, August 2024) describes the same design under the older names, and says that fork is implemented with uvmcopy, “which allocates physical memory for the child and copies the parent’s memory into it”.
The fork this chapter starts from
kfork allocates a process, gives it a page table, and fills the table by calling uvmcopy:
// xv6-riscv 06aad25, kernel/proc.c:270-275
// Copy user memory from parent to child.
if (uvmcopy(p->pagetable, np->pagetable, p->sz) < 0) {
freeproc(np);
release(&np->lock);
return -1;
}
uvmcopy walks the parent’s user pages, one PGSIZE (4096 bytes) at a time:
// xv6-riscv 06aad25, kernel/vm.c:292-326
// Given a parent process's page table, copy
// its memory into a child's page table.
// Copies both the page table and the
// physical memory.
// returns 0 on success, -1 on failure.
// frees any allocated pages on failure.
int
uvmcopy(pagetable_t old, pagetable_t new, uint64 sz)
{
pte_t *pte;
uint64 pa, i;
uint flags;
char *mem;
for (i = 0; i < sz; i += PGSIZE) {
if ((pte = walk(old, i, 0)) == 0)
continue; // page table entry hasn't been allocated
if ((*pte & PTE_V) == 0)
continue; // physical page hasn't been allocated
pa = PTE2PA(*pte);
flags = PTE_FLAGS(*pte);
if ((mem = kalloc()) == 0)
goto err;
memmove(mem, (char *)pa, PGSIZE);
if (mappages(new, i, PGSIZE, (uint64)mem, flags) != 0) {
kfree(mem);
goto err;
}
}
return 0;
err:
uvmunmap(new, 0, i / PGSIZE, 1);
return -1;
}
For each page that is present, walk returns the leaf page-table entry (PTE) at that address in the parent’s table, PTE2PA takes the physical address out of it, PTE_FLAGS takes its low ten bits (the permissions V, R, W, X, U, and their neighbours), kalloc finds a fresh page, memmove copies 4096 bytes into it, and mappages makes the child’s PTE point at the copy with the same flags. The cost is the size of the parent, paid at the moment of fork, whether or not the child ever touches the memory. For the commonest use of fork the child touches almost none of it: the shell forks and the child immediately calls exec, which discards the address space the copy just built.
The comment at the top of labs/ch16/cowtest.c states the problem, and the arithmetic is short. Physical memory is PHYSTOP - KERNBASE, 128 MiB (kernel/memlayout.h), and its simple test grows the process to two thirds of that and forks. A copy needs two thirds again; there is a third. Run against the unpatched kernel, with only cowtest added to the image, the test prints the failure:
$ cowtest
simple: fork() failed
Copy-on-write, and a count
Under copy-on-write (COW from here on), the child’s page table is built to point at the parent’s physical pages; nothing is copied; and both tables are marked so that the first store through either one is caught and given a private copy of that one page. Memory is copied on the write that needs it, for the pages that are written, and never for the rest.
Three things have to be true for that to work.
The share must be visible to the hardware. A page that two page tables map must fault when either writes. RISC-V’s PTE has a write bit, W, and a store to a page with W clear raises a store page fault, scause 15 (the privileged specification: “Attempting to execute a store, store-conditional, AMO, or cache-block zero instruction instruction whose effective address lies within a page without write permissions raises a store page-fault exception”; sic, the doubled word is the specification’s). So uvmcopy clears W in the parent’s PTE as well as the child’s. A page that was read-only to begin with (the program’s text) stays as it is and is shared without any further mark: nothing will ever store to it.
The fault must be able to tell a share from a mistake. A store to a page with W clear is also what a store to the program’s own text looks like, and that one has to kill the process. The handler needs one bit of its own. The PTE reserves two for exactly this: the RSW field, bits 9 and 8, which the privileged specification calls “reserved for use by supervisor software; the implementation shall ignore this field” (Figure 22, Sv39 page table entry, the format chapter 4 introduced). The patch names bit 8 PTE_COW:
// xv6-riscv 06aad25 + 0001-cow-fork.patch, kernel/riscv.h
@@ -397,6 +397,7 @@ typedef uint64 *pagetable_t; // 512 PTEs
#define PTE_W (1L << 2)
#define PTE_X (1L << 3)
#define PTE_U (1L << 4) // user can access
+#define PTE_COW (1L << 8) // copy-on-write: RSW bit, ours (ch16)
// shift a physical address to the right place for a PTE.
#define PA2PTE(pa) ((((uint64)pa) >> 12) << 10)
A PTE now has one of three states for a user page: W=1, COW=0 (private and writable), W=0, COW=1 (shared, or formerly shared, until the next store), and W=0, COW=0 (read-only: text). W=1 together with COW=1 is never written, and the design depends on that.
The kernel must know when a shared page is free. Upstream kfree puts a page on the free list, and a process’s pages are freed when its parent reaps it with wait (kwait calls freeproc, which reaches uvmunmap with do_free set, below; kexit only makes a zombie, which keeps its references until then). With shared pages the first process to be reaped would free pages the other still maps. The allocator needs a reference count per page: the number of holders of the page, where a holder is a PTE (or a kernel structure that owns the page outright: pipealloc takes a page from kalloc for a struct pipe, and the pipe is its one holder). kalloc hands a page out with a count of one. kfree becomes “drop a reference” and frees the page only when the count reaches zero. uvmcopy raises the count of every page it shares, read-only ones included, because a text page is held by every process running the program.
The count is a static array indexed by page number, from KERNBASE to PHYSTOP: 32768 ints, 128 KiB of the kernel’s BSS. It lives in the allocator, not in the page (the patch’s comment: a page with a count is exactly a page someone may still be reading), and not in the PTE, which is per table where the count is per physical page. The invariants the rest of the chapter keeps are two. A page’s count is the number of holders that name it, at every point. No PTE has W and COW both set.
The fault
A store to a PTE_COW page traps into usertrap with scause 15. The handler has two cases, and they are the whole point of the count.
If the count is greater than one, the page really is shared: the handler allocates a page, copies the 4096 bytes, points the faulting process’s PTE at the copy with W set and COW clear, and calls kfree on the old page, which drops one reference (the process’s own) and leaves the others. If the count is one, every other holder has already let go (the sibling was reaped, or took its own copy first), and the page is this process’s alone; copying it would be waste, so the handler sets W, clears COW, and returns. The page the parent held read-only through the whole fork becomes writable again in place, with no copy at all.
The handler writes the PTE directly. The obvious tool, mappages, refuses:
// xv6-riscv 06aad25, kernel/vm.c:164-167
if ((pte = walk(pagetable, a, 1)) == 0)
return -1;
if (*pte & PTE_V)
panic("mappages: remap");
A mapping that exists is a bug to mappages, so replacing a PTE goes around it. The fault returns to the same store, which now succeeds. The handler needs no sfence.vma, the instruction that tells a hart to discard its cached translations, to make the hart see the new PTE: kernel/trampoline.S’s userret executes one on every return to user mode, and the return from usertrap goes through it:
// xv6-riscv 06aad25, kernel/trampoline.S:100-112
.globl userret
userret:
# usertrap() returns here, with user satp in a0.
# return from kernel to user.
# flush icache, in case this is the first time
# we're running this proc on this hart.
fence.i
# switch to the user page table.
sfence.vma zero, zero
csrw satp, a0
sfence.vma zero, zero
The first sfence.vma waits for earlier memory operations to finish under the table they started with; both sfence.vma zero, zero discard every cached translation, and the one after csrw satp, a0 is the one that matters here: nothing the hart remembered about this process’s table before the kernel changed it survives into user mode. A PTE rewritten while the process is in the kernel is therefore never seen stale: uvmcopy rewrites the parent’s PTEs during fork and the parent returns through the same code.
In usertrap the patch puts the new case first. Order is a matter of cost here, not of correctness: upstream’s next case, vmfault, handles the lazily allocated pages sbrklazy creates (a page the kernel promised and has not backed with memory yet) and returns zero at once for a page that is already mapped:
// xv6-riscv 06aad25, kernel/vm.c:458-469
uint64
vmfault(pagetable_t pagetable, uint64 psz, uint64 va, int read)
{
uint64 mem;
if (va >= psz)
return 0;
va = PGROUNDDOWN(va);
if (ismapped(pagetable, va)) {
return 0;
}
mem = (uint64)kalloc();
so a COW page falls through vmfault to the else that kills the process, which is why the COW case must exist at all, and why either order works. The COW case goes first because it is exact (scause 15 only: a COW page keeps R, so only stores fault on it) and vmfault is the general one. A page that was lazily left unallocated in the parent is skipped by uvmcopy (if ((*pte & PTE_V) == 0) continue), so the child’s copy of that range is unmapped too and the child faults it in the old way.
The kernel writes too
User code is not the only writer of user memory. copyout copies from the kernel into a process, by looking the user address up in the page table and writing to the physical page through the kernel’s own mapping of RAM. It never stores through the user’s PTE, so no store page fault can happen to catch it, and the only guard upstream has is a software test:
// xv6-riscv 06aad25, kernel/vm.c:362-365
pte = walk(pagetable, va0, 0);
// forbid copyout over read-only user text pages.
if ((*pte & PTE_W) == 0)
return -1;
That test refuses a COW page, so a read into shared memory fails with -1; without the test, the write would go through to a page the parent still reads. Either way a COW page needs a fault taken on the process’s behalf: the patch’s copyout hunk calls cowfault itself, looks the physical address up again (the PTE now points at a copy) and goes on. Only copyout needs it. copyin and copyinstr only read, and the one other writer, exec’s loadseg (kernel/exec.c, through walkaddr), writes into pages it has just allocated in a fresh table, which no one shares.
What the count already handles
uvmunmap, which reaping a child (kwait to freeproc), exec and a failed uvmcopy all reach, frees a page with kfree:
// xv6-riscv 06aad25, kernel/vm.c:207-211
if (do_free) {
uint64 pa = PTE2PA(*pte);
kfree((void *)pa);
}
*pte = 0;
With counts, that call is “drop this process’s reference”, which is what a holder letting go of a shared page should do, and the change that makes it so is in kfree, not here. uvmcopy’s own failure path (uvmunmap(new, 0, i / PGSIZE, 1)) is right for the same reason: every page already mapped into the child has had its count raised, and the page that failed to map has not.
The kernel’s own page table maps RAM directly and writable, with no COW bit, so a kernel store to a user page lands on the physical page whatever the user’s PTE says: that is why copyout is the one place that has to check. The trapframe and the trampoline are mapped into every process’s table above sz, outside the range uvmcopy walks. The trapframe page is the child’s own; the trampoline is one page in every table, never counted and never freed (proc_freepagetable unmaps both with do_free zero).
Walkthrough
The patch is fourteen hunks in six files, in the order git diff lists them, which is alphabetical by path; this section takes them by mechanism, not by path.
kernel/kalloc.c carries five. The first holds the count array and the two functions the rest of the kernel uses to read and raise it; the comment in the patch is the specification of the invariant:
// xv6-riscv 06aad25 + 0001-cow-fork.patch, kernel/kalloc.c
@@ -18,11 +18,42 @@ struct run {
struct run *next;
};
+// listing:ch16-refcount
+// One reference count per physical page from KERNBASE to PHYSTOP,
+// indexed by page number. A page is free when its count reaches zero;
+// fork's copy-on-write share raises it, and a write fault or a kfree
+// lowers it. The count lives in the kernel, not in the page: a page
+// with a count is exactly a page someone may still be reading.
+#define PGREF(pa) (refs[((uint64)(pa) - KERNBASE) / PGSIZE])
+static int refs[(PHYSTOP - KERNBASE) / PGSIZE];
+
struct {
struct spinlock lock;
struct run *freelist;
} kmem;
+// Raise the count of the page holding pa. Called by uvmcopy when a
+// child comes to share a parent's page.
+void
+krefinc(void *pa)
+{
+ acquire(&kmem.lock);
+ PGREF(pa)++;
+ release(&kmem.lock);
+}
+
+// The count, for cowfault's "am I the only one" test.
+int
+krefcount(void *pa)
+{
+ int n;
+ acquire(&kmem.lock);
+ n = PGREF(pa);
+ release(&kmem.lock);
+ return n;
+}
+// end-listing:ch16-refcount
+
void
kinit()
{
krefinc and krefcount take kmem.lock, the allocator’s existing spinlock, rather than a lock of their own: the count is read and written in kfree under the same lock, and two locks around one number is a bug waiting for a second hart. freerange runs once at boot, before anything has a count, and calls kfree for every page of RAM; kfree now expects a count of at least one, so freerange sets one first. The same hunk replaces kfree’s header comment:
// xv6-riscv 06aad25 + 0001-cow-fork.patch, kernel/kalloc.c
@@ -35,14 +66,13 @@ freerange(void *pa_start, void *pa_end)
{
char *p;
p = (char *)PGROUNDUP((uint64)pa_start);
- for (; p + PGSIZE <= (char *)pa_end; p += PGSIZE)
+ for (; p + PGSIZE <= (char *)pa_end; p += PGSIZE) {
+ PGREF(p) = 1; // so that kfree below frees it
kfree(p);
+ }
}
-// Free the page of physical memory pointed at by pa,
-// which normally should have been returned by a
-// call to kalloc(). (The exception is when
-// initializing the allocator; see kinit above.)
+// Drop one reference; free the page when nobody holds it.
void
kfree(void *pa)
{
kfree decrements under the lock, panics if the count was already zero (a page freed twice, the invariant’s negative), and returns without touching the page if anyone still holds it. Only the last release fills the page with junk and links it into the free list, as before:
// xv6-riscv 06aad25 + 0001-cow-fork.patch, kernel/kalloc.c
@@ -51,6 +81,16 @@ kfree(void *pa)
if (((uint64)pa % PGSIZE) != 0 || (char *)pa < end || (uint64)pa >= PHYSTOP)
panic("kfree");
+ acquire(&kmem.lock);
+ if (PGREF(pa) < 1)
+ panic("kfree: refcount");
+ PGREF(pa)--;
+ if (PGREF(pa) > 0) {
+ release(&kmem.lock);
+ return;
+ }
+ release(&kmem.lock);
+
// Fill with junk to catch dangling refs.
memset(pa, 1, PGSIZE);
The last two change kalloc’s comment and kalloc itself, which sets the count of a page it hands out to one:
// xv6-riscv 06aad25 + 0001-cow-fork.patch, kernel/kalloc.c
@@ -62,7 +102,7 @@ kfree(void *pa)
release(&kmem.lock);
}
-// Allocate one 4096-byte page of physical memory.
+// Allocate one 4096-byte page of physical memory, with a count of one.
// Returns a pointer that the kernel can use.
// Returns 0 if the memory cannot be allocated.
void *
// xv6-riscv 06aad25 + 0001-cow-fork.patch, kernel/kalloc.c
@@ -72,8 +112,10 @@ kalloc(void)
acquire(&kmem.lock);
r = kmem.freelist;
- if (r)
+ if (r) {
kmem.freelist = r->next;
+ PGREF(r) = 1;
+ }
release(&kmem.lock);
if (r)
kernel/defs.h gains the three prototypes, and Makefile adds cowtest to UPROGS:
// xv6-riscv 06aad25 + 0001-cow-fork.patch, kernel/defs.h
@@ -60,6 +60,8 @@ void ireclaim(int);
void* kalloc(void);
void kfree(void *);
void kinit(void);
+void krefinc(void *);
+int krefcount(void *);
// log.c
void initlog(int, struct superblock*);
// xv6-riscv 06aad25 + 0001-cow-fork.patch, kernel/defs.h
@@ -156,6 +158,7 @@ void kvminit(void);
void kvminithart(void);
void kvmmap(pagetable_t, uint64, uint64, uint64, int);
int mappages(pagetable_t, uint64, uint64, uint64, int);
+int cowfault(pagetable_t, uint64);
pagetable_t uvmcreate(void);
uint64 uvmalloc(pagetable_t, uint64, uint64, int);
uint64 uvmdealloc(pagetable_t, uint64, uint64);
// xv6-riscv 06aad25 + 0001-cow-fork.patch, Makefile
@@ -143,6 +143,7 @@ UPROGS=\
$U/_sh\
$U/_stressfs\
$U/_usertests\
+ $U/_cowtest\
$U/_grind\
$U/_wc\
$U/_zombie\
uvmcopy is the first of four hunks in kernel/vm.c. The diff shows the old body going and the new one arriving in two adjacent hunks, the comment with the dropped mem, and the loop:
// xv6-riscv 06aad25 + 0001-cow-fork.patch, kernel/vm.c
@@ -289,19 +289,19 @@ uvmfree(pagetable_t pagetable, uint64 sz)
freewalk(pagetable);
}
-// Given a parent process's page table, copy
-// its memory into a child's page table.
-// Copies both the page table and the
-// physical memory.
-// returns 0 on success, -1 on failure.
-// frees any allocated pages on failure.
+// listing:ch16-uvmcopy
+// Given a parent process's page table, give a child the same physical
+// pages, copy-on-write: every writable page is mapped read-only in both
+// tables with PTE_COW set and its reference count raised. Nothing is
+// copied here; the copy happens in cowfault, on the first write, for the
+// pages that are written, and never for the rest. Returns 0 on success,
+// -1 on failure, freeing what it mapped.
int
uvmcopy(pagetable_t old, pagetable_t new, uint64 sz)
{
pte_t *pte;
uint64 pa, i;
uint flags;
- char *mem;
for (i = 0; i < sz; i += PGSIZE) {
if ((pte = walk(old, i, 0)) == 0)
// xv6-riscv 06aad25 + 0001-cow-fork.patch, kernel/vm.c
@@ -309,14 +309,13 @@ uvmcopy(pagetable_t old, pagetable_t new, uint64 sz)
if ((*pte & PTE_V) == 0)
continue; // physical page hasn't been allocated
pa = PTE2PA(*pte);
- flags = PTE_FLAGS(*pte);
- if ((mem = kalloc()) == 0)
- goto err;
- memmove(mem, (char *)pa, PGSIZE);
- if (mappages(new, i, PGSIZE, (uint64)mem, flags) != 0) {
- kfree(mem);
- goto err;
+ if (*pte & PTE_W) {
+ *pte = (*pte & ~PTE_W) | PTE_COW;
}
+ flags = PTE_FLAGS(*pte);
+ if (mappages(new, i, PGSIZE, pa, flags) != 0)
+ goto err;
+ krefinc((void *)pa);
}
return 0;
The loop is upstream’s with the allocation and the copy gone. For a writable page it replaces the parent’s PTE with (*pte & ~PTE_W) | PTE_COW, then takes the flags from that, so the child inherits them; mappages builds the child’s PTE; krefinc raises the count. No kalloc, no memmove. Read-only pages go through the same lines without the first if.
cowfault is the fault handler as a function the trap path and copyout can both call. Its return value has three meanings (not a COW page: 0; handled: 1; out of memory: -1), because its two callers need to tell them apart:
// xv6-riscv 06aad25 + 0001-cow-fork.patch, kernel/vm.c
@@ -324,6 +323,40 @@ err:
uvmunmap(new, 0, i / PGSIZE, 1);
return -1;
}
+// end-listing:ch16-uvmcopy
+
+// listing:ch16-cowfault
+// A store to a PTE_COW page. If this process is the page's only holder,
+// the page becomes writable in place; otherwise it gets its own copy and
+// drops its reference to the shared one. Returns 0 if va is not a COW
+// page (the caller decides what that means), 1 on success, -1 when out
+// of memory.
+int
+cowfault(pagetable_t pagetable, uint64 va)
+{
+ pte_t *pte;
+ uint64 pa;
+ char *mem;
+
+ if (va >= MAXVA)
+ return 0;
+ va = PGROUNDDOWN(va);
+ pte = walk(pagetable, va, 0);
+ if (pte == 0 || (*pte & PTE_V) == 0 || (*pte & PTE_U) == 0 || (*pte & PTE_COW) == 0)
+ return 0;
+ pa = PTE2PA(*pte);
+ if (krefcount((void *)pa) == 1) {
+ *pte = (*pte | PTE_W) & ~PTE_COW;
+ return 1;
+ }
+ if ((mem = kalloc()) == 0)
+ return -1;
+ memmove(mem, (char *)pa, PGSIZE);
+ *pte = PA2PTE(mem) | ((PTE_FLAGS(*pte) | PTE_W) & ~PTE_COW);
+ kfree((void *)pa); // one fewer holder of the shared page
+ return 1;
+}
+// end-listing:ch16-cowfault
// mark a PTE invalid for user access.
// used by exec for the user stack guard page.
The guards before the count check are not decoration: va is the faulting address, any 64-bit value, so it is checked against MAXVA before walk sees it; the PTE must exist, be valid, be a user page and carry PTE_COW. A scause 15 fault on anything else returns 0 and the old path decides. The krefcount(...) == 1 branch is the in-place take-over. The other branch builds the PTE from the new page with the old flags, W forced on and COW forced off, and then calls kfree on the old page: the count drops by this process’s one. Neither branch holds a lock across the decision, and neither needs to. A count of one means the faulting process’s own PTE is the only reference, and only a fork by that same single-threaded process could raise it, which cannot happen while it is in this handler. On the copy path the faulter’s own reference keeps the page alive while the other holders let go.
copyout and usertrap get the last two hunks, one call site each:
// xv6-riscv 06aad25 + 0001-cow-fork.patch, kernel/vm.c
@@ -360,6 +393,14 @@ copyout(pagetable_t pagetable, uint64 psz, uint64 dstva, char *src, uint64 len)
}
pte = walk(pagetable, va0, 0);
+ if (*pte & PTE_COW) {
+ // the kernel is about to write a shared page on the user's behalf:
+ // take the same fault the user would have taken.
+ if (cowfault(pagetable, va0) != 1)
+ return -1;
+ pa0 = walkaddr(pagetable, va0);
+ pte = walk(pagetable, va0, 0);
+ }
// forbid copyout over read-only user text pages.
if ((*pte & PTE_W) == 0)
return -1;
// xv6-riscv 06aad25 + 0001-cow-fork.patch, kernel/trap.c
@@ -68,10 +68,14 @@ usertrap(void)
syscall();
} else if ((which_dev = devintr()) != 0) {
// ok
+ // listing:ch16-trap
+ } else if (r_scause() == 15 && cowfault(p->pagetable, r_stval()) == 1) {
+ // store to a copy-on-write page: now the process's own
} else if ((r_scause() == 15 || r_scause() == 13) &&
vmfault(p->pagetable, p->sz, r_stval(),
(r_scause() == 13) ? 1 : 0) != 0) {
// page fault on lazily-allocated page
+ // end-listing:ch16-trap
} else {
printk("usertrap(): unexpected scause 0x%lx pid=%d\n", r_scause(), p->pid);
printk(" sepc=0x%lx stval=0x%lx\n", r_sepc(), r_stval());
If cowfault returns -1, memory ran out while copying. In usertrap the process falls through vmfault, which refuses a mapped page, and the final else kills it. In copyout the same -1 makes the system call return -1 and the process survives. A fork that cannot be paid for at the first user store kills the writer, which is what an unbackable lazy sbrk page already does upstream; a system call that meets the same shortage fails instead.
cowtest.c
The test program is ours, after MIT’s 6.1810 copy-on-write test, and build.sh copies it into xv6’s user/ before the build:
// cowtest: copy-on-write fork, proven three ways. Without COW, "simple"
// cannot fork at all: the parent holds most of physical memory and a
// copying fork has nowhere to put the copy.
//
// After cowtest.c from MIT 6.1810's copy-on-write lab (Kaashoek, Morris,
// Cox; MIT license, as xv6's LICENSE file), with the comments rewritten
// for this chapter.
#include "kernel/types.h"
#include "kernel/memlayout.h"
#include "user/user.h"
// Allocate more than half of physical memory, then fork. Without COW
// the fork fails; with COW the child shares the pages, writes to each,
// and exits; the parent's copies are unchanged.
void
simpletest()
{
uint64 phys_size = PHYSTOP - KERNBASE;
int sz = (phys_size / 3) * 2;
printf("simple: ");
char *p = sbrk(sz);
if (p == (char *)0xffffffffffffffffL) {
printf("sbrk(%d) failed\n", sz);
exit(-1);
}
for (char *q = p; q < p + sz; q += 4096)
*(int *)q = getpid();
int pid = fork();
if (pid < 0) {
printf("fork() failed\n");
exit(-1);
}
if (pid == 0)
exit(0);
wait(0);
if (sbrk(-sz) == (char *)0xffffffffffffffffL) {
printf("sbrk(-%d) failed\n", sz);
exit(-1);
}
printf("ok\n");
}
// Three processes all writing COW memory: the counts reach 3, and each
// write copies. The parent's bytes survive the children's writes.
void
threetest()
{
uint64 phys_size = PHYSTOP - KERNBASE;
int sz = phys_size / 4;
int pid1, pid2;
printf("three: ");
char *p = sbrk(sz);
if (p == (char *)0xffffffffffffffffL) {
printf("sbrk(%d) failed\n", sz);
exit(-1);
}
pid1 = fork();
if (pid1 < 0) {
printf("fork failed\n");
exit(-1);
}
if (pid1 == 0) {
pid2 = fork();
if (pid2 < 0) {
printf("fork failed");
exit(-1);
}
if (pid2 == 0) {
for (char *q = p; q < p + (sz / 5) * 4; q += 4096) {
*(int *)q = getpid();
}
for (char *q = p; q < p + (sz / 5) * 4; q += 4096) {
if (*(int *)q != getpid()) {
printf("wrong content\n");
exit(-1);
}
}
exit(-1);
}
for (char *q = p; q < p + (sz / 2); q += 4096) {
*(int *)q = 9999;
}
exit(0);
}
for (char *q = p; q < p + sz; q += 4096) {
*(int *)q = getpid();
}
wait(0);
pause(1);
for (char *q = p; q < p + sz; q += 4096) {
if (*(int *)q != getpid()) {
printf("wrong content\n");
exit(-1);
}
}
if (sbrk(-sz) == (char *)0xffffffffffffffffL) {
printf("sbrk(-%d) failed\n", sz);
exit(-1);
}
printf("ok\n");
}
char junk1[4096];
int fds[2];
char junk2[4096];
char buf[4096];
char junk3[4096];
// copyout() must fault a COW page in before writing to it: read a pipe
// into a page the child shares with the parent. Without the fault-in,
// the read writes through the shared page or fails.
void
filetest()
{
printf("file: ");
buf[0] = 99;
for (int i = 0; i < 4; i++) {
if (pipe(fds) != 0) {
printf("pipe() failed\n");
exit(-1);
}
int pid = fork();
if (pid < 0) {
printf("fork failed\n");
exit(-1);
}
if (pid == 0) {
pause(1);
if (read(fds[0], buf, sizeof(i)) != sizeof(i)) {
printf("error: read failed\n");
exit(1);
}
pause(1);
int j = *(int *)buf;
if (j != i) {
printf("error: read the wrong value\n");
exit(1);
}
exit(0);
}
if (write(fds[1], &i, sizeof(i)) != sizeof(i)) {
printf("error: write failed\n");
exit(-1);
}
}
int xstatus = 0;
for (int i = 0; i < 4; i++) {
wait(&xstatus);
if (xstatus != 0) {
exit(1);
}
}
if (buf[0] != 99) {
printf("error: child overwrote parent\n");
exit(1);
}
printf("ok\n");
}
int
main(int argc, char *argv[])
{
simpletest();
simpletest();
threetest();
threetest();
threetest();
filetest();
printf("ALL COW TESTS PASSED\n");
exit(0);
}
simple is the test COW exists for: it holds two thirds of memory and forks. Without COW its output is the simple: fork() failed above; with it, the child shares the parent’s pages, exits without writing, and the parent gives the memory back with sbrk(-sz). It runs twice because the second run starts from whatever state the first left in the allocator: a count that was not restored shows up there.
three has no failing counterpart without COW; against the unpatched kernel it prints three: ok, because a copying fork of 32 MiB three times fits. It exists to check the implementation: a parent and two descendants write the same pages in different orders, so the counts reach three and come back, and every process re-reads what it wrote and the parent re-reads after its children are gone. A count that is off by one makes a page be freed while a process still maps it, or never; a missed copy makes the parent see a child’s 9999. file also passes on the unpatched kernel. Against the patched kernel without the copyout hunk it is the test that fails, and Exercise (c) shows how.
Exercises
(a) Delete krefinc((void *)pa); from uvmcopy, rebuild, and run cowtest. Say which line of the output is first and what the kernel was checking when it stopped.
Answer
Observed, in a scratch copy of the pinned tree with the patch applied and that one line deleted, on one hart:
$ cowtest
simple: usertrap(): unexpected scause 0x2 pid=3
sepc=0x1000 stval=0xb000
panic: kfree: refcount
The first casualty is not a test but the process running one: pid=3 is cowtest itself (the shell is 2), killed for an illegal instruction (scause 2) after it has printed simple: . The panic is the check if (PGREF(pa) < 1) panic("kfree: refcount"): some page’s count was already zero when a kfree reached it, which is a page freed twice. By the code, that is what the missing line allows. Without krefinc every shared page has a count of one while two page tables map it. The first share is init’s fork of sh at boot, before any shell exists; each later shell command repeats it. The child’s exec releases the table it copied, which takes each count to zero and puts the parent’s live pages on the free list, where the next kalloc (the new program’s own pages) finds them. The damage starts before cowtest’s first fork, and the kernel does not stop until a page is released twice.
(b) Make cowfault always copy, even when the count is 1, so cowtest still passes; then count the extra copies with a counter in a scratch build. What do they cost?
Answer
Observed with two scratch builds, each with a pair of global counters (cow_take bumped where the reference takes the page over, cow_copy where a page is copied) printed from kexit when the exiting process is named cow…, one hart, one run of cowtest from boot. The reference build ends at take=12295 copy=44251. The always-copy build ends at take=12798 copy=56546, and cowtest prints ALL COW TESTS PASSED in both (the counters are kernel-wide since boot, so take in the second build counts the stores that would have been take-overs). The difference in copies, 56546 − 44251 = 12295, is exactly the reference build’s number of take-overs: every one became a kalloc, a 4096-byte memmove and a kfree, 28 percent more copies in a run whose only work is writing memory. The cost is not correctness, which is why the always-copy kernel passes; it is that the take-over is the case COW exists to make free (a parent writing after its children are gone), and it is also the case that cannot fail for want of memory, which a copy can.
(c) Remove the copyout hunk and leave the rest of the patch. Run file alone (a scratch cowtest whose main calls only filetest). What fails first, and why there?
Answer
Observed, in a scratch tree with the patch applied and the if (*pte & PTE_COW) { … } block deleted from copyout:
$ cowtest
file: pipe() failed
$ error: read failed
Two failures, in two processes, and the first is not the read the test is about. pipe(fds) is a system call that stores two integers into the user’s fds array, through copyout; fds is a global, so after the first fork its page is COW in the parent, and copyout’s (*pte & PTE_W) == 0 test refuses the store. That is the second iteration of the parent’s loop. The child’s read(fds[0], buf, …) fails the same test on buf. With the patch intact, file: ok. The lesson is the breadth of the hunk: a system call that looks like it only reads (pipe) writes user memory, and every such call goes through the one function.
(d) Chapter 4’s PTE has G at bit 5 and A at bit 6. Make PTE_COW bit 6 and run cowtest. What happens, and does it show the bit is a safe choice?
Answer
cowtest prints ALL COW TESTS PASSED with PTE_COW as bit 6, and with bit 5; the test does not distinguish them, which is the reason a test is not an argument here. The privileged specification gives both bits a meaning the hardware acts on. Bit 6 is the accessed bit: “When a virtual page is accessed and the A bit is clear, the PTE is updated to set the A bit” (the scheme in force without the Svade extension, under which it faults instead). Bit 5, G, is a global mapping, and “marking a non-global mapping as global is a software bug”. Linux’s arch/riscv/include/asm/pgtable-bits.h at v7.2.8 (lines 16 to 19) says the same of the layout: _PAGE_GLOBAL (1 << 5), _PAGE_ACCESSED (1 << 6) “Set by hardware on any access”, _PAGE_SOFT (3 << 8) “Reserved for software”.
The failure the bit-6 build allows is a store to read-only text. A scratch program forks, and the child stores into main. With PTE_COW at bit 8 the child is killed (usertrap(): unexpected scause 0xf pid=4) and the parent prints parent done. With bit 6, on the same kernel and QEMU: child stored into its own text. QEMU sets the accessed bit in the PTE when the text page is fetched from (the no-Svade scheme quoted above), and cowfault read that bit as PTE_COW; the page’s count was two (parent and child), so it gave the child a private, writable copy of its own code. Only RSW bits 8 and 9 are the software’s.
(e) Chapter 13’s spawn is on ember’s single page table. Of this patch’s fourteen hunks, which would still mean something on ember, and which could not exist?
Answer
Read from the sources. The ones that cannot exist are the two uvmcopy hunks: it builds a child’s table from a parent’s, and ember has one table (satp is never switched, as ember/proc.c says in its header; chapter 13: “this kernel has one page table”), so there is no second table to point at the parent’s pages, and a second mapping of the same page in the one table would have to be at a different virtual address, which a program linked for its own base cannot use. Every other hunk has a counterpart but nothing in ember to trigger it. PTE_COW: ember/pt.h defines the PTE bits through PTE_D (bit 7), so bit 8 is free. The count and the changed kfree: ember/kalloc.c is a free list with no metadata, and the comment on kfree_page says a page freed twice is pushed twice (chapter 9, Exercise (a), shows what the list then does); a count is the fix for that bug as well as for sharing. The trap hook: chapter 5 delegates page faults to S (medeleg bits 12, 13 and 15, ember/trap.c), but trapper handles only illegal instruction, the two interrupts and ecall, and anything else prints S: unexpected scause= and halts; a store page fault has no case. copyout: ember/copyio.c’s copy_out_user finds the physical page from the PTE’s V and U bits and writes to it; it has no W test at all, so on a COW ember that function would be the first thing to change and would need more than xv6’s one hunk. Makefile and defs.h are xv6’s plumbing and only their names change.
(f) The count is read and written under kmem.lock. Name the race that removing the lock would allow when xv6 runs with three harts, and then try to catch it.
Answer
The race is two holders of one page changing its count at once. PGREF(pa)++ is a load, an add and a store; so is PGREF(pa)--. A parent and its child share a page (count 2). The parent forks again, which raises it, while the child forks, which raises it, on two harts: both load 2, both store 3, and the page has four holders and a count of three. The last kfree frees it with one holder still mapping it. The same interleaving between a krefinc and a kfree has two outcomes: a lost release leaves the count too high and leaks the page, and a lost increment leaves it too low and frees the page early. The krefcount(...) == 1 test in cowfault takes the lock to read the count but holds none across the decision that follows, and is safe for the reason given with that function: a count of one has no other holder that could change it. Any two holders will do: a parent and its child here, or two children of one parent forking at once.
Observed: with acquire and release removed from krefinc and from the decrement in kfree, CPUS=3 and the harts up (hart 2 starting, hart 1 starting), three runs of cowtest in a row passed in each of two boots. The race is in the source and the tests do not trigger it, which is the use of a lock that the reader can only get by reading, not by running.
Lab
make lab CH=16
make lab CH=16 IMPL=mine
labs/ch16/build.sh fetches xv6-riscv at commit 06aad25c735fd3159bdfae5680be4eab7b1668b2 from https://github.com/mit-pdos/xv6-riscv into ${XDG_CACHE_HOME:-$HOME/.cache}/hp/ch16/, outside the tree, resets that checkout to the pin on every run, applies every *.patch in the patch directory it is given, copies cowtest.c into the checkout’s user/ and builds the kernel and the file system image with xv6’s own Makefile: kernel/kernel and fs.img, one hart (CPUS=1), the cross prefix of whichever of riscv64-linux-gnu- and riscv64-unknown-linux-gnu- is installed. The patch is the object you read and edit. A cached checkout is never edited by hand: the build resets it, so a change you want to keep goes in the patch (git -C <checkout> diff writes one).
The boot is xv6’s own: -machine virt -bios none -kernel out/kernel -m 128M -smp 1, with -global virtio-mmio.force-legacy=false and the file system as a virtio-blk disk. -snapshot keeps QEMU’s writes to the disk out of out/fs.img, and build.sh copies a fresh image every run, so no run starts from the file system the last one left. input.txt holds the two commands the shell runs: cowtest, then usertests -q. run.sh feeds them two seconds after QEMU starts. Fed at once, QEMU hands the first byte to the UART before xv6 has initialised it, and the driver discards it; the first run of this lab printed owtest and exec owtest failed.
xv6 has no poweroff. run.sh follows the console and stops QEMU when ALL TESTS PASSED or a panic: line appears; timeout (300 s) bounds a run that reaches neither. The capture is the console from xv6 kernel is booting to ALL TESTS PASSED. Three things in it are not what they look like:
usertestsprovokes faults on purpose (writes through null, pastMAXVA, into kernel memory) and the kernel reports each as ausertrap(): unexpected scauseline with the process id and thensepcandstval. The process ids were identical in every run on both hosts (straylight: four transcripts including a cold rebuild;talos: three). If one ever drifts, adds/pid=[0-9]*/pid=PID/torun.sh’ssedbeside thesepcandstvalrules and re-capture; the verdicts and fault counts would stay pinned. The two addresses move when the toolchain does (the same source built withriscv64-linux-gnu-and withriscv64-unknown-linux-gnu-differs in code addresses), sorun.shreplaces them withADDR. Nothing else in the capture is edited.$ cowtestis followed at once byusertests -q: the console driver echoes characters when they arrive (kernel/console.c:173-174), not when the shell reads them, and both lines arrive together. The echo is the second command’s, before the first one’s output.- A
userteststest that provokes a fault printstest NAME:, then the kernel’susertraplines, thenOK: its verdict lands on a line of its own.
The capture is the transcript of cowtest’s six ok lines, ALL COW TESTS PASSED, then usertests -q’s verdicts and ALL TESTS PASSED. Two runs on straylight were byte-identical to each other and to capture.txt, and the build on talos matches it.
Timings, measured on 2026-09-30. usertests -q under QEMU’s TCG (software CPU emulation): on straylight run.sh reports the pass marker 39 s after QEMU started (the two-second feed delay included); on talos, 89 s. A cold make lab CH=16 on talos with an empty cache (the clone, the build and the run) took 1 min 27 s.
IMPL=mine applies labs/ch16/mine/patches/0001-cow-fork.patch, which is the reference patch with cowfault’s body replaced by printk("MINE: cowfault stub\n"); return 0; (xv6’s kernel prints with printk). The kernel builds and boots, the banner and $ cowtest match, and the transcript diverges at the line after usertests -q where simple: ok was expected: MINE: cowfault stub and usertrap(): unexpected scause 0xf pid=3, the shell’s child; then the same for the shell, pid=2; then for init, pid=1; then panic: init exiting. The stub kills the parent as well because uvmcopy cleared W in the parent’s PTEs, and the first store to the parent’s stack after the fork returns faults. run.sh stops at the panic.
Further reading
- xv6-riscv at commit
06aad25(MIT PDOS) — the pinned commit; every file quoted above is read at it. - xv6: a simple, Unix-like teaching operating system (Russ Cox, Frans Kaashoek, Robert Morris, rev4, August 2024) — the book that describes this design; its names for the kernel’s functions predate the pinned commit’s
kprefixes. - The RISC-V Instruction Set Manual, Volume II: Privileged Architecture (RISC-V International, v20260120) — the Sv39 page table entry, the RSW field, the accessed bit and
sfence.vma.