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.

25 minfree previewLinux 6.12C11glibc 2.39→ module 3 lab
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 inode and type-safe CONTAINER_OF / offsetof math.
  • Inspect hard-link st_ino/st_nlink sharing via stat() and live f_pos/O_CLOEXEC flags 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.

ast_m03_l01_inode_table.svg — Static ext4 disk layout — directory entries map…

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 TierMemory / Media LocationCore State FieldsSharing & 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_inodeAllocated per open(); shared across dup()/fork()
3. VFS struct inode + Page CacheKernel inode + XArray folios (RAM)i_ino, i_size, i_nlink, i_rwsem, 4 KiB pagesSingle unified instance per active file
4. Static partition structuresNVMe / eMMC 4 KiB blocksSuperblock, inode table, dentry blocks, extentsPersistent across power cycles
fig_m03_l01_arch.svg — Dynamic Linux kernel VFS pointer chain (task_struct ->…

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_m03_l01.svg — Filenames map to inode numbers on disk, while open…step 1/4
  1. Step 1. Each process PCB (task_struct) owns a private files_struct slot array storing FD_CLOEXEC and a struct file pointer.
  2. Step 2. System-wide struct file tracks open status flags (f_flags), active byte cursor (f_pos), and reference count (f_count).
  3. 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.
  4. 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.

Verifying Shared st_ino, Orphan Inode Survival & fdinfo

Compile and execute vfs_fdinfo_probe: confirm path_a and path_b share one st_ino (hard_links=2), orphan_alive=1 proves st_nlink == 0 keeps data alive while fd stays open, /proc/self/fdinfo/<fd> reports pos: 128 and O_CLOEXEC, and strace logs the hard-link syscall.

learner@ksa: ~/gl-c01/m03-l01
learner@ksa:~/gl-c01/m03-l01gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror vfs_fdinfo_probe.c -o vfs_fdinfo_probelearner@ksa:~/gl-c01/m03-l01./vfs_fdinfo_probesame_inode=1 hard_links=2 st_size=128 orphan_alive=1fdinfo_pos=128 cloexec_in_flags=1 intrusive_ok=1learner@ksa:~/gl-c01/m03-l01strace -e trace=link,linkat ./vfs_fdinfo_probe 2>&1 | grep -c 'ksa_vfs_b.dat'1learner@ksa:~/gl-c01/m03-l01rm -f vfs_fdinfo_probelearner@ksa:~/gl-c01/m03-l01

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:

  1. Step 1 (Calculate offsetof(struct rx_ring, hook)): Compute the offset of drops (0..7), mask (8..11), and hook (which contains a 64-bit pointer next requiring 8-byte alignment, inserting 4 padding bytes [12..15] so offsetof == 16).
  2. Step 2 (Recover the enclosing address): Subtract 16 (0x10) from (char *)0x7ffc10004010 (0x7ffc10004000), and verify in a 10-line C test with offsetof(struct rx_ring, hook) and CONTAINER_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

quiz · 1 of 4

Where is a regular file's human-readable filename stored inside a POSIX filesystem such as ext4?

quiz · 2 of 4

(Review from earlier lesson) Which kernel structure stores the active byte offset f_pos returned by lseek(fd, 0, SEEK_CUR)?

quiz · 3 of 4

When two independent processes open /etc/hosts with O_RDONLY simultaneously, how many copies of /etc/hosts's 4 KiB data pages does the Linux kernel maintain in RAM?

quiz · 4 of 4

How does the Linux VFS implement zero-overhead polymorphism and generic intrusive list manipulation in ISO C across ext4, pipefs, procfs, and /dev drivers?

Key takeaways

  • Block storage groups 512-byte sectors into 4 KiB blocks organized into boot block, superblock, inode table (metadata + extents, never filenames), and directory/data blocks.
  • Directory entries map filenames to st_ino numbers (ls -i, stat()), allowing hard links (link()) to share one underlying inode (st_nlink >= 2).
  • Calling open() links three dynamic kernel RAM tiers: per-process files_struct (fd, FD_CLOEXEC) -> system-wide struct file (f_flags, f_pos, f_count, f_op) -> shared VFS struct inode + page cache.
  • VFS dispatches generic syscalls through struct file_operations vtables while subsystems recover enclosing types intrusively via offsetof (CONTAINER_OF) and unlink list nodes via struct node **pp.
  • /proc/self/fdinfo/<fd> exposes live kernel pos: and octal flags:, and physical blocks are reclaimed only when both st_nlink == 0 and f_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 why exit() and _exit() diverge on buffered output.
Progress is saved on this device.

search — fzf

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

keyboard shortcuts — less

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

figure