
Recall first from The lazy lab and lazytests
- The pinned xv6 commit already contains lazy allocation; the lab switches off the usertrap branch, watches usertests fail, and rebuilds it.
- usertests contains five lazy cases (lazy_alloc, lazy_unmap, lazy_copy, lazy_copyinstr, lazy_sbrk) that cover access after growth, shrinking, fork, kernel copies and the TRAPFRAME limit.
- When kalloc fails inside vmfault, vmfault returns 0 and usertrap kills the process with the unexpected scause message; the kernel never panics for a user's memory demand.
What fork really copies
4 min readM3-S05A made allocation lazy to save work; fork still copies every page eagerly. This lesson measures that cost and introduces copy-on-write, where parent and child share pages read-only and only a write triggers a private copy.
Every command you type into the xv6 shell starts the same way: sh calls fork, and the child calls exec to load the program. kfork in kernel/proc.c does the copy with one call, uvmcopy(p->pagetable, np->pagetable, p->sz), and the loop you read in the last session does real work for every valid page below sz: kalloc a fresh page, memmove 4096 bytes into it, and mappages it into the child's page table with the parent's flags. The child gets a full private duplicate, which is what the semantics of fork require: after the call, a store by either process must not be visible to the other.
Then the child calls exec. kexec in kernel/exec.c builds a completely new page table for the new program, loads its segments, sets up a fresh stack, and only then frees the old page table and every page in it. Every page that uvmcopy copied for that child is freed without having been read once. The copy was pure overhead.
You already saw the shell pay this price. In the instrumented run from the fork and walkaddr lesson, the first console line after typing lazyfork was uvmcopy: copied 5 pages, skipped 0 holes: the shell duplicating all five of its pages for a child whose only job was to call exec("lazyfork", ...). Five pages is small because sh is small. The cost is per page of the parent, so it is paid again for every command, and it grows with whatever the parent has accumulated: a large heap, big buffers, a long history.
Measuring it
Claims about cost are cheap; a counter is better. Add a global to kernel/vm.c, increment it right after the memmove in uvmcopy, and expose it through a system call (SYS_pgcopies, number 23 in a clean tree, wired through the usual five files):
// kernel/vm.c (lab addition)
uint64 pgcopies; // pages copied by fork or by COW faults
// kernel/sysproc.c (lab addition)
uint64
sys_pgcopies(void)
{
extern uint64 pgcopies;
return pgcopies;
}
A test program reads the counter around two experiments. The first forks a child that immediately runs echo hi. The second grows the heap by 64 pages, fills them, forks, and lets the child write a single byte:
// user/copycount.c (lab program)
#include "kernel/types.h"
#include "kernel/riscv.h"
#include "user/user.h"
int
main(void)
{
char *argv[] = {"echo", "hi", 0};
int before = pgcopies();
if (fork() == 0) {
exec("echo", argv);
exit(1);
}
wait(0);
printf("fork+exec of echo: %d pages copied\n", pgcopies() - before);
char *p = sbrk(64 * PGSIZE);
memset(p, 7, 64 * PGSIZE);
printf("parent size now %d pages\n", (int)((uint64)sbrk(0) / PGSIZE));
before = pgcopies();
if (fork() == 0) {
p[0] = 1; // the child writes one heap page
exit(0);
}
wait(0);
printf("fork + one write in child: %d pages copied\n", pgcopies() - before);
exit(0);
}
On the stock pinned kernel, a real run printed:
$ copycount
hi
fork+exec of echo: 4 pages copied
parent size now 68 pages
fork + one write in child: 68 pages copied
The small program has four pages (program, guard, stack), and all four were copied for a child that ran exec straight away. The second fork copied all 68 pages so the child could change one byte. The cost grows with the parent's size, not with what the child does. A process with a few hundred megabytes of heap that forks to run a shell command pays for a few hundred megabytes of copying, and needs that much free memory: if there is not enough, uvmcopy fails and fork returns -1.
The MIT copy-on-write lab ships a test, cowtest, whose first case uses exactly that limit. It allocates two thirds of physical memory, fills it, and forks. On the stock kernel the real result is immediate:
$ cowtest
simple: fork() failed
Two thirds plus two thirds does not fit in one machine, even though the child only calls exit.
Share read-only, copy on write
4 min readThe observation behind a technique where processes share the same physical pages read-only after fork and a page is duplicated only when one of them first writes to it is that a copy only matters once the two processes disagree about a page's contents, and they can only disagree after one of them writes. Until then one physical page can serve both.
The mechanism uses pieces you already know from the lazy allocation lessons:
Share at fork: for each valid page,
uvmcopymaps the parent's physical page into the child instead of allocating a new one.Remove write permission: for writable pages it clears
PTE_Win both page tables and marks the PTE as copy-on-write, so the hardware will refuse a store.Trap the first store: a store by either process raises a store/AMO page fault,
scause15, exactly the signal lazy allocation used.Copy for the writer: the fault handler allocates a page, copies the shared contents, maps the copy writable in the faulting process only, and the store runs again.
Pages that were never writable, such as program text, need no special treatment at all: neither process may write them, so sharing them is always safe. Only writable pages carry the copy-on-write mark.
Two new problems appear, and they are the subject of the next two lessons. First, a physical page may now be mapped by several page tables, so it must not return to the free list when one of them unmaps it; the kernel needs a count of sharers per page. Second, the fault handler must tell a copy-on-write fault apart from a store to a page that is read-only for a real reason, such as text, which must still kill the process.
Built that way, the same copycount program on the copy-on-write kernel of the next lessons printed this in a real run:
$ copycount
hi
fork+exec of echo: 2 pages copied
parent size now 68 pages
fork + one write in child: 1 pages copied
Sixty-eight copies became one, the page the child wrote. And cowtest's first case, the fork that could not fit, printed simple: ok. Fork still has fixed costs: allocproc allocates a trapframe page and a page table for the child, and mappages allocates page-table pages as it installs the shared mappings. Those grow with the number of mappings, not with the bytes behind them.
This is not a teaching trick. The Linux fork(2) manual page explains in its notes that Linux implements fork with copy-on-write pages, so the remaining cost is the time and memory to duplicate the parent's page tables and to create the child's task structure. The design you are about to build in xv6 is the same idea at a smaller scale, with the same two supporting pieces: a per-page count of sharers and a fault handler that knows which read-only pages are really writable.
Going deeperCopy-on-write and exec
The pattern that made stock fork wasteful, fork followed immediately by exec, is the pattern that copy-on-write helps most. Between fork returning in the child and exec replacing its address space, the child runs only a few instructions, and nearly all of them read. In the real run above, a lab printk in the fault handler showed that the two copies for the echo experiment were both of the same stack page, at virtual page 0x3000: once when the child wrote its stack before calling exec, and once when the parent wrote its own stack after fork returned. Then kexec built the child a new page table and freed the old one, which for shared pages only drops the child's share. The parent's 68 pages, its text, and everything else never moved. One of those two copies is even avoidable: once the child has its own copy, the parent is the last process mapping the original page, so it could simply be made writable again instead of copied. The cow lab lesson adds that shortcut and measures it.
Copy-on-write needs two things the kernel does not have yet: a way to know how many page tables map a physical page, and a mark in the PTE that says this page is read-only only for now. The next lesson, reference counting and marking COW pages, adds both.
Key takeaways
- Stock uvmcopy calls kalloc and memmove for every valid page below sz, so forking a 68-page process copied 68 pages even though the child wrote one.
- exec builds a new page table and frees the old one, so pages that fork copied for a child that then calls exec are thrown away unused.
- With copy-on-write, fork maps the parent's physical pages into the child, clears PTE_W in both and lets a store page fault make a private copy for the writer.
- In a real run the COW kernel copied 2 pages for a fork plus exec of echo and 1 page for a fork followed by one write, against 4 and 68 on the stock kernel.
Reflect
- Explain to a colleague, in two sentences: explain what kfork and uvmcopy allocate and copy for each page of the parent.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Source codexv6-riscv kernel/vm.c (uvmcopy)
- Source codexv6-riscv kernel/proc.c (kfork)
- Source codexv6-riscv kernel/exec.c (kexec)
- Bookxv6: a simple, Unix-like teaching operating system (RISC-V book)
- Man pagefork(2) Linux manual page
Official documentation first. Links checked when the lesson was published.