File System Abstraction

Understanding how operating systems organize and manage files through abstraction layers, from physical storage to logical file operations.

published: reading time: 32 min read author: Geek Workbench
Quick Summary

File system abstraction lets programs work with paths while Linux resolves directories and inodes, caches data, and handles device I/O. This guide follows a read through Linux 6.12's VFS and ext4, then covers ext4 journaling, Btrfs copy-on-write, network mounts, and FUSE. It also covers inode exhaustion, fragmentation, permissions, and storage troubleshooting.

File System Abstraction

Introduction

Run cat /var/log/app.log, and the file looks like a path with bytes to read. The kernel still has to resolve each path component, check permissions, find the file’s metadata, and route the read through the mounted file system and storage stack.

This is a Unix/Linux-focused walkthrough. Its concrete trace follows the Linux 6.12 VFS with ext4 as the local filesystem example. Other kernels and filesystems organize metadata, caching, and recovery differently. The guide also covers inodes, directories, and failures that can make storage appear full or slow.

When to Use / When Not to Use

Understanding file system abstraction helps you make informed decisions about data storage and performance optimization.

When file system abstraction shines:

  • Application development where persistence and portability matter
  • Database design that relies on durability guarantees
  • Backup systems that need to understand what’s stored where
  • Debugging storage-related issues in production

When to look deeper:

  • Embedded systems with custom storage controllers
  • Performance-critical applications where every I/O matters
  • Distributed systems where consistency guarantees get murky
  • When the abstraction leaks and you need to understand why

Architecture or Flow Diagram

graph TD
    A[Application System Calls] --> B[VFS Layer]
    B --> C[Specific File System ext4, NTFS, FAT]
    C --> D[Block Layer]
    D --> E[Storage Device Driver]
    E --> F[Physical Storage Device]

    G[Inode Cache] -.-> B
    H[Directory Entry Cache] -.-> B
    I[Page Cache] -.-> B

Applications speak to the kernel through system calls. The Linux VFS provides a common interface for mounted filesystems. Each filesystem handles its own format, while the block layer and device driver handle requests to storage hardware.

A syscall trace: Linux 6.12 with ext4

For cat /var/log/app.log, a simplified trace is openat(AT_FDCWD, "/var/log/app.log", O_RDONLY) → read(fd, buffer, size) → close(fd). During openat, the VFS resolves path components through the dentry cache. On a cache miss, it asks the mounted filesystem, ext4 here, to look up the component. A successful open returns a file descriptor. During read, a page-cache hit can supply the requested data from memory without a device read. On a miss, ext4 may request data through the block layer. Cache state determines whether that read needs device I/O. See the Linux VFS documentation, openat(2), and read(2).

Core Concepts

Files: The Logical Unit

A file is an abstract container for data, defined by a set of attributes rather than physical properties. The file system maintains:

  • Name: Human-readable identifier with case-sensitive or insensitive rules
  • Metadata: Size, creation time, modification time, permissions, ownership
  • Data blocks: Actual storage locations for content
  • Location references: Pointers to where data lives on disk

Files are named sequences of bytes. The operating system doesn’t care what’s inside. A text document and a compiled binary are both just sequences of bytes to the file system layer.

Inodes: The Metadata Engine

In the Linux VFS, an inode represents a filesystem object and carries its metadata. On ext4, the inode number identifies that object within the filesystem. A name does not have its own inode: hard links let multiple directory entries refer to the same inode.

struct inode {
    unsigned long i_ino;          // Inode number
    umode_t         i_mode;       // File type and permissions
    unsigned int    i_nlink;      // Link count (hard links)
    uid_t           i_uid;       // Owner UID
    gid_t           i_gid;       // Owner GID
    loff_t          i_size;      // Size in bytes
    struct timespec i_atime;      // Access time
    struct timespec i_mtime;      // Modification time
    struct timespec i_ctime;      // Change time
    unsigned long   i_blocks;    // Blocks allocated (512-byte blocks)
    unsigned short  i_bytes;     // Bytes per block
    struct super_block *i_sb;     // Super block reference
    struct inode_operations *i_op;// Operations table
};

The inode doesn’t contain the actual file name. In ext4, directory entries map names to inode numbers, and multiple entries can refer to the same inode as hard links. Other filesystems may represent names and metadata differently; see the ext4 directory documentation.

Inode Internals

Inodes are stored in an inode table on disk, with each file system block group maintaining its own inode table region. The inode table size is fixed at file system creation time—you cannot expand it later without reformatting. This is why inode exhaustion can occur even when disk space remains available.

Inode generation numbers track whether an inode number has been reused. NFSv4 uses generation numbers to detect stale handles—when a client holds a file handle and the server reuses that inode number, the generation number will have changed, signaling the client to request a new handle.

File locks are implemented through the inode’s flock list. When a process calls flock() on a file, the kernel attaches a lock structure to the inode. Unlike fcntl() locks (which are stored in the inode’s fl_flock field), flock() locks are bound to the inode itself, meaning all file descriptors pointing to the same inode share the same lock state.

Directories: Name-to-Inode Mappings

A directory is itself a special file. In the ext4 example, it maps names to inode numbers. Early Unix directories were represented as files containing records:

struct direct {
    unsigned long d_ino;    // Inode number
    unsigned short d_reclen;// Record length
    unsigned char d_type;   // File type (directory, regular, etc.)
    char d_name[];          // File name (variable length)
};

Filesystem directory formats vary. In ext4, directory entries associate names with inode numbers; hard links allow more than one entry to refer to the same inode.

Hierarchical Organization

The directory tree creates the familiar path structure:

graph TD
    A["/ (root)"] --> B["/home"]
    A --> C["/etc"]
    A --> D["/var"]
    B --> E["/home/user"]
    E --> F["/home/user/documents"]
    F --> G["report.pdf"]

    style A stroke:#ff00ff,stroke-width:3px
    style G stroke:#ff00ff,stroke-width:2px

As the VFS resolves a path, each component is looked up in its parent directory. The resolved path reaches an inode-backed object; multiple paths can reach the same inode, as with hard links.

The Superblock: File System Metadata

The superblock stores metadata the filesystem needs to mount and manage a volume. Its layout and location vary by filesystem. In ext4, the primary superblock starts at byte offset 1024; backup copies are stored in selected block groups. The details below describe ext4. See the ext4 layout documentation.

The superblock contains:

  • Magic number: ext2/3/4 use 0xEF53 to identify the filesystem.
  • Block size and total block count: Defines the fundamental allocation unit (usually 4096 bytes on modern systems) and the total storage capacity. This determines how many blocks the file system can manage.
  • Inode count and free inode count: The file system pre-allocates space for a fixed number of inodes when you format. This is why you can run out of inodes before disk fills—common with millions of tiny files in /tmp.
  • Free block count: Tracks available storage. The kernel consults this during allocation to find free extents.
  • Block group descriptor location: Points to the data structures that track which blocks and inodes belong to each group.
  • Mount and write state: Filesystem tools use these fields when deciding whether to check or repair a volume.
  • Journal details: These are filesystem-specific. Ext4 typically stores its journal as a hidden file (often inode 8); other filesystems use different logging or recovery designs.

Ext2/3/4 can store backup superblocks in selected block groups. If the primary copy is damaged, recovery tools may be able to use a backup:

# Check primary superblock
sudo dumpe2fs /dev/sda1 | grep -i superblock

# Mount using an alternate superblock number found with dumpe2fs
sudo mount -o superblock=32768 /dev/sda1 /mnt

XFS and Btrfs use their own superblock layouts and recovery procedures.

Btrfs and Copy-on-Write

Btrfs is one example of a copy-on-write filesystem. It uses COW for metadata and, by default, file data; files marked NOCOW can use in-place updates. When a COW extent is modified, Btrfs writes a new version and updates metadata, leaving the old extent available while snapshots or other references need it. See the Btrfs administration documentation.

Snapshots initially share extents, so creating one does not immediately duplicate all file data. Btrfs checksums data and metadata; when checksums and redundant copies are available, a read error may allow it to use a good copy and repair the damaged one.

These trade-offs depend on workload and configuration. COW can increase write amplification and fragmentation for some workloads. SSD wear leveling is handled by the device controller, though extra writes can still affect drive endurance.

FUSE: Filesystem in Userspace

On Linux, FUSE lets a userspace process provide filesystem data and metadata through the kernel interface, using /dev/fuse. Non-privileged mounts are supported when system policy and mount configuration allow them.

The architecture works like this: a user-space program registers with the FUSE kernel module. When VFS receives operations on the mount point, it passes them to the FUSE kernel module, which forwards them to the registered user-space program. The program performs the operation (reading from network, decrypting, aggregating) and returns the result through FUSE back to VFS.

Common FUSE implementations include:

  • sshfs: Mount remote SSH servers as local directories
  • gocryptfs: Encrypted file system without kernel modules
  • mergerfs: Pool multiple drives into one logical volume
  • ntfs-3g: FUSE-based NTFS driver for Linux

FUSE can add communication and context-switch overhead. Performance depends on the implementation, caching, and workload. Non-privileged mounting depends on system policy; see the Linux FUSE documentation.

Network File Systems

Network filesystems extend a local directory hierarchy across machines. NFS and SMB have different cache and lock models. NFSv4 tracks client opens and locks; its server may grant delegations that let a client cache data until recall. CIFS/SMB uses leases or oplocks for client caching under supported dialects. Exact behavior depends on protocol, client and server versions, and mount options. A remote share can therefore show different latency and data visibility from a local ext4 mount. See the Linux nfs(5) manual page and CIFS VFS documentation for client details.

Production Failure Scenarios

Scenario 1: Inode Exhaustion

What happened: A web server’s /tmp directory accumulated millions of small session files. The disk showed 40% free space, but the system couldn’t create new files. The issue: inode exhaustion. The partition had 100 million inodes, and 99 million were allocated to tiny files.

Detection:

df -i /tmp
# Filesystem  Inodes  IUsed  IFree  IUse%  Mounted on
# /dev/sda1   100M    99M    1M     99%     /tmp

Mitigation:

  • Monitor inode usage in production: df -i
  • Set up alerts when inode usage exceeds 80%
  • Implement file expiration policies for temporary directories
  • Consider partitioning strategies that balance inode allocation

Scenario 2: Orphaned Inodes

What happened: A database application crashed mid-transaction, leaving behind an inode that referenced blocks on disk but no directory entry pointed to it. The storage was allocated but inaccessible. This is a “lost” file eating disk space silently.

Detection:

# Use fsck in no-write mode to find orphans
sudo fsck -n /dev/sda1

# Or in debug mode
sudo debugfs -w /dev/sda1
debugfs: dump_unreachable

Mitigation:

  • Always properly unmount file systems before maintenance
  • Choose a filesystem and recovery process whose crash guarantees fit the workload; journaling can reduce metadata inconsistency but does not prevent every orphan or data loss
  • Run periodic integrity checks: xfs_repair for XFS, e2fsck for ext4
  • Take advantage of file system features like tune2fs -l to check state

Scenario 3: Fragmentation-Induced Performance Death

What happened: A heavily-used file server showed acceptable space metrics but catastrophic performance. Reads that should take milliseconds stretched to seconds. The culprit: external fragmentation. File data was scattered across thousands of non-contiguous blocks.

Detection:

# Check fragmentation on ext4
sudo fsck.ext4 -nv /dev/sda1

# Check fragmentation percentage
sudo tune2fs -l /dev/sda1 | grep -i frag

Mitigation:

  • Monitor fragmentation levels with vendor tools
  • Defragment proactively with e4defrag (ext4) or xfs_fsr (XFS)
  • Choose allocation strategies that minimize fragmentation (extents over blocks)
  • Plan capacity with headroom to prevent fragmentation-inducing fullness

Trade-off Table

Aspect ext4 XFS Btrfs NTFS
Max File Size 16TB 8EB 16EB 256TB
Max Volume Size 1EB 16EB 16EB 256TB
Journaling Metadata only Metadata only Copy-on-write Metadata only
Snapshots Via LVM Via LVM Native Via VSS
Performance General purpose Large files Mixed Windows optimal
Fragmentation Moderate Low Low (COW) Moderate

Treat the table as a rough comparison. Capacity limits and behavior depend on filesystem version, features, configuration, and the operating system or driver.

Implementation Snippet

Reading File Metadata in C

#include <stdio.h>
#include <sys/stat.h>
#include <time.h>

void print_file_info(const char *path) {
    struct stat st;

    if (stat(path, &st) == -1) {
        perror("stat");
        return;
    }

    printf("File: %s\n", path);
    printf("Size: %lld bytes\n", (long long) st.st_size);
    printf("Blocks: %lld\n", (long long) st.st_blocks);
    printf("IO Block: %ld bytes\n", st.st_blksize);
    printf("Inode: %lu\n", st.st_ino);
    printf("Links: %hu\n", st.st_nlink);
    printf("Permissions: %o\n", st.st_mode & 0777);

    // Timestamps
    printf("Access: %s", ctime(&st.st_atime));
    printf("Modify: %s", ctime(&st.st_mtime));
    printf("Change: %s", ctime(&st.st_ctime));
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <file>\n", argv[0]);
        return 1;
    }
    print_file_info(argv[1]);
    return 0;
}

Exploring Inodes with Python

import os
import stat

def explore_inode(filepath):
    """Explore file system inode information."""
    st = os.stat(filepath)

    print(f"Path: {filepath}")
    print(f"Inode: {st.st_ino}")
    print(f"Device: {st.st_dev}")
    print(f"Hard links: {st.st_nlink}")
    print(f"Size: {st.st_size} bytes")
    print(f"Blocks (512b): {st.st_blocks}")
    print(f"Block size: {st.st_blksize}")

    mode = st.st_mode
    print(f"\nPermissions: {oct(stat.S_IMODE(mode))}")
    print(f"Type: ", end="")

    if stat.S_ISDIR(mode):
        print("Directory")
    elif stat.S_ISREG(mode):
        print("Regular File")
    elif stat.S_ISLNK(mode):
        print("Symbolic Link")
    else:
        print("Other")

    # Access timestamps
    print(f"\nAccessed: {stat.getmtime(filepath)}")
    print(f"Modified: {stat.getctime(filepath)}")

if __name__ == "__main__":
    import sys
    explore_inode(sys.argv[1] if len(sys.argv) > 1 else ".")

Observability Checklist

Monitor these metrics to keep your file systems healthy:

  • df -h: Check available space across all mounted file systems
  • df -i: Monitor inode usage to prevent inode exhaustion
  • mount | grep -v tmpfs: List persistent mounts with their options
  • tune2fs -l /dev/sdX | grep -i state: Check file system clean/dirty state
  • dmesg | grep -i error | grep -i ext4: Scan kernel logs for file system errors

Key metrics to track:

  • Available space percentage (alert at >85% for critical partitions)
  • Inode usage percentage (alert at >80%)
  • I/O wait time (CPU waiting on storage operations)
  • Read/write throughput per partition
  • Error counts from smartctl output

Logs to watch:

# Check for file system errors
sudo journalctl -b | grep -i "ext4\|xfs\|filesystem"

# Monitor inotify watch consumption
cat /proc/sys/fs/inotify/max_user_watches

# Check for file handle leaks
lsof | wc -l

Common Pitfalls / Anti-Patterns

Permission and Access Control Pitfalls

Unix file permissions are a common source of issues. Understanding the three classes (owner, group, other) and three permission types (read, write, execute) is essential:

# View permissions
ls -la /path/to/file
# -rw-r--r--  1 owner group  1234 May 19 10:00 file.txt

# Modify permissions
chmod 640 /path/to/file      # Owner: rw, Group: r, Other: none
chmod u+x /path/to/file      # Add execute for owner
chmod -R 755 /path/to/dir    # Recursive

Beyond traditional permissions, ACLs provide fine-grained control:

# Set ACL for specific user
setfacl -m u:alice:rw /path/to/file

# Set ACL for specific group
setfacl -m g:developers:rx /path/to/directory

# View ACLs
getfacl /path/to/file

# Remove specific ACL entry
setfacl -x u:alice /path/to/file

Extended attributes (xattr) store metadata beyond standard file attributes. They’re used for SELinux labels (security.selinux), capabilities (security.capability), and custom application data (user.*):

# Set extended attribute
setfattr -n user.comment -v "Release version 2" /path/to/file

# Get extended attribute
getfattr /path/to/file

# Remove extended attribute
setfattr -x user.comment /path/to/file

Security-relevant permission features often get overlooked:

  1. Sticky bit on shared directories: Prevents users from deleting others’ files in /tmp-like directories

    chmod +t /shared/directory
  2. Immutable files: Even root cannot modify immutable files without removing the flag

    chattr +i /important/file
    lsattr /important/file
    # ---i---------- /important/file
  3. Audit file access: Enable audit daemon to track who accesses what

    sudo auditctl -w /etc/shadow -p wa -k shadow_access
    sudo ausearch -k shadow_access

Storage and Path Handling Pitfalls

Assuming unlimited storage space is a common mistake in production systems:

# BAD: Writing without checking space
with open("/tmp/large_file", "w") as f:
    while True:
        f.write("data" * 1000)  # Will fail eventually

# GOOD: Check before writing
import shutil

def safe_write(path, data):
    stat = shutil.disk_usage("/tmp")
    if stat.free < len(data):
        raise IOError(f"Insufficient space. Need {len(data)}, have {stat.free}")
    with open(path, "w") as f:
        f.write(data)

Path length limits catch many developers off guard. Early file systems had 255-byte path components, and mixing older code with modern systems can cause silent truncation and security issues.

Cross-Platform Compatibility Pitfalls

Case sensitivity behaves differently across file systems:

# On case-insensitive file system (Windows, macOS default)
touch MyFile.txt
ls myfile.txt  # Shows MyFile.txt

# On case-sensitive file system (Linux, some network mounts)
touch MyFile.txt
ls myfile.txt  # No such file or directory

Confusing hard links with symbolic links leads to data loss or broken references:

# Hard link - same inode, must be on same filesystem
ln /existing/file /path/to/hardlink
ls -li /existing/file /path/to/hardlink  # Same inode number

# Symbolic link - separate file pointing to path
ln -s /existing/file /path/to/symlink
ls -li /existing/file /path/to/symlink  # Different inodes

Security and Compliance Notes

  • Give the application service account only the directory and file permissions it needs. Avoid broad recursive permissions such as chmod -R 777.
  • Treat user-supplied paths as untrusted. A path can escape an allowed directory with .. or a symlink; resolve and open files relative to a trusted directory, and prevent symlink following where the platform supports it. Checking a path and opening it later can also create a race if an attacker changes a symlink between those steps.
  • Create temporary files with exclusive, unpredictable-name APIs such as mkstemp, inside a private directory with restrictive permissions. Remove them when finished, including after errors.
  • Keep sensitive files out of shared temporary locations, restrict access to their directories, and apply the service’s encryption, retention, and deletion rules to stored files and backups.

Quick Recap Checklist

  • File systems provide abstraction over raw storage devices
  • Inodes store metadata; directories map names to inode numbers
  • Hard links share inodes; symbolic links store paths
  • Journaling can help restore filesystem metadata after a crash; the guarantees vary by filesystem and configuration
  • Monitor inode and space usage to prevent production surprises
  • Permissions (rwx) apply to owner/group/others
  • ACLs provide finer-grained access control
  • Different file systems have different strengths and limits

Interview Questions

1. What is an inode and what information does it contain?

An inode (index node) is a data structure that stores metadata about a file in Unix-style file systems. It contains:

  • The file's size and block count
  • Owner UID and group GID
  • File permissions (mode)
  • Timestamps: access, modification, and change time
  • Link count (number of hard links pointing to this inode)
  • Pointers to the actual data blocks on disk

The inode does not store the file name—that lives in directory entries.

2. Explain the difference between hard links and symbolic links.

Hard links are multiple directory entries pointing to the same inode. They must be on the same file system and cannot link to directories. When you delete one hard link, the file persists until all hard links are removed. The inode's link count tracks this.

Symbolic links are special files that store a path (not an inode number). They can cross file systems and point to directories. Deleting the target breaks the symlink. They occupy a small inode for the link itself plus space for the path string.

Use hard links for equal-weight file names within a filesystem. Use symlinks when you need flexibility or cross-filesystem references.

3. What happens when you run `ls -la`? Walk through the kernel layers involved.

When you execute ls -la, the journey through the kernel looks like:

  1. Shell parses the command and calls fork() to create a child process
  2. execve() system call replaces the child with the /bin/ls program
  3. ls calls getdents64() or readdir() system call
  4. Kernel transfers control to the VFS layer, which identifies the mounted file system type
  5. File system driver (e.g., ext4) reads directory entries from disk or cache
  6. Page cache may serve frequently-accessed directory data
  7. Results flow back up through VFS to the application

The application never touches the disk directly—it only knows about the VFS interface.

4. How would you diagnose a "disk full" error when `df` shows space is available?

This classic problem usually means one of two things is exhausted: inodes or file handles.

First, check inode usage: df -i. If the IUse% is near 100%, the partition has run out of inodes (common with millions of tiny files in /tmp).

If inodes are fine, check file handle limits:

  • lsof | wc -l — current open file count
  • cat /proc/sys/fs/file-max — system-wide limit
  • ulimit -n — per-process limit

Also check for deleted files still held open by processes: lsof +L1 shows files deleted but not yet freed.

5. Describe what happens during a file open operation in the kernel.

For a Linux local file such as one on ext4, the open() system call triggers a multi-step process:

  1. Path resolution: Starting from the root directory (or current working directory for relative paths), each path component is looked up in its parent directory
  2. VFS lookup: A dcache hit may resolve a component; on a miss, VFS calls the mounted filesystem's lookup function
  3. Permission checking: The kernel verifies the process has execute permission on each directory component and read/write on the file itself
  4. Inode retrieval: If the file exists, VFS gets its inode, loading it into memory if needed
  5. Open file table entry: A new entry is created in the process's file descriptor table, pointing to a global open file table entry
  6. File structure allocation: Memory is allocated for the file structure, including current position and access mode

On success, a file descriptor (small integer) is returned. Subsequent read(), write(), and close() calls use this descriptor.

6. What is the superblock and what critical information does it contain?

The superblock stores metadata the filesystem needs to mount and manage its volume. Its location and contents depend on the filesystem. In ext4, it contains:

  • File system magic number: Identifies the file system type (0xEF53 for ext2/3/4)
  • Block size and total blocks: Fundamental geometry of the storage
  • Inode count and free inode count: Total and available inodes
  • Block count and free block count: Storage capacity information
  • Last mount time and last write time: File system usage timestamps
  • Journal information: Ext4's journal is usually an internal hidden file; other filesystems arrange logging differently
  • Block group descriptors: Locations of block and inode bitmaps

Ext2/3/4 can store backup superblocks. If the primary copy is damaged, recovery tools may be able to use a backup.

7. How does the page cache improve file system performance?

For ordinary buffered reads on Linux, the page cache keeps file data in memory. If the requested data is already cached, the kernel can return it without reading that data from the storage device. On a cache miss, the filesystem may request data from storage and cache it for later reads. See the Linux page cache documentation; O_DIRECT can bypass this cache.

Benefits:

  • Read amplification reduction: Frequently read data doesn't require repeated disk reads
  • Write coalescing: Multiple writes to the same region are combined before disk I/O
  • Access time elimination: RAM access is nanoseconds; disk I/O is milliseconds
  • Writeback batching: Delayed writes allow the kernel to batch and optimize I/O patterns

The page cache uses system memory that can also be reclaimed for other purposes. Linux's reclaim policy is more involved than a strict least-recently-used list.

8. What is the difference between direct I/O and buffered I/O?

Buffered I/O on Linux normally uses the page cache. Writes dirty cached pages that the kernel later writes back; reads can be served from cache or cause a read on a miss.

Direct I/O: Applications can request this with O_DIRECT to bypass the page cache. Alignment and behavior requirements vary by filesystem and device; the kernel still handles the I/O request. See open(2).

When to use direct I/O:

  • Database systems that manage their own cache (PostgreSQL, Oracle)
  • Applications doing sequential scans that don't benefit from caching
  • When you need predictable I/O patterns without kernel interference

Direct I/O is not a durability guarantee and does not necessarily bypass every lower-level cache.

9. What are the fundamental POSIX file operations and how does the kernel handle them?

POSIX defines the standard file operations: open(), close(), read(), write(), lseek(), stat(), rename(), unlink().

The kernel handles these through the VFS layer:

  1. open(): Returns a file descriptor after VFS path resolution. A dcache hit may satisfy a component lookup; a miss may call the mounted filesystem's lookup operation.
  2. read(fd, buf, n): Kernel looks up the fd in the process's file descriptor table, finds the file struct, calls the file's file_operations->read() which chains to the underlying file system driver.
  3. write(): Same path but calls file_operations->write(). Data may go through the page cache and be dirty-flushed to disk later.
  4. lseek(): Updates the file offset in the open file table entry. Doesn't touch the underlying storage.

The kernel keeps a per-process file descriptor table, an open file description with state such as the file offset, and cached path information such as dentries. These are separate structures with different roles.

10. What is the difference between journaling and non-journaling file systems, and what are the trade-offs?

Journal and recovery behavior depends on the filesystem and its configuration. In Linux 6.12 ext4, the default data=ordered mode journals metadata and writes related file data before metadata commits. A crash can still lose recent application data that had not reached storage. Ext4's data=journal and data=writeback modes change these guarantees. See the ext4 journal documentation.

Other filesystems use different logging, journaling, or copy-on-write designs. Check the filesystem documentation and mount options before relying on a particular recovery guarantee.

11. How does copy-on-write (COW) work in file systems like Btrfs, and what advantages does it provide?

Copy-on-Write (COW) writes changed data or metadata to new locations and then updates references. Btrfs is one filesystem that uses this approach.

In Btrfs, by default:

  1. When file data is modified, Btrfs writes a new version to a different location unless the file is marked NOCOW
  2. Only the metadata (which points to the data) is updated to reference the new location
  3. The old data remains unchanged until the old metadata pointers are also updated

Advantages:

  • Repair with redundancy: Checksums can detect corruption; with a redundant profile and a valid copy, Btrfs may repair a damaged block.
  • Snapshots: Shared extents remain available while snapshots reference them.

Disadvantages:

  • Fragmentation: COW can scatter data across the disk over time
  • Extra writes: Frequent small updates can increase write amplification. SSD wear leveling is handled by the device.
12. What is the role of the VFS (Virtual File System) layer and how does it enable multiple file systems?

The Virtual File System (VFS) is Linux's kernel interface between userspace file operations and supported filesystem implementations. Applications use that interface rather than calling ext4 or another filesystem driver directly.

VFS defines standard operations:

struct super_block  // The file system as a whole
struct inode        // A specific file
struct dentry        // A directory entry (name to inode mapping)
struct file         // An open file handle

Each Linux filesystem provides operations for its own implementation. When an application calls open(), VFS:

  1. Determines which mounted file system should handle the request
  2. Uses cached dentries where available and calls the filesystem's lookup operation when needed
  3. Creates a struct file with the file system's file_operations

This design allows Linux to mount different filesystems under one directory tree. A network mount also appears in that tree, though its caching and consistency behavior depends on the protocol and configuration.

13. How does file system fragmentation occur and what tools exist to defragment?

Fragmentation occurs when file data blocks are not contiguous on disk. As files are created, modified, and deleted, free space becomes scattered, and new files must be allocated from non-contiguous blocks.

Types:

  • Internal fragmentation: Wasted space within blocks (file smaller than block size)
  • External fragmentation: File blocks scattered across disk (causes slow reads)
  • Metadata fragmentation: Directory entries spread across disk

Tools for defragmentation:

  • ext4: e4defrag /dev/sda1 or e4defrag /mount/point
  • XFS: xfs_fsr /dev/sda1 (online defragmentation)
  • Btrfs: btrfs defrag /mount/point (btrfs balances allocations instead)
  • Windows: defrag C: in command prompt or Optimize Drives utility

Defragmentation helps mechanical hard drives (sequential access is faster) but is less important for SSDs (random access is fast, COW complicates it). Modern file systems with extent allocation (rather than block allocation) are more resistant to fragmentation.

14. What is the difference between a hard link count and a symbolic link, and when would you use each?

A hard link is a directory entry that points directly to an inode. Multiple hard links share the same inode, link count (in the inode) tracks how many directory entries reference it. When all hard links are deleted (link count becomes 0), the inode and its data blocks are freed.

Hard link rules:

  • Must be on the same file system as the original file
  • Cannot link to directories (prevents cycles in the directory tree)
  • The inode is shared—modifying the file affects all hard links

A symbolic link is a special file type containing a path string. It points to a path (not an inode), can cross file systems, and can point to directories or non-existent targets.

When to use hard links:

  • Multiple names for the same file in the same directory tree
  • Backup schemes where you want to maintain multiple references

When to use symbolic links:

  • Creating shortcuts or aliases
  • Linking across file systems or to directories
  • Pointing to files that may be renamed or moved
15. Explain the difference between block devices and character devices in Unix/Linux.

Block devices transfer data in fixed-size blocks (typically 512 bytes to 4KB). They support random access—you can seek to any block location. Examples: hard drives, SSDs, USB mass storage. The kernel buffers reads/writes through the page cache for efficiency.

Character devices transfer data as a stream of bytes, one character at a time. No random access, no buffering. Examples: keyboards, serial ports, terminals (/dev/tty), /dev/null. Programs read and write byte streams without knowing the underlying device.

Key differences:

  • Block devices: buffered I/O, random access, block-oriented
  • Character devices: unbuffered, sequential stream, byte-oriented

Device files are created with mknod: mknod /dev/sda b 8 0 (b = block device), mknod /dev/tty c 5 0 (c = character device). The major number identifies the driver; the minor number identifies the specific device instance.

16. What is the purpose of the directory entry cache (dentry cache) and how does it improve performance?

The dentry cache keeps recently used path components in memory, linking a name in a parent directory to the resolved filesystem object. Path resolution involves looking up each component, and a dcache hit can avoid repeating a filesystem lookup.

For example, opening /home/user/documents/report.txt requires:

  1. Look up root / → inode
  2. Look up home in root → inode
  3. Look up user in /home → inode
  4. Look up documents in /home/user → inode
  5. Look up report.txt in /home/user/documents → inode

On a dcache miss, VFS consults the mounted filesystem. It may answer from another cache, read local storage, or make a remote request. Path lookup complexity depends on the implementation.

When directories are modified, the kernel invalidates affected dentry entries. The dentry cache is integrated with the inode cache—dentries reference inodes, and inodes reference their dentries.

17. How does the Linux page cache work with file-backed memory mappings?

For ordinary Linux file reads and mappings, the page cache holds file data in memory. A cache hit can avoid a storage-device read for the requested data; a miss may trigger I/O through the filesystem. The Linux page cache documentation notes that O_DIRECT can bypass this cache.

