Back to series
· 19 min read

How Does a File System Manage Disk Data?


I. Why Do We Need a File System?

A disk is essentially a block device capable of storing data over the long term. Whether it is an HDD, an SSD, or a USB flash drive, it ultimately uses data blocks of a fixed size as the unit of read and write.

Without a file system, the operating system can see only a series of contiguous or scattered disk blocks, but cannot directly understand which file each piece of data belongs to, what the file is called, where it is stored, or which space remains available.

For example, a 1 TB disk may be divided at the bottom layer into a large number of sectors and logical blocks. Yet users want to access data in this way:

/home/user/documents/report.pdf
/home/user/photos/avatar.png
/home/user/videos/demo.mp4

The file system is the management layer that bridges physical storage and the user's view of files.

It organizes disk space into files, directories, metadata, and data blocks, enabling the operating system to perform operations such as file creation, reading, modification, deletion, permission control, and space reclamation.

1. What Problems Does a File System Solve?

A file system mainly solves the following problems:

Problem Capability Provided by the File System
How data is organized File and directory structure
Where files are stored Data block allocation and indexing
What files are named Directory entries and name mapping
How large a file is File metadata
Who can access files Permissions and access control
How to find free space Free-space management
How to handle abnormal power loss Journaling, checksums, and recovery mechanisms
How to improve access speed Caching, readahead, and delayed writes
How to ensure data consistency Metadata updates and transaction mechanisms

2. Where Is the File System Located in the Operating System?

The file system is not part of the disk hardware; rather, it is an important component of the operating system's storage management architecture.

A typical storage access architecture is as follows:

flowchart TD
    A["Application"] --> B["File API"]
    B --> C["Virtual File System VFS"]
    C --> D["Specific file system"]
    D --> E["Block device layer"]
    E --> F["Device driver"]
    F --> G["Disk controller"]
    G --> H["HDD or SSD"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#E8E4FA,stroke:#B6A9E5,color:#51427A
    style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style E fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style F fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style G fill:#FFF2CC,stroke:#E8D28A,color:#755A18
    style H fill:#F1F5F9,stroke:#CBD5E1,color:#334155

For example, in Linux, applications access files through system calls such as open(), read(), and write().

VFS is responsible for providing a unified file access interface, the specific file system is responsible for organizing files and managing disk data, and the block device layer is responsible for submitting read/write requests to the underlying storage device.

This means applications generally do not need to care whether the data is ultimately stored on an HDD, an SSD, or another block device.


II. How Does a Disk Organize Data?

Before understanding file systems, it is necessary to first understand the underlying storage structure of disks.

1. Sectors, Logical Blocks, and Physical Blocks

Disks do not store data in units of files; rather, they read and write in units of blocks.

Common concepts include:

  • Sector: The basic addressing unit exposed by a storage device.
  • Logical sector: The sector numbering and size used by the operating system and device interface.
  • Physical sector: The physical unit by which data is actually organized inside the device.
  • Logical block: The space management unit used by the file system, usually consisting of one or more logical sectors.

Common logical sector sizes are 512 bytes or 4096 bytes. The block size of a Linux file system is commonly 4 KiB, but it depends on the file system and device configuration.

For example, suppose the file system block size is 4 KiB:

Disk space

Block 0       4 KiB
Block 1       4 KiB
Block 2       4 KiB
Block 3       4 KiB
Block 4       4 KiB
...
Block N       4 KiB

A file system usually allocates space in units of blocks.

Suppose a file is 10 KiB in size and each block is 4 KiB; then at least three data blocks are needed:

Block A: 4 KiB
Block B: 4 KiB
Block C: 2 KiB valid data

The remaining 2 KiB in the last block may not be allocatable to other files; this phenomenon is called internal fragmentation.

2. Partitions and File Systems

A physical disk can be divided into multiple partitions, and each partition can have its own file system created independently.

For example:

Physical disk
│
├── Partition 1: System partition
│   └── ext4
│
├── Partition 2: Data partition
│   └── XFS
│
└── Partition 3: Swap partition
    └── Swap

Note the following:

  • A partition is a logical division of disk space.
  • A file system is the way data is organized within a partition.
  • A partition can usually contain one file system.
  • A file system may also span multiple underlying devices, for example by using logical volumes or storage pools.

Modern systems may also use GPT partition tables to manage disk partitions.

You can use the following command to view disks and partitions:

lsblk

View the partition table:

sudo fdisk -l

View the file system type:

lsblk -f

3. Overall Layout of a File System

A file system usually needs to store two types of information:

  1. The data of the files themselves.
  2. The metadata needed to manage the files.

A typical layout can be abstracted as:

flowchart TD
    A["File system"] --> B["Superblock"]
    A --> C["Space management information"]
    A --> D["Metadata area"]
    A --> E["Data area"]
    A --> F["Journal area"]

    B --> B1["File system capacity"]
    B --> B2["Block size"]
    B --> B3["File system status"]

    C --> C1["Free block bitmap"]
    C --> C2["Free inode information"]

    D --> D1["inode or file records"]
    D --> D2["Directory entries"]

    E --> E1["File content"]
    E --> E2["Directory data"]

    F --> F1["Metadata change records"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style C fill:#E8E4FA,stroke:#B6A9E5,color:#51427A
    style D fill:#FFF2CC,stroke:#E8D28A,color:#755A18
    style E fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style F fill:#FCE8E6,stroke:#E6B2AA,color:#854B45
    style B1 fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B2 fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B3 fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C1 fill:#E8E4FA,stroke:#B6A9E5,color:#51427A
    style C2 fill:#E8E4FA,stroke:#B6A9E5,color:#51427A
    style D1 fill:#FFF2CC,stroke:#E8D28A,color:#755A18
    style D2 fill:#FFF2CC,stroke:#E8D28A,color:#755A18
    style E1 fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style E2 fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style F1 fill:#FCE8E6,stroke:#E6B2AA,color:#854B45

The actual layouts of different file systems are not exactly the same.

For example, ext4 uses structures such as superblocks, block group descriptors, inode tables, block bitmaps, and data blocks; NTFS uses the Master File Table (MFT) to manage file records; APFS uses mechanisms such as containers, volumes, and copy-on-write.


III. What Exactly Are Files and Directories?

The two most central concepts in a file system are files and directories.

1. A File Is More Than Just a File Name

Users usually think of a file as consisting of a file name, an extension, and content.

But from the perspective of a file system, the file name and the file content are managed separately.

A file usually includes:

  • File name: the name the user sees.
  • File identifier: the unique identifier used internally by the file system.
  • File type: regular file, directory, symbolic link, etc.
  • File size: the current length of the file content.
  • Permissions: which users can read, write, or execute.
  • Timestamps: time information such as creation, modification, and access.
  • Data block location: where the file content is actually stored.

In Linux's ext4 file system, the inode is an important structure for managing file metadata.

An inode usually records:

  • File type and permissions.
  • File owner and owning group.
  • File size.
  • Timestamps.
  • Number of hard links.
  • Index information for the file's data blocks.

An inode usually does not store the file name.

The file name is mainly stored in directory entries.

2. Inodes and Directory Entries

In Linux, a directory can be understood as a mapping from file names to inode numbers.

For example:

/home/user
│
├── report.txt  → inode 1001
├── photo.png   → inode 1002
└── notes.md    → inode 1003

Directory entries are responsible for associating names with inodes.

The inode is then responsible for describing file attributes and providing the information needed to access the file's data.

Their relationship is as follows:

flowchart TD
    A["Directory"] --> B["Directory entry report.txt"]
    A --> C["Directory entry photo.png"]
    A --> D["Directory entry notes.md"]

    B --> E["inode 1001"]
    C --> F["inode 1002"]
    D --> G["inode 1003"]

    E --> H["Data blocks A, B"]
    F --> I["Data blocks C, D, E"]
    G --> J["Data block F"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style E fill:#E8E4FA,stroke:#B6A9E5,color:#51427A
    style F fill:#E8E4FA,stroke:#B6A9E5,color:#51427A
    style G fill:#E8E4FA,stroke:#B6A9E5,color:#51427A
    style H fill:#FFF2CC,stroke:#E8D28A,color:#755A18
    style I fill:#FFF2CC,stroke:#E8D28A,color:#755A18
    style J fill:#FFF2CC,stroke:#E8D28A,color:#755A18

This also explains an important phenomenon:

A file name is not the file itself; the inode is the important basis on which the file system identifies a file object.

3. One inode can correspond to multiple file names

Linux supports hard links.

Multiple directory entries can point to the same inode.

For example:

report.txt ──┐
             ├── inode 1001
backup.txt ──┘

These two file names actually point to the same file object.

You can use the following command to create a hard link:

ln report.txt backup.txt

View the inode:

ls -li report.txt backup.txt

If the two files show the same inode number, they point to the same inode.

Deleting one of the file names does not immediately delete the file contents. Only when the hard link count reaches zero and no other references continue to use the file can the file system reclaim its data space.

Note that Linux also has symbolic links. A symbolic link is an independent file object whose contents usually store the target path; this is different from the inode-sharing mechanism of hard links.

4. Directories are also a special type of file

In Linux, a directory itself also has an inode and also occupies disk space.

Inside a directory, directory entries establish the relationship between file names and file identifiers.

For example:

/
└── home
    └── user
        ├── documents
        │   └── report.txt
        └── pictures
            └── avatar.png

Access:

/home/user/documents/report.txt

The file system needs to resolve the path layer by layer, find the corresponding directory entry, and then locate the final file.


IV. How does a file system allocate disk space?

A file system needs to solve one core problem:

Where on the disk should a file's data be stored?

A file system cannot simply arrange all files next to one another, because files may continuously grow, shrink, or be deleted, and may also be accessed by multiple programs at the same time.

Common space allocation methods include contiguous allocation, linked allocation, and indexed allocation.

1. Contiguous allocation

Contiguous allocation means that a file occupies a contiguous range of disk blocks.

For example:

File A: Block 10 ~ Block 14
File B: Block 15 ~ Block 18
File C: Block 19 ~ Block 22

Advantages:

  • File data is contiguous, so sequential read/write efficiency is high.
  • Locating data within a file is relatively simple.
  • Metadata management overhead is relatively low.

Disadvantages:

  • A file may be unable to expand when it grows.
  • It easily causes external fragmentation.
  • It requires finding a sufficiently large contiguous space.

Contiguous allocation is suitable for data of fixed size that does not change often after being written, but it has clear limitations for general-purpose file systems.

2. Linked allocation

Linked allocation connects a file's data blocks together.

Each data block stores the location of the next data block.

For example:

File A:

Block 10 → Block 25 → Block 17 → Block 42

Advantages:

  • Files can use non-contiguous disk space.
  • File growth is relatively flexible.
  • There is no need to preallocate contiguous space.

Disadvantages:

  • Random access efficiency is relatively low.
  • Additional storage is needed to record the links between blocks.
  • Damage to the link information may make subsequent data inaccessible.

The FAT file system uses a similar linked-management approach, recording the relationships between clusters through a file allocation table.

3. Indexed Allocation

Indexed allocation uses a dedicated index structure to record the locations of a file's data blocks.

For example:

inode
  │
  ├── Block 10
  ├── Block 25
  ├── Block 17
  └── Block 42

The file system can locate data blocks through the index information without relying on the previous data block.

Advantages:

  • Supports random access.
  • Files can be stored in a dispersed manner.
  • File growth is relatively flexible.

Disadvantages:

  • The index structure requires additional space.
  • Large files may require multi-level indexes.
  • Accessing and maintaining the index structure incurs overhead.

ext2, ext3, and ext4 use inodes to manage files and describe data locations through mechanisms such as direct block pointers, indirect block pointers, or extents.

Modern ext4 typically uses extents to manage contiguous ranges of data blocks, reducing the index metadata overhead for large files.

4. The Extent Mechanism in ext4

Traditional block pointers may need to record a large number of individual data block numbers.

Suppose a file occupies 1000 contiguous data blocks:

Block 100
Block 101
Block 102
...
Block 1099

If each one is recorded individually, a large number of block addresses must be stored.

An extent, by contrast, can record the starting block and length of a contiguous range:

Start block: 100
Length: 1000

This can significantly reduce the indexing overhead for contiguous data blocks.

When a file's data is not contiguous, a single file can also be described by multiple extents.

5. Comparison of the Three Allocation Methods

Allocation Method Core Idea Advantages Disadvantages
Contiguous Allocation Uses contiguous blocks Fast sequential access External fragmentation, difficult to extend
Linked Allocation Data blocks are linked to one another Flexible expansion Slow random access
Indexed Allocation Locates data through an index Supports random access Requires index maintenance
Extent Records contiguous block ranges Reduces indexing overhead Requires managing multiple ranges

V. How Does a File System Find Free Disk Space?

A file system must not only know which blocks belong to a given file but also which blocks can be allocated to new files.

This is free space management.

1. Bitmap Management

A bitmap is a common space management method.

One bit is used to indicate whether a disk block has already been used.

For example:

Disk block:  0 1 2 3 4 5 6 7
Bitmap:      1 1 0 0 1 0 1 0

Assume:

  • 1 means used.
  • 0 means free.

Then Blocks 2, 3, 5, and 7 are free space.

Advantages of a bitmap:

  • Simple data structure.
  • Relatively small space usage.
  • Free regions can be found quickly through bit operations.
  • Makes it easy to track space usage.

Disadvantages:

  • Large-capacity devices require maintaining a larger bitmap.
  • Finding contiguous free space requires additional optimization.

ext4 uses block bitmaps and inode bitmaps to manage the allocation status of blocks and inodes.

2. Free List

A free list organizes all available data blocks into a linked list.

Each node records the location of the next free block.

Its advantage is a simple structure, while its disadvantage is that finding contiguous space and counting free space may not be efficient enough.

3. Group Management and Space Allocation Optimization

Modern file systems generally do not rely solely on a simple global free list.

They may divide the disk into multiple regions or allocation groups and manage space information separately for each.

This can:

  • Reduce global lock contention.
  • Improve concurrent allocation capability.
  • Keep file data as close as possible to related metadata.
  • Improve locality and sequential read/write performance.

ext4 uses block groups to organize file system space and optimizes write behavior through mechanisms such as delayed allocation and multi-block allocation.


VI. How Are Files Created, Read, and Written?

The most direct way to understand a file system is to trace a single file operation.

1. Creating a File

For example, run:

touch report.txt

The file system needs to complete the following steps:

  1. Resolve the current directory.
  2. Check whether a file with the same name already exists.
  3. Allocate a new inode.
  4. Create a directory entry.
  5. Initialize the file metadata.
  6. Update the relevant directory and space management information.

When creating an empty file, it is usually not necessary to allocate actual data blocks immediately.

flowchart TD
    A["Call touch or open"] --> B["Resolve parent directory"]
    B --> C["Check whether file name exists"]
    C --> D{"Is creation allowed"}
    D -->|No| E["Return error"]
    D -->|Yes| F["Allocate inode"]
    F --> G["Create directory entry"]
    G --> H["Initialize metadata"]
    H --> I["Update file system state"]
    I --> J["Return file descriptor or operation result"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style C fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style D fill:#FFF2CC,stroke:#E8D28A,color:#755A18
    style E fill:#FCE8E6,stroke:#E6B2AA,color:#854B45
    style F fill:#E8E4FA,stroke:#B6A9E5,color:#51427A
    style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style H fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style I fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976

2. Reading a File

Suppose the program executes the following:

int fd = open("report.txt", O_RDONLY);

char buffer[1024];

ssize_t n = read(fd, buffer, sizeof(buffer));

close(fd);

A typical file read process includes:

  1. The application calls open().
  2. The kernel resolves the path.
  3. The file system locates the corresponding inode.
  4. The kernel creates and returns a file descriptor.
  5. The application calls read().
  6. The kernel checks whether the required data is in the page cache.
  7. If the cache hits, data is provided directly from the cache.
  8. If the cache misses, a block device read request is submitted.
  9. The data enters the kernel page cache.
  10. The data is copied to the user-space buffer.

The read flow is as follows:

flowchart TD
    A["Application calls read"] --> B["The kernel checks the file descriptor"]
    B --> C["Locate file offset"]
    C --> D["Query page cache"]
    D --> E{"Cache hit"}
    E -->|Yes| F["Read data from page cache"]
    E -->|No| G["Submit block device I/O"]
    G --> H["Device reads data from disk"]
    H --> I["Data enters page cache"]
    I --> F
    F --> J["Copy data to user buffer"]
    J --> K["Return number of bytes read"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style C fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style D fill:#E8E4FA,stroke:#B6A9E5,color:#51427A
    style E fill:#FFF2CC,stroke:#E8D28A,color:#755A18
    style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style G fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style H fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style I fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style K fill:#E0F0FE,stroke:#93BCE8,color:#1E4976

Note: Actual kernels may also use direct I/O, memory-mapped I/O, asynchronous I/O, and other methods. The diagram above describes a common buffered I/O path; not every file read must go through exactly the same steps.

3. Writing to a File

For example:

int fd = open("report.txt", O_WRONLY | O_APPEND);

write(fd, "Hello File System\n", 18);

close(fd);

In the common buffered I/O mode, write() usually writes data to the kernel page cache first and marks the corresponding pages as dirty.

A dirty page means that the content in memory has been modified, but the persistent data on disk may not yet have been synchronized.

Later, the kernel writes the dirty pages to the storage device according to the writeback policy.

flowchart TD
    A["Application calls write"] --> B["Check file descriptor and permissions"]
    B --> C["Determine file write offset"]
    C --> D["Update page cache"]
    D --> E["Mark page as dirty"]
    E --> F["Update file length and metadata"]
    F --> G["write returns"]
    G --> H["Kernel background writeback"]
    H --> I["Submit block device write request"]
    I --> J["Device completes data write"]
    J --> K["Clear completed dirty page state"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style C fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style E fill:#FFF2CC,stroke:#E8D28A,color:#755A18
    style F fill:#E8E4FA,stroke:#B6A9E5,color:#51427A
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style H fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style I fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style J fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style K fill:#DCEFE5,stroke:#8EBFA5,color:#24563F

Important: A successful return from write() does not mean the data has been safely written to the physical medium.

It usually only means that the kernel has accepted the write request.

If you need a stronger durability guarantee, you can use:

fsync(fd);

fsync() requests that file data and associated metadata be synchronized to stable storage.

If you also need to ensure that directory entry operations such as file creation or renaming are durable, you may also need to call fsync() on the parent directory.

Even if synchronization interfaces are called, ultimate reliability also depends on the storage device correctly implementing cache flush and durability semantics.

4. File Offset and Random Access

The file system allows a program to read from or write to a file at any position.

For example:

lseek(fd, 1024, SEEK_SET);
read(fd, buffer, 512);

This means reading 512 bytes starting at file offset 1024.

At a lower level, the file system needs to map the logical file offset to a specific data block.

Assume:

  • The file system block size is 4096 bytes.
  • The file offset is 8192 bytes.

Then:

Data block index = 8192 / 4096 = 2
Offset in block  = 8192 % 4096 = 0

If the file's data blocks are stored discontinuously, the file system needs to find the corresponding physical location based on the inode or extent index.


VII. How Does the File System Improve Disk Access Performance?

Disk access speed is usually much slower than CPU and memory.

If every file read directly accessed the disk, system performance would be greatly affected.

Therefore, the operating system and file system adopt various caching and optimization techniques.

1. Page Cache

The page cache is an important mechanism for Linux file system performance optimization.

It caches file data in memory, reducing the number of repeated disk accesses.

For example:

First read of report.txt
       │
       ▼
    Disk read
       │
       ▼
    Write to page cache
       │
       ▼
    Return to application

Second read of report.txt
       │
       ▼
    Query page cache
       │
       ▼
    Return cached data directly

This caching mechanism can significantly improve performance for repeated reads.

In Linux, ordinary buffered file I/O typically uses the page cache.

2. Read Ahead

Programs often read files sequentially.

For example:

Read Block 1
Read Block 2
Read Block 3
Read Block 4

If the kernel can predict subsequent accesses, it can read the following data in advance.

This mechanism is called readahead.

Readahead can reduce the time spent waiting for disk I/O and improve sequential read throughput.

However, if the access pattern is completely random, readahead may generate useless I/O and even waste cache space.

3. Write Back

Write-back allows a program to first modify cached data in memory, and the kernel then writes it back at an appropriate time.

Main benefits:

  • Combines multiple small writes.
  • Reduces the number of disk I/O operations.
  • Improves write throughput.
  • Allows data to be submitted in batches in the background.

However, delayed writing also means that data that has not yet been persisted may be lost in the event of a sudden power failure.

4. Direct I/O

Some applications want to reduce the extra copying and cache management overhead caused by the page cache.

For example, a database may manage its own cache and therefore consider using O_DIRECT.

Example:

int fd = open("data.db", O_RDWR | O_DIRECT);

Direct I/O typically bypasses the normal page cache path, but it comes with constraints regarding alignment, buffers, and filesystem support.

It does not mean the data automatically gains durability guarantees, nor does it mean performance will be better in every scenario.

5. Memory-Mapped Files

The operating system also allows a program to map a file into the process's virtual address space via mmap().

For example:

int fd = open("data.bin", O_RDONLY);

void *ptr = mmap(
    NULL,
    file_size,
    PROT_READ,
    MAP_PRIVATE,
    fd,
    0
);

A program can access the file contents as if it were accessing memory.

When it accesses a page that has not yet been loaded into memory, the operating system may trigger a page fault and then load the corresponding data from the filesystem.

Memory-mapped files are well suited for:

  • Random access to large files.
  • Sharing data among multiple processes.
  • Certain database and indexing systems.
  • Scenarios that need simplified file access code.

6. Comparison of Performance Optimization Mechanisms

Mechanism Primary Purpose Use Cases
Page Cache Cache file data Repeated reads
Read Ahead Preload data Sequential reads
Write Back Coalesce and defer writes Frequent small writes
Direct I/O Bypass the normal page cache Applications that manage their own cache
mmap Map files into virtual memory Random access, shared mappings
Extent Reduce data block indexing overhead Large files and contiguous data

8. How Do Journaling Filesystems Ensure Data Consistency?

Besides managing data, a filesystem must also cope with unexpected power loss, kernel crashes, and device failures.

If the system suddenly loses power while modifying a file, the following may occur:

  • Only part of the file contents is written.
  • The inode has been updated, but the directory entry has not yet been updated.
  • Data blocks have been allocated, but the bitmap has not been synchronized.
  • Inconsistencies appear among metadata.

For example, creating a file may require modifying several places:

Allocate an inode
Update the inode bitmap
Create a directory entry
Update the directory metadata

If only some of these modifications are completed, the filesystem may be left in an inconsistent state.

1. The Journaling Mechanism

A journaling filesystem reduces the risk of metadata inconsistency after a crash by recording information about critical changes.

Taking metadata journaling as an example, a typical process includes:

  1. Write the metadata about to be modified into the journal.
  2. Ensure the journal records reach the required durable state.
  3. Update the actual metadata in the filesystem.
  4. Commit the journal transaction.
  5. Later, reclaim journal space that is no longer needed.
flowchart TD
    A["Begin filesystem transaction"] --> B["Record metadata changes"]
    B --> C["Write to journal area"]
    C --> D["Persist journal record"]
    D --> E["Update actual metadata"]
    E --> F["Commit transaction"]
    F --> G["Transaction complete"]

    C --> H["System crash occurs"]
    D --> H
    E --> H
    H --> I["Remount filesystem"]
    I --> J["Check journal state"]
    J --> K["Replay committed transactions"]
    J --> L["Discard uncommitted transactions"]
    K --> M["Restore filesystem consistency"]
    L --> M
    G --> N["Subsequent journal cleanup"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E8E4FA,stroke:#B6A9E5,color:#51427A
    style C fill:#E8E4FA,stroke:#B6A9E5,color:#51427A
    style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style H fill:#FCE8E6,stroke:#E6B2AA,color:#854B45
    style I fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style J fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style K fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style L fill:#FFF2CC,stroke:#E8D28A,color:#755A18
    style M fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style N fill:#F6FAF7,stroke:#DCE9E0,color:#334155

The core idea of journal recovery is:

After a system crash, determine from the journal which transactions have already been committed, and then restore consistency of the filesystem metadata.

2. Journaling modes in ext4

ext4 supports several data and journaling modes:

Mode Main characteristics
journal Both data and metadata are recorded in the journal
ordered Data is written to its final location before the related metadata; metadata uses the journal
writeback Metadata uses the journal, but data is not guaranteed to be written before metadata

Among these, ordered is the common default mode in ext4.

Note that the journaling mechanism is mainly used to maintain consistency of the filesystem structure; it does not mean that all user data has transaction-level durability guarantees.

For example, a normal write() returning successfully does not mean that all the data just written will necessarily survive a power loss.

3. Copy-on-Write

Another important mechanism is Copy-on-Write, or CoW for short.

It does not overwrite the original data directly; instead, it writes the modified content to a new location and then updates the metadata references.

For example:

Original data:
Block A → Block B → Block C

After modification:
Block A → Block B → Block D

The original Block C is not overwritten immediately.

Only after the new metadata references are safely established can the old data blocks be reclaimed.

Advantages of CoW include:

  • Supports snapshots.
  • Makes rollback easy.
  • Avoids overwriting old data directly.
  • Facilitates the implementation of certain consistency-protection mechanisms.

Representative filesystems include:

  • Btrfs.
  • ZFS.
  • APFS.

However, CoW can also bring write amplification, space fragmentation, and random-write performance issues.

4. Differences between Journaling and CoW

Aspect Journaling Copy-on-Write
Core mechanism Write to the journal first, then update the actual location Write to a new location, then switch the references
Main goal Crash recovery and metadata consistency Preserving old data versions and consistency
Data at the original location Can usually be overwritten The old version is usually kept on modification
Snapshot capability Requires additional mechanisms Easier to implement
Typical filesystems ext4, XFS, NTFS Btrfs, ZFS, APFS

Note that the actual implementations of journaling filesystems and CoW filesystems differ in many more ways; one cannot simply assume that journaling protects only metadata, nor that CoW automatically solves all data-integrity problems.


9. When a file is deleted, how is disk space released?

Execute:

rm report.txt

does not mean the operating system immediately wipes all of the file's contents.

In Linux, deleting a filename usually involves the following operations:

  1. Removing the corresponding directory entry from the parent directory.
  2. Decrementing the inode's hard link count.
  3. Only when the hard link count reaches zero and no other kernel references continue to use the file can the filesystem reclaim the inode and data blocks.
  4. The reclaimed space re-enters the free space management structures.

1. Why isn't space freed after deleting a file?

This is a very common problem in Linux.

Suppose a program has already opened a file:

int fd = open("large.log", O_RDONLY);

At this point, even if another process deletes the file:

rm large.log

as long as the original process still holds the file descriptor, the file object may continue to exist.

The filename has already been removed from the directory, but the kernel still retains that file object.

Only when the last relevant reference is released can the filesystem reclaim the corresponding space.

This is why sometimes after running rm, the disk space does not noticeably increase.

You can use:

lsof +L1

to find files that are still open by processes but no longer have a directory link.

The usual solution is to have the process holding the file close the file descriptor, or to restart the relevant process depending on the business situation.

2. Deleting a file and wiping data are not the same thing

An ordinary delete operation usually only releases the reference relationships and space allocation records in the filesystem.

The original contents of the file may still remain on the storage medium until the corresponding space is reused or handled through some other mechanism.

Therefore:

  • Deleting a file is not the same as secure erasure.
  • Formatting does not necessarily mean data is thoroughly cleared.
  • SSD TRIM is also not the same as verifiable secure erasure.

If sensitive data destruction is involved, a plan needs to be developed based on the device type, encryption method, and the secure erase capabilities provided by the device.


10. What are the differences between filesystems?

Different filesystems use different data structures, space management mechanisms, and consistency strategies.

1. FAT32

FAT32 is an earlier filesystem with very strong compatibility.

Main characteristics:

  • Uses the FAT file allocation table to manage data clusters.
  • Records file information through directory entries.
  • Does not have the crash recovery capabilities common in modern journaling filesystems.
  • The maximum size of a single file is approximately 4 GiB minus 1 byte.

Suitable for:

  • Some older devices.
  • Removable storage media that need broad compatibility.
  • Scenarios that do not require the advanced features of modern filesystems.

2. NTFS

NTFS is the filesystem commonly used by Windows.

Core characteristics: