Copy-on-write

Also known as: COW

On this page 7

Copy-on-write (COW) is a memory management technique in which several processes or mappings share the same physical pages marked read-only, and the kernel creates a private copy of a page only when one of them writes to it. In operating systems, it is the mechanism that makes process creation with fork() cheap, lets shared libraries and memory-mapped files load efficiently, and underpins snapshots in modern file systems and hypervisors.

The idea rests on a simple observation: most duplicated memory is never modified. By postponing the copy until a write actually happens, the system saves time, physical memory and cache bandwidth, and pays the cost only for the pages that truly diverge.

How copy-on-write works in the page table

Copy-on-write works by combining read-only page table entries with the page fault handler. When the kernel duplicates an address space, it does not copy the underlying page frames. Instead, it points the page table entries of both address spaces at the same physical frames, clears the writable bit in each entry and increments a per-frame reference count.

Reads proceed at full speed because the memory management unit translates both virtual addresses to the shared frame. A write, however, violates the read-only protection and triggers a protection fault. The kernel recognizes the fault as a COW fault, because the region itself is logically writable, and resolves it in a fixed sequence.

  1. The fault handler checks the reference count of the shared frame.
  2. If other mappings still use the frame, it allocates a new frame and copies the page contents, typically 4 KiB.
  3. It updates the faulting process’s page table entry to point at the new frame with write permission restored.
  4. It decrements the reference count of the original frame and flushes the stale TLB entry.
  5. If the count shows that only one mapping remains, the kernel simply makes the page writable again without copying.

The table below summarizes the state of a single page as it moves through the copy-on-write life cycle.

StagePage table entryReference countPhysical frames used
After forkRead-only in both processes21
Read by either processUnchanged21
First write by childChild gets new writable entry1 on each frame2
Parent writes laterParent made writable, no copy12
Life cycle of a copy-on-write page

Where operating systems apply copy-on-write

Operating systems apply copy-on-write wherever logically separate copies start out identical. The best-known case is the Unix fork() system call, but the same mechanism appears in loaders, file mappings and storage layers.

Use caseWhat is sharedBenefit
Process creation with forkEntire parent address spaceFork costs page table setup, not data copying
Private file mappingsPage cache pages of a fileWrites stay private, file stays unchanged
Shared library data segmentsInitialized data of a libraryMany processes share pages until modified
Zero page mappingOne global page filled with zerosUntouched allocations consume no frames
File system snapshotsDisk blocks of a volumeInstant snapshots, new blocks on change
Virtual machine cloningGuest memory or disk imagesFast cloning and memory deduplication
Common uses of copy-on-write

In Linux, a private mapping created with the MAP_PRIVATE flag of mmap() uses copy-on-write against the page cache. Windows exposes the same behavior through the PAGE_WRITECOPY protection and uses it for image sections of executables and DLLs. The zero page is a special case: anonymous memory is initially mapped to a single shared zero-filled frame, and a real frame is allocated only on the first write.

Copy-on-write is one of several lazy allocation strategies in virtual memory, and it is easy to confuse with its neighbors. The key distinction is that copy-on-write defers copying existing data, whereas related techniques defer loading or allocating it.

TechniqueWhat is deferredTriggerTypical example
Copy-on-writeDuplicating a shared pageWrite to a read-only shared pageChild process after fork
Demand pagingLoading a page from diskFirst access to a non-resident pageStarting a large program
Eager copyingNothing, copy happens immediatelyThe duplication itselfEarly Unix fork implementations
Shared mappingNothing, writes are visible to allNot applicableShared memory between processes
vforkCreating a separate address spaceChild calls exec or exitsShells spawning commands
Copy-on-write and neighboring concepts

The difference from a shared mapping matters in practice. With MAP_SHARED, a write by one process is immediately visible to all others and may reach the underlying file. With copy-on-write, each writer receives a private version and the original remains untouched, which preserves the semantics of a full copy.

Performance effects and tuning

Copy-on-write makes duplication fast, but it moves cost into later page faults. Each COW fault involves a trap into the kernel, a frame allocation, a 4 KiB copy and a TLB update, which together typically cost a few microseconds on current hardware. A process that writes to most of its inherited pages after fork therefore pays almost the full copying cost, only spread over time.

Several factors determine whether copy-on-write saves or costs time, and the following table lists the most relevant ones.

FactorEffectPractical guidance
Huge pagesOne write copies 2 MiB instead of 4 KiBWatch latency spikes after fork with large pages
Write-heavy childMost pages copied anywayConsider posix_spawn or exec soon after fork
Large parent heapPage table copying still takes timeFork latency grows with mapped memory size
Multithreaded parentTLB shootdowns on many coresAvoid fork in heavily threaded programs
Memory overcommitCopies may fail when memory runs outMonitor commit charge and out of memory events
Factors that change copy-on-write behavior

A well-known pattern is the snapshot by fork used by in-memory databases: the parent keeps serving requests while the child writes a consistent image to disk. The approach is elegant, but under heavy write load the parent may nearly double its resident set size, so administrators reserve memory headroom accordingly.

Limitations, risks and common mistakes

Copy-on-write is not free of correctness and security pitfalls. Because it relies on precise reference counting and page table updates under concurrency, it has been a source of serious kernel bugs, including the Dirty COW vulnerability in Linux, a race condition that let unprivileged users write to read-only files.

  • Memory accounting surprises: a fork appears to consume no memory, yet later writes can trigger allocation failures or the out of memory killer.
  • Unpredictable latency: real-time code may stall on a COW fault at an awkward moment; such code often locks and pre-touches memory.
  • Fragmented copies on disk: copy-on-write file systems can fragment files that receive many small random writes, such as database files.
  • Misreading memory statistics: shared COW pages are counted in the resident set size of every process, so summing RSS overstates real usage.

A non-technical view

Imagine two students who need the same textbook. Instead of printing a second copy right away, the library lets them share one book. Only when one student wants to write notes in the margins does the library make that student a personal copy of that single page.

Copy-on-write does the same with computer memory. Programs share identical pieces of memory for as long as they only read them. The computer makes a separate copy only when something changes, so it saves time and space.

A concrete example

A web server process on Linux uses 2 GB of memory, mostly configuration data, compiled code and cached lookup tables. To handle traffic, it forks eight worker processes. Without copy-on-write, the system would need about 18 GB and spend seconds copying data. With copy-on-write, each fork completes in a few milliseconds, because the kernel copies only page tables.

During operation, each worker writes to its own request buffers and counters, which amounts to roughly 150 MB per worker. Those pages are copied on first write, while the remaining shared data stays in common frames. Total physical usage settles near 3.2 GB instead of 18 GB, and the administrator can run more workers on the same machine.