Copy-on-write and shared pages
About this lesson
fork() promises the child its own copy of the parent's memory, yet on Linux it copies none of the program's pages up front. The trick is copy-on-write: the kernel copies the page table, not the pages, and marks the shared pages read-only. Follow one global variable through fork, a refused write, a page fault and a single page copy, and see why reads stay shared for good. The lessons on fork, exec and wait and on the kernel's page tables show the pieces this lesson puts together.
Copying is expensive
fork() must give the child its own copy of the parent's memory. Copying every page at once is slow, and often wasted: many children call exec(), which loads a new program, and throw the copy out. Copy-on-write puts off each copy until someone writes.
the whole program (C99, POSIX):
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int x = 1;
int main(void) {
pid_t pid;
pid = fork();
if (pid == 0) x = 2;
else wait(NULL);
printf("x=%d\n", x);
return 0;
}
fork() child gets a copy of the address space
exec() often called next: replaces it all
COW copy a page only when it is writtenRead the lesson step by step
Copying is expensive
fork() must give the child its own copy of the parent's memory. Copying every page at once is slow, and often wasted: many children call exec(), which loads a new program, and throw the copy out. Copy-on-write puts off each copy until someone writes.
the whole program (C99, POSIX): #define _POSIX_C_SOURCE 200809L #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> int x = 1; int main(void) { pid_t pid; pid = fork(); if (pid == 0) x = 2; else wait(NULL); printf("x=%d\n", x); return 0; } fork() child gets a copy of the address space exec() often called next: replaces it all COW copy a page only when it is writtenPages, frames and entries
Each process has a page table. An entry names the frame of physical memory holding a page, and whether writes are allowed. The parent's code page sits in frame 4, read-only (R); its data page, with x = 1, in frame 5, writable (RW).
parent's page table code page -> frame 4 R (the program) data page -> frame 5 RW (int x = 1) a page is 4096 bytes on x86-64 R = read only RW = read and write (x86: the W bit of the entry)fork copies the table
Line 1 calls fork(). The kernel gives the child a new page table and copies the parent's entries into it, not the pages. Both tables now point at the same two frames. Not one byte of the program's memory was copied.
line 1 pid = fork(); kernel new page table for the child entries copied: code -> 4, data -> 5 memory frames copied: none fork(2): "the only penalty that it incurs is the time and memory required to duplicate the parent's page tables, and to create a unique task structure"Both made read-only
Before fork returns, the kernel clears the write bit on the data page in both tables: 5 · RW becomes 5 · R. It also notes that frame 5 now has two users. Either process may read it; neither may write.
parent data -> 5 RW -> R (marked copy-on-write) child data -> 5 RW -> R (marked copy-on-write) users frame 4: 2 frame 5: 2 the kernel keeps a count per frame, and marks the page as copy-on-write (the xv6 lab uses a spare RSW bit in the RISC-V page table entry)Reading costs nothing
Reads need no help. Both processes read x = 1 straight from frame 5 and run the same code from frame 4. The code page was read-only from the start, so it stays shared for good: two processes, one copy.
read x parent -> frame 5 -> 1 child -> frame 5 -> 1 run code both -> frame 4 shared read-only for good: program code, and libraries mapped into many processesThe child writes x
The child runs line 2, x = 2. The CPU's memory unit (MMU) looks up the child's entry for the data page: frame 5, read-only. It refuses the store before any byte changes and raises a page fault into the kernel.
line 2 if (pid == 0) x = 2; (child: pid == 0) MMU child data page -> frame 5 R store refused: nothing in frame 5 changed trap page fault -> kernel modeThe kernel copies one page
The kernel sees a copy-on-write page, not a bug. It takes free frame 6, copies all 4096 bytes of frame 5 into it, and points the child's entry at frame 6 with writing allowed: 6 · RW.
fault child, data page, write, entry is COW frame 5 2 users: still shared, so copy copy frame 5 -> frame 6 (4096 bytes) child data -> 6 RW users frame 5: 1 frame 6: 1 a write to a page that was never writable (code) is a real error: the process is killed (on Linux, by the signal SIGSEGV)The store runs again
The kernel returns from the fault, and the CPU runs the same store again. This time the entry allows it, so frame 6 now holds x = 2. Frame 5 still holds x = 1, and only the parent uses it.
return from the page fault, back to user mode retry the same store instruction MMU child data page -> frame 6 RW ok frame 6 x = 2 frame 5 x = 1 (parent only)Each sees its own x
The child prints x=2 and exits; the parent, done waiting, prints x=1. Same address, different frames: each process saw only its own writes, exactly as if fork had copied everything.
child line 4 -> frame 6 -> prints x=2, exits parent line 3 waits for the child line 4 -> frame 5 -> prints x=1 output: x=2 x=1 if the parent writes x later, it faults too; frame 5 now has one user, so the kernel can just make the entry writable again, with no copyWhy copy-on-write wins
Only pages that are written get copied, one at a time, when it happens. A child that calls exec() at once copies almost nothing. The same trick backs private file mappings, and Linux KSM merges identical pages into one write-protected copy.
copy-on-write as a Python simulation: frames = {4: "code", 5: "x=1", 6: None} # physical memory users = {4: 1, 5: 1, 6: 0} # tables using each frame parent = {"code": [4, "R", False], "data": [5, "RW", False]} def fork(table): # copy entries, not pages child = {} for page, e in table.items(): if e[1] == "RW": e[1], e[2] = "R", True # read-only, copy-on-write child[page] = list(e) users[e[0]] += 1 return child def write(table, page, value): frame, perm, cow = table[page] if perm == "R": # page fault if not cow: raise PermissionError(page) if users[frame] > 1: # still shared: copy it new = min(f for f in users if users[f] == 0) frames[new] = frames[frame] users[frame] -= 1 users[new] = 1 frame = new table[page] = [frame, "RW", False] frames[frame] = value child = fork(parent) write(child, "data", "x=2") # copies frame 5 to 6 print(frames, users) write(parent, "data", "x=3") # last user: no copy print(frames, users) prints: {4: 'code', 5: 'x=1', 6: 'x=2'} {4: 2, 5: 1, 6: 1} {4: 'code', 5: 'x=3', 6: 'x=2'} {4: 2, 5: 1, 6: 1}
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01What does a copy-on-write fork() copy for the child straight away?
The child gets its own page table, filled with copies of the parent's entries. The frames themselves are shared. fork(2) says the only cost is duplicating the page tables and creating the child's task structure.
02Why does the kernel clear the write bit on writable pages in BOTH tables at fork?
If either side could write the shared frame directly, the other would see the change. Read-only entries turn the first write into a page fault, which is the kernel's chance to copy.
03The child writes x = 2 to a copy-on-write page. In what order do things happen?
The store is refused before any byte changes. The fault handler sees a copy-on-write page, copies it, makes the child's entry writable and returns; the retried store then succeeds in the child's new frame.
04After the copy, the parent writes to its own x. The frame now has only one user. What can the kernel do?
The kernel keeps a count of page tables using each frame. With one user left there is nobody to protect, so a kernel that keeps this count can simply restore the write permission.
05Which of these is NOT copy-on-write?
MAP_SHARED is real sharing: every process maps the same frames and sees the others' writes. MAP_PRIVATE is a private copy-on-write mapping, and KSM replaces identical pages with one write-protected page that is copied when someone writes.
Glossary
- Page
- A fixed-size block of a process's virtual memory, 4096 bytes (4 KB) on x86-64 by default.
- Frame
- A page-sized block of physical memory. A page table entry says which frame holds a page.
- Page table entry
- One row of a page table: the frame for a page plus permission bits such as the write bit.
- Copy-on-write (COW)
- Sharing a page read-only between address spaces and copying it only when one of them writes.
- Page fault
- The exception the MMU raises when an access breaks the page table's rules, such as a write to a read-only entry. It enters the kernel.
- MMU
- The memory management unit in the CPU. It looks up every access in the current page table and checks its permissions.
- Reference count
- The kernel's count of how many page tables use a frame. The frame is freed only when the count falls to zero.
Notes and sources
- Frame numbers 4, 5 and 6 are made up for the picture: a real kernel takes whatever frames its free list hands out. A real process also has many more pages (stack, heap, libraries); the lesson shows the two that matter.
- R and RW stand for the write bit in a page table entry (W on x86). A normal x86-64 page is 4096 bytes (4 KB); larger huge pages exist too.
- In a real fork the kernel copies each entry and clears its write bit in the same pass; the figure shows the copy and the write-protect as two steps. Which process runs first after fork is not fixed: here the parent's wait() makes the child print first.
- The kernel keeps a count of how many page tables use each frame. A frame goes back on the free list only when the last user lets go, which is why frame 5 is not freed when the child moves to frame 6.
- Copy-on-write is not only for fork. mmap with MAP_PRIVATE maps a file copy-on-write, so your writes never reach the file; MAP_SHARED is the opposite, and every process sees the same frames and each other's writes.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 23: Complete Virtual Memory Systems (copy-on-write)
- MIT 6.1810 (2024), Lab: Copy-on-Write Fork for xv6
- Berkeley CS162, Lecture 15: page table entries and the copy-on-write usage example
- Berkeley CS162, Lecture 16: page faults that fix the situation and retry the instruction
- Linux man-pages: fork(2)
- Linux man-pages: mmap(2)
- Linux kernel documentation: Kernel Samepage Merging
- Linux kernel documentation: Concepts overview (memory)
Quiz Unlocks after the last step.