POSIX File I/O & Filesystem Semantics

The POSIX File I/O specification (IEEE Std 1003.1) establishes the foundational contract between user-space applications and operating system filesystems across Unix-like systems (Linux, macOS, FreeBSD, illumos).

Rather than treating files as database records or complex objects, POSIX defines a file as an unformatted sequence of bytes accessible through integer File Descriptors (FDs). Understanding POSIX I/O semantics—particularly around path resolution race conditions, durability guarantees, scatter-gather access, and kernel cache hinting—is essential for building high-performance storage engines, databases, and container sandboxes.

1. Directory-Relative Path Resolution (*at Syscalls)

Traditional path-based APIs (open(), stat(), unlink(), rename()) accept absolute paths (/var/data/file) or paths relative to the current working directory (./file). In multi-threaded programs or sandboxed environments, this model suffers from critical security flaws:

  1. TOCTOU (Time-of-Check to Time-of-Use) Vulnerabilities: Between checking a path and operating on it, an attacker can manipulate symlinks or swap parent directories.
  2. Global Process State: The current working directory (cwd) is shared across all threads within a process. One thread calling chdir() alters path resolution for every other thread.

The POSIX.1-2008 *at Architecture

POSIX.1-2008 introduced directory-relative APIs:

int openat(int dirfd, const char *pathname, int flags, ... /* mode_t mode */);
int fstatat(int dirfd, const char *pathname, struct stat *statbuf, int flags);
int unlinkat(int dirfd, const char *pathname, int flags);
int renameat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath);
  • When pathname is relative, resolution begins at the directory referred to by the open file descriptor dirfd, rather than the process cwd.
  • Passing the special constant AT_FDCWD as dirfd reproduces traditional open() behavior relative to the process current working directory.
  • Passing O_NOFOLLOW prevents symlink traversal, eliminating race conditions when traversing untrusted directory structures.

Safe Directory Traversal Pattern

// Open base directory descriptor
int root_fd = open("/var/lib/app", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (root_fd < 0) {
    perror("open base directory");
    return -1;
}

// Atomically open target file relative to root_fd without relying on global cwd
int data_fd = openat(root_fd, "secure/payload.bin", O_RDWR | O_NOFOLLOW | O_CLOEXEC);
if (data_fd < 0) {
    perror("openat target");
    close(root_fd);
    return -1;
}

close(root_fd);

2. Durability & Synchronized I/O Contracts

Modern operating systems buffer writes in the Kernel Page Cache (dirty pages). A successful write() system call only guarantees that bytes were copied from user-space memory into kernel buffer cache—it does not guarantee that data has been committed to non-volatile physical storage.

POSIX standardizes four levels of persistence:

┌────────────────────────────────────────────────────────┐
│               User Space Application                   │
│               Buffer (char buf[4096])                  │
└───────────────────────────┬────────────────────────────┘
                            │ write() (syscall)
                            ▼
┌────────────────────────────────────────────────────────┐
│                 Kernel Page Cache                      │
│             (Dirty Pages in Host RAM)                  │
└─────────────┬────────────────────────────┬─────────────┘
              │ fdatasync()                │ fsync()
              ▼                            ▼
┌────────────────────────────────────────────────────────┐
│            Physical Storage Device Cache               │
│          (Volatile Drive Controller DRAM)              │
└───────────────────────────┬────────────────────────────┘
                            │ Hardware Flush Barrier
                            ▼
┌────────────────────────────────────────────────────────┐
│           Non-Volatile Storage Medium                  │
│               (NAND Flash / Platter)                   │
└────────────────────────────────────────────────────────┘
Mechanism Scope Flushed Metadata Updated? Typical Latency Cost
write() User memory -> Page Cache No disk flush ~1-5 microseconds
fdatasync(fd) File data bytes only Only if essential for data retrieval (file size) ~1-10 milliseconds
fsync(fd) File data + all filesystem metadata Yes (mtime, ctime, inode attributes) ~2-20 milliseconds
sync() Entire system buffer cache All modified inodes and superblocks ~10-100+ milliseconds

fsync() vs. fdatasync()

  • fsync(int fd): Forces all dirty in-core data along with all metadata associated with fd to disk. If you overwrite existing bytes in a pre-allocated file, fsync() will still force a costly write of the inode table on disk (because st_mtime changed), resulting in two disk I/O operations.
  • fdatasync(int fd): Flushes data blocks, but only writes metadata if it is strictly necessary to correctly read the file data later (e.g., if the file length st_size changed). For transactional databases like PostgreSQL and SQLite, using fdatasync() eliminates unnecessary inode writes, drastically improving transaction commit latency.

Synchronous Open Flags: O_SYNC and O_DSYNC

Rather than calling synchronization functions explicitly, files can be opened with synchronous completion semantics:

  • O_SYNC: Every subsequent write() blocks until both data and metadata are committed to physical media (equivalent to calling fsync() after every write).
  • O_DSYNC: Every subsequent write() blocks until data is committed to physical media (equivalent to calling fdatasync() after every write).

3. Scatter-Gather & Offset-Based I/O

Standard read() and write() alter the implicit file offset stored in the kernel's Open File Description. In multi-threaded applications where multiple worker threads share a single file descriptor, concurrent reads and writes corrupt each other's offsets without locks.

Positional I/O: pread() and pwrite()

POSIX defines positional I/O primitives:

ssize_t pread(int fd, void *buf, size_t count, off_t offset);
ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);
  • Atomically performs the I/O operation at the specified file offset.
  • Does not inspect or update the file pointer.
  • Guarantees thread safety: multiple threads can execute concurrent pread() and pwrite() calls on the same file descriptor simultaneously.

Vectored (Scatter-Gather) I/O: readv() and writev()

Rather than copying contiguous bytes from a single buffer, vectored I/O operates on an array of struct iovec buffers:

#include <sys/uio.h>

struct iovec {
    void   *iov_base;  /* Starting address */
    size_t  iov_len;   /* Number of bytes to transfer */
};

ssize_t readv(int fd, const struct iovec *iov, int iovcnt);
ssize_t writev(int fd, const struct iovec *iov, int iovcnt);
  • Scatter Read (readv): Sequentially fills multiple non-contiguous memory buffers from a single file read.
  • Gather Write (writev): Writes multiple non-contiguous buffers (e.g., header, payload, checksum) in a single atomic system call, eliminating the need to allocate and copy data into a contiguous temporary buffer in user space.

4. Kernel Page-Cache Hinting & Space Allocation

Page-Cache Advisory: posix_fadvise()

High-throughput engines can declare their file access patterns in advance, enabling the kernel to optimize read-ahead windows or immediately release memory:

int posix_fadvise(int fd, off_t offset, off_t len, int advice);
Advice Flag Meaning & Kernel Behavior Best Use Case
POSIX_FADV_NORMAL Default heuristic; balanced readahead window. General random/sequential mix.
POSIX_FADV_SEQUENTIAL Doubles kernel readahead window and drops pages shortly after read. Streaming logs, big data scanning.
POSIX_FADV_RANDOM Disables readahead entirely. B-tree index lookup, key-value stores.
POSIX_FADV_WILLNEED Initiates asynchronous kernel read into page cache before use. Pre-warming memory before query execution.
POSIX_FADV_DONTNEED Instructs the kernel to free page-cache pages backing this range. Log rotation, write-once archiving.

Contiguous Space Allocation: posix_fallocate()

Traditional sparse writes extend files on demand, leading to file fragmentation and catastrophic ENOSPC (Disk Full) errors mid-write.

int posix_fallocate(int fd, off_t offset, off_t len);
  • Guarantees disk blocks are allocated and unfragmented on physical storage.
  • If storage is exhausted, posix_fallocate() fails upfront, guaranteeing that subsequent writes to the allocated range will never fail due to lack of space.

Related Topics