Skip to content

Research notes / File I/O

Memory-mapped files: visibility, size and synchronization

Published / Updated / Measured API behavior

A mapped address, a visible byte and a durable record are different promises. In seven Linux checks repeated five times, a private edit stayed private after a successful sync, while shrinking a mapped file made an address inside the original mapping fault.

A private mapping is not a snapshot. In a separate ordered Linux experiment, it combined pages into an image that never existed in the file. A six-control comparison shows why, and a compiler control explains why translating the test into optimized C can change its result.

On this page20 sections

Seven checks, three independent boundaries

Each file started with byte A. The harness used ordinary file-backed mappings with a 4,096-byte system page. All 5 repetitions produced identical observations. These are deterministic API examples, not 35 independent samples from a storage fleet.

Observed on Linux 6.8.0-146-generic; all byte reads could use cache.
CaseOperationObserved resultWhat it establishes
Private modificationStore P, then MS_SYNCMapping P; file ASuccessful sync did not publish the private edit.
Shared modificationStore S; read before and after MS_SYNCS before; S afterA matching read did not require an explicit sync first.
Descriptor closureClose fd; read the existing mappingAThe mapping outlived its original descriptor.
Larger mappingMap twice the existing file length8192 mapped bytes; 4096 file bytesThe larger mapping did not extend the file.
Partial final pageStore T at EOF within the last page; MS_SYNCTail byte 84 before sync; read at EOF returns 0 bytesThe accessible tail did not become file content.
Unaligned syncMS_SYNC from mapping start + 1-1 / EINVALAn argument error is not evidence of media failure.
Mapped-file shrinkShrink two pages to one; touch page twoSIGBUSThe child accessed a discarded whole page.

Both private and shared msync(MS_SYNC) calls returned zero. The return value cannot be interpreted without the mapping mode. The shared before-sync read establishes visibility in this test; it tells us neither that storage had persisted the byte nor that it had not.

Private edits are not deferred shared writes

MAP_SHARED permits updates to the backing file. MAP_PRIVATE uses copy-on-write for local modifications; it is not a promise that later external file changes are invisible. Closing the original descriptor does not invalidate either mapping. [1]

The private case deliberately invokes synchronization after its edit. The unchanged file byte is therefore not an omitted-sync bug in the experiment. It demonstrates a different update contract. A memory-mapped database's transaction semantics must come from its own protocol, not the mapping flag alone. Compare the LMDB reader-lifetime experiment.

Private page history is not a file version

Measured result: after an external writer finished changing a two-page file, its private mapping contained AB: old page 0, new page 1. The ordered file history was AA -> BA -> BB, never AB. A private mapping can therefore assemble an image that is not even a past version of that file.

Here each letter denotes an entire uniform 4,096-byte page, not a sampled byte. Before starting the writer, the reader read both pages and stored one byte in page 0 back to its existing value. The visible bytes still matched AA. A child process then wrote page 0 completely, verified BA, wrote page 1 and verified BB. The parent waited for child exit before reading the mapping. This is not a read overlapping an unfinished write.

Reproduction detail: the read-only control explicitly combines MAP_PRIVATE with PROT_READ. That is not the same configuration as access=ACCESS_READ: CPython 3.12.3's Unix constructor selects MAP_SHARED for that convenience mode. ACCESS_COPY selects a private mapping with read/write protection. These source-level choices distinguish access permissions from sharing mode; the experiment did not test the convenience modes separately. [30, new_mmap_object]

Six controls on Linux 6.8.0-146-generic, ext4, CPython 3.12.3; three repetitions in each of two original captures. File/path means the currently named file.
Reader preparationFile/path after writerMapping after writerFollow-up
Read-only, fully readBBBBNo follow-up
Writable private, fully read, no storeBBBBNo follow-up
Same-value store in page 0BBABNo follow-up
Same-value store in each pageBBAANo follow-up
Page 0 store; discard after writerBBABDiscard page 0: BB
Replace path; mutate retained old inodeBBAAOld-inode write: mapping CC, path BB

The writer order excludes AB even if a page write is not atomic: while page 0 is changing, page 1 is still all A; before page 1 changes, page 0 is already all B. Full-image and per-page hashes check the observed bytes. This argument concerns the single controlled writer, without truncation, rollback or another mutator.

Mechanism, with limits: the same-value store is consistent with Linux's page-granular copy-on-write path, which copies a page for a private write fault. CPython's indexed mapping assignment performs a native store. Neither source inspection nor this probe directly traces page tables or proves that the distribution binaries equal the upstream tags. [29] [30] The documented visibility of subsequent file changes remains unspecified; this is an observed Linux counterexample, not a portable guarantee or a new kernel defect. [1]

Reproduction caveat: a source-level assignment is not proof that a store occurred. In the separate GCC 13.3.0 / Linux 6.8 / ext4 control, p[offset] = p[offset] emitted a byte store at -O0 and the final mapping read AB. At -O2 that function contained no memory access and the mapping read BB. A volatile-qualified byte self-assignment retained a load/store and AB at both settings; a volatile-read-only control yielded BB. All compiler-control mappings were writable and private; read-only describes the emitted access, not mapping protection. Every case still began with AA and used the same completed AA -> BA -> BB writer. The retained disassembly establishes the emitted access; the optimization manual alone does not. [32]

The self-contained compiler-control package includes C/Python sources, disassembly, both raw captures and checksums. Its six-row result table summarizes 24 repeated observations across two captures, not independent population samples. This is a reproduction qualification, not a compiler defect or a refutation of the original Python observation. Neither -O0 nor volatile is a general snapshot recipe; volatile is not a memory barrier, cross-process synchronization, atomicity or durability. Here the subprocess protocol supplies writer ordering. [33] No new compiler/platform, database benchmark or power-loss result is implied. After extraction, follow COMPILER-PUBLICATION.md and run python3 -B -m unittest discover -s compiler-control -p 'test_control.py' -v.

Reading every page first and using read-only protection did not freeze the clean mappings. Touching both private pages retained AA here, but preparation happened while the writer was excluded: it is not a general snapshot recipe. A copied bytes buffer also retained AA in every control, under the same exclusion. Discarding page 0 with MADV_DONTNEED changed AB to BB, not to a permanently preserved historical image.

