Virtual memory

Memory ownership and paging

The kernel controls privileged mappings, TLB operations, physical resources, and delivery of faults. Userspace controls VM objects, anonymous and file-backed memory, demand paging, copy-on-write, reclaim, swap, and accounting. The native base-page constant in common/include/vm_page.hh sets the allocator, process loader, and pager granule and the startup AT_PAGESZ value. The default is 4 KiB. ARM64 UEFI can select 16 KiB with --vm-page-size=16384 on a CPU that supports the granule. That profile uses 16 KiB pages for native frames and TTBR0 user address spaces. Firmware mappings and the temporary MMIO window retain their own geometry. Build the kernel, supervisor and native binaries together for the selected page size.

Each physical allocator serializes bitmap updates and reserve accounting across CPUs. Callers enter with local interrupts masked. The ordinary and recovery pools have separate locks. A contiguous allocation claims its entire run within one physical range and preserves the page-in reserve. This lets a kernel-owned hardware table retain physically contiguous pages for the lifetime of its firmware registration.

class palloc_t

Allocate physical pages from the kernel’s direct mapping. Region metadata lives in the first pages of each region. Call with local interrupts masked.

On NUMA machines the pager supplies the managed address-space capability and page address with a frame request. The kernel uses the CPU that took the outstanding fault, or the primary thread’s last CPU when there is no matching fault. Anonymous page-in and the kernel’s copy-on-write allocation then prefer allocator-owned pages inside that CPU’s enabled SRAT or device-tree NUMA memory ranges. Exhaustion or missing locality data falls back to the ordinary pool search. The same reserve rules apply to both searches. A firmware range cannot add pages to the physical pool. Existing resident pages retain their backing when threads migrate.

Resident user entry holds a pin from translation activation through restoration of the previous root. The address space’s table lock excludes new pins while a writer waits for existing pins. Table replacement and architecture invalidation complete before the writer releases the lock. The caller retains the mapped frame for that whole interval. A CPU exiting userspace releases the pin before acquiring the resident dispatch lock. Each address space has its own table lock. Native frame map and unmap retain task and frame references while changing the leaf outside the resident dispatch lock. Same-task bookkeeping waits until the in-flight leaf change commits. PowerPC also serializes allocation and removal of entries in the hardware hash shared by those spaces. The SMP check updates an unrelated address space while the first space is draining its pins.

class pmap_t

An address space owns its lower-half page tables and shares the kernel mappings. A resident entry pins the translation tree until the CPU restores its kernel translations. Mutators exclude new entries and wait for those pins before changing or reclaiming tables.

The initial RISC-V pager installs a demand-zero page for load and store faults at the demonstration address. The supervisor delegates a capability for the faulting address space, and the pager allocates the frame from its granted application pool. If the pager stops after mapping the page but before replying, the replacement checks the existing protections and acknowledges that mapping. The address space’s mapping keeps the frame alive through pager replacement.

Native applications send anonymous mmap, munmap, mprotect, and madvise(MADV_PAGEOUT) requests to the supervisor. The supervisor authenticates the caller’s badge and grants VM a mapping capability for that application’s address space. Applications retain the same supervisor endpoint across a pager replacement. Kernel fault events identify the faulting task and the supervisor checks that identity against its current process slot.

The per-process arena reserves 128 MiB of virtual address space. VM installs a native page on demand for an authorized load or store. fork() shares resident anonymous pages with the child and resolves the first write through copy-on-write. A read-only or inaccessible mapping retains its backing. An inaccessible mapping has no valid user translation until protection is restored. Unmap splits or trims the affected ranges and releases resident and saved pages. Task exit retires the kernel mappings and clears the pager’s process slot.

Private mappings of regular files reserve an interval in VM and retain a VFS file reference. They read file bytes at first fault without changing the descriptor offset. Closing the original descriptor leaves the mapping usable. VM installs private pages, preserves their contents through swap and copy-on-write, and zeroes the unused tail of the last file page. An access to a full page beyond EOF delivers SIGBUS. One bounded file I/O worker brings pages in through VFS while the pager continues resolving other faults. Before installation VM checks the live mapping capability, source identity, file offset, and required protections. The worker’s badge only admits reads of existing mapping sources.

The source identity and file offset survive range splits, forks, and VM restart. The supervisor releases the VFS reference after the last live region disappears. VFS replacement retires the old worker and its sources. Resident or swapped private copies remain usable. A later fault that needs the retired source delivers SIGBUS. New sources receive new identities throughout the boot. The RV64 guest touches a subset of a large mapping and exercises descriptor close, partial unmap, protection changes, EOF, and the last reference across fork. A second test holds a completed file read, unmaps the original range, and verifies that an anonymous write to the same address completes before VM rejects the stale result. The staged LLVM SDK probe also maps the ELF interpreter through libc.

A first fault on a writable volume reads the current file contents, including bytes visible through resident shared mappings. Private writes remain private. The supervisor pauses file page-in while resizing a file and rejects reads submitted before that pause. A shrink discards private resident and swapped pages wholly beyond the new EOF. Already private bytes in the surviving partial page remain private. Later faults see the current file size and zero-fill the last page. O_TRUNC returns EBUSY while a source exists.

Native shared mappings reserve a range at mmap() and fault in pages from a 16-page wired VFS cache. The cache limits resident pages independently of the mapping size. The supervisor retains the source after descriptor close. On a shared fault it uses bounded VFS IPC to acquire a cache page and installs the shared translation. When the cache fills, the supervisor first freezes and unmaps every alias of a victim. VFS then flushes the victim and releases the frame for reuse. A later fault reloads the same file offset. A failed flush leaves the frame reserved until the error can be handled.

VFS identifies each cached page by mount, inode, and aligned file offset. It retains an open file reference while a cached page is in use. The supervisor maps the same frame for independently opened descriptors and for inherited mappings after fork(). Each view retains the access allowed by its own descriptor. VFS overlays resident bytes onto ordinary reads and reflects ordinary writes in the cache. The native msync(MS_SYNC) and fsync() paths write cached bytes through the filesystem and flush the volume. When the last mapping is removed, VFS attempts writeback and retains the cache entry if storage reports an error.

msync(MS_ASYNC) queues the selected resident shared pages and returns after VFS accepts their cache indices. Repeated requests coalesce in one bounded bitmap for the current VFS instance. VFS writes and flushes one eligible page at a time between client IPC requests. The filesystem and VFS still serialize each write transaction. Pending work follows the current file size and waits while a resize has frozen the cache entry. Explicit sync and the final release retire queued work for that page. After an asynchronous I/O failure, msync(MS_SYNC) or fsync() reports the error for a retained page even if the retry succeeds.

The pager tracks shared ranges through mprotect() and munmap(). It excludes their wired frames from anonymous swap. For ftruncate(), VFS validates the descriptor and reserves the file resize. The supervisor freezes all affected aliases before VFS writes back the surviving prefix and publishes the new size. VFS zeroes the truncated part of the final page. An access to a page wholly beyond the file end is reported as SIGBUS. After a successful shrink the supervisor unmaps all aliases of pages wholly beyond the new end and releases their cache slots. Once a write or another ftruncate() grows the file, those pages fault in again with their region protections and the current file contents. Opening a file with O_TRUNC while it has active mappings returns EBUSY.

Native file record locks support the F_SETLK and F_GETLK paths used by a WAL index and the blocking F_SETLKW operation. See the Native processes, loading, and the C runtime description of lock ownership and wait handling.

The supervisor keeps aliases inaccessible when the result of the resize is uncertain. It removes views belonging to a failed VFS instance before it wires another cache. A writable caller can use msync(MS_SYNC) to ensure writeback before a failure.

Pager metadata lives in wired frames retained by the supervisor. VM publishes reservation changes through two banks per process slot and records unmap and protection work until the corresponding translations have been updated. When restarting VM, the supervisor rebuilds the delegated capabilities and the new pager finishes incomplete operations before accepting faults for the affected slot. Pageout freezes the translation while it captures the contents and releases the frame only after the saved record is visible. Recovery restores an interrupted freeze or completes the frame release according to that record.

The native supervisor retains a bounded set of kernel fault reply tokens and posts requests into a wired mailbox array. The array has one entry per possible faulting application thread. Badged notifications wake the pager and supervisor without a synchronous rendezvous. The supervisor can receive process messages while the pager works. Faults for the same task, page, and access share a completion. Before resuming each thread the supervisor checks that the reply still belongs to the task and that the current translation permits the access. The pager validates the delegated address-space capability carried by each request. A new pager instance starts with empty mailboxes. The supervisor can resubmit a live fault after replacement.

During a wired debugger stop the supervisor holds fault replies and rejects new mapping changes. Builds with an application pager start a wired vm-io worker in the recovery pool for each active swap provider. The supervisor admits each worker to a bounded CPU reservation for request submission and completion. The pager and storage providers keep their ordinary timeshare policy. See Scheduling and CPU accounting. The GPT worker handles disk reads and background writes, and each configured zram worker handles reads for its own device. Each worker uses bounded IPC and reserves only its provider’s buffer. The pager can continue resolving faults that use other providers or need no I/O. Before installing a page it checks the delegated mapping, provider, and saved slot again. The pager puts a deadline on each submitted request independent of the worker’s IPC timeout. When that deadline expires the pager fails the affected read, keeps the saved slot intact, and holds the transfer buffer until the worker relinquishes it. A late completion cannot install a page or commit a writeback. The RV64 worker-stall test delays a completed read past this deadline and checks that a later read can recover the saved data without a pager restart. Queued GPT reads take priority over the next background write. Foreground evictions retain bounded synchronous paths. While a worker holds a provider’s buffer, the pager skips that provider for new evictions. Fault submissions and I/O completions share a coalescing notification. The pager scans the fault array and all provider mailboxes when it wakes. The RV64 unmap regression holds a completed GPT read, unmaps the original view, and writes to a new mapping at the same address. When the worker publishes the old read, the pager must reject it before it can resume the original thread or install the old contents.

The QEMU debugger pressure fixture fills the anonymous RAM backing store, stops VM, and verifies that the blocked client restores its saved pages after detach. The application-debug profiles enable the fixture with --vm-debug-pressure=y and the app-vm-pressure test.

Pin critical pager code, stacks, IPC state, and metadata. Keep the pager’s essential path accessible while it handles faults and avoid circular dependencies among VM, VFS, filesystem, and swap services. Evaluate batched map operations, mapping-and-fault reply, per-core frame reserves, sharded pager workers, fault clustering, read-ahead, huge pages, and authorized delegation to memory-object owners against fault latency and memory-pressure measurements.

Boot-resident service executables, stacks, and the VM state are mapped before they enter the service loop. The anonymous fault path depends on the supervisor, VM and kernel-managed frames. A complete backing service must also keep its fault-resolution path wired and reserve its own requests and buffers. See Service lifecycle and failure.

The supervisor owns the kernel fault receive endpoint and delegates each managed process’s address-space capability to the VM server. The VM server receives send authority to the selected swap provider. GPT receives raw block authority to the resident storage driver. Each driver receives its wired transfer buffer at startup. These capabilities establish the dependency order from the faulting thread through the supervisor, VM, GPT and the driver. A compressed RAM device ends the chain at its own wired store. Service entry and fault recovery have no dependency on resolving an application page fault. The RV64 two-hart recovery test attempts a synchronous call through the pager’s notify-only supervisor capability and verifies denial. It then faults the pager at a pageable application address, checks that the kernel records that fault, and verifies that the replacement restores the retained VM state.

The ordinary pool retains a 16-page emergency allocation budget while the resident system runs. VM tries ordinary allocation and reclaim before it uses this budget to restore saved anonymous data. Associated page-table and mapping metadata can draw on the same budget. The resident pager’s separate pool holds the recovery image, state, and disk transfer page. The RV64 reserve test boots with 128 MiB of RAM, drains ordinary allocations, and installs and reads an emergency mapping. It then exhausts the reserve and verifies that a fresh translation fails without losing the first one. It returns the held pages before the guest continues booting.

Swap and compression

Anonymous RAM compression

The pager can compress a mapped anonymous page under memory pressure. It freezes access while capturing the contents and removes the translation after publishing the compressed record. The page stays in RAM and is decompressed on the next fault. Wired and shared file pages are excluded. Reclaim can use ordinary swap when a page cannot be compressed or the anonymous store is full. madvise(MADV_COLD) is a best-effort request to compress a caller’s eligible pages without sending them to swap. MADV_PAGEOUT continues to use the configured swap policy.

Set the initial policy with --vm-resident-codec. The default is off. /sbin/vmctl resident reports the codec, compressed bytes, and number of saved mappings. Root can select any of the swap codecs except raw, or set off to stop new compression. The store has its own budget of four native pages and 24 saved mappings. It retains only encodings smaller than a page. Earlier records keep their original codec and remain readable after a policy change or pager replacement. Fork shares the compressed bytes until each mapping is faulted back in or removed.

Anonymous compression, the zswap cache, and each zram device select their policies independently. For example, use vmctl resident off, vmctl swap wkdm, and vmctl zram 0 lz4 to keep ordinary anonymous pages uncompressed while using these codecs for swap.

Swap cache

The anonymous pager has a wired RAM backing store with a budget of 12 native pages and 48 records. It can evict pages on allocation failure or at an application’s MADV_PAGEOUT request. Explicit pageout can release some pages before reporting ENOMEM for a full store. Saved and resident pages remain readable after that failure.

/sbin/vmctl swap reports the active codec, bytes used in RAM, and the number of saved mappings across RAM and disk. Root can select raw, lz4, lz4hc, deflate, wkdm, lzo, lzo-rle, zstd, or 842 for future evictions. The default is raw. Select a boot default with Xmake’s --vm-swap-codec option. The firmware command line accepts system.vm-swap=lz4 or system.vm-swap=lz4hc where it is passed to the kernel. A page that would expand is stored raw. Each RAM record retains its codec and size across policy changes and pager replacement. Fork duplicates references to immutable saved contents without consuming another extent.

The DEFLATE backend uses zlib 1.4 from FreeBSD revision 4ba6fd2ef5a739b6fdc955890d27e07ae8794fb3, with its original zlib license and a fixed work area. The VM server compiles it as freestanding C, with Z_SOLO and no heap access. Zstandard 1.5.7 comes from the contrib/zstd vendor import under its BSD license. It uses a fixed workspace and encodes each page as an independent level-one frame. The other codecs are System implementations. WKdm uses the published direct-mapped algorithm with a System-private packed format. LZO and LZO-RLE use the page-sized subset of the LZO1X stream format. The 842 codec uses software on all architectures and emits whole-page streams with wire templates and a CRC.

Disk backing and writeback

The GPT partition server and pager I/O worker use the same interfaces on every profile. The block transport depends on the firmware and machine. VirtIO exchanges little-endian registers and queue entries with the device and uses the architecture’s device I/O barrier. The programmed-I/O drivers use the same sector and flush operations without mapping DMA buffers.

The RV64 native disk can include a dedicated FreeBSD-type GPT swap partition. It is enabled by --native-root-swap=y when building the image. VM holds a badged GPT endpoint with access to that extent and a wired buffer shared with the partition server. VM issues page I/O through GPT and VirtIO with a bounded caller deadline. This path has no VFS or filesystem dependency. The same block driver currently serves native storage and swap requests.

A resident profile can attach a separate GPT disk for swap while the application root stays on its existing filesystem. The supervisor starts the block driver and a swap-only GPT instance from recovery memory. It retains their transfer frames for bounded restart attempts. This GPT instance publishes only the swap partition and issues I/O without involving the filesystem or VFS. The pager checks the partition’s GUID before reattaching saved pages after a restart.

On AMD64 and ARM64 UEFI, configure --application-debug=y --native-root-swap=y to boot QEMU with a separate swap.img disk. The AMD64 PC profile uses IDE. The ARM64 virt profile uses a device-tree-described VirtIO MMIO device and supports both native page sizes. The test xmake test uefi-entry/app-disk-swap uses a private copy of the image, faults evicted pages back in, and checks that the GPT partition received the writes.

Use the same options on Raspberry Pi to include the SD driver. QEMU’s Pi 4 test connects the separate swap.img card to the emulated eMMC2 controller. Run xmake test rpi4-entry/app-disk-swap for the same round-trip and backing-image checks. Pi 5 verification covers firmware image assembly.

On PowerVM and PowerNV, the resident QEMU profiles use a PCI SD host controller. Configure the same options and run xmake test powerpc-entry/app-disk-swap with each supported byte order (-a ppc64 and -a ppc64le). The SD driver preserves byte order in the data FIFO while treating controller registers as little-endian. The QEMU disk-swap checks use --vm-swap-codec=raw, --zram-codec=none, and --zram-secondary-codec=none so the probe fills the RAM cache and writes to GPT.

/sbin/vmctl backing displays the mode for new evictions. Root can select ram, cache, or disk. Cache mode fills RAM first and writes out a cached page when it needs an extent. When cached data reaches three quarters of the byte budget and GPT is the preferred provider, the pager also submits one background write. It reserves the source extent until completion, even if a client discards the last reference during the transfer. A failed transfer or worker replacement leaves the RAM copies usable. The disk holds raw pages and the cache stores a disk location only after write and flush succeed. A failed writeback retains the original RAM bytes. Disk mode sends new evictions directly to the partition. RAM mode keeps existing disk records readable and stops writing new ones. The store uses a common 48-record budget across both media. Each backend has a separate wired transfer page and identity. On provider replacement, the pager can attach existing disk records only to the same GPT partition GUID. A stalled provider’s IPC is bounded, and a failed eviction can try the other backend.

Compressed RAM block device

Configure --zram-codec for device 0 and --zram-secondary-codec for device 1. Each enabled device runs its own instance of the compressed RAM block server and exposes 48 logical pages with a compressed data budget of 16 native pages. The supervisor retains each instance’s state and transfer buffer for replacement. The kernel budgets supervisor capabilities and service slots for both resident devices. Each write publishes a new extent after the replacement data is complete. A failed write preserves the previous extent. The pager discards an extent when its last reference is released.

The application VM tests can boot with zram on AMD64, ARM64 and both PowerPC byte orders. They check that guest evictions actually reach the device and that page-in and copy-on-write preserve the data after a fork. RV64 also tests two simultaneous devices and their fallback to the GPT swap partition.

vmctl zram [device] [codec] reports or sets the selected device’s codec. Device 0 is the default. Only root can change the policy, and earlier extents retain their original decoders. Use vmctl zram device off to route new evictions to other providers while saved pages remain readable, on to resume new writes, and status to query the setting. The pager retains the current policy if disabling the device would leave the current backing mode without a usable provider. New evictions try the enabled devices in index order, then GPT if they are full or unavailable. Root can select vmctl order disk-first to reverse the order. Existing records retain their source and codec. vmctl backing reports saved mapping counts for GPT and for the compressed devices in aggregate. When zram is the first provider attached, the initial mode sends pages directly to backing providers. Root can enable the RAM cache separately.

Future backing and mapping work

Extend cache budgets, reclaim and writeback, and per-domain accounting to negotiated device capacity. Avoid redundant compression when a cache fronts a compressed block device.

The RV64 writable ext4 guest was exercised with the Unix VFS from SQLite 3.54.1, source ID 555e07ef33f69a0957d24d8e555b702464a131d6f1607f4c3c1e4551e8e6ca76. Two independently opened processes read and committed transactions in WAL mode. The local test used a fixture compatibility header and functions for the missing Unix build interfaces, disabled loadable extensions and floating-point SQL, and did not enable ordinary database-file mmap. The WAL index still used native shared mappings and file record locks.

The asynchronous writeback queue is local to the VFS instance and is discarded when that instance is replaced. The supervisor removes old shared translations before the replacement can reuse their frames. A mapping whose source vanished delivers SIGBUS when it next needs that source.

Drain or migrate data before removing a swap backend. A transition that runs out of memory or backing space must preserve a working configuration and report failure.

Codec

Purpose or trade-off

WKdm

Page-oriented baseline from a suitable upstream implementation.

LZO and LZO-RLE

Fast codecs with low overhead. LZO-RLE encodes zero runs efficiently.

LZ4 and LZ4HC

Share a fast decoder. LZ4HC spends more CPU time compressing to improve the space trade-off.

Zstandard

Tunable compression for cases where additional work can save memory.

DEFLATE

Widely implemented zlib baseline for CPU cost and memory savings.

842

Software baseline with hardware acceleration on some IBM POWER systems. Evaluate offload where available.

Use license-checked userspace implementations. Linux’s configurable defaults are useful reference points. Its zram Kconfig specifies LZO-RLE, and its zswap Kconfig specifies LZO. Choose System’s defaults from representative compression and page-in latency, CPU cost under pressure, and RAM savings after metadata overhead.

See Scheduling and CPU accounting for CPU reservations used by wired VM workers and Resource domain controls for memory accounting and limits.