Memory-mapped file

Also known as: mmap

On this page 6

A memory-mapped file is a file, or a region of one, that the operating system maps into the virtual address space of a process, so the program reads and writes the file through ordinary memory accesses instead of explicit read and write calls. In memory management, it connects the virtual memory system and the file system through the page cache, and on Unix-like systems it is created with the mmap system call.

Memory mapping is used by program loaders, databases, search indexes and inter-process communication. It can eliminate copying between kernel and user buffers, but it also moves I/O errors and performance behavior into the paging machinery, which changes how programs must be designed.

How a memory-mapped file works

When a process calls mmap, or MapViewOfFile on Windows, the kernel reserves a range of virtual addresses and records that the range is backed by a specific file and offset. No data is read at that moment; the page table entries for the range start out not present.

The first access to a page triggers a page fault. The kernel locates the corresponding file page in the page cache, reading it from disk if necessary, and maps that physical page frame into the process. Later accesses to the same page run at full memory speed without kernel involvement, because the memory management unit translates the address directly.

Writes follow the same path in reverse. A store marks the page dirty, and the kernel writes it back to the file later, during memory pressure, periodic writeback or an explicit msync call. The table summarizes the life cycle of a mapped page.

StageWhat the kernel doesCost to the process
Mapping createdReserves addresses, records file and offsetOne system call
First accessHandles page fault, loads page from cache or diskMicroseconds to milliseconds
Repeated accessNone, hardware translation onlyNormal memory latency
Page modifiedMarks page dirtyNone until writeback
Writeback or evictionWrites dirty page to file, may unmap framePossible later fault on reuse
Life cycle of a page in a memory-mapped file

Shared and private mappings

The mapping mode decides whether changes reach the file and whether other processes see them. A shared mapping writes modifications back to the file and makes them visible to every process that maps the same region. A private mapping uses copy-on-write: the first write to a page creates a private copy, and the file itself never changes.

The table compares the main mapping types available on Unix-like systems; Windows offers equivalent options through file mapping objects.

Mapping typeWrites reach the fileVisible to other processesTypical use
Shared file mappingYesYesDatabases, shared data files
Private file mappingNo, copy-on-writeNoExecutable code and libraries
Shared anonymous mappingNo file existsYes, after forkShared memory between related processes
Private anonymous mappingNo file existsNoHeap allocation for large blocks
Types of memory mappings

Program loaders rely heavily on private mappings. The code of a shared library is mapped once into physical memory and shared by every process that uses it, while each process receives its own copy of any page it modifies, such as relocated data.

Memory mapping compared with conventional file I/O

Memory mapping is not automatically faster than read and write. It avoids the copy from the page cache into a user buffer and lets the program use pointers directly, but each first touch of a page costs a fault, and changing mappings requires TLB invalidation, which can be expensive on multicore systems.

AspectMemory-mapped fileRead and write calls
Data copyingNone after the page is mappedCopy between kernel and user buffer
Random accessVery efficient, pointer arithmeticOne system call per access
Sequential streamingComparable, depends on readaheadOften equal or faster
Error reportingSignal such as SIGBUSReturn code from the call
Control over writebackIndirect, through msyncExplicit, through write and fsync
Memory-mapped access versus read and write calls

The strongest case for mapping is random access to large, read-mostly data that several processes share, such as an index or a model file. For streaming a file once from start to end, conventional reads with a large buffer are usually simpler and at least as fast.

Limitations and common mistakes

A memory-mapped file inherits every weakness of the paging system. Experienced engineers watch for the following problems, several of which have led database authors to abandon memory mapping in favor of their own buffer managers.

  • Truncated files: if another process shrinks the file, access to the missing pages raises SIGBUS and can crash the program.
  • Unpredictable stalls: any pointer dereference may block on disk I/O, which is invisible in the code and hard to profile.
  • Weak durability control: the kernel may write dirty pages in any order, so crash consistency requires careful use of msync and fsync.
  • Address space limits: on 32-bit systems a mapping cannot exceed the free virtual address range, often well below the file size.
  • Memory accounting confusion: mapped pages count toward resident set size, so monitoring tools may report a large process that is mostly cache.

Hints such as madvise with sequential or random flags, and huge pages for very large read-only mappings, can reduce fault overhead and TLB pressure when access patterns are known in advance.

A non-technical view

Normally a program reads a file by asking the system to copy parts of it into the program’s own memory, piece by piece. A memory-mapped file skips that step. The system makes the file appear as if it were already in memory, and the program simply looks at the address it needs.

It is like a library that places a book’s pages on a long wall instead of handing them over one at a time. You walk to the page you want, and staff fetch only the pages you actually look at. The main benefit is speed and simplicity for jumping around large files.

A concrete example

A search service keeps a 40 GB read-only index on a server with 128 GB of RAM and runs 16 worker processes. With conventional reads, each worker would maintain its own buffers, and popular index blocks would be duplicated in memory sixteen times.

Instead, every worker maps the index file with a private read-only mapping. All workers share the same physical pages in the page cache, so the index occupies about 40 GB once rather than many times over. After a warm-up period, nearly every lookup is served from memory, and median query latency falls to a few milliseconds. When a new index is built, the service writes it to a new file and swaps the mapping, avoiding the SIGBUS risk of modifying a file that is still mapped.