Highlights

Contents

Part VIII
08

Copy-on-write and mappings

Process creation, file loading and allocation all use virtual mappings. Copy-on-write delays copies until a write, mmap gives files and anonymous memory an address-space view, and allocators serve small requests above kernel primitives. We will connect those mechanisms to stack lifetime, heap fragmentation and shared mappings.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1OS fundamentals2Processes3Fork, exec and threads4Synchronization5Deadlocks6CPU scheduling7Paging and memory8Copy-on-write9Filesystems10I/O and IPC11Protection and Linux12Complete server trace

#Section 32Copy-on-write after fork

The parent and child can initially point at the same 8 pages marked read-only. A child write triggers a protection fault, the kernel allocates a new frame, copies 4,096 bytes and updates the child’s mapping. The model therefore grows from 32,768 bytes to 36,864 bytes after one private page, while 7 pages remain shared.

Copy-on-write is a sharing policy, not a promise that writes are free. Many writes create many copies, and dirty pages consume memory. Private file mappings can also use copy-on-write; shared writable mappings instead deliberately expose changes to peers.

FORK SHARES PHYSICAL PAGES; A WRITE CREATES ONE PRIVATE COPYFORK SHARES PHYSICAL PAGES; A WRITE CREATES ONE PRIVATE COPYparent mapchild mapphysical framespage 0page 0frame 0page 1page 1frame 1page 2page 2frame 2page 3page 3frame 3page 4page 4frame 4page 5page 5frame 5page 6page 6frame 6page 7page 7frame 7copybefore write: 32,768 B; after: 36,864 Bseven shared pages, one extra physical page
Figure 3.44Illustrative copy-on-write placement. Eight shared pages use 32,768 bytes; a write leaves seven pages shared and adds one private copy, increasing physical storage to 36,864 bytes.

The byte count measures unique physical page payload across parent and child, excluding page tables and kernel records. Counting both mappings as separate payload would incorrectly report a full copy immediately after fork. The new copy changes the physical-frame count from eight to nine, while each process still sees eight virtual pages. The writer’s page-table entry changes; the sibling keeps its previous mapping.

Copy-on-write intentionally faults before a private write. Shared writable mappings use another contract and deliberately expose changes to other mappings.

#Section 33mmap and file-backed memory

mmap associates a virtual range with a file or anonymous backing. The first access can fault in the relevant page, so a program can address file contents like memory without issuing a read for every byte. Dirty file-backed pages can later be written back according to mapping and synchronization rules.

The same mechanism supports shared memory, executable loading, shared libraries and anonymous arenas. read gives an explicit copy into a supplied buffer, while mmap exposes a mapping whose faults and page cache interactions are managed by the kernel.

MMAP: A FILE RANGE BECOMES ADDRESSES, AND PAGES ARRIVE ONLY WHEN TOUCHEDMMAP: A FILE RANGE BECOMES ADDRESSES, AND PAGES ARRIVE ONLY WHEN TOUCHEDfile on diskoff 0off 4096off 8192off 12288virtual address spacemapped regionp[8192]RAMpage faultdirty page written back laterloads and stores, no read() calls
Figure 3.45Illustrative file offset becomes a virtual mapping, then a page fault loads the needed page before the memory access. Orange marks the mapping because it connects file identity to an address.

A mapping records backing, not necessarily a resident frame. First access establishes residency; shared and private policies determine who observes subsequent writes.

Mapping can avoid some explicit copies but retains faults and lifetime rules. Truncation can invalidate accesses. Neither mmap nor a buffered read automatically makes later modifications durable.

#Section 34Heap allocators

malloc(100) normally asks a user-space allocator for a block from existing arenas. If it lacks space, the allocator may request more virtual memory with mechanisms such as brk or mmap. The allocator stores metadata, rounds sizes, splits blocks and coalesces freed neighbors.

Internal fragmentation is space inside an allocated block that the caller does not use. External fragmentation is free space split into pieces that cannot satisfy a larger request. Arenas can reduce lock contention for threads but can increase total retained memory. A leak is different from fragmentation: the program loses useful ownership of allocated memory instead of merely having unusable holes.

For the page-level allocation model, a 10,000-byte request needs the ceiling of 10000/409610000/4096, namely three pages. The payload allowance is 3×4096=122883\times4096=12288 bytes, leaving 12288−10000=228812288-10000=2288 unused. Read ceiling as taking enough whole pages to contain the request. A user allocator may subdivide such regions into much smaller blocks, so this calculation must not be presented as the exact cost of every malloc call.

Freeing a block returns it to the allocator’s bookkeeping, which may retain the backing region for future requests. Process resident memory therefore need not fall immediately after every free. Coalescing and arena reuse can reduce future kernel calls while retaining spare capacity. Diagnose whether bytes are still owned, available for reuse or returned to the kernel before calling every stable resident footprint a leak.

THE STACK IS A PILE OF CALL FRAMES; THE HEAP IS BLOCKS YOU MUST HAND BACKTHE STACK IS A PILE OF CALL FRAMES; THE HEAP IS BLOCKS YOU MUST HAND BACKstack (call-scoped)guard page: overflow faults heremain()handle()parse()log()return pops the frame: free in O(1)heap (explicit lifetime)usedfreeusedfreeusedfreeusedleaked?grey strip: allocator header with sizemalloc() searches free blocks; free() returns one
Figure 3.46Illustrative heap allocation tracks explicit block ownership, while stack frames follow calls. Orange marks call-scoped lifetime.

#Section 35Stack frames and overflow

A call frame commonly contains arguments, a return address, saved registers and local variables. The stack pointer identifies the current frame, while a frame pointer may help debugging when used. Recursion allocates another frame per call, so unbounded recursion can exhaust the mapped stack and fault.

The stack is not simply faster than the heap. It has structured lifetime tied to calls and often favorable locality. The heap supports data that outlives a call but needs allocator metadata and an ownership rule. A dangling pointer violates lifetime in either region.

THE STACK IS A PILE OF CALL FRAMES; THE HEAP IS BLOCKS YOU MUST HAND BACKTHE STACK IS A PILE OF CALL FRAMES; THE HEAP IS BLOCKS YOU MUST HAND BACKstack (call-scoped)guard page: overflow faults heremain()handle()parse()log()return pops the frame: free in O(1)heap (explicit lifetime)usedfreeusedfreeusedfreeusedleaked?grey strip: allocator header with sizemalloc() searches free blocks; free() returns one
Figure 3.47Illustrative drawing separates call-scoped stack lifetime, explicit heap lifetime, allocator metadata and stack overflow. Orange marks lifetime because it determines safe ownership.

Compiler and calling conventions determine which values occupy a frame. The lifetime rule remains: returning a pointer to local storage does not extend that storage’s valid lifetime.

Guard mappings detect some stack growth beyond supported space. Frame size and recursion depth both matter; callbacks need bounded stack use and owned longer-lived buffers.