The replacement control distinguishes identity from immutability. Renaming a new BB file over the pathname left the old mapping at AA. A later write through the retained old descriptor changed that mapping to CC while the pathname still read BB. Rename does not redirect an existing descriptor to the replacement. [31]

Engineering consequence: specify which file generation a reader must consume and how mutation is excluded or coordinated. Read-only access, prefaulting, synchronization and pathname replacement are not interchangeable with a snapshot protocol. Crotty, Leis and Pavlo's CIDR 2022 discussion describes the additional bookkeeping needed to propagate committed updates and reclaim private workspaces. Our small probe illustrates a consistency boundary; it does not reproduce their read-throughput study or demonstrate a database-engine bug. [18, section 3.1]

Reproduce from the complete source and evidence package; inspect the first raw capture, second raw capture, artifact hashes and publication and method notes. Run inside the extracted directory:

python3 -B verify_package.py
python3 -B -m unittest -v test_probe
python3 -B probe.py --output new-capture.json

The separate probe needs Linux, CPython with native mmap.madvise, findmnt and a writable test directory. It uses fresh temporary files and refuses to overwrite output. The 36 original observations are repeated controls on one host, not independent population samples. No DAX, huge pages, remote filesystem, memory-pressure workload, crash, power cut or performance measurement was tested. Unexpected replay outcomes need investigation, not an automatic operating-system failure label. The original sequential experiments below retain their own narrower scopes.

When "don't need" discards private edits

Measured result: after a private file mapping was filled with P, Linux MADV_DONTNEED made its next read return the original file bytes, A. The similarly named POSIX_MADV_DONTNEED left P intact on the tested glibc. All advice calls returned zero. A successful call therefore needs to be read together with the exact interface and mapping mode.

Six separate cases, each repeated 5 times on Linux 6.8.0-146-generic, glibc 2.39. Each mapping contains P across the whole page before the listed step.
Private mappingStepMapped bytes afterReturn
File-backedNo operationPNot called
File-backedMS_SYNCP0
File-backedMADV_DONTNEEDA0
File-backedPOSIX_MADV_DONTNEEDP0
AnonymousMADV_DONTNEEDzero0
AnonymousPOSIX_MADV_DONTNEEDP0

The file-backed cases use a fresh 4,096-byte file filled with A, on ext4. The anonymous cases begin as zero-filled pages. The harness verifies every byte after filling each private mapping with P and again after the operation. Every file-backed case also verifies that the complete file and its length remain unchanged. The anonymous cases retain an unused file as a control. All 30 observations agreed within their case; they are consistency checks, not independent failure-rate samples.

The no-operation and MS_SYNC controls retained the private edit. The native discard instead restored the backing-file view in this sequential test; it did not publish the edit. For a private anonymous mapping, the next read returned zeros. Linux documents that MADV_DONTNEED changes memory-access semantics, unlike ordinary access-pattern hints. It works on page-aligned ranges, and discarding a process's mapping is not a guarantee that every shared cached copy is evicted. [21]

POSIX requires memory advice to preserve access semantics. Glibc therefore treats POSIX_MADV_DONTNEED as a no-op; the pinned 2.39 implementation returns success without issuing the destructive advice. The manual dates this behavior to glibc 2.6. [22] [23] [24] Do not infer identical behavior from the shared numeric constant or a similar function name. Also check errors correctly: posix_madvise returns an error number directly, while madvise uses -1 and errno.

Practical consequence: an optimization that discards private pages can destroy an application's only copy of pending edits. Decide whether the page is disposable before making the call. Conversely, replacing native discard with POSIX advice cannot promise the same reclamation effect. Neither successful advice nor the unchanged file in this probe is a commit, a secure-erasure result or a cold-cache guarantee. File-descriptor advice is a third interface, not a spelling variant of either mapped-memory operation.

Crotty, Leis and Pavlo's CIDR 2022 discussion separates access-pattern hints from managing private update workspaces: section 2.2 covers NORMAL, RANDOM and SEQUENTIAL, while section 3.1 explains why pending changes must be preserved before a private workspace is destroyed. [18] Our probe illustrates one discard boundary; it does not reproduce their read-throughput experiments or establish that a database engine has this bug.

Reproduce with the standalone Python probe and inspect the full observations and source hash:

python3 madvise-contracts.py --repetitions 5 --output observations.json

Requirements: Linux, glibc, Python 3.8+ and findmnt. The probe creates only private mappings and fresh temporary files; it rejects unexpected outcomes and an existing output filename. Use --temp-dir to choose the test filesystem. It records the kernel, architecture, Python, libc, page size and mount type. No shared mappings, concurrent writer, memory-pressure workload, residency measurement, throughput test, reboot or power interruption was exercised.

Corpus: MADV_DONTNEED and POSIX_MADV_DONTNEED.

Lazy discard is not backing-file removal

Source-based comparison, not new measurements: the names below describe different ownership decisions. The earlier probe tested native MADV_DONTNEED and POSIX advice, not MADV_FREE or MADV_REMOVE.

Linux API contracts; the mapping type is part of each row.
OperationTargetConsequence
MADV_DONTNEEDPrivate anonymous mappingSubsequent access obtains zero-filled memory.
MADV_FREEPrivate anonymous mappingOld contents may remain until reclamation; a write after advice but before reclamation cancels pending discard for that page.
MADV_REMOVEEligible shared mappingPunches a hole in the backing object without shortening it.

MADV_FREE is not a promise of a retention interval or an immediate cold cache. The Linux v6.14 reclaim path handles lazy-free anonymous folios separately from ordinary swap-backed contents. Relinquish data only when it is disposable. [21] [39]

MADV_REMOVE instead reaches the backing object: v6.14 translates the mapping range and invokes FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE. Its capability check is VM_SHARED | VM_MAYWRITE, not current VM_WRITE alone. Read-only protection now need not remove potential write capability, as the separate seal controls also illustrate. [37] [38]

Within the object's logical extent, hole punching makes the affected range read as zeros until another write, but requires filesystem support. KEEP_SIZE does not extend EOF or make out-of-file mapped pages readable. Partial blocks can be zeroed without being deallocated, so requested bytes do not measure reclaimed allocation. This is not secure erasure. Nor does successful removal replace a durability protocol and its synchronization checks. These are API-scope limits, not hardware-test results. [40] [41]

An error is not an unchanged-data guarantee. A range spanning an unmapped gap can return ENOMEM while advice still applies to mapped parts. In Linux v6.14, the range walker records the gap and continues; if a later mapping fails, earlier effects are not rolled back. For MADV_REMOVE, this can include backing-file changes. Do not interpret one error code as a transaction abort over the entire requested range. [21] [37]

Database implication: dropping a private workspace and committing its updates are separate steps. Crotty, Leis and Pavlo describe propagation and coordination requirements for copy-on-write workspaces; a memory-advice result does not establish that transaction protocol. Their CIDR 2022 experiments evaluate read-only I/O on a specified Linux and SSD setup, not failure atomicity of these two advice operations. [18, sections 3.1 and 4]

A valid mapping is not a promise of valid file bytes

Mapping length does not enlarge the underlying object. POSIX distinguishes the unused tail of the last partial page from whole pages outside the object; the latter can raise SIGBUS. Do not use apparent accessibility beyond the file end as a file-growth API. Bytes in the unused final-page tail are initially zero-filled; modifications beyond EOF are not written to the file. Linux documents page-cache caveats for that tail. The original check uses a fresh partial page; the separate remapping experiment follows the byte into a new process. [2] [1]

ftruncate() changes file length without moving the descriptor's file offset. An extension reads as zeros on supporting Linux filesystems. [5] For a shrink, POSIX.1-2017 specifically requires previously mapped whole pages beyond the new end to be discarded, with later accesses generating SIGBUS. [6]

Our child touched offset 4,096 after a file of 8,192 bytes was shortened to 4,096. That is the first byte of a discarded whole page, not a partial-page edge case. The parent checked the child's terminating signal, so an arbitrary nonzero exit could not pass.

Engineering implication: a reader needs a lifetime and resizing contract for the object it maps. A size check followed by an uncoordinated access can race with a writer. This experiment had no such race: shrinking finished before the child was created.

The last byte of a page need not belong to the file

For the added case, the file is 4,095 bytes long but the mapping covers 4,096 bytes. The byte at offset equal to the file length initially reads as 0. Storing T there is observable in the mapping before synchronization. After MS_SYNC returns zero, the file has not grown and a one-byte pread() at that offset returns 0 bytes: end of file.

This is a partial-page tail, unlike the discarded whole page in the SIGBUS case. Linux documents that tail modifications are not written to the file, and warns that later mappings can sometimes still see cached tail data. [1, Notes and Bugs] That original case did not test later remapping or file growth; the following supplement tests remapping separately. Its operational lesson remains: an accessible address and a successful sync do not turn an out-of-file store into an append.

After the writer exits: cached tail bytes can reappear

Measured result: a new process saw T beyond EOF on tmpfs even after the writer successfully called MS_SYNC, unmapped, closed the file and exited. On the tested ext4 mount, the synchronized shared case instead read zero. Neither result changed the file's contents or length.

This supplement uses four cases on each of two mounts, repeated 5 times on Linux 6.8.0-146-generic. Every fresh file contains 4,095 bytes of A; its mapping spans one 4,096-byte page. The store targets offset 4,095, exactly EOF. The runner starts the reader executable only after the writer process has exited successfully. The reader opens the file afresh, verifies every in-file byte and maps the partial page read-only.

All five repetitions agreed within each mount. Zero and T are mapped tail values, not extra file bytes. MS_SYNC is omitted only in shared-no-sync.
Mount typeCaseWriter tail after stepNew reader tail
ext4shared-no-syncT (84)T (84)
ext4shared-synczerozero
ext4private-syncT (84)zero
ext4untouched-synczerozero
tmpfsshared-no-syncT (84)T (84)
tmpfsshared-syncT (84)T (84)
tmpfsprivate-syncT (84)zero
tmpfsuntouched-synczerozero

All 40 reader observations verified the full original payload, a 4,095-byte file size and zero bytes returned by pread() at EOF. Both private and untouched controls read zero in the later mapping. The private writer still saw its own T after sync, separating a private COW change from shared cached state. These repetitions check consistency, not a failure probability.

Linux documents this partial-page cache caveat, including the limitation of the msync workaround on tmpfs. It is known behavior reproduced here, not a newly discovered kernel defect. [1, Bugs] The upstream v6.8 msync path dispatches synchronization for shared file mappings through vfs_fsync_range; it is not a generic command to clear every mapped byte. This source inspection explains the interface boundary, not the exact Ubuntu patch set used by our host. [19] Tmpfs stores data in virtual memory and may use swap; this experiment does not establish that bytes never reach a device. [14]

Engineering consequence: file-format parsers should bound valid input by the actual file length, not the page-rounded mapping length. Do not put a record, sentinel or secret in accessible padding and assume that unmapping, closing or MS_SYNC erases it. The no-sync ext4 observation is especially timing-sensitive because background writeback was not suppressed. The measured zero after ext4 sync is not a portable clearing guarantee.

Download the C probe, Python runner and complete observations. Put both source files together and run from a writable directory on an executable filesystem:

python3 run-mmap-tail.py --build-dir . --temp-dir . --temp-dir /dev/shm --repetitions 5 > tail.json

Requirements: Linux, Python 3, a C compiler, GNU stat and findmnt. Choose the test directories explicitly; the command does not assume the current directory is ext4. Private temporary directories contain only fresh mode-0600 files. The JSON records compiler flags, kernel, mount types, filesystem-magic labels, all observations and SHA-256 hashes of both sources. No reboot, power interruption, forced cache eviction, file growth, concurrent writer, cross-principal disclosure or exploit was tested.

Where memory-backed file bytes can go

tmpfs, zram and zswap operate at different layers. The Linux 6.12 documentation distinguishes a filesystem, a block device and a swap cache. That distinction matters when interpreting the tmpfs controls above: volatile file lifetime does not establish that bytes never reached storage.

Capacity and backing-storage boundaries in Linux 6.12 documentation
MechanismLayerCapacity meaningPossible storage path
tmpfsFilesystemsize caps allocated bytes; nr_inodes limits inode-accounted usage. Neither reserves RAM.File pages may enter swap unless this mount uses noswap. [tmpfs]
zramBlock devicedisksize and actual memory use are different.Optional writeback can use a configured backing device. [zram]
zswapSwap cachemax_pool_percent caps the compressed pool as a percentage of memory.Eviction can write backing swap; disabling the cache does not drain it. [zswap]

A tmpfs mount's noswap option, introduced in Linux 6.4, is not a global policy for every shared-memory object. A size limit also allocates no RAM in advance. [tmpfs(5)] For zram, compare logical disksize with mm_stat counters: mem_used_total includes allocation overhead, not just compressed payload. [zram]

Each zswap cache entry retains a swap type and offset identifying its backing swap entry. The accounting consequence is that the compressed pool does not add swap address capacity; its RAM limit and the configured paging area are different budgets. [zswap]

Compressed payload is not the whole memory bill

The Linux v6.12 driver computes mem_used_total from zsmalloc pool pages. Its per-slot table is allocated separately. same_pages counts pages represented by a repeated word in that table, bypassing payload allocation. Consequently, zero compressed payload is not zero device memory cost. This is a source-code accounting distinction, not a measured saving. [51]

Wilson, Kaplan and Smaragdakis studied adaptive compressed caching at USENIX ATC 1999. Their detailed simulations used data-page traces from six UNIX programs, measured compression costs and modeled disk costs, including a 5 ms seek and zero dirty-page write cost. The useful design question is how much RAM to compress as locality changes. Those historical results are not zram or zswap benchmarks, and do not establish modern NVMe speedups. [52]

Read the configuration with the observation: identify the filesystem and swap/writeback settings before claiming RAM-only behavior. This comparison is a source review, not a new memory-pressure or performance experiment.

Which swap path did the control actually stop?

memory.swap.max limits charged swap usage, not RAM plus swap. It differs from the compressed-pool budget memory.zswap.max and the throttling threshold memory.swap.high. Reducing a limit is not proof that old entries have disappeared. [swap controls]

Linux v6.12 source paths, not measured device outcomes. Except for the first row, assume an already charged entry and successful swap preparation.
ConditionReachable path
New charge; swap limit is zeroNew swap charge denied, including a new zswap-backed entry.
Zero-filled folioZero bitmap before compression or writeback permission.
zswap enabled; store succeeds; writeback disabledCompressed store permitted.
zswap enabled; store fails; writeback disabledRedirty/activate instead of backing-device fallback.
zswap enabled; store fails; ancestors permit writebackBacking-device write path reachable.
zswap disabled; writeback flag is zeroPermission helper allows ordinary backing-device swap.

The last row is the important exception: mem_cgroup_zswap_writeback_enabled returns true when zswap is disabled, before checking ancestor flags. Meanwhile swap_writepage handles zero-filled folios before zswap_store. A quiet disk therefore proves neither compression nor a universal no-swap policy. These paths do not cancel previously submitted I/O. [charging and permission] [page dispatch]

TMO's ASPLOS 2022 study gives the performance context: compressed-memory and SSD backends have different costs, so Senpai uses pressure feedback and also monitors I/O pressure. That historical evaluation does not establish the semantics of these later Linux controls or a portable tuning value. This table is a source review, not a reproduction of TMO or a memory-pressure experiment. [TMO, sections 3.3-4]

Prefaulting can fail after doing some work

Observed boundary: an explicit population request over a two-page mapping of a one-page file returned EFAULT, yet the first page became present in the process page tables. Both READ and WRITE behaved this way in all three repetitions. Failure did not roll back the completed part of the request.

MADV_POPULATE_READ prepares readable access; MADV_POPULATE_WRITE prepares writable access. Available since Linux 5.14, they report population failures, unlike the best-effort population attached to mmap(MAP_POPULATE). The selected access must match the mapping permissions. [21]

Eight controls, each repeated 3 times on Linux 6.8.0-151-generic; 4096-byte pages. Every page-table presence bit was clear before the call. No mapped application store was performed.
MappingProtectionAdviceReturnPresent after
Anonymous, one pageReadREAD0yes
Anonymous, one pageReadWRITE-1 / EINVALno
Anonymous, one pageRead/writeREAD0yes
Anonymous, one pageRead/writeWRITE0yes
Private file, one pageRead/writeREAD0yes
Private file, one pageRead/writeWRITE0yes
Shared file, second page beyond EOFRead/writeREAD-1 / EFAULTyes, no
Shared file, second page beyond EOFRead/writeWRITE-1 / EFAULTyes, no

The READ path can retain shared zero pages; WRITE can prepare private copies. Linux v6.14 requests dirty marking for write population, and shared-file write faults can invoke filesystem handling. Unchanged file bytes therefore do not demonstrate unchanged allocation or an absence of writeback. This is not a general substitute for fallocate. [60] [61]

Choose the contract: population prepares access once, memory locking addresses continued residency, and synchronization addresses file updates. None of these alone coordinates a consistent version with a concurrent writer. A successful population call is not a promise that every subsequent access will be fault-free. [44] [60]

Reproduce with the Python probe, raw observations and method and test instructions. The probe samples /proc/self/pagemap, never dereferences beyond EOF, and verifies file bytes and size after the call. These 24 observations are repeated controls on one host, not a benchmark, allocation measurement, memory-pressure experiment or power-loss test.

Residency, synchronization and swap eligibility

mlock addresses residency, not durability. Successful ordinary locking populates the range; MLOCK_ONFAULT can leave pages unpopulated until accessed. A later fork does not transfer the locks to the child. Memory locking also does not exclude RAM from suspend-to-disk images. [44]

MAP_LOCKED is not an equivalent success test: mmap can return successfully despite incomplete prefaulting. [1] File synchronization remains a separate operation. In particular, msync with MS_INVALIDATE may report EBUSY for a locked range; do not reinterpret that as a failed storage device. [3]

A swapfile has a different contract: creating a large file does not activate a paging area. Linux rejects holes, and usable preallocation depends on the filesystem. [45] On Btrfs, eligibility also depends on extent placement and NODATACOW; active swapfiles prevent snapshots of their containing subvolume. [46]

These are documented interface constraints, not new measurements in the experiments below. Keep the checks separate: mapping access, page residency, file synchronization and swap activation answer different questions.

Synchronization is neither isolation nor a crash test

MS_SYNC waits for synchronization. On Linux, MS_ASYNC has been a no-op since 2.6.19; unmapping is not a substitute completion barrier. [3] POSIX also permits background writeback before a caller requests synchronization. A sync call therefore cannot provide transaction isolation or an all-or-nothing multi-page commit. [4]

The harness neither interrupted power nor evicted caches. It cannot validate device flush honesty, recovery ordering, directory persistence or hardware protection. Those questions require different tests. See writeback errors and synchronization and durable pathname publication.

Ordinary file mapping is also distinct from DAX, which can bypass the page cache for CPU-addressable storage. The kernel documents media-error handling for that path, including SIGBUS; a signal alone is not a unique diagnosis of truncation. No DAX device was used here. [7]

Windows: flush the view, then the file

Documented API comparison: the Linux measurements above do not establish Windows behavior. The following boundaries come from Win32 documentation reviewed on 14 November 2026, not a Windows runtime or power-loss experiment.

Different operations cover different cache layers; this is not a performance ranking.
OperationWhat completion means
FlushViewOfFileStarts writeback of dirty pages in the selected mapped range. No file-metadata flush or hardware-cache persistence completion. [54]
FlushFileBuffersFlushes buffered file information through a writable file handle. For mapped modifications, first flush the view. [53] [54]
FILE_FLAG_WRITE_THROUGH aloneRequests prompt writeback while system caching can remain enabled. Write-through does not by itself mean cache bypass. [55]
FILE_FLAG_NO_BUFFERING aloneBypasses system caching for file-data reads and writes. Does not govern hardware disk caches or mapped-file access. [55]

Microsoft specifies FlushViewOfFile followed by FlushFileBuffers for dirty mapped pages plus metadata and physical disk completion. Check both results: nonzero means success, zero requires GetLastError. The file handle needs GENERIC_WRITE. A successful view flush over a network does not establish remote persistence. [53] [54]

The two file-open flags are independent. Combined, they bypass the Windows system cache and request write-through of the drive cache to persistent media, but device support matters. The detailed caching contract explicitly permits system caching with write-through alone. Metadata has a separate flush requirement, and unbuffered I/O imposes transfer-size, offset and memory-alignment constraints. [55, Caching Behavior] [56] [57]

For seekable unbuffered I/O, check three values separately: transfer length, file offset and buffer address. Length and offset must be multiples of the volume's logical sector size; Microsoft recommends physical-sector alignment for unbuffered I/O, including buffer addresses. An aligned allocation alone does not validate the request. [57] Query the actual geometry: STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR distinguishes logical size, physical size and the first logical sector's offset within a physical sector. That offset is not a memory-buffer address. [58]

These are completion and caching controls, not a multi-operation transaction protocol. Coordinate writers and define a recoverable update sequence separately; do not transfer the Linux experiment's outcomes to Windows by matching function names.

Check recovery before completion, too. Pillai et al. separate persistence atomicity from ordering; their ALICE example accepts either the old or new application state before a success acknowledgement, but requires the new state afterward. Its checker still rejects malformed intermediate data. [59, sections 2.1 and 3.1] Applied as a design principle, a final flush cannot retroactively make earlier writes indivisible: define which states recovery may accept if interruption occurs before either flush returns. This is a protocol-design inference, not evidence about NTFS crash states or a Windows reproduction of ALICE.

An invalid sync request is not a failed storage write

The argument-error case calls msync() one byte past the page-aligned mapping start. It records -1 and checks the saved error specifically for EINVAL; any other failure fails the harness. Linux requires a page-aligned starting address. [3] This checks an API precondition, not the device's health or persistence.

Rebello et al.'s ATC 2020 study makes a useful methodological distinction: its filesystem experiments exclude input-validation failures and inject transient sector or block write faults after synchronization begins. The authors tested ext4, XFS and Btrfs on Linux 5.2.11, then used CuttleFS for application-level cases. Their cache-sensitive recovery findings concern that fault model, not every nonzero return from a synchronization API. [8, sections 3-5] Our checks do not reproduce those faults.

For monitoring, a mapped modification can increase storage-related accounting without a write-family syscall. See the measured process I/O counters and cancellation control.

For change detection, see the inotify experiment: shared mapped stores changed bytes without IN_MODIFY, while closing an unchanged writable file still emitted IN_CLOSE_WRITE.

File seals: a stable buffer needs more than a read-only reader

A read-only view does not by itself stop another holder from changing the underlying object. Linux memfd_create() provides an anonymous volatile file that can support file seals. Unlike a restriction on one descriptor, these restrictions belong to the inode. A receiver should inspect the seal mask with F_GET_SEALS before relying on it. [9] [11]

The following supplement is a separate experiment: seven sequential scenarios, each run 3 times on Linux 6.8.0-146-generic, using fresh non-executable memfds. It does not extend the original file-backed experiment's sample. Every case checks the entire file payload and expected error codes, not merely the first byte shown below.

Observed seal boundaries; each file starts at 4,096 bytes, with A followed by zeros. Labels show additional seals, omit the common F_SEAL_ prefix, and exclude the shared initial F_SEAL_EXEC from MFD_NOEXEC_SEAL.
CaseObserved outcomeBoundary
WRITE with an existing shared writable mapEBUSY; succeeds after unmapping.Installing the restriction requires releasing the writable mapping first.
WRITE with an earlier shared read-only mapEBUSY from a PROT_READ map on the O_RDWR descriptor; succeeds after unmapping.Current read permission does not remove the mapping's potential write capability.
FUTURE_WRITEEarlier mapping changes the file to B; pwrite and a new shared writable map return EPERM.Earlier writers retain access: this is not an immutable snapshot.
WRITE without size sealsGrowth to 8,192 bytes and shrink to 2,048 bytes succeed.A write seal alone does not freeze the extent.
WRITE + SHRINK + GROWWrite, new shared writable map, shrink and growth all return EPERM; file stays 4,096 bytes.Private COW modification still succeeds without changing the file.
SEAL aloneAdding WRITE through a duplicate fd returns EPERM; writing B and growing still succeed.Locking the seal list does not lock the data.
SHRINK aloneShrink returns EPERM; the shared edit and growth still succeed.Protecting the existing extent is narrower than freezing the buffer.

In the FUTURE_WRITE case, a private mapping changed its own first byte to P while a full file read still matched the earlier shared edit, B followed by zeros. Adding WRITE returned EBUSY while the earlier shared mapping existed, then succeeded after it was closed. The fixed-content case likewise allowed private COW changes. The distinction is shared versus private modification, not simply whether a mapping is writable. [12]

The new read-only case creates MAP_SHARED with PROT_READ from the writable descriptor before installing WRITE. Linux counts shared mappings that may become writable (VM_MAYWRITE), not only those currently permitting stores. That explains the observed EBUSY; releasing this mapping lets the seal succeed. The next controls test protection changes and a separately opened read-only descriptor; neither experiment exercises an interprocess race. [15] [11]

Read-only now, writable later?

Three further controls distinguish descriptor access from mapping capability. Each ran 3 times on Linux 6.8.0-146-generic. All mappings below are shared; each case uses a separate fresh memfd and checks its complete payload and extent.

Order matters: protections, seals and descriptor access are independent inputs.
SetupObserved resultConsequence
Map a separately reopened O_RDONLY descriptormprotect to read/write returns EACCES. A write through the original descriptor is visible as B.Reader permissions do not freeze the object. WRITE can be installed through the original writable descriptor while this reader remains mapped.
Create writable map, downgrade to read-only, then add FUTURE_WRITEpwrite returns EPERM; upgrading the old mapping succeeds and its store changes the file to B.Downgrading current permissions did not revoke the earlier mapping's write capability. WRITE still returns EBUSY until unmapping.
Add FUTURE_WRITE, then create a read-only map from O_RDWRThe later mprotect upgrade returns EACCES; the file remains A.This later mapping does not block adding WRITE, even while it remains mapped.

The first control also checks that adding a seal through the read-only descriptor returns EPERM. After the writable descriptor installs WRITE, both descriptors report the same seal mask and another write returns EPERM. This is an object-wide restriction, not a change to the reader's open mode. [10] [16]

The pinned Linux implementation clears VM_MAYWRITE when a new shared read-only mapping is created under a write seal. It deliberately leaves private COW mappings outside that rule. Earlier mappings are not retroactively processed by that creation-time check, explaining the before/after distinction. The results above measure Linux 6.8; the linked v6.12 source explains the mechanism, not the exact distribution build. [12] [17]

Practical rule: do not treat mprotect(PROT_READ) as revoking a producer's pre-existing write capability. Check the seal set, mapping lifetime and order of operations. These sequential controls are not a race test or a complete hostile-peer protocol.

Reproduce these controls separately with the standalone mapping-capability probe and inspect all recorded outcomes. It needs 64-bit Linux 6.3+, Python 3.8+, libc and access to the process's own descriptors through procfs. It maps only its own fresh non-executable memfds.

python3 file-seal-capability.py --repetitions 3 --output capability.json

For a finalized in-memory object, a producer can finish its writes, release shared mappings that retain write capability, and successfully add F_SEAL_WRITE | F_SEAL_SHRINK | F_SEAL_GROW before handing over the descriptor. The recipient must validate both the required seals and the application-level format; kernel restrictions do not prove that the initial data is correct. F_SEAL_SEAL can additionally prevent changes to the seal set, but installed seals cannot be removed in any case. This sequence is an API-based design implication. The separate handoff experiment below tests an additional boundary: the shared read cursor. [10]

Sealing is not a persistence or cryptographic-authentication mechanism. Ordinary memfd backing can use swap; "volatile" does not mean "never reaches a storage device." [11] [14] The probe explicitly uses MFD_NOEXEC_SEAL, so it requires Linux 6.3 or later and does not infer the host's default execution policy. [13]

Download the standalone Python probe and raw observations. Python 3.8+ with Linux memfd support and the required fcntl seal constants is required; no packages, compiler or elevated privileges are needed on a host whose policy permits these calls.

python3 file-seals.py --repetitions 3 --output observations.json

The JSON includes source SHA-256, kernel, Python version and all repetitions. The probe uses fresh anonymous objects and closes every mapping and descriptor. Unsupported calls or unexpected errors fail the run. The original seal probe tested no power interruption, reboot, concurrent writer, cross-process descriptor transfer, huge-page mapping, asynchronous I/O, pinned-page behavior or performance. The following supplement adds only its explicitly ordered two-process handoffs. Repetition is a consistency check, not a reliability estimate.

Sealed bytes, shared cursor

An unchanged object can still be incompletely consumed. In a separate Linux experiment, a fully sealed 4096-byte memfd kept its original full-file hash, but a sender's seek made the receiver read only its final 3072 bytes. A duplicate descriptor did not isolate the offset.

SCM_RIGHTS passes a reference to an open file description, not a private copy of its state. dup() also shares that object's offset. File seals constrain operations on the inode; they do not allocate a private cursor. [25] [26] [10]

The receiver inspected the seals, hashed the complete object with positional reads, reset its reader to zero and acknowledged readiness. Only then did the sender seek to byte 1024 and permit consumption. Resetting the offset before that acknowledgment did not prevent the sender's later change.

Four cursor controls on Linux 6.8.0-146-generic. All have WRITE, SHRINK and GROW seals. Each outcome repeated 3 times. Whole-file hashes and lengths matched.
Receiver strategyRead bytesSame bytes?
Received descriptor: read3,072Yes
Duplicate descriptor: read3,072Yes
Explicit offset: pread4,096Yes
Separate O_RDONLY reopen: read4,096Yes

This is range selection, not a checksum collision, changed file or kernel vulnerability. A consumer that requires the expected full length can reject the short read; no real parser's acceptance was tested. pread() supplies an offset for each call without advancing the shared cursor. A complete loop must still handle errors and short reads. [27]

