Notes
All notes

File Systems and I/O (OS Core #7)

A file is a name for bytes that survive a reboot. Everything else — inodes, descriptors, caches, journals — exists to make that promise efficient and safe. The questions are usually about descriptors and offsets, or about why a write is not on disk yet.

Files, directories, and the VFS

Files and directories are the two basic objects in the namespace. A file is a sequence of bytes plus metadata. A directory is a mapping from names to files (and to other directories).

Linux layers a virtual file system (VFS) over ext4, XFS, Btrfs, tmpfs, NFS, and more. The VFS defines the operations (open, read, write, stat) and each filesystem implements them. That is why the same read() works on a USB stick, a network share, and /proc.

A path is resolved one component at a time: start at the root (or the current directory), look up each name in the directory, follow symlinks, and check permissions at every step. Each lookup hits the dentry cache; a miss goes to disk.

int fd = open("dir/file.txt", O_RDONLY);

open returns a descriptor, not a file object. The kernel keeps the mapping.

QQuestionWhat does a directory entry contain?
ASolution

A name and a reference to an inode (the inode number). It does not contain the file’s data or most of its metadata; those live in the inode.

File descriptors

A file descriptor is a small integer indexing a per-process table. The entry points to an open file description, which holds the offset, flags, and a reference to the inode.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, minimum width=1.9cm, minimum height=0.5cm, font=\scriptsize},
  a/.style={->, thick}]
  \node[font=\scriptsize, anchor=east] at (-0.2,0) {process};
  \node[b, fill=blue!10] (fd0) at (1.3,0.9) {fd 0};
  \node[b, fill=blue!10] (fd1) at (1.3,0.3) {fd 1};
  \node[b, fill=blue!10] (fd3) at (1.3,-0.3) {fd 3};
  \node[b, fill=orange!18] (ofd) at (4.1,0.3) {open file description\\offset, flags};
  \node[b, fill=green!18] (in) at (7.0,0.3) {inode\\data blocks, metadata};
  \draw[a] (fd0) -- (2.2,0.3) -- (ofd.west);
  \draw[a] (fd1) -- (ofd.west);
  \draw[a] (fd3) -- (4.1,-0.5) -- (ofd.south);
  \draw[a] (ofd) -- (in);
  \node[font=\scriptsize, anchor=north] at (4.1,-0.9) {shared by dup and fork};
\end{tikzpicture}

Descriptors 0, 1, and 2 are stdin, stdout, and stderr by convention. dup creates a second descriptor pointing at the same open file description, so both share the offset:

int fd = open("log.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
dup2(fd, 1);             // stdout now goes to the file
std::printf("hello\n");  // written to log.txt

That is how shell redirection works: the shell opens the file, dup2s it onto 1, then execs the program. The program does not know or care.

fork copies the descriptor table, so parent and child share every open file description and its offset. exec keeps descriptors open unless FD_CLOEXEC is set.

QQuestionTwo descriptors refer to the same file but have independent offsets.

What went wrong?

ASolution

They were created by separate open calls, so they refer to different open file descriptions. Sharing an offset requires dup, dup2, or fork.

Inodes

An inode stores everything about a file except its name:

#include <sys/stat.h>
struct stat st;
stat("file.txt", &st);
std::printf("inode=%llu size=%lld links=%llu mode=%o\n",
            (unsigned long long)st.st_ino,
            (long long)st.st_size,
            (unsigned long long)st.st_nlink,
            st.st_mode & 0777);

Names are in directories; inodes are in a table. A hard link is a second directory entry pointing at the same inode, which is why the link count exists. A symbolic link is a separate file containing a path.

Deleting a name decrements the link count. The data is freed when the count reaches zero and no process has the file open. That is why a deleted file can still occupy space (an open descriptor keeps it alive) until the process closes it.

QQuestionHow can a file use disk space after rm?
ASolution

A process still holds an open descriptor. The inode’s link count is zero, but the data is freed only when the last descriptor closes.

File allocation methods

How a filesystem maps logical block numbers to disk blocks:

Method Idea Pros Cons
Contiguous each file gets consecutive blocks fast sequential and random external fragmentation, hard to grow
Linked each block points to the next no fragmentation, easy to grow random access is \(O(n)\)
FAT linked blocks with a table in memory simple, used on removable media table size grows with disk
Indexed (inode) inode holds an array of block pointers direct random access large files need indirect blocks
Extents inode records (start, length) runs compact, fast for large files fragmentation over time

ext4 uses extents: an inode stores a few extent descriptors (start block, length) and falls back to a tree for fragmented files. A 4 KB block and a 4 KB page means page-cache reads align with disk blocks.

Inode pointers: typically 12 direct blocks, one single-indirect, one double-indirect, one triple-indirect. With 4 KB blocks and 4-byte pointers, direct covers 48 KB, single-indirect covers 4 MB, double-indirect 4 GB, triple-indirect 4 TB.

\[ \text{max size} = 12 \times 4\text{KB} + 1024 \times 4\text{KB} + 1024^2 \times 4\text{KB} + 1024^3 \times 4\text{KB} \]

QQuestionWhy can a file not grow beyond the maximum represented by its indirect

pointers?

ASolution

Every data block must be reachable from the inode’s pointer tree. Once the tree’s capacity is exhausted, there is no way to address another block; filesystems with extents or larger pointers raise the limit.

Buffering and caching

The page cache holds file contents in memory. Reads hit the cache; writes go to the cache and are flushed later.

int fd = open("out.bin", O_WRONLY | O_CREAT, 0644);
write(fd, buf, n);
fsync(fd);        // now it is on stable storage
close(fd);

Without fsync, a crash can lose the write even though write returned success. That is not a bug; it is the cache doing its job.

O_DIRECT bypasses the page cache for the file’s data, which databases use to manage their own cache. It has strict alignment requirements and usually makes small I/O slower.

QQuestionwrite returned success, then the machine lost power, and the data is

gone. Why?

ASolution

The bytes were in the page cache, not on disk. write only promises that the kernel accepted them. Durability requires fsync (and a filesystem that honours it).

Synchronous versus asynchronous I/O

// synchronous
ssize_t n = read(fd, buf, size);

// POSIX AIO (simplified)
struct aiocb cb{};
cb.aio_fildes = fd;
cb.aio_buf = buf;
cb.aio_nbytes = size;
aio_read(&cb);
// ... do other work ...
while (aio_error(&cb) == EINPROGRESS) { }
ssize_t got = aio_return(&cb);

Linux’s modern interface is io_uring, which submits batches of operations and completes them through a shared ring, avoiding a syscall per operation. For most programs, a thread pool doing blocking I/O is simpler and fast enough.

QQuestionWhat problem does asynchronous I/O solve that a thread pool does not?
ASolution

It avoids one thread per outstanding operation. With 100,000 connections, threads cost gigabytes of stacks and context switches; async I/O keeps the state in the kernel and uses a few event threads.

Blocking versus non-blocking I/O

A blocking descriptor makes the call sleep until data is available. A non-blocking one returns EAGAIN immediately if it would block.

int fd = open("fifo", O_RDONLY | O_NONBLOCK);
ssize_t n = read(fd, buf, sizeof buf);
if (n < 0 && errno == EAGAIN) {
    // nothing available yet; come back later
}

Non-blocking alone means polling. The scalable pattern is readiness notification: select, poll, or epoll tell you which descriptors are ready, then you read.

// epoll sketch
int ep = epoll_create1(0);
epoll_event ev{};
ev.events = EPOLLIN;
ev.data.fd = fd;
epoll_ctl(ep, EPOLL_CTL_ADD, fd, &ev);

epoll_event events[64];
int n = epoll_wait(ep, events, 64, -1);   // -1: block until something is ready
for (int i = 0; i < n; ++i) {
    if (events[i].events & EPOLLIN) read(events[i].data.fd, buf, size);
}

epoll is \(O(\text{ready})\) per wait, while select is \(O(\text{max fd})\) and has a 1024-descriptor limit by default. That is why servers use epoll/kqueue/IOCP.

QQuestionWhy is read on a non-blocking socket returning EAGAIN not an error?
ASolution

It means “no data right now”. The call did nothing wrong; the program should wait for readiness and retry.

Memory-mapped I/O and files

mmap maps a file (or anonymous memory) into the address space, and accesses go through the page cache without a read/write copy.

int fd = open("data.bin", O_RDWR);
char* p = (char*)mmap(nullptr, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
p[0] = 'X';
msync(p, len, MS_SYNC);      // flush to disk
munmap(p, len);

MAP_SHARED writes are visible to other mappings and eventually to the file; MAP_PRIVATE gives copy-on-write and discards changes. A read-only mapping of an executable is how the loader maps code.

For random access over a large file, mmap avoids syscalls and buffer copies. For small sequential reads, read is simpler and often faster.

QQuestionDoes mmap avoid I/O?
ASolution

No. It avoids the copy between kernel and user buffers, but the first touch still faults a page in from disk (or the page cache). The I/O happens on demand.

Permissions and access control

Every file has an owner, a group, and permission bits for each:

-rwxr-xr--  1 alice dev  4096 Oct 24 12:00 run.sh

umask masks permissions at creation: open(..., 0666) with umask 022 creates 0644. chmod changes bits; chown changes owner. ACLs (setfacl) extend the model to specific users.

Special bits:

The kernel checks permissions on open, not on every read/write. Once the descriptor exists, the check is done.

QQuestionWhy does /tmp have the sticky bit?
ASolution

So any user can create files there, but only the file’s owner (or root) can delete them. Without it, one user could delete another’s temporary files.

Journaling

A crash in the middle of an update can leave the filesystem inconsistent: an inode points to a block that was never written, or a directory entry references a freed inode.

A journal (write-ahead log) records the intended changes before applying them. After a crash, the filesystem replays or discards the incomplete transaction, so it returns to a consistent state.

Mode What is journaled Cost Risk
data=journal data + metadata slowest smallest window
data=ordered (ext4 default) metadata, data written before commit moderate data may be lost, metadata consistent
data=writeback metadata only fastest stale data can appear after a crash

Journaling is not a backup. It guarantees consistency, not that your latest write survived; that still needs fsync and, ultimately, replication.

QQuestionDoes journaling make fsync unnecessary?
ASolution

No. The journal protects metadata consistency across a crash. fsync is what forces your specific data to stable storage before you return success to a user.

Bugs and edge cases

QQuestionA log writer reports success but the last lines are missing after a

crash. What is the fix?

ASolution

Call fsync on the file (or fdatasync) before acknowledging the write, and handle the error. Buffered write only reaches the page cache.

Next: Inter-Process Communication (OS Core #8) — pipes, shared memory, sockets, and signals.