Disk Inodes & Kernel VFS Tables
Confusing directory filenames with on-disk inodes—or confusing per-process descriptors with kernel struct file descriptions—makes unlinked 10 GiB disk leaks, hard links, and shared cursors impossible to diagnose. You will map ext4 disk geometry into the three-tier VFS RAM hierarchy, trace CONTAINER_OF dispatch, and inspect /proc/self/fdinfo live.
What you'll learn
- Distinguish static disk structures (superblock, inode table, dentries, 4 KiB blocks) from dynamic VFS RAM tables.
- Trace
files_struct->struct file(f_pos,f_op) ->struct inodeand type-safeCONTAINER_OF/offsetofmath. - Inspect hard-link
st_ino/st_nlinksharing viastat()and livef_pos/O_CLOEXECflags in/proc/self/fdinfo.
Why rm Can Free Zero Disk Bytes & Inodes Never Store Filenames
Every production systems engineer eventually receives the midnight alert: /var/log is 99% full, an operator deletes a 10 GiB /var/log/telemetry.log file with rm, ls -la /var/log confirms the filename is gone, yet df -h still reports 99% disk usage and ENOSPC continues! Equally puzzling to newcomers, creating a hard link ln a.cfg b.cfg makes mutations through a.cfg appear instantly in b.cfg, and unlinking a.cfg leaves b.cfg intact—even though no bytes were copied.
Mental models that picture a "file" as a named blob attached directly to an integer fd break down completely on both scenarios. Solving storage leaks, cursor sharing, and polymorphic device I/O requires separating static on-disk partition structures from the three-tier dynamic Virtual File System (VFS) hierarchy constructed in kernel RAM whenever open() executes.
note: Think of a library card catalog versus an active reading-room checkout slip. Multiple catalog cards in different drawers can reference the exact same numbered shelf volume, while each reader at a table holds a personal bookmark slip tracking their current page in that volume.
Where it stops working: Unlike paper catalog cards, the Linux kernel caches active 4 KiB book pages inside shared RAM (the page cache) rather than fetching from disk on every read or write.
definition (Directory Entry (dentry), Inode, Three-Tier VFS & CONTAINER_OF): Index Node (inode) vs Directory Entry (dentry): Named by Dennis Ritchie for "index node", an on-disk inode stores numeric ownership (st_uid, st_gid), st_mode, st_size, st_blocks, hard-link count (st_nlink), and data-block extents—never the filename. Parent directory entries (dentries) map human strings ("sensor.log") to st_ino numbers. Three-Tier VFS Hierarchy: open() links per-process files_struct (fd, FD_CLOEXEC) -> system-wide struct file (f_pos, f_flags, f_count, f_op) -> shared VFS struct inode + 4 KiB RAM , while CONTAINER_OF(ptr, type, member) recovers enclosing driver structs from embedded VFS anchors via offsetof subtraction.
Figure 3.1a. Static ext4 disk layout — directory entries map filenames to inode numbers in the Inode Table, which index 4 KiB data blocks.
One Layer Down: Block Geometry, Reclamation Condition & CONTAINER_OF Math
On non-volatile storage, 512-byte hardware sectors are grouped into 4 KiB (4,096-byte) filesystem blocks partitioned across four static regions: boot block, superblock (filesystem geometry, free-inode and free-block bitmaps), inode table, and data blocks (storing both regular file payloads and directory (name, st_ino) records). Because unlink() only deletes one directory entry and decrements inode->i_nlink, the Linux kernel reclaims an inode and its physical 4 KiB extents if and only if both reference counters hit zero simultaneously: reclaim_blocks(inode) <==> (inode->i_nlink == 0) && (sum(file->f_count) == 0). Until the logging daemon closes its open struct file (f_count -> 0), all 10 GiB of unlinked blocks remain allocated!
How does pure ISO C inside the Linux kernel dispatch a single read(fd, buf, len) syscall across ext4 extents, pipefs ring buffers, /proc virtual files, and /dev character drivers with zero heap wrapper overhead? Every struct file carries a const struct file_operations *f_op function-pointer table (.read, .write, .llseek, .unlocked_ioctl). Subsystems embed generic anchor structs intrusively inside domain structs at compile-time byte offset delta = offsetof(type, member), recovering the outer object via byte-pointer subtraction CONTAINER_OF(p, T, m) = (T *)((char *)p - offsetof(T, m)). Paired with indirect-pointer list traversal (struct vfs_hook **pp = &head;), intrusive C containers achieve zero-allocation polymorphism and branchless node unlinking without special-casing prev == NULL.
| Storage / Kernel Tier | Memory / Media Location | Core State Fields | Sharing & Lifetime Scope |
|---|---|---|---|
1. Process FD table (files_struct) | task_struct->files (RAM) | fd integer, FD_CLOEXEC, struct file * | Private per process (clone without CLONE_FILES) |
2. Open file (struct file) | Kernel filp slab cache (RAM) | f_flags, f_pos, f_count, f_op, f_inode | Allocated per open(); shared across dup()/fork() |
3. VFS struct inode + Page Cache | Kernel inode + XArray folios (RAM) | i_ino, i_size, i_nlink, i_rwsem, 4 KiB pages | Single unified instance per active file |
| 4. Static partition structures | NVMe / eMMC 4 KiB blocks | Superblock, inode table, dentry blocks, extents | Persistent across power cycles |
Figure 3.1b. Dynamic Linux kernel VFS pointer chain (task_struct -> fdtable -> struct file -> inode -> address_space), orphan block survival, and CONTAINER_OF recovery.
- Step 1. Each process PCB (task_struct) owns a private files_struct slot array storing FD_CLOEXEC and a struct file pointer.
- Step 2. System-wide struct file tracks open status flags (f_flags), active byte cursor (f_pos), and reference count (f_count).
- Step 3. All open struct file instances for the same file point to one VFS struct inode and one shared 4 KiB RAM page cache.
- Step 4. Physical disk blocks are reclaimed only when both st_nlink == 0 (unlinked) and f_count == 0 (all FDs closed).
Figure 3.1c. Filenames map to inode numbers on disk, while open descriptors index through private FD slots into struct file cursors and one shared VFS inode page cache.
Observing Live VFS State with stat(), link() & /proc/self/fdinfo
Include <sys/stat.h>, <fcntl.h>, <stddef.h>, and <unistd.h> under #define _POSIX_C_SOURCE 200809L. Call stat(path, &st) or fstat(fd, &st) to inspect st_ino, st_nlink, st_mode, st_size, and st_blocks; call link(oldpath, newpath) to attach a second directory entry to the same st_ino (st_nlink++); and read /proc/self/fdinfo/<fd> to inspect the live kernel pos: (struct file.f_pos) and octal flags: (including O_CLOEXEC = 02000000 on x86-64/ARM).
Probing Hard Links, Orphaned Open Inodes, CONTAINER_OF & fdinfo
Save vfs_fdinfo_probe.c below. It verifies type-checked CONTAINER_OF(&c2.hook, struct dev_chan, hook) recovery and branchless indirect-pointer list removal (unlink_hook_branchless), links path_b to path_a (st_nlink == 2, identical st_ino), inspects /proc/self/fdinfo/<fd> (pos: 128, O_CLOEXEC set), and then unlinks both filenames while fd remains open—proving fstat(fd, &st_unlinked) reports st_nlink == 0 while all 128 payload bytes remain readable from the live VFS inode until close(fd)!
learner@ksa:~/gl-c01/m03-l01$ bat -H 13 -H 28 -H 74 -H 89 vfs_fdinfo_probe.c File: vfs_fdinfo_probe.c #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <fcntl.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #define CONTAINER_OF(ptr, type, member) \ ((type *)((char *)(1 ? (ptr) : &((type *)0)->member) - \ offsetof(type, member))) struct vfs_hook { struct vfs_hook *next; int tag; }; struct dev_chan { uint32_t id; struct vfs_hook hook; }; static void unlink_hook_branchless(struct vfs_hook **head, const struct vfs_hook *target) { struct vfs_hook **pp = head; while (*pp != NULL && *pp != target) { pp = &(*pp)->next; } if (*pp != NULL) { *pp = target->next; } } int main(void) { struct dev_chan c1 = {101U, {NULL, 1}}; struct dev_chan c2 = {202U, {NULL, 2}}; c1.hook.next = &c2.hook; struct vfs_hook *head = &c1.hook; struct dev_chan *rec = CONTAINER_OF(&c2.hook, struct dev_chan, hook); unlink_hook_branchless(&head, &c1.hook); int intrusive_ok = (rec->id == 202U && head == &c2.hook); const char *path_a = "/tmp/ksa_vfs_a.dat"; const char *path_b = "/tmp/ksa_vfs_b.dat"; (void)unlink(path_a); (void)unlink(path_b); int fd = open(path_a, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (fd == -1) return EXIT_FAILURE; if (link(path_a, path_b) == -1) { (void)close(fd); (void)unlink(path_a); return EXIT_FAILURE; } uint8_t payload[128]; memset(payload, 0x42U, sizeof(payload)); if (write(fd, payload, sizeof(payload)) != (ssize_t)sizeof(payload)) { return EXIT_FAILURE; } struct stat sta, stb, stf, st_orphan; if (stat(path_a, &sta) == -1 || stat(path_b, &stb) == -1 || fstat(fd, &stf) == -1) { return EXIT_FAILURE; } char fdinfo_path[64]; snprintf(fdinfo_path, sizeof(fdinfo_path), "/proc/self/fdinfo/%d", fd); int info_fd = open(fdinfo_path, O_RDONLY | O_CLOEXEC); long long kernel_pos = -1; unsigned long kernel_flags = 0UL; if (info_fd != -1) { char info_buf[512]; ssize_t n = read(info_fd, info_buf, sizeof(info_buf) - 1U); if (n > 0) { info_buf[n] = '\0'; const char *p_pos = strstr(info_buf, "pos:"); const char *p_flg = strstr(info_buf, "flags:"); if (p_pos != NULL) kernel_pos = strtoll(p_pos + 4, NULL, 10); if (p_flg != NULL) kernel_flags = strtoul(p_flg + 6, NULL, 8); } (void)close(info_fd); } (void)unlink(path_a); (void)unlink(path_b); uint8_t check_byte = 0U; int orphan_alive = (fstat(fd, &st_orphan) == 0 && st_orphan.st_nlink == 0U && lseek(fd, 0, SEEK_SET) == 0 && read(fd, &check_byte, 1U) == 1 && check_byte == 0x42U); (void)close(fd); int same_ino = (sta.st_ino == stb.st_ino && sta.st_ino == stf.st_ino && sta.st_ino > 0U); int cloexec_bit = ((kernel_flags & (unsigned long)O_CLOEXEC) != 0UL); printf("same_inode=%d hard_links=%lu st_size=%lld orphan_alive=%d\n", same_ino, (unsigned long)sta.st_nlink, (long long)sta.st_size, orphan_alive); printf("fdinfo_pos=%lld cloexec_in_flags=%d intrusive_ok=%d\n", kernel_pos, cloexec_bit, intrusive_ok); return EXIT_SUCCESS; }- Ternary type-check (1 ? (ptr) : &((type *)0)->member) triggers a compile error if ptr does not match member's exact type.
- Indirect pointer struct vfs_hook **pp updates head or prev->next uniformly without an if (prev == NULL) branch.
- Reading /proc/self/fdinfo/<fd> queries live kernel struct file.f_pos and octal flags directly from procfs.
Why Page-Cache & Reference-Counted Inodes Outlive Directory Names
Notice how orphan_alive=1 demystified the 10 GiB unlinked-log incident in twenty lines of C! Unlinking path_a and path_b dropped st_orphan.st_nlink to 0 and removed both directory entries from /tmp, yet because fd still held struct file.f_count == 1, the VFS struct inode and its 4 KiB page-cache folio stayed alive in RAM (check_byte == 0x42) until close(fd) dropped f_count to 0 and freed the blocks!
Guided Practice: Tracing CONTAINER_OF Byte Arithmetic by Hand
Given struct rx_ring { uint64_t drops; uint32_t mask; struct vfs_hook hook; }; on 64-bit Linux where &r.hook is at virtual address 0x7ffc10004010:
- Step 1 (Calculate
offsetof(struct rx_ring, hook)): Compute the offset ofdrops(0..7),mask(8..11), andhook(which contains a64-bit pointernextrequiring8-byte alignment, inserting4padding bytes[12..15]sooffsetof == 16). - Step 2 (Recover the enclosing address): Subtract
16(0x10) from(char *)0x7ffc10004010(0x7ffc10004000), and verify in a 10-line C test withoffsetof(struct rx_ring, hook)andCONTAINER_OF.
Independent Practice: Live Process Open-File & Orphan Inspector
Write a C11 tool self_fd_audit.c that opens two regular files (unlinking one while keeping its descriptor open), iterates integers fd = 0..15, calls fstat(fd, &st) (errno == EBADF skips unused slots), reads /proc/self/fdinfo/<fd> for every open slot, and prints a formatted table of fd, st_ino, st_nlink (highlighting st_nlink == 0 unlinked open files!), pos, and O_CLOEXEC.
Common Production Pitfalls
warning: Symptom: Removing a runaway /var/log/app.log file with rm clears the directory listing, yet df -h shows 0 freed gigabytes and new writes fail with ENOSPC. Root Cause: The running process still holds an open struct file (f_count > 0) referencing the unlinked inode (st_nlink == 0), blocking block reclamation until close(). Fix: Signal the service (SIGHUP / SIGUSR1) to close and reopen its log descriptor, or truncate the active file in place (truncate -s 0 / O_TRUNC).
warning: Symptom: Decommissioning an embedded flash partition after unlink() or a quick mkfs allows forensic sector reads to recover plaintext keys. Root Cause: Quick-formatting resets only the superblock and inode/block bitmaps, and unlink() clears directory entries and inode metadata without overwriting physical 4 KiB data blocks. Fix: Overwrite sensitive payloads explicitly (fdatasync before unlink) or issue block-device secure erase (BLKSECDISCARD).
Knowledge Check
Key takeaways
- Block storage groups
512-byte sectors into4 KiBblocks organized into boot block, superblock, inode table (metadata + extents, never filenames), and directory/data blocks. - Directory entries map filenames to
st_inonumbers (ls -i,stat()), allowing hard links (link()) to share one underlying inode (st_nlink >= 2). - Calling
open()links three dynamic kernel RAM tiers: per-processfiles_struct(fd,FD_CLOEXEC) -> system-widestruct file(f_flags,f_pos,f_count,f_op) -> shared VFSstruct inode+ page cache. - VFS dispatches generic syscalls through
struct file_operationsvtables while subsystems recover enclosing types intrusively viaoffsetof(CONTAINER_OF) and unlink list nodes viastruct node **pp. /proc/self/fdinfo/<fd>exposes live kernelpos:and octalflags:, and physical blocks are reclaimed only when bothst_nlink == 0andf_count == 0.- Next, we trace how VFS failures propagate back to user space via thread-local
errno, how multi-resource functions unwind cleanly in reverse (LIFO) order, and whyexit()and_exit()diverge on buffered output.