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.

20 minfree previewLinux 6.12C11glibc 2.39→ module 6 lab
What you'll learn
  • Distinguish SIGKILL survival in the volatile Linux kernel page cache from power-loss durability on storage media.
  • Select fsync(), fdatasync(), O_DSYNC, and parent-directory fsync(dir_fd) barriers for crash-consistent persistence.
  • Allocate STATX_DIOALIGN-aligned buffers via posix_memalign() for O_DIRECT DMA while handling tmpfs EINVAL.

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 PathData DestinationMetadata & Barrier CostCrash & Cache Semantics
Buffered write() (default)Kernel RAM page cache0 media waits (~1..3 us)Survives SIGKILL; lost on power cut
fdatasync(fd) / O_DSYNCNon-volatile media + drive flush1 flush if pre-sized (i_size fixed)Ideal for preallocated WAL commit frames
fsync(fd) / O_SYNCNon-volatile media + drive flushData + journaled mtime/inode flushRequired when metadata timestamps matter
fsync(dir_fd) (O_DIRECTORY)Parent directory blocks & journal1 directory commit barrierMandatory after O_CREAT, link, rename
O_DIRECT (posix_memalign)Direct user-RAM <-> controller DMABypasses page cache (EINVAL unaligned)Zero cache double-buffering (SQLite/DBs)
fig_m06_l01_arch.svg — Unified VFS page cache, mmap() MAP_SHARED vs…

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_m06_l01.svg — Buffered writes only reach volatile DRAM; power-cut…step 1/4
  1. Step 1. Query STATX_DIOALIGN for posix_memalign() O_DIRECT buffers, or pre-size WAL segments so i_size stays fixed.
  2. Step 2. Dirty shared VFS folios via pwrite() / MAP_SHARED (whereas MAP_PRIVATE clones private Copy-on-Write RAM).
  3. Step 3. Call fdatasync(fd) to flush dirty data blocks and controller write caches onto non-volatile media.
  4. 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) at a glance — GL-C01
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 

Probing Sync Barriers, mmap CoW vs Shared & STATX_DIOALIGN O_DIRECT

Save pagecache_odirect.c below. It preallocates /tmp/ksa_m06_l01.wal, commits 64 bytes via fdatasync() + fsync(), maps the 4 KiB folio under both MAP_PRIVATE (writing 'P' to private CoW byte 0) and MAP_SHARED (writing 'S' through to VFS page-cache byte 1), checks getrusage(RUSAGE_SELF) minor faults, hints eviction via posix_fadvise(..., POSIX_FADV_DONTNEED), syncs /tmp via fsync(dir_fd), and tests STATX_DIOALIGN + posix_memalign() O_DIRECT aligned I/O vs EINVAL unaligned rejection (with a clean fallback when /tmp is tmpfs, which rejects open(..., O_DIRECT) with EINVAL because tmpfs is the page cache!).

learner@ksa: ~/gl-c01/m06-l01
learner@ksa:~/gl-c01/m06-l01$ bat -H 30 -H 43 -H 66 pagecache_odirect.c File: pagecache_odirect.c    #define _GNU_SOURCE    #define _FILE_OFFSET_BITS 64    #include <errno.h>    #include <fcntl.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/mman.h>    #include <sys/resource.h>    #include <sys/stat.h>    #include <unistd.h>        int main(void) {        const char *wal_path = "/tmp/ksa_m06_l01.wal";        const char *dio_path = "/tmp/ksa_m06_l01_dio.bin";        int base_fl = O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC;            int fd = open(wal_path, base_fl, 0644);        if (fd < 0 || ftruncate(fd, 4096) != 0) return 1;        char rec[64];        memset(rec, 'C', sizeof(rec));        if (pwrite(fd, rec, sizeof(rec), 0) != (ssize_t)sizeof(rec)) return 1;        int fds_ok = (fdatasync(fd) == 0) ? 1 : 0;        int fs_ok = (fsync(fd) == 0) ? 1 : 0;            struct rusage ru0, ru1;        getrusage(RUSAGE_SELF, &ru0);        int prot = PROT_READ | PROT_WRITE;      uint8_t *sh = mmap(NULL, 4096U, prot, MAP_SHARED, fd, 0);        uint8_t *pr = mmap(NULL, 4096U, prot, MAP_PRIVATE, fd, 0);        if (sh == MAP_FAILED || pr == MAP_FAILED) return 1;        pr[0] = 'P';        sh[1] = 'S';        getrusage(RUSAGE_SELF, &ru1);        char chk[2] = {0};        int mmap_ok = (pread(fd, chk, 2U, 0) == 2 && chk[0] == 'C' &&                       chk[1] == 'S' && ru1.ru_minflt >= ru0.ru_minflt);        (void)munmap(pr, 4096U);        (void)munmap(sh, 4096U);        (void)posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED);        (void)close(fd);          int dir_fd = open("/tmp", O_RDONLY | O_DIRECTORY | O_CLOEXEC);        if (dir_fd < 0) return 1;        int dir_sync_ok = (fsync(dir_fd) == 0) ? 1 : 0;        (void)close(dir_fd);        (void)unlink(wal_path);        printf("durability: fdatasync=%d fsync=%d dir_fsync=%d mmap_cow=%d\n",               fds_ok, fs_ok, dir_sync_ok, mmap_ok);            size_t align = 4096U;        struct statx sx;        int pfd = open(dio_path, base_fl, 0644);        if (pfd < 0) return 1;        if (statx(pfd, "", AT_EMPTY_PATH, STATX_DIOALIGN, &sx) == 0 &&            (sx.stx_mask & STATX_DIOALIGN) && sx.stx_dio_mem_align > align) {            align = sx.stx_dio_mem_align;        }        (void)close(pfd);            void *raw = NULL;        if (posix_memalign(&raw, align, align * 2U) != 0) return 1;        uint8_t *abuf = (uint8_t *)raw;        memset(abuf, 0x5AU, align * 2U);      int addr_aligned = (((uintptr_t)abuf % align) == 0U) ? 1 : 0;            int dfd = open(dio_path, base_fl | O_DIRECT, 0644);        int aligned_io_ok = 0, unaligned_rejected = 0;        if (dfd < 0 && errno == EINVAL) {            dfd = open(dio_path, base_fl | O_DSYNC, 0644);            if (dfd < 0) { free(raw); return 1; }            aligned_io_ok = (write(dfd, abuf, align) == (ssize_t)align);            unaligned_rejected = 1;        } else if (dfd >= 0) {            ssize_t nw = write(dfd, abuf, align);            errno = 0;            ssize_t bad_ptr = write(dfd, abuf + 1, align);            int err_ptr = errno;            errno = 0;            ssize_t bad_len = pwrite(dfd, abuf, 500U, 0);            int err_len = errno;            uint8_t *rbuf = abuf + align;            memset(rbuf, 0, align);            ssize_t nr = pread(dfd, rbuf, align, 0);            aligned_io_ok = (nw == (ssize_t)align && nr == (ssize_t)align &&                             rbuf[0] == 0x5AU);            unaligned_rejected = (bad_ptr == -1 && err_ptr == EINVAL &&                                  bad_len == -1 && err_len == EINVAL);        } else {            free(raw);            return 1;        }        (void)close(dfd);        (void)unlink(dio_path);        free(raw);            printf("odirect: mem_ok=%d aligned_io=%d unaligned_einval=%d\n",               addr_aligned, aligned_io_ok, unaligned_rejected);        return 0;    }
  1. MAP_PRIVATE clones a private Copy-on-Write page on store ('P' invisible to pread), whereas MAP_SHARED dirties the shared VFS folio ('S').
  2. Syncing the parent O_DIRECTORY descriptor commits the newly created filename's dentry onto non-volatile storage.
  3. Query STATX_DIOALIGN and allocate with posix_memalign(); unaligned pointers (abuf + 1) or lengths (500) fail O_DIRECT with EINVAL.

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-l01
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-l01

Inside 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()?

  1. Step 1 (Compare metadata mutations): When appending past EOF, every pwrite() grows inode->i_size and allocates new extents—forcing even fdatasync() to commit filesystem metadata! When overwriting inside a preallocated 4 MiB segment, i_size and extent maps stay constant.
  2. Step 2 (Add creation durability): Write a 12-line helper int create_wal_segment(int dfd, const char *name, off_t seg_bytes) that opens name via openat(dfd, ...) (O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC), pre-sizes it, calls fsync(fd) and fsync(dfd) once, and returns fd ready for single-flush fdatasync() 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

quiz · 1 of 4

Why do Write-Ahead Log (WAL) storage engines prefer fdatasync(fd) over fsync(fd) when committing records into a preallocated segment file?

quiz · 2 of 4

Which three values must all be integer multiples of the device's STATX_DIOALIGN alignment boundary when calling pread() or pwrite() on an O_DIRECT descriptor?

quiz · 3 of 4

(Review from earlier lesson) Suppose you open a file without O_DIRECT and later enable O_DIRECT at runtime via fcntl(). Which fcntl() call sequence is required?

quiz · 4 of 4

When a process calls mmap(NULL, 4096, PROT_READ | PROT_WRITE, flags, fd, 0) on a file whose 4 KiB folio is already resident in the VFS page cache, how do fault counters and store visibility behave under MAP_SHARED vs MAP_PRIVATE?

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_DSYNC enforce per-write syncs, and fsync(dir_fd) hardens newly created or renamed directory entries.
  • Demand-paged mmap() faults in VFS page-cache folios on first touch (ru_minflt vs ru_majflt), aliasing dirty folios under MAP_SHARED and cloning Copy-on-Write shadow pages under MAP_PRIVATE.
  • O_DIRECT bypasses the page cache via statx() (STATX_DIOALIGN) + posix_memalign() when buffer address, transfer length, and file offset are aligned, while posix_fadvise(..., POSIX_FADV_DONTNEED) evicts cold sequential cache pages.
  • Next, we connect Ring 3 <stdio.h> buffering (_IOFBF, _IOLBF, _IONBF) directly onto this Ring 0 page-cache model to master the two-stage fflush -> fdatasync commit pipeline and fdopen/fileno ownership rules.
Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure