Buffer Cache & Page Cache
How operating systems cache disk blocks in RAM, the difference between write-back and write-through caching, and how sync semantics work.
How operating systems cache disk blocks in RAM, the difference between write-back and write-through caching, and how sync semantics work.
Introduction
For ordinary buffered file I/O on Linux, the page cache keeps file data in RAM so repeated reads can avoid storage access and writes can be combined before writeback. This is the common path, not a universal rule: direct I/O can bypass or change page-cache use, and device, filesystem, and memory-mapped paths have their own behavior. RAM can serve a cache hit faster than storage, but an uncached read still has to reach the storage stack.
Historically, “buffer cache” referred to cached disk blocks, while “page cache” referred to file contents. Linux’s normal buffered file-data path uses the page cache rather than two independent copies. struct buffer_head still appears in some filesystem paths to track individual blocks; it usually sits on a page-cache page and records block mapping and I/O state.
This distinction helps when tuning file I/O or diagnosing memory pressure.
When to Use / When Not to Use
When Page Cache Is Your Friend
- Repeated reads: Reused file data may be served from memory on a cache hit, avoiding storage I/O.
- Write-heavy workloads: Write-back caching batches multiple small writes into sequential disk operations
- Boot and application startup: Frequently-used libraries and configuration files stay cached after first use
- Database workloads: Some engines use the OS page cache, while others manage their own buffer pool; the best path depends on the engine and workload.
When Caching Causes Problems
- Database with its own cache: A database buffer pool and OS page cache can duplicate cached data;
O_DIRECTmay avoid page-cache use, but benchmark it and check filesystem alignment rules. - Durability requirements: A successful buffered
write()may return before storage writeback; useO_SYNCorfsync()when the application needs a durability boundary. - Memory-constrained systems: Large page cache can cause swapping if not properly sized
- Predictable latency: Buffered I/O introduces variable latency depending on cache hits
Write Policy Selection
| Path / flag | Page-cache behavior | What a successful call means | Durability boundary |
|---|---|---|---|
| Buffered write (default) | Updates page-cache data and marks it dirty | write() accepted the bytes; they may still be waiting for writeback |
Use fsync(fd) when the file data and required metadata must be durable |
Synchronous write (O_SYNC) |
Uses the normal file path unless combined with another mode | Each write waits for the file data and required metadata to reach the storage device | Depends on filesystem and device honoring flushes |
Direct I/O (O_DIRECT) |
Attempts to bypass the page cache for file data; support and alignment rules vary | I/O completed through the direct-I/O path, not necessarily a durable name or crash-safe update | Use the required sync operation for durability; direct I/O is not a substitute for fsync() |
Architecture or Flow Diagram
This is the normal buffered read path. A cache hit avoids storage I/O; a miss reads data through the filesystem and storage stack, then makes it available in the page cache.
flowchart LR
APP["Application read()"] --> VFS["VFS"]
VFS --> LOOKUP{"Valid page cached?"}
LOOKUP -- "Hit" --> COPY["Copy cached bytes to application"]
COPY --> APP
LOOKUP -- "Miss" --> FS["Filesystem read"]
FS --> BLOCK["Block layer"]
BLOCK --> DEVICE["Storage device"]
DEVICE --> PAGE["Fill page-cache page"]
PAGE --> COPY
Normal buffered reads and file-backed mmap use the page cache. Direct I/O can take a different path and bypass the page cache for file data; details and alignment requirements depend on the filesystem and kernel.
Core Concepts
Page Cache Structure
The page cache indexes file data by offset in an address_space. Page size varies by architecture and is often 4 KiB. Recent Linux kernels represent cached data with folios indexed through an XArray; older kernel versions used radix trees of struct page objects, as sketched below:
// Historical sketch: current kernels use an XArray and folios
struct address_space {
struct radix_tree_root page_tree; // Maps offset → struct page
spinlock_t tree_lock;
atomic_t i_mmap_writable;
struct radix_tree_root i_mmap; // For mmap'd file
// ... other fields
};
// Each file's inode has an address_space
struct inode {
// ...
struct address_space *i_data;
// ...
};
// struct page represents one cached page
struct page {
unsigned long flags;
struct address_space *mapping; // Which file this belongs to
pgoff_t index; // Offset within file (in pages)
void *virtual; // Kernel virtual address
// ... reference counting, dirty bits, etc.
};
Read Path
The diagram above shows the common buffered path. On a cache hit, Linux can copy the requested bytes from cached file data. On a miss, the filesystem reads the data from storage into the page cache before returning it. File-backed mmap uses the same cached file data, although it maps pages rather than copying each read() result into a user buffer. Direct I/O can take a different path and is described separately below.
Write Path
With ordinary buffered writes, the kernel updates file data in the page cache and marks the affected pages dirty. A successful write() means the kernel accepted the bytes; it does not by itself mean those bytes have reached durable storage. Dirty data is written back later, and fsync(fd) provides an explicit request to flush a file’s data and required metadata.
Dirty Page Writeback
Writeback may begin later because of background work, memory pressure, or an explicit sync request. The application can continue after a buffered write() while pages remain dirty; fsync(fd) asks the system to write the file’s changes and waits for completion.
flowchart LR
APP["Application"] -->|"write() returns"| DIRTY["Page-cache data (dirty)"]
DIRTY -->|"later writeback"| FS["Filesystem"]
FS --> BLOCK["Block layer"]
BLOCK --> DEVICE["Storage device"]
APP -->|"fsync(fd)"| WAIT["Request writeback and wait"]
WAIT --> FS
A completed writeback is not the same as a durable directory entry for a newly created or renamed file. That requires syncing the containing directory too; the crash-consistency example below shows the sequence.
Buffer Cache vs Page Cache (Historical Context)
Historically, “buffer cache” referred to cached disk blocks, while “page cache” referred to file contents. Linux’s normal buffered file-data path uses a unified page cache rather than two independent copies. struct buffer_head still appears in some filesystem paths to track individual blocks; it usually sits on a page-cache page and records block mapping and I/O state rather than holding a second copy of the whole file.
// buffer_head—legacy structure layered on page cache
struct buffer_head {
struct page *b_page; // Parent page
sector_t b_blocknr; // Block number on disk
size_t b_size; // Block size
char *b_data; // Pointer to data within page
// Buffer state flags
bit 0: BH_Uptodate // Contains valid data
bit 1: BH_Dirty // Needs writeback
bit 2: BH_Locked // I/O in progress
bit 3: BH_Req // Has been scheduled for I/O
bit 4: BH_Mapped // Maps a valid block
// ...
};
The kernel’s internal writeback functions vary by filesystem and kernel version. Applications should rely on the documented fsync() behavior, not a particular internal call chain.
Production Failure Scenarios
Scenario 1: Data Loss from Write-Back Caching
What happened: A buffered write() can return while file data is still dirty in the page cache. If the system loses power before the data is synced, recent changes may be lost. Writeback timing varies; there is no fixed delay.
Detection: Check every write() and sync return value. After restart, compare application recovery state with filesystem and device error logs; system-wide dirty/writeback counters can help identify a storage backlog.
For a crash-safe create or replace, syncing the file is only part of the sequence. Write a temporary file in the target directory, sync its contents, rename it, then sync the parent directory so the name change is durable:
flowchart LR
WRITE["Write temporary file"] --> FILESYNC["fsync(temp file)"]
FILESYNC --> RENAME["rename(temp, final)"]
RENAME --> DIRSYNC["fsync(parent directory)"]
DIRSYNC --> ACK["Acknowledge durable update"]
A same-directory rename is atomic to concurrent readers, but a crash can still lose the new directory entry until the directory is synced. For a newly created file without rename, call fsync(fd) and then fsync(dirfd) on its containing directory.
// Pseudocode: write_all handles short writes; check every durability step.
int persist_replace(int dirfd, int fd, const void *data, size_t length)
{
if (write_all(fd, data, length) < 0)
return -1;
if (fsync(fd) < 0)
return -1;
if (renameat(dirfd, ".state.tmp", dirfd, "state.dat") < 0)
return -1;
if (fsync(dirfd) < 0)
return -1;
return 0;
}
Mitigation: Check for short writes and errors, call fsync(fd) when file contents must be durable, and check its result. For a create or rename, sync the containing directory after syncing the file. O_SYNC is another option when each write needs synchronous completion; filesystem and device behavior still determines the durability guarantee.
Scenario 2: Memory Pressure Causing Thrashing
A large sequential scan can fill the page cache with file data it will not reuse, evicting a working set that would have been useful. This can increase storage I/O and memory-reclaim work.
Detection: Compare available memory, dirty/writeback pages, and device I/O while the workload runs. Treat these as workload signals, not fixed thresholds.
Mitigation: Keep buffered I/O as the default. For sequential scans with little reuse, test posix_fadvise() access-pattern hints; consider O_DIRECT only if measurements show cache pollution or duplicated caching. Linux direct I/O attempts to avoid the page cache for file data, but filesystem support and buffer, length, and offset alignment rules vary. Reads can be short or fail, so check every return value. O_DIRECT does not establish durability; benchmark both paths with the real workload.
Trade-off Table
| Choice | Page-cache effect | Main trade-off |
|---|---|---|
| Buffered I/O | Uses cached file data and read-ahead | Good general default; sync separately when durability matters |
| O_DIRECT | Attempts to bypass page cache for file data | Can avoid duplicate caching, with filesystem-specific alignment and coherency rules |
| O_SYNC / fsync() | Does not mean “disable the page cache” | Adds a durability wait; sync frequency affects latency |
Direct I/O is a performance option, not a durability policy. Use the normal buffered path unless measurements show a problem and the application can meet the direct-I/O requirements.
Implementation Snippets
Checking and Controlling Page Cache Behavior
Applications can pass access-pattern hints with posix_fadvise(). These hints may change readahead or reclaim behavior; they do not guarantee a cache hit, eviction, or durability.
posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
posix_fadvise(fd, 0, 0, POSIX_FADV_WILLNEED);
Use these only after measuring the workload. Avoid dropping the system-wide page cache on a production host to benchmark one application.
Monitoring Page Cache Effectiveness
A larger Cached value is not itself a cache-hit ratio. Compare dirty/writeback trends with device I/O and application latency to tell whether writeback or storage is limiting the workload. A short command set appears in the Observability Checklist below.
Caching Behavior in Applications
Application policy depends on data reuse and durability needs: Scenario 2 covers cache pollution, and Scenario 1 shows the file and directory sync sequence.
Observability Checklist
Linux Page Cache Metrics
grep -E '^(Cached|Dirty|Writeback):' /proc/meminfo
grep -E '^(nr_dirty|nr_writeback):' /proc/vmstat
iostat -x 1
These are system-wide signals. They do not report a universal per-file page-cache hit ratio.
Key Metrics to Monitor
| Signal | What it can indicate |
|---|---|
| Sustained dirty/writeback growth | The workload is creating dirty data faster than storage is completing writeback |
| Device latency and queue depth | Storage saturation or slow flush completion |
| Available memory and reclaim activity | Page-cache pressure that may affect the workload |
Compare against a baseline for the same workload; fixed cache-size or percentage thresholds are not portable.
Common Pitfalls / Anti-Patterns
Page Cache Security Considerations
Buffered file data can remain in RAM after an application closes a file. Encryption at rest does not mean cached file contents are encrypted in memory, and O_DIRECT is not a memory-erasure or confidentiality guarantee. Include page-cache contents, swap, and crash dumps in the system’s sensitive-data threat model.
Compliance Considerations
Requirements depend on the data and deployment. Document how sensitive file contents may exist in RAM, swap, and crash dumps, and apply the controls required by the applicable policy or regulation.
Coding Anti-Patterns
| Mistake | Safer rule |
|---|---|
Treating a successful buffered write() as crash-durable |
Sync the file; sync its parent directory after creating or renaming it |
| Treating O_DIRECT as a durability flag | Treat it as a page-cache performance option; check alignment and sync requirements |
| Ignoring write or sync errors | Handle short writes, ENOSPC, and errors returned by fsync |
| Expecting mmap writes to be immediately durable | Use msync for mapped writeback and fsync when file durability is required |
Quick Recap Checklist
- Buffered reads normally check the page cache first; a miss reads through the filesystem and storage stack.
- Buffered writes can return while page-cache data remains dirty; writeback happens later.
- O_DIRECT attempts to bypass page-cache use for file data, with filesystem-specific support and alignment rules.
- A successful write is not the durability boundary: fsync the file, then fsync its directory after create or rename.
- The historical buffer cache refers to block-oriented caching; current Linux uses a unified page cache for normal buffered file data.
Interview Questions
write() mean the data is durable?No. It usually means the kernel accepted the bytes into the page cache; the page may still be dirty. Call fsync(fd) when the file data and required metadata must survive a crash, and check its return value.
fsync(fd) syncs the file's data and metadata, but not necessarily the directory entry that names it. After writing and syncing a new file, or after renaming a temporary file into place, call fsync(dirfd) on the containing directory to make that name change durable.
O_DIRECT change?On Linux, O_DIRECT attempts to avoid the page cache for file data. Filesystem support and alignment requirements vary, and misaligned I/O may fail or fall back to buffered I/O. It is a performance option, not a durability guarantee.
The terms originally described different roles: block-oriented buffers and cached file contents. Normal Linux buffered file I/O uses a unified page cache. Some filesystem paths still use buffer_head metadata to track individual blocks, usually on page-cache pages; it is not a second complete copy of each file.
mmap() use the page cache?Normally, yes. File-backed mappings use the same cached file data as buffered reads and writes. msync(MS_SYNC) requests writeback for a mapped range; use fsync() when the application needs a file durability boundary.
Background writeback sends dirty pages to storage. When dirty data grows beyond dynamic thresholds, the kernel can throttle processes producing more dirty data. The thresholds and timing depend on workload and system configuration; there is no fixed writeback interval.
A journal helps a filesystem recover its metadata structures after a crash. It does not automatically make every application write durable; applications still need the appropriate file and directory sync sequence.
fdatasync() be enough instead of fsync()?fdatasync() syncs file data and metadata needed to retrieve that data, such as a changed file size. fsync() also syncs other file metadata. Choose based on the metadata your application needs to persist.
Further Reading
- Linux Kernel Documentation: Page Cache — Official page cache documentation
- Linux Kernel Documentation: VFS Layer — Virtual File System documentation covering inode and address_space
- Understanding the Linux Kernel, Chapter 16 — Memory mapping and page cache internals
- Linux man-pages: fsync(2) — File and directory synchronization semantics
- Linux man-pages: open(2) —
O_DIRECTcaveats and alignment requirements - Linux Kernel Documentation: Buffer Heads — Block-level buffer metadata
- Cache Buffer Management — buffer cache internals — Buffer cache mechanisms and management strategies
- I/O Scheduling Algorithms — disk request optimization — Scheduling algorithms for disk I/O optimization
Conclusion
For normal buffered Linux file I/O, the page cache serves reads on a hit, fills on a miss, and holds dirty writes for later writeback. Direct I/O can change or bypass page-cache use for file data, but its support and alignment rules vary and it does not replace durability synchronization.
A successful buffered write is not enough to guarantee crash recovery. Sync the file with fsync(fd); when creating or renaming a file, sync the containing directory too.
Category
Related Posts
ASLR & Stack Protection
Explore ASLR, PIE, stack canaries, and NX on Linux with GCC, then inspect a harmless C program to see what each mitigation does and where it falls short.
Assembly Language Basics: Writing Code the CPU Understands
Learn x86-64 Linux assembly with the System V ABI: track registers, assemble and run a small program, debug it in GDB, then compare AArch64.
Boolean Logic & Gates
Understanding AND, OR, NOT gates and how they combine into arithmetic logic units — the building blocks of every processor.