Account for the range actually read

A file offset selects a byte position, not a private reader. A separate lseek() then read() can be interleaved by another cursor holder. dup() does not fix that shared state. [26]

Application decisions for positive-count reads of a regular file; source-based guidance, not additional experiment results. [34]
ResultExact-length consumer
Positive byte countAdvance the explicit offset by bytes returned and reduce the remaining count.
Zero before completionReject the incomplete fixed-length record. A zero-count request is not an EOF test.
ErrorHandle the reported error; never count missing bytes as consumed.

This accounting does not create a snapshot. An unsealed file may change between calls; content stability and expected-version validation remain separate requirements. See short reads for partial-transfer semantics.

Several buffers, one file range

readv() distributes a read across ordered memory buffers; it does not select a different file offset for each buffer. On a seekable file it uses and advances the shared position. preadv() instead starts at an explicit offset without changing that position. [35]

Worked example, not an additional measurement: with a two-byte header buffer followed by a four-byte payload buffer, a return count of three means the header and only the first payload byte arrived. An exact-length retry must skip the header, start one byte into the payload buffer and request the remaining three bytes. For positional reading from byte p, the next offset is p + 3. For readv(), continuation also requires coordinating users of the shared file position. Retrying the original buffer array can overwrite accepted bytes. This accounting follows the documented buffer order and byte-count result. [36]

The Linux preadv2() extension is different: offset -1 uses and updates the shared position. Neither a vector nor an exact-length retry loop freezes the file across calls; source-version acceptance remains a separate protocol requirement. These are API and application-design boundaries, not throughput, concurrency or power-loss measurements. [35]

The reopen control used /proc/self/fd before signaling readiness, reaching the same inode with a separate open file description. That is a Linux control, not a portable fix for arbitrary descriptors: procfs availability and permissions matter. For this seekable object, positional consumption avoids the shared offset without reopening. Neither approach replaces content-stability checks. [28]

Separate object acceptance from complete consumption

The full supplement has eleven deterministic cases, three repetitions per capture. Two original captures and a publication replay have identical observations. Other controls show that FUTURE_WRITE retains an earlier mapped writer, WRITE alone permits resizing, and a fully sealed object can start with invalid toy-format magic. All objects are non-executable and already carry EXEC: merely finding a nonzero seal mask is not enough.

The memfd is created after fork(); the receiver obtains it only through one Unix socket descriptor transfer. Socket messages order the actions without sleeps. Payloads are synthetic, kernel calls are native, and repetitions are consistency checks, not a failure-rate estimate. The receiver deliberately continues rejected controls for observation. This is not a complete hostile-peer protocol, disk-durability test or independent multi-host replication.

For a fixed-object contract, verify the received mask contains every required WRITE, SHRINK and GROW bit; validate bounded content and format; then consume the intended range with exact coverage checks. Producer authorization, ancillary-data validation, resource limits and descriptor lifecycle remain separate responsibilities. Compare the IO-Lite distinction between immutable buffers and separately described ranges.

Download the reproduction guide and file list, all observations and claim-to-case evidence. Linux 6.3+, Python 3.9+, permitted memfd/descriptor-passing calls and procfs are required; no external Python packages or elevated privileges.

python3 -B probe.py --repetitions 3 --output new-capture.json

Where the database literature applies

Crotty, Leis and Pavlo's CIDR 2022 paper examines mmap as a database buffer-pool replacement. Section 3 separates transaction safety, I/O control, error handling and performance. Section 4 compares read-only random access and scans on Linux 5.11, with a 100 GB page-cache allowance over a 2 TB range, against fio 3.25 using direct I/O. The scan configurations also differ in thread and queue settings. These are workload-specific experiments, not a universal ranking of mmap against every alternative. [18]

File sealing answers a narrower question: which changes are permitted to a particular volatile object? It does not supply database transactions, a durable commit protocol or control over page-cache eviction. Our memfd tests neither reproduce that paper's throughput results nor evaluate a database engine. Use the article's measured API boundaries to design a protocol, then evaluate that protocol under the actual storage and concurrency workload.

FastMap (ATC 2020) explores a redesigned mapping path. Its reported gains do not measure stock mmap. A numerical distinction matters: section 5.1 and Figure 7 report Ligra BFS at 21.3 versus 6.42 seconds on an Optane SSD (about 3.31x), and 21.9 versus 4.15 seconds on pmem (5.27x). Section 4 defines that pmem device as DRAM-backed emulation. The abstract instead associates 5.27x with Optane; we retain the detailed experiment labels and flag the discrepancy rather than merge the claims. These are reported results, not a Hesela replication. [20, sections 4-5.1, Figure 7]

Read the configuration with the speedup: the larger testbed has 40 physical cores and 80 hardware threads. Figure 4's 11.89x read-IOPS gain combines FastMap with adapted Speculative Page Faults (SPF); without SPF the reported gain is 4.7x at 80 threads. Both use null_blk, not a physical SSD throughput measurement. [20, sections 4-5.1]

The released README also contains a cache-size error: 1024 pages at 4096 bytes per page equal 4,194,304 bytes (4 MiB), not its stated 4 GB. A 4 GiB page buffer requires 1,048,576 such pages. The pinned driver identifies perma_mmap_buf_size as a page count. This is a parameter-unit check, not measured allocation or total module memory usage. Record the page size and cache budget before comparing experiments. [42] [43]

Reproduce and inspect the evidence

Download the C harness and Python runner into one directory, then run:

python3 run-mmap-boundaries.py --repetitions 5 > observations.json

The runner needs Linux, Python 3, a C compiler and GNU stat. It creates a private temporary directory, immediately unlinks each test file, checks every API result and removes temporary artifacts. The deliberately faulting child disables core dumps and restores the default SIGBUS disposition. No existing file or block device is opened.

Use --temp-dir /path/to/disposable/test-area to choose the filesystem. The published run used cc (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0; GNU stat -f reported ext2/ext3. That filesystem-magic label does not distinguish ext-family versions or expose mount options. This is one host, not a comparison of filesystems.

The raw JSON retains every repetition, compiler flags, kernel version, page size and SHA-256 hashes of both source files. The displayed table is generated from the same observations. No random seed is needed: the workload is deterministic.

The original seven-case harness excludes concurrent writers, huge pages, partial-tail remapping, file-growth remapping, performance measurement and recovery after failure. The separate tail-remapping supplement above adds only its explicitly listed cases. Repetition checks consistency of this run, not a universal probability.

Corpus: memory-mapped file, file truncation, and msync.

Primary sources

  1. Linux man-pages: mmap(2), mapping modes and lifetime
  2. POSIX.1-2017: mmap(), file extent and page boundaries
  3. Linux man-pages: msync(2), completion flags
  4. POSIX.1-2017: msync(), private mappings and background writeback
  5. Linux man-pages: truncate(2), file length and offset
  6. POSIX.1-2017: ftruncate(), discarded whole mapped pages
  7. Linux kernel documentation: Direct Access for files
  8. Rebello et al., Can Applications Recover from fsync Failures? USENIX ATC 2020, sections 3-5
  9. Linux man-pages: memfd_create(2)
  10. Linux man-pages: F_GET_SEALS / F_ADD_SEALS
  11. Linux v6.12: memfd sealing implementation
  12. Linux v6.12: seal_check_write mapping checks
  13. Linux kernel: non-executable memfd policy
  14. Linux kernel: tmpfs and swap
  15. Linux v6.12: shared mappings with potential write capability
  16. Linux man-pages: mprotect(2), access changes and EACCES
  17. Linux v6.12: mprotect access-capability checks
  18. Crotty, Leis and Pavlo, Are You Sure You Want to Use MMAP in Your Database Management System? CIDR 2022, sections 3-4
  19. Linux v6.8: shared-mapping msync dispatch to vfs_fsync_range
  20. Papagiannis, Xanthakis, Saloustros, Marazakis and Bilas, Optimizing Memory-mapped I/O for Fast Storage Devices, USENIX ATC 2020, pp. 813-827
  21. Linux man-pages: madvise(2), discard and explicit population semantics
  22. POSIX.1-2017: posix_madvise(), advice preserves memory-access semantics
  23. glibc 2.39: Linux posix_madvise implementation
  24. Linux man-pages: posix_madvise(3), glibc behavior and error convention
  25. Linux man-pages: unix(7), SCM_RIGHTS and open file descriptions
  26. Linux man-pages: dup(2), shared offsets
  27. Linux man-pages: pread(2), positional reads and short transfers
  28. Linux man-pages: proc_pid_fd(5), descriptor paths and permissions
  29. Linux v6.8: wp_page_copy(), private write-fault copying
  30. CPython v3.12.3: mmap_ass_subscript(), indexed native store
  31. Linux man-pages: rename(2), existing descriptors and pathname replacement
  32. GCC 13.3: optimization options; emitted accesses checked separately in retained disassembly
  33. GCC: volatile accesses do not order arbitrary nonvolatile memory
  34. Linux man-pages 6.19: read(2), byte counts, EOF and errors
  35. Linux man-pages: readv(2), buffer order, positional access and preadv2
  36. Python 3.12: os.preadv, buffer ordering and returned byte counts
  37. Linux v6.14: anonymous lazy-free and shared backing-object removal
  38. Linux v6.14: vma_is_shared_maywrite and mapping capability
  39. Linux v6.14: lazy-free folio reclamation
  40. Linux man-pages: fallocate(2), hole punching and KEEP_SIZE
  41. Linux man-pages: fsync(2), file-data and metadata synchronization
  42. FastMap pinned README: cache-page parameter and size example
  43. FastMap pinned driver: page-count parameter and load-time assignment
  44. Linux man-pages: mlock(2), residency, on-fault locking and lifetime
  45. util-linux: swapon(8), swapfile allocation restrictions
  46. Btrfs documentation: Swapfile, extent placement and active-file restrictions
  47. Linux 6.12: tmpfs, swap and per-mount limits
  48. Linux man-pages: tmpfs(5), dynamic allocation and noswap
  49. Linux 6.12: zram, memory accounting and optional writeback
  50. Linux 6.12: zswap, backing swap and runtime disabling
  51. Linux v6.12 zram driver: pool accounting, slot table and same-filled pages
  52. Wilson, Kaplan and Smaragdakis: The Case for Compressed Caching in Virtual Memory Systems (USENIX ATC 1999), sections 3-4.1
  53. Microsoft: FlushFileBuffers, parameters, return value and remarks
  54. Microsoft: FlushViewOfFile, mapped pages and persistence boundaries
  55. Microsoft: CreateFileA, Caching Behavior and independent file flags
  56. Microsoft: File Caching, write-through and metadata
  57. Microsoft: File Buffering, alignment and hardware-cache scope
  58. Microsoft: STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR, logical and physical sector geometry
  59. Pillai et al.: All File Systems Are Not Created Equal (OSDI 2014), sections 2.1, 3.1 and 3.6
  60. Linux v6.14: faultin_page_range, access flags and dirty marking
  61. Linux v6.14: do_fault, private COW and shared write-fault paths
  62. Linux 6.12 cgroup v2: memory.swap and memory.zswap controls
  63. Linux v6.12 memcontrol.c: swap charging and mem_cgroup_zswap_writeback_enabled
  64. Linux v6.12 page_io.c: swap_writepage and zero-filled folios
  65. Weiner et al.: TMO: Transparent Memory Offloading in Datacenters, ASPLOS 2022, DOI 10.1145/3503222.3507731, sections 3.3-4

Original mapping sources checked 17 October 2026; seal-capability and tail-remapping supplements reviewed 18 October 2026. Discard-advice supplement reviewed 20 October 2026. Sealed-handoff supplement reviewed and replayed 23 October 2026. POSIX extracts cited here are explicitly the 2017 edition.

Published by Hesela team · Published · Updated

Report a correction · Editorial standards · Reuse guidance

Change history

: first published.

: latest recorded update. A detailed change note is not available for this revision.

New-publication RSS · Correction RSS

Cite this page
Hesela team. Memory-mapped files: visibility, size and synchronization. Hesela. 2026-12-01. https://hesela.com/analyses/mmap-visibility-size-durability/