Skip to content

Virtual memory

ebenali edited this page Dec 1, 2026 · 2 revisions

Virtual memory, from the ground up

Part III of the system development guide.

How a kernel gives every process its own address space, fills it on demand, shares and copies memory, and gets memory back when it runs short. NetBSD's virtual memory system is UVM (Charles Cranor's design, which replaced the 4.4BSD VM in NetBSD 1.4); Linux's is the mm subsystem. The two solve the same problems with different data structures, and the compat layer lives in the gap between them, so both are described here, UVM first.

The hardware half -- page tables, TLBs, memory types -- has its own chapter; the APIs a driver uses are in Memory and DMA.

The problem

A process sees a large, private range of addresses. Most of it is empty; the parts in use come from different places:

Region Contents come from Shared?
program text the executable file yes, read-only
data the file, then private changes copy-on-write
heap, stack nowhere: zero-filled on first touch private
mmap of a file the file MAP_SHARED: yes; MAP_PRIVATE: copy-on-write
shared memory anonymous memory shared between processes yes
mmap of a device the driver (registers, GPU buffers) yes

Three ideas make this cheap:

  1. Demand paging. Nothing is copied or read when a region is set up. The page tables start empty; the first access to a page faults, and the fault handler finds or makes the page and maps it.
  2. Copy-on-write. A private copy (of a file's data, or of a parent at fork) starts as a read-only mapping of the original page; only a write makes a real copy, page by page.
  3. Paging out. Memory that has not been used for a while can be written to its backing store (the file, or swap for anonymous memory) and the RAM reused; a later access faults it back in.

UVM's data structures

 struct vmspace (one per process)
 +-- struct vm_map: the address space, a tree of entries
 |     entry [start, end)  prot  inheritance  offset
 |       |                                     |
 |       +-- aref ---> struct vm_amap ---------+--> anon, anon, ...   upper layer
 |       |             (one slot per page)          (private pages)
 |       +-- object -> struct uvm_object ---------> pages by offset   lower layer
 |                     (file, anonymous object,      (the backing)
 |                      device, ...) + its pager
 +-- struct pmap: the page tables (machine-dependent)

The map (struct vm_map, uvm/uvm_map.h) is the process's address space: a red-black tree of map entries, each covering [start, end) with one protection, one inheritance mode (what fork does with it) and the two layers below. mmap adds entries; munmap and mprotect clip them, splitting one entry into two or three when only part of it changes.

The lower layer: objects. A struct uvm_object is a source of pages, indexed by byte offset (a radix tree of struct vm_page). The entry maps [start, end) to [offset, offset + (end - start)) of its object. Every object has a pager (struct uvm_pagerops) that knows how to produce pages and write them back:

Object Pager Backing
vnode (a file) uvm_vnodeops (genfs) the file system
anonymous object (uao_create) aobj_pager swap
device (d_mmap) uvm_deviceops the driver, page by page
"special" objects with pgo_fault their own whatever they decide

The upper layer: amaps and anons. Private changes do not go into the object -- a file mapped MAP_PRIVATE must not change. They go into an amap (anonymous map, struct vm_amap): an array with one slot per page of the entry, each slot empty or holding an anon (struct vm_anon): one page of anonymous memory with a reference count, its page if in RAM (an_page) and its swap slot if paged out (an_swslot). Heap and stack entries have an amap and no object.

Copy-on-write in two levels. An entry marked copy-on-write maps the object's pages read-only. The first write to a page allocates an anon, copies the object's page into it, puts it in the amap and maps it writable: the page is "promoted" to the upper layer. At fork, a private entry's amap is shared by parent and child and both entries are marked needs-copy. The first write fault in either process gives that entry its own amap (amap_copy): a new array pointing to the same anons, whose reference counts go up. A write to a page whose anon is still shared (count above one) then copies the anon.

The pmap is the machine-dependent part: it builds and changes page tables (pmap_enter, pmap_remove, pmap_protect) and keeps, for every managed physical page, the list of its mappings (pv list), so that a page can be unmapped everywhere at once (pmap_page_protect(pg, VM_PROT_NONE)). UVM's data structures are the truth; page tables are a cache of them that the pmap may lose and the fault handler rebuilds.

Faults

When a process touches an address with no valid mapping, the processor traps and the kernel calls uvm_fault(map, va, access_type). The comment at the top of uvm/uvm_fault.c draws the cases; in words:

  1. Look up the map entry for the address (with the map read-locked); check the access against the entry's protection; if the entry is needs-copy and this is a write, give it its own amap first.
  2. Upper layer: if the amap has an anon for this page, use it -- paging it in from swap if needed. If the access is a write and the anon is shared (reference count above one), copy it into a new anon first (case 1B: the copy half of copy-on-write).
  3. Lower layer: otherwise ask the object's pager for the page (pgo_get), reading it from the file or swap if needed. If the entry is copy-on-write and the access is a write -- or there is no object at all -- promote: copy the page (or zero-fill) into a new anon in the amap (case 2B).
  4. pmap_enter the page, with write permission only if writing is allowed now (a copy-on-write page that was only read stays read-only, so that a later write faults and copies).

Faults also map neighbouring pages that are already resident ("fault ahead"), so a sequential reader faults far less than once per page.

Locking order in UVM is maps, then amap, then object, then anon, then the page queues. To read from disk, the fault handler marks the page busy (PG_BUSY), drops every lock and sleeps; afterwards the world may have changed (the entry unmapped, the page freed), so it starts over from the lookup (ERESTART, the ReFault loop). Restart is the general tool: whoever must sleep in a fault drops the locks and has the fault looked up again.

Special objects. An object whose pager has pgo_fault takes over step 3 completely: UVM calls it with the maps and the object locked, and it enters whatever pages it likes and unlocks everything. The device pager uses this to ask the driver for each page (udv_fault); the compat layer uses it to run Linux fault handlers (see below).

The life of a page

               uvm_pagealloc / uvm_pglistalloc
   free lists  ------------------------------->  allocated
       ^                                         |      \
       | uvm_pagefree                 enqueue    |       \ wire
       |                                         v        v
       +------- page daemon frees <------ active <---> inactive     wired
                (clean, unmapped)         queue  ref.   queue     (not on
                                                  bit             a queue)
  • Free. Free pages sit on free lists per page color and NUMA bucket; allocation takes from them (uvm_pagealloc for one page, uvm_pglistalloc for a contiguous or address-limited run).
  • Owned. A page belongs to an object (pg->uobject, at pg->offset) or to an anon (pg->uanon), or to nobody -- kernel memory and pages a driver holds.
  • Queued. Pageable pages are on the page daemon's queues (below); pdqueue and pqflags in struct vm_page belong to it.
  • Wired. A wired page (wire_count > 0) is off the queues and cannot be paged out: kernel memory, mlocked memory, pages a driver is using for DMA (uvm_obj_wirepages, uvm_vslock). Wiring counts: every wiring must be undone once.
  • Busy. PG_BUSY marks a page whose contents or identity are changing (I/O in progress, being set up); others wait on it (uvm_pagewait).
  • Dirty or clean. A dirty page differs from its backing store and must be written back before its RAM can be reused; a clean one can simply be dropped. Anonymous pages that were never written to swap are dirty by definition.

Getting memory back: the page daemon

UVM keeps a reserve of free pages (uvmexp.freemin, and a target a third above it, freetarg). Allocations that find the free lists below the reserve fail or wait (uvm_wait) -- the allocating thread does not reclaim memory itself -- and the page daemon (uvm_pageout, uvm/uvm_pdaemon.c) runs until free memory is back above the target.

Which pages to take is the page replacement policy; NetBSD's default is a clock (an approximation of least-recently-used, uvm_pdpolicy_clock.c):

  • Pages are on an active queue or an inactive queue. The daemon keeps the inactive queue at a target size by moving pages from the head of the active queue, clearing their hardware referenced bits (pmap_clear_reference) as it goes.
  • To free memory it scans the inactive queue. A page whose referenced bit is set again was used since it was deactivated: it goes back to the active queue. Otherwise it is a victim: unmapped everywhere (pmap_page_protect), written to its backing store if dirty, and freed.
  • Anonymous pages (anons and anonymous objects) are written to swap in clusters: the daemon reserves a run of swap slots and gathers victims into one large write.

Intents. Updating the queues takes a global lock, and pages are activated on every fault. So queue changes are only recorded on the page -- an intent bit in pqflags (activate, deactivate, dequeue) -- and the page put in a small per-CPU array; the queues are updated in batches, when the array fills or when the daemon meets the page. A consequence that matters to anyone who reuses vm_page fields: a page freed from a queue can still be linked on it, with a pending dequeue, after it has been allocated again. pdqueue and pqflags therefore belong to the page daemon at all times.

Reclaim hooks (aiBSD): subsystems with caches of their own -- Linux shrinkers, through the compat layer -- register hooks that the page daemon's pool-drain thread calls when memory is short, after pool(9) caches have given theirs back (uvm/uvm_reclaim.c).

Swap

Swap is the backing store of anonymous memory: partitions or files (swapctl(8)), joined into one array of page-sized slots whose free space is tracked by a radix-tree bitmap (subr_blist.c). A slot number is all a page needs to be found again. Where that number is kept depends on who owns the page:

Owner Swap slot recorded in
anon (heap, stack, copy-on-write copies) anon->an_swslot
anonymous object (shared memory, tmpfs, memfd, Linux shmem) the object: an array per page for small objects, a hash of 16-page clusters for large ones

A page brought back from swap may keep its slot, so that paging it out again unchanged needs no write. The slot is freed when the copy in swap can no longer be trusted or is no longer needed: when an anonymous object's page is wired for writing (uvm_obj_wirepages, uao_dropswap), when the page daemon runs short of swap (uvmpd_dropswap frees the slots of resident pages), and when the memory is freed or truncated -- including pages that are only in swap.

How Linux does it

The same ideas, other structures:

Concept UVM Linux
address space vm_map + pmap mm_struct, page tables walked by the core
region map entry (clipped on change) VMA, vm_area_struct (split and merged)
backing object + pager vm_file + address_space (page cache, an xarray of folios)
private changes amap of anons anonymous pages found through anon_vma
copy-on-write promote into an anon write fault copies the page, per PTE
where a paged-out anonymous page is an_swslot / object table a swap entry stored in the page table entry itself
reverse mapping (page to its mappings) pmap pv lists rmap: anon_vma and address_space->i_mmap trees
page identity and lifetime owner + wiring reference count and map count per page (folio)
reclaim page daemon only; allocations wait kswapd, and direct reclaim by the allocating thread
replacement clock: active/inactive LRU lists per type (anon/file), or multi-generational LRU
device mapping d_mmap or pgo_fault object VMA with vm_ops->fault inserting PFNs

Three differences shape the compat layer:

  • Linux page tables are the source of truth for anonymous memory: a paged-out page leaves a swap entry in its PTE. UVM's page tables are a cache; the truth is in amaps and objects. Compat code never reads page tables to learn about memory -- it asks UVM.
  • Linux pages are reference-counted; whoever holds a reference keeps the page. UVM keeps a page in memory by wiring it, and frees pages explicitly. The compat layer maps one onto the other: a reference to a shmem page is a wiring, folio_put an unwiring.
  • Linux VMAs carry the driver's state (vm_ops, vm_private_data) and are visited by the core on every fault. UVM's map entries carry an object, and objects with pgo_fault see their faults. The compat layer therefore makes each Linux VMA an object.

The compat layer on UVM

How the Linux side is built on the structures above (details and code in Memory and DMA):

  • struct page is a struct vm_page. Linux fields a driver uses on pages it allocated (lru, private, mapping) overlay vm_page fields that UVM does not use for an owner-less page -- never pdqueue/pqflags, which the page daemon owns.
  • alloc_pages takes pages from the free lists; large orders only try, as on Linux, because waiting for a contiguous run in UVM means evicting pages until one appears.
  • shmem files are anonymous objects: pages come from the aobj pager (zero-filled or from swap), references are wirings, and the page daemon swaps them out once unwired.
  • A Linux mmap is an object with pgo_fault. One per mmap call, holding the VMA; its entries reference it (Linux's vm_ops->open and close); its fault routine calls the VMA's ->fault, whose vmf_insert_pfn becomes pmap_enter at the faulting entry's address. The VMA's addresses are relative to the mapping because UVM, unlike Linux, does not tell an object where its entries are -- and they change with every clip, fork and mremap.
  • Revoking mappings (unmap_mapping_range, when a buffer moves) works by mapping, as in Linux: each file lists its VMAs, each VMA remembers where it was faulted in, and revoking removes the range from those map entries with pmap_remove. The next access faults, and the fault handler maps the buffer's new location. See Memory and DMA.

Further reading

Charles D. Cranor, The Design and Implementation of the UVM Virtual Memory System (1998) -- the design of everything above except the page daemon policy and intents, which came later; uvm(9), pmap(9), uvm_map(9), uvm_obj_init(9); sys/uvm/uvm_fault.c (the comment at the top), uvm_amap.c, uvm_aobj.c, uvm_pdaemon.c, uvm_pdpolicy_clock.c, uvm_swap.c, kern/subr_blist.c. For Linux: Mel Gorman, Understanding the Linux Virtual Memory Manager (2004: older, but the concepts stand), and the kernel's Documentation/mm/ (process addresses, page tables, the multi-generational LRU).

Clone this wiki locally