For file-backed memory mappings (via mmap()), the page cache is used as the backing store. When a program accesses a memory-mapped file:

  1. The CPU accesses a virtual address
  2. If the page is not mapped, a page fault occurs
  3. The kernel finds the file data in the page cache or asks the filesystem to load it
  4. The kernel maps the page, then the access resumes

Modifications to memory-mapped files go through the page cache. The kernel writes modified pages back to disk (dirty pages) either periodically or when msync() is called.

File data and anonymous memory use system memory managed by Linux. The reclaim policy can evict file-cache pages when memory is needed.

18. What is FUSE (Filesystem in Userspace) and when would you use it?

FUSE lets a userspace process provide filesystem data and metadata through the Linux kernel interface, communicating through /dev/fuse. Non-privileged mounts are possible when system policy and configuration allow them.

FUSE architecture:

  1. User-space program registers with FUSE kernel module
  2. When VFS receives operations on the mount point, it passes them to the FUSE kernel module
  3. FUSE forwards operations to the user-space program
  4. User-space program performs the operation (reads from network, decrypts, etc.)
  5. FUSE returns the result to VFS

FUSE use cases:

  • sshfs: Mount remote SSH servers as local directories
  • gocryptfs: Encrypted file systems without kernel modules
  • mergerfs: Pool multiple drives into one logical volume
  • bindfs: Permission remapping layer
  • ntfs-3g: FUSE-based NTFS driver for Linux

FUSE can add communication and context-switch overhead. Actual performance depends on the implementation, caching, and workload; non-privileged mounting depends on system policy. See the Linux FUSE documentation.

19. How does the kernel handle file descriptor exhaustion and what limits apply?

A file descriptor is a small integer (index) in the process's file descriptor table. Each entry points to a struct file kernel object. The number of open files is limited by system and per-process limits.

System-wide limits:

  • /proc/sys/fs/file-max: Maximum number of open files system-wide
  • /proc/sys/fs/file-nr: Currently allocated (allocated, free, max)

Per-process limits:

  • ulimit -n: Soft limit (can increase to hard limit)
  • ulimit -Hn: Hard limit
  • Default: 1024 soft, 4096 hard (can be higher)

When limits are hit:

  • open() returns -1 with errno = EMFILE (too many open files)
  • Daemons may fail silently or crash
  • Long-running processes can leak file descriptors if not closed properly

Common causes of exhaustion:

  • File descriptor leaks (opened but never closed)
  • Logging to many files simultaneously
  • Making many network connections
20. What is the difference between synchronous and asynchronous I/O, and when would you use each?

Synchronous I/O: The call blocks until the operation completes. read() blocks until data is available; write() blocks until data is written to the kernel buffer. Simple to use, but blocks the thread.

Asynchronous I/O: The call returns immediately, before the operation completes. The application continues executing and receives notification (via callback, signal, or poll) when the operation finishes. More complex but better for high concurrency.

Linux async I/O APIs:

  • io_setup()/io_submit()/io_getevents(): Native Linux AIO
  • libaio: Wrapper around system calls
  • io_uring: New interface (kernel 5.1+) with significantly lower overhead

When to use synchronous I/O:

  • Simple programs with few concurrent operations
  • When blocking is acceptable (low concurrency requirements)

When to use asynchronous I/O:

  • High-concurrency servers (thousands of simultaneous connections)
  • I/O-bound workloads where blocking would limit throughput
  • Overlapping multiple I/O operations

Further Reading

Conclusion

A read such as cat /var/log/app.log crosses several layers. The kernel resolves path components to directory entries and inodes, VFS dispatches operations to the mounted file system, and the page cache and block layer mediate device I/O. Those boundaries help explain why df can show free bytes while a process cannot create a file, or why a network mount behaves differently from local storage.

When you diagnose a storage problem, identify which layer owns the metadata, cache, or recovery behavior involved. That gives you a more useful starting point than treating the file system as a single black box.

Category

Related Posts

ASLR & Stack Protection

Explore ASLR, PIE, stack canaries, and NX on Linux with GCC, then inspect a harmless C program to see what each mitigation does and where it falls short.

#operating-systems #aslr-stack-protection #computer-science

Assembly Language Basics: Writing Code the CPU Understands

Learn x86-64 Linux assembly with the System V ABI: track registers, assemble and run a small program, debug it in GDB, then compare AArch64.

#operating-systems #assembly-language-basics #computer-science

Boolean Logic & Gates

Understanding AND, OR, NOT gates and how they combine into arithmetic logic units — the building blocks of every processor.

#operating-systems #boolean-logic-gates #computer-science