Page Cache, fsync & Direct I/O
A successful write() only copies bytes into volatile kernel DRAM—an abrupt power cut erases committed transactions unless explicit persistence barriers flush both file data and parent directories. You will master fsync(), fdatasync(), directory syncs, demand-paged mmap() CoW vs shared faults, and STATX_DIOALIGN O_DIRECT DMA.
What you'll learn
- Distinguish
SIGKILLsurvival in the volatile Linux kernel page cache from power-loss durability on storage media. - Select
fsync(),fdatasync(),O_DSYNC, and parent-directoryfsync(dir_fd)barriers for crash-consistent persistence. - Allocate
STATX_DIOALIGN-aligned buffers viaposix_memalign()forO_DIRECTDMA while handlingtmpfsEINVAL.
Why write() Loses Data on Power Loss & rename() Needs Directory fsync
Two post-outage failures shock engineers who confuse process-crash survival with power-loss durability. First, a financial ledger service calls write(fd, &tx, 64) (== 64) and close(fd) (== 0), sends "200 OK" over the network, and loses power 3 seconds later—upon reboot, the committed transaction is completely gone! Why? Because write() only dirtied a 4 KiB folio inside volatile kernel Dynamic RAM (DRAM), scheduled for background writeback up to 30 seconds later (vm.dirty_expire_centisecs = 3000). Second, an updater carefully calls write(tfd, ...) -> fsync(tfd) -> close(tfd) -> rename("cfg.tmp", "cfg.json"), cuts power immediately, and boots up to find neither "cfg.json"'s new dentry nor "cfg.tmp" visible because the parent directory's modified dentry sat unsynced in RAM!
Engineering crash-consistent storage on Linux requires distinguishing process death (SIGKILL, where kernel RAM survives) from power loss / kernel panic (where DRAM vanishes), selecting the exact persistence barrier (fdatasync vs fsync + fsync(dir_fd)), and understanding how mmap() and O_DIRECT interact with the VFS page cache.
note: A successful write() call is like handing a ledger entry to a clerk who pins it onto an erasable whiteboard in RAM; only fsync() or fdatasync() waits until the clerk engraves the entry onto non-volatile stone.
Where it stops working: Erasing a physical whiteboard loses everything in the room, whereas a user-space process crash (SIGSEGV or SIGKILL) leaves dirty kernel page-cache pages intact for normal background writeback.
definition ( Writeback, fdatasync(), Dir Sync & O_DIRECT): Page Cache Writeback: Buffered write() copies user bytes into inode->i_mapping XArray folios marked PG_dirty and governed by vm.dirty_background_ratio (10%) and vm.dirty_ratio (20%). fsync(fd) vs fdatasync(fd): fsync() flushes dirty data folios plus all inode metadata (mtime, ctime, i_size) and issues a storage controller cache flush (REQ_PREFLUSH / NVMe Flush), whereas fdatasync() skips metadata flushes when i_size and extent maps have not changed (~2x fewer media round-trips on preallocated logs!). O_DIRECT: Bypasses the page cache via Direct Memory Access (DMA) when memory address, byte count, and file offset satisfy statx() STATX_DIOALIGN alignment.
One Layer Down: O_DIRECT 3-Way Modulo Invariant & mmap Page Faults
When opening a block-backed file with O_DIRECT (queried dynamically on Linux 6.1+ via statx(fd, "", AT_EMPTY_PATH, STATX_DIOALIGN, &sx) yielding A_mem = stx_dio_mem_align and A_off = stx_dio_offset_align, typically 512 or 4,096 bytes), the block layer programs NVMe/eMMC scatter-gather DMA descriptors directly against user physical pages if and only if all three modulo checks equal zero: ((uintptr_t)buf % A_mem == 0) && (count % A_off == 0) && (offset % A_off == 0). Violating any one of the three returns -1 with errno == EINVAL immediately! Meanwhile, demand-paged mmap() maps the same VFS page-cache folios into user page tables lazily on first touch: hitting an already-cached folio increments minor page faults (ru_minflt) with zero disk I/O, fetching an uncached page from media increments major page faults (ru_majflt), MAP_SHARED stores dirty the shared VFS folio directly, and MAP_PRIVATE stores clone a private Copy-on-Write (CoW) RAM page invisible to pread(fd, ...).
| Persistence / I/O Path | Data Destination | Metadata & Barrier Cost | Crash & Cache Semantics |
|---|---|---|---|
Buffered write() (default) | Kernel RAM page cache | 0 media waits (~1..3 us) | Survives SIGKILL; lost on power cut |
fdatasync(fd) / O_DSYNC | Non-volatile media + drive flush | 1 flush if pre-sized (i_size fixed) | Ideal for preallocated WAL commit frames |
fsync(fd) / O_SYNC | Non-volatile media + drive flush | Data + journaled mtime/inode flush | Required when metadata timestamps matter |
fsync(dir_fd) (O_DIRECTORY) | Parent directory blocks & journal | 1 directory commit barrier | Mandatory after O_CREAT, link, rename |
O_DIRECT (posix_memalign) | Direct user-RAM <-> controller DMA | Bypasses page cache (EINVAL unaligned) | Zero cache double-buffering (SQLite/DBs) |
Figure 6.1. Unified VFS page cache, mmap() MAP_SHARED vs MAP_PRIVATE CoW faults, fdatasync()/dir_fd barriers, and 3-way aligned O_DIRECT DMA.
- Step 1. Query STATX_DIOALIGN for posix_memalign() O_DIRECT buffers, or pre-size WAL segments so i_size stays fixed.
- Step 2. Dirty shared VFS folios via pwrite() / MAP_SHARED (whereas MAP_PRIVATE clones private Copy-on-Write RAM).
- Step 3. Call fdatasync(fd) to flush dirty data blocks and controller write caches onto non-volatile media.
- Step 4. Open the parent directory with O_RDONLY | O_DIRECTORY | O_CLOEXEC and call fsync(dir_fd) after creation or rename.
Figure 6.1b. Buffered writes only reach volatile DRAM; power-cut durability requires fdatasync()/fsync() plus fsync(dir_fd) on directory updates.
Sync Prototypes, posix_memalign(3) & mmap(2) Reference
Define #define _GNU_SOURCE and #define _FILE_OFFSET_BITS 64 before <fcntl.h>, <sys/mman.h>, <sys/stat.h>, <stdlib.h>, and <unistd.h>. Watch posix_memalign(&ptr, align, size)'s return convention: unlike -1 syscalls, posix_memalign() returns 0 on success or a positive error code (EINVAL, ENOMEM) directly without setting errno!
mmap(2) GL-C01 Quick Reference mmap(2) NAME mmap, munmap, msync, fdatasync - map page-cache folios and sync media SYNOPSIS #include <sys/mman.h> #include <unistd.h> void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset); int munmap(void *addr, size_t length); int msync(void *addr, size_t length, int flags); int fdatasync(int fd); STANDARDS POSIX.1-2008; O_DIRECT and STATX_DIOALIGN require _GNU_SOURCE on Linux. RETURN VALUE mmap() returns mapped address, or MAP_FAILED ((void *)-1) on error. munmap(), msync(), fsync(), and fdatasync() return 0 or -1. ERRORS EACCES fd is not open for the requested prot/flags combination. EINVAL Unaligned addr/offset, length == 0, or missing MAP_SHARED/PRIVATE. EIO Storage writeback failed during fsync() or fdatasync(). FLAGS MAP_SHARED Share dirty page-cache folios and write back to fd. MAP_PRIVATE Copy-on-write mapping; stores stay private to process. SEE ALSO fsync(2), open(2), posix_fadvise(2), posix_memalign(3), statx(2) Kernel Systems Academy Lesson 6.1 mmap(2) GL-C01 quick reference · full manual page: man 2 mmap Verifying Durability Barriers, mmap CoW & O_DIRECT Alignment
Compile and run pagecache_odirect: verify fdatasync=1, fsync=1, dir_fsync=1, mmap_cow=1, and odirect: mem_ok=1 aligned_io=1 unaligned_einval=1.
learner@ksa:~/gl-c01/m06-l01gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror pagecache_odirect.c -o pagecache_odirectlearner@ksa:~/gl-c01/m06-l01./pagecache_odirectdurability: fdatasync=1 fsync=1 dir_fsync=1 mmap_cow=1odirect: mem_ok=1 aligned_io=1 unaligned_einval=1learner@ksa:~/gl-c01/m06-l01test ! -e /tmp/ksa_m06_l01.wal && test ! -e /tmp/ksa_m06_l01_dio.bin && rm -f pagecache_odirectlearner@ksa:~/gl-c01/m06-l01Inside Writeback Flushes, CoW Shadow Pages & Block DMA
Notice how pagecache_odirect exposed the unified VFS page cache from three angles: pwrite() dirtied page 0 ('C'), MAP_PRIVATE cloned a private shadow page so pr[0] = 'P' left byte 0 untouched at 'C', MAP_SHARED aliased the page-cache folio directly so sh[1] = 'S' appeared immediately to pread(), and O_DIRECT bypassed that folio cache altogether whenever 3-way alignment held!
Guided Practice: Preallocated WAL Segment Initializer (fallocate + fdatasync)
Why do high-throughput WAL writers pre-size segments (ftruncate or posix_fallocate) once at creation before running pwrite() + fdatasync()?
- Step 1 (Compare metadata mutations): When appending past
EOF, everypwrite()growsinode->i_sizeand allocates new extents—forcing evenfdatasync()to commit filesystem metadata! When overwriting inside a preallocated4 MiBsegment,i_sizeand extent maps stay constant. - Step 2 (Add creation durability): Write a 12-line helper
int create_wal_segment(int dfd, const char *name, off_t seg_bytes)that opensnameviaopenat(dfd, ...)(O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC), pre-sizes it, callsfsync(fd)andfsync(dfd)once, and returnsfdready for single-flushfdatasync()commits.
Independent Practice: CLOCK_MONOTONIC Buffered write vs O_DSYNC Latency Distribution
Write a C11 benchmark sync_latency.c (-std=c11 -O2 -Wall -Wextra -Werror) on a disk-backed directory (such as ./ inside a scratch subdir, cleaning up afterward) that records N = 32 individual 64-byte pwrite() latencies (CLOCK_MONOTONIC) under (a) buffered mode (no sync) vs (b) O_DSYNC, sorts the 32 samples in uint64_t ns[32], and prints p50 and p95 nanoseconds for both regimes.
Common Production Pitfalls
warning: Symptom: An atomic updater runs write(tfd) -> fsync(tfd) -> close(tfd) -> rename("cfg.tmp", "cfg.json") and still loses the update on a sudden power cut! Root Cause: fsync(tfd) persisted the file's data blocks and inode, but rename() modified the parent directory's dentry in volatile RAM without syncing the directory inode. Fix: Open the parent directory (O_RDONLY | O_DIRECTORY | O_CLOEXEC), call fsync(dir_fd) after rename() (or O_CREAT), and close dir_fd.
warning: Symptom: Adding O_DIRECT to an existing log writer causes write(fd, line, strlen(line)) to fail with EINVAL (or causes open("/tmp/x", O_DIRECT) on tmpfs to fail with EINVAL). Root Cause: O_DIRECT rejects unaligned malloc/stack buffers, non-block-multiple byte counts, unaligned file offsets, and RAM-backed filesystems (tmpfs). Fix: Query STATX_DIOALIGN, allocate posix_memalign() buffers for block-aligned engines, or use buffered writes + fdatasync() for variable-length records.
Knowledge Check
Key takeaways
- A successful
write()only places bytes in the volatile Linux kernel page cache (SIGKILL-safe, not power-fail durable) until an explicit sync barrier completes. fsync(fd)flushes data and all inode metadata,fdatasync(fd)skips non-essential timestamp flushes,O_SYNC/O_DSYNCenforce per-write syncs, andfsync(dir_fd)hardens newly created or renamed directory entries.- Demand-paged
mmap()faults in VFS page-cache folios on first touch (ru_minfltvsru_majflt), aliasing dirty folios underMAP_SHAREDand cloning Copy-on-Write shadow pages underMAP_PRIVATE. O_DIRECTbypasses the page cache viastatx()(STATX_DIOALIGN) +posix_memalign()when buffer address, transfer length, and file offset are aligned, whileposix_fadvise(..., POSIX_FADV_DONTNEED)evicts cold sequential cache pages.- Next, we connect
Ring 3<stdio.h>buffering (_IOFBF,_IOLBF,_IONBF) directly onto thisRing 0page-cache model to master the two-stagefflush->fdatasynccommit pipeline andfdopen/filenoownership rules.