Definition
Copy-on-write (COW) is a technique in which several users of some data share a single copy until one of them changes it. Only then does the writer get a private copy of the part it changes; the change goes into that copy, and the original stays untouched for everyone else. Copy-on-write saves the cost of copying data that is never changed and keeps old versions intact. Its central bookkeeping problem is knowing when a shared original is no longer used, so that its storage can be reused.
The idea
A process, a running program with its own memory, asks the operating system for an exact duplicate of itself; on Unix-like systems the call is named fork. Copying all of a 100 MiB process would take time and double the memory used, and the duplicate often replaces its memory with a different program a moment later. Copy-on-write lets both processes share the same physical memory and copies a piece only when one of them writes to it.
The same idea protects stored data. A file system that never overwrites a block in use can keep yesterday’s state of a disk, called a snapshot, at almost no cost: the snapshot and the live file system share every block that has not changed since. A crash during an update cannot damage the old state, because nothing in it was written.
Colleagues sharing one printed report give a fair picture. Anyone who wants to mark up a page first photocopies that page and writes on the copy, and the others keep reading the clean original. The picture stops at the cleanup: someone must know when the last reader has put down the original page before it can be thrown away, and in copy-on-write that is the hard part.
How it works
Copy-on-write has four parts.
Share. Several references point to one object, such as a page of memory or a block on a disk. The object is protected so that a write to it is caught: memory pages are mapped read-only, and a copy-on-write file system never writes a block in place.
Copy on the first write. A writer that wants to change a shared object gets a new object, copies the old contents into it and applies the change to the copy.
Redirect. The writer’s own reference now points to the copy. In a tree of blocks, the parent that held the reference must itself be copied, and so on up to the top, because changing the parent in place would change it for the other users too.
Reclaim. The old object is freed when no reference to it remains.
Step 4 needs a way to track sharing. Four methods are in common use.
Reference counting §9.22. Each object stores the number of references to it. Sharing raises the count, dropping a reference lowers it, and the object is freed when the count reaches zero. A write to an object whose count is 1 needs no copy, because no one else can see the object. Linux keeps such counts for each physical page of memory, and Btrfs, a Linux file system, keeps reference counts for its extents, runs of consecutive disk blocks.
Reachability §3.21. A collector starts from every root still in use, such as the live file system and each snapshot, marks every object it can reach, and frees the rest. This is a form of garbage collection §8.16.
Birth times. Each block records when it was written, and each snapshot records when it was taken. ZFS, originally the Zettabyte File System, frees a block that the live file system stops using at once if the block was written after the newest snapshot. Otherwise the newest snapshot still contains the block, and ZFS puts it on a list to examine when snapshots are deleted.
Grace periods §9.21. A thread that is reading an old version in memory holds a reference that no count records. Read-copy update (RCU) §9.20 frees an old version only after every thread that might have seen it has passed a quiescent point §14.34, a moment at which it holds no such reference.
Worked example
Memory pages. Process P uses three pages, A, B and C, of 4 KiB each. P calls fork, which creates process Q.
Both processes map A, B and C read-only, and each page has a count of 2. Physical memory used: KiB, instead of KiB for a full copy.
Q writes one byte to B. Because B is mapped read-only, the processor raises a fault, an interruption that hands control to the operating system. The operating system sees that the count of B is 2, allocates a new page B’, copies all 4096 bytes of B into B’, maps B’ writable in Q only, and lowers the count of B to 1. Memory used: KiB.
P writes to B. The count of B is 1, so no one else sees B, and the operating system makes B writable for P without copying.
Q exits. The counts of A and C fall from 2 to 1, and the count of B’ falls from 1 to 0, so B’ is freed. Memory used: KiB.
One changed byte cost a copy of 4096 bytes.
Stored versions. A snapshot references blocks X and Y. The live version changed Y, so it references X and a new block Y’. The counts are X 2, Y 1 and Y’ 1. Deleting lowers X to 1 and Y to 0: Y is freed, and X stays because still uses it. The naive rule “free every block of the deleted version” would free X as well, and would be left with a dangling pointer §4.1, a reference to storage that may now hold something else.
Stated precisely
For an object , let be the set of references to that someone may still follow: from the current version, from every retained old version, from every reader that is running, and, for stored data, from the root that recovery will use after a crash. Copy-on-write keeps two rules.
No shared write: a writer changes in place only if holds no reference other than its own; otherwise it copies and changes the copy.
No early free: the storage of is reused only when is empty.
Reference counting implements both rules with a stored count and is correct only if equals the number of references in whenever a decision is made from it. Three assumptions secure that.
Raising and lowering a count are atomic operations §9.8, so two threads that change one count at once lose neither change.
No thread can take a new reference to after has reached zero. This needs a protocol such as RCU, because a thread may have read the pointer to just before another thread dropped the last count.
For stored data, a change of a count is committed in the same atomic step as the change of references it reflects; otherwise a crash between the two leaves the count wrong.
The two kinds of wrong count are not equally bad. A count that is too high only leaks storage. A count that is too low frees storage that is still in use, which is a use-after-free §4.6.
Limits and common mistakes
Copy-on-write keeps the old version safe; it does not by itself make the new version current in a crash-safe way. A crash-safe update still needs one atomic, durable step that switches to the new version, such as the root write of shadow paging §8.9, made only after everything the new version reaches is durable.
The first write is expensive. In memory it costs a fault and a copy of a whole page, even for one byte. In a tree of blocks it costs a copy of every node on the path to the top. On storage this extra writing is write amplification §8.18, and the new blocks scatter across the disk.
Memory promised at fork is not reserved. If both processes later write to all their pages, the system needs twice the memory it started with, and Linux may then end a process with its out-of-memory killer.
The decision “the count is 1, so write in place” races with a thread that is taking a new reference. Dirty COW, a Linux kernel flaw listed as CVE-2016-5195 in the CVE (Common Vulnerabilities and Exposures) catalog, was a race condition §9.2 in copy-on-write handling that let an unprivileged user write to read-only memory mappings, and through them change files that user could only read.
Reference counting cannot free objects that refer to each other in a cycle, because each keeps the counts of the others above zero. Trees of disk blocks have no cycles; general data structures may need a collector.
Copy-on-write separates readers from a writer, not writers from each other. Two writers that copy the same object at once produce two separate copies, and only one of their changes survives unless something orders them.
Questions answered
How is sharing tracked before old storage is freed?
Sharing is tracked by recording, for each shared object, which references to it may still be followed, and the old storage is freed only when none is left. In copy-on-write, several versions or processes share one copy of data until one of them writes; the writer then gets a private copy, so the original may still be in use by others. The common tracking methods are these.
A reference count per object, raised when a reference is shared and lowered when one is dropped; the object is freed at zero. Operating systems use this for memory pages, and some file systems for disk blocks.
Reachability: start from every root still in use, such as the current version and each snapshot, mark everything that can be reached and free the rest.
Birth times: compare when a block was written with when each snapshot was taken, so that a block written after the newest snapshot can be freed at once.
Grace periods: for readers in memory, wait until every reader that might hold an old reference has finished.
Whichever method is used, the set of references must include running readers and, for stored data, the root that recovery would use after a crash. Retiring one old version frees only what no other version shares: a block referenced by two versions stays after one of them is deleted.
Related entries: Shadow paging (§8.9), Reference counting (§9.22), Quiescent point (§14.34), Ownership (§4.2), Read-copy update (RCU) (§9.20), Use-after-free (§4.6).