File Allocation Methods
A guide to contiguous, linked, and indexed allocation, and how FAT, ext2/3/4, and NTFS map file data and track free space.
A guide to contiguous, linked, and indexed allocation, and how FAT, ext2/3/4, and NTFS map file data and track free space.
File Allocation Methods
File allocation describes how a file system maps file data to storage blocks. Textbooks often introduce three models—contiguous, linked, and indexed—to explain locality, random access, and fragmentation. Real file systems use more detailed structures, and those structures vary by file system, version, and enabled features.
Introduction
The three models are useful for learning, but they do not map one-to-one onto modern file systems. FAT stores cluster chains in a central allocation table; ext2 and ext3 use block maps with direct and indirect pointers; ext4 can map file ranges with extents; NTFS stores file metadata in MFT records and describes non-resident data with runs. Free-space tracking and crash recovery are separate concerns from the file-to-block mapping.
Lab safety: Never experiment on your live system disk. Use a disposable virtual disk image, confirm the image-backed target before every command, and keep a backup. In Linux examples,
/dev/test-volumeis a placeholder for the disposable image’s mapped file system. Formatting, partition-table changes, and repair commands can make existing data inaccessible.
| Command class | Examples | Effect |
|---|---|---|
| Read-only inspection | df -i, tune2fs -l, e2fsck -n, chkdsk E: without repair switches, defrag E: /A, e4defrag -c, DiskPart list disk |
Reports information or checks status without applying repairs. |
| Modifies a file system | defrag E: without /A, e4defrag without -c, tune2fs -m, tune2fs -c, tune2fs -i |
Changes file layout or file-system settings. Use a disposable test volume. |
| Overwrites file data or free space | shred -vu /path/to/file, sfill -f /mount/point |
Can destroy recoverable data or write across a volume. Use only on a disposable image. |
| Repairs or reinitializes a volume | chkdsk E: /f or /r, e2fsck without -n, mkfs.ext4, DiskPart clean, delete partition, or format |
Writes file-system or partition metadata and can make existing data inaccessible. |
Microsoft documents that chkdsk without repair switches reports status, while /f and /r fix errors; /r includes /f. DiskPart’s list reports objects, while commands such as clean and delete partition modify the selected disk. defrag E: /A performs analysis; without /A, defrag can change file layout. See Microsoft’s CHKDSK, DiskPart, and defrag references.
When to Use / When Not to Use
Allocation method knowledge helps with system design and troubleshooting.
When allocation method understanding helps:
- Formatting drives for specific workloads (large files vs many small files)
- Understanding why fragmentation occurs and how to prevent it
- Designing applications that interact heavily with storage
- Troubleshooting performance issues in file-heavy workloads
- Choosing the right file system for a given use case
When you can rely on defaults:
- General desktop and server use (ext4/XFS/NTFS handle this well)
- Cloud storage where abstracted block devices are provided
- Containerized workloads with overlay file systems
Architecture or Flow Diagram
graph TD
A[File Creation Request] --> B{Allocation Strategy}
B --> C[Contiguous Allocation]
B --> D[Linked Allocation]
B --> E[Indexed Allocation]
C --> F[Find large enough hole]
D --> G[Track free blocks with linked list]
E --> H[Build index block for file]
F --> I[Allocate consecutive blocks]
G --> J[Allocate from anywhere, link blocks]
H --> K[Pointers in index block]
style C stroke:#ff00ff,stroke-width:2px
style D stroke:#00fff9,stroke-width:2px
style E stroke:#ff00ff,stroke-width:2px
Core Concepts
Contiguous Allocation
The simplest approach: allocate consecutive blocks for each file.
File "video.mp4" - 5 blocks:
[Block 100][Block 101][Block 102][Block 103][Block 104]
▲ Start block
└────── 5 consecutive blocks ──────┘
Directory Entry:
Name: video.mp4
Start: 100
Length: 5
Advantages:
- Excellent sequential read performance (no seeks between blocks)
- Simple to implement
- Small metadata overhead (only start block + length needed)
Disadvantages:
- External fragmentation (must find large enough continuous hole)
- Compaction required to reclaim space
- File growth problematic (adjacent blocks may be taken)
// Simulated contiguous allocation
typedef struct {
char filename[255];
int start_block;
int length_blocks;
} FileEntry;
int allocate_contiguous(int file_id, int blocks_needed) {
int start = find_contiguous_hole(blocks_needed);
if (start == -1) {
// No hole large enough
return -1;
}
allocate(start, blocks_needed);
return start;
}
Linked Allocation
Each block contains a pointer to the next block:
File "document.txt" - 4 blocks:
[Block 50][data][Block 89] -> [Block 12][data][Block 200] ->
[Block 200][data][NULL] -> [Block 75][data][NULL]
Directory Entry:
Name: document.txt
Start: 50
End: 75 (cached or NULL if unknown)
Advantages:
- No external fragmentation (use any free block)
- File can grow easily (just add more blocks)
- Simple directory entry (only start block needed)
Disadvantages:
- Poor random access (must follow chain from start)
- Pointer overhead (4-8 bytes per block)
- Pointer integrity critical (corrupted pointer = data loss)
- No concept of file size without scanning
// Linked allocation block structure
typedef struct {
char data[BLOCK_SIZE - sizeof(int)];
int next_block; // Pointer to next block, -1 = end of file
} LinkedBlock;
Indexed Allocation
Store all block pointers in an index block:
File "database.db" - 7 blocks:
Index Block (Block 500):
┌─────────────────────────────────┐
│ Pointer: 120 │
│ Pointer: 45 │
│ Pointer: 389 │
│ Pointer: 12 │
│ Pointer: 201 │
│ Pointer: 88 │
│ Pointer: 156 │
│ Pointer: -1 (end of index) │
└─────────────────────────────────┘
│
├──> [Block 120][data]
├──> [Block 45][data]
├──> [Block 389][data]
├──> [Block 12][data]
├──> [Block 201][data]
├──> [Block 88][data]
└──> [Block 156][data]
Directory Entry:
Name: database.db
Index Block: 500
Advantages:
- Direct random access to any block
- Good sequential performance
- Blocks can be anywhere on disk
- File metadata self-contained in index block
Disadvantages:
- Index block overhead (1 block per file regardless of size)
- Limit on file size based on index block entries
- Extra I/O to read index block first
Multilevel block pointers in ext2 and ext3: Their traditional inode block maps use direct pointers plus single-, double-, and triple-indirect blocks. This is one real implementation of indexed mapping; it is not the layout used by every file system. ext4 can use extent trees instead (see the comparison below).
- Single indirect block (pointers to data blocks)
- Double indirect block (pointers to single indirect blocks)
- Triple indirect block (pointers to double indirect blocks)
Textbook models and real file systems
| Textbook model | What the model assumes | A real implementation | What differs |
|---|---|---|---|
| Contiguous | One file occupies one continuous run of blocks. | ext4 can describe contiguous ranges with extents. | A file may need several extents as it grows or the volume fills; it is not guaranteed one continuous run. |
| Linked | Each data block points to the next block. | FAT stores the next-cluster links in entries in a central File Allocation Table. | The links are kept in the FAT, not inside each data block. |
| Indexed | One index block lists all blocks belonging to a file. | ext2/ext3 use direct and indirect block pointers; ext4 uses extent trees for files with the extent feature; NTFS records file attributes and maps non-resident data with runs. | Real mappings can be multi-level and use different metadata layouts. They are not all a single index block. |
These structures do different jobs. A bitmap or free-space tree tracks available blocks; an extent tree or run list maps file ranges to storage; a journal supports recovery. Keep free-space tracking, file mapping, and journaling separate when comparing implementations. See the Linux kernel’s ext4 documentation and Microsoft’s NTFS Master File Table documentation.
FAT: File Allocation Table
FAT uses a variation of linked allocation with a central table:
graph LR
A[FAT Table] --> B[Cluster 0]
A --> C[Cluster 1]
A --> D[Cluster 2]
B --> E[End of file]
C --> D
D --> E
style A stroke:#ff00ff,stroke-width:3px
The FAT table stores one entry per cluster:
- 0x0000: Free cluster
- 0xFFFF: End of file
- Other values: Next cluster in chain
FAT-16 Entry Example:
┌────────┬────────┬────────┬────────┐
│ Cluster│ Value │ Meaning│ Next │
├────────┼────────┼────────┼────────┤
│ 0 │ 0xFFF8 │ Media │ - │
│ 1 │ 0xFFFF │ EOF │ - │
│ 2 │ 5 │ Next │ Cluster 5
│ 3 │ 6 │ Next │ Cluster 6
│ 4 │ 0 │ Free │ - │
│ 5 │ 0xFFFF │ EOF │ - │
│ 6 │ 0xFFFF │ EOF │ - │
└────────┴────────┴────────┴────────┘
File "example.txt" starting at cluster 2:
[Cluster 2] -> [Cluster 5] -> EOF
FAT Fragmentation Physics: On FAT, fragmentation isn’t just about free space scatter—it’s about how the FAT chain grows. When a file grows, new clusters are allocated wherever free space exists. Over time, a file’s cluster chain becomes a scattered sequence across the drive.
The impact depends on the storage device and workload. On a spinning disk, reading a file split across distant runs can require extra seeks. Flash storage has no mechanical head, so the same layout does not produce the same seek penalty. FAT can fragment as files grow, but fragmentation and its performance cost are not fixed.
Operating systems cache FAT data as needed; the cache size depends on the system and workload. The table itself grows with the number of clusters, so FAT type and cluster size affect its size.
ext2, ext3, and ext4: Free-space maps and file mappings
The ext family uses block bitmaps to track free space. The on-disk mapping for file data differs by version and feature: ext2 and ext3 traditionally use direct and indirect block pointers, while ext4 supports extent trees. Do not treat “ext2/3/4” as one allocation layout.
Block Bitmap: One bit per block indicates free/allocated. Fast for finding free space.
Extent-based mapping in ext4: When the extents feature is enabled, ext4 represents file data as ranges of adjacent blocks rather than listing every block separately:
Extent format in ext4:
Start block: 1024
Length: 50 blocks (means blocks 1024-1073 are contiguous)
File stored in extents:
Extent 1: start=1024, len=50 (blocks 1024-1073)
Extent 2: start=2048, len=25 (blocks 2048-2072)
Extent 3: start=4096, len=10 (blocks 4096-4105)
This can reduce mapping metadata for files with long contiguous ranges. It does not guarantee that a file stays in one range or avoid fragmentation in every workload.
Extent Tree Structure in ext4: The inode stores an extent tree rather than simple block pointers. The extent header contains:
eh_entries: Number of valid extent entrieseh_max: Maximum entries in this nodeeh_depth: Tree depth (0 = all extents in inode, 1+ = external nodes)
An extent entry records a starting block and a length. In this example, the two ranges need two entries instead of 100 separate block pointers. A single contiguous run can use one entry; a fragmented file may need many. Extents reduce mapping metadata when they cover multiple blocks, but do not make the inode itself smaller.
Delayed allocation (delalloc):
ext4 can postpone choosing physical blocks until writeback, which gives its allocator more data to place together. This is an allocation policy, not a promise that recent writes are durable. In the common data=ordered mode, ext4 orders data writes before committing related metadata; file data itself is not written to the journal. Applications still need the appropriate synchronization calls when they require durable writes. See the ext4 documentation.
NTFS: MFT and Attribute Records
NTFS uses the Master File Table (MFT) where each file has one or more records:
MFT Record for large file:
$DATA attribute (non-resident):
Runlist: cluster 1000-1023, then 2048-2063, then 4096-4105
$FILE_NAME attribute:
Name: large_video.avi
Size: 2GB
Small data may fit inside an MFT record; the available space depends on the record’s other attributes. Non-resident data uses runs to describe its cluster ranges.
MFT Structure Details: The MFT is a file containing records. NTFS reserves space near its initial location for possible MFT growth, but the on-disk metadata layout is more involved than a single fixed table. Records contain attributes such as:
- $STANDARD_INFORMATION: Timestamps, permissions, flags
- $FILE_NAME: File name (multiple possible for hard links)
- $DATA: File content (resident within MFT or non-resident with runlist)
- $BITMAP: In the
$MFTfile, this attribute marks which MFT records are in use; the separate$Bitmapfile tracks volume cluster allocation. See Microsoft’s MFT developer notes.
Whether data is resident depends on record space and the file’s attributes. Non-resident data uses runlists; the MFT can grow, and NTFS reserves space for its growth.
NTFS file mappings:
NTFS stores file attributes in MFT records. A non-resident $DATA attribute uses runs to describe where file data is stored. This mapping is different from ext4’s extent tree and from ext2/ext3 block maps. Microsoft’s MFT reference describes how file information may live in MFT entries or in data outside the MFT.
Production Failure Scenarios
Scenario 1: FAT Fragmentation Spiral
Example: A camera that writes many video chunks to a nearly full FAT32 volume may leave each file in several cluster runs. The effect depends on the device and workload; on a spinning disk, scattered runs can mean more seeks, while flash storage has no mechanical seek time.
Why it can happen: FAT records each cluster chain in its allocation table. As free space becomes fragmented, a file may occupy many separate runs. That can slow reads, especially on spinning disks, but FAT does not guarantee that every file will fragment or that a fixed performance drop will occur.
Detection:
For this experiment, use a disposable FAT32 image; E: represents its mounted volume.
# READ-ONLY analysis report for a Windows volume
defrag E: /A /V
# READ-ONLY fragmentation listing for files on FAT/FAT32
chkdsk E:\*.*
Do not add /f or /r when you only want to inspect a volume. Those CHKDSK options repair errors; /r includes /f and may write file-system metadata. Use them only on a disposable test image after backing up any data you need.
Mitigation:
- Larger clusters reduce FAT table size but can waste space in small files; choose at format time for the expected workload.
- If defragmentation is appropriate for the device, use a supported tool after backing up. It changes file layout.
- For video recording, use dedicated file systems (NTFS, ext4)
- Consider exFAT for large files on removable media
Scenario 2: ext4 Inode Exhaustion vs Block Exhaustion
What happened: A mail server stored millions of tiny email files. df showed plenty of disk space, but new files couldn’t be created. The issue: inode exhaustion. All inodes were allocated even though blocks remained.
Detection:
df -i # Check inode usage
# Filesystem Inodes IUsed IFree IUse% Mounted on
# /dev/sda1 100M 99.9M 100K 99% /var/mail
# READ-ONLY: list file-system details
tune2fs -l /dev/test-volume | grep -i inode
# Inode count: 100000000
# Inodes per group: 8192
# Block size: 4096
Mitigation:
- On a new disposable file system only,
mkfs.ext4 -N <inode_count>sets the inode count.mkfs.ext4formats the target and replaces its existing file system. mkfs.ext4 -i <bytes_per_inode>sets the inode ratio when formatting a new disposable file system.- Monitor inode usage with alerting
Scenario 3: Database File Fragmentation
Example: A database can have fragmented files, but slower queries do not prove that allocation layout is the cause. Measure the workload and storage before blaming file-system fragmentation.
Detection:
# READ-ONLY: -n prevents e2fsck from changing the file system
sudo fsck.ext4 -nv /dev/test-volume
# READ-ONLY inspection with debugfs (do not add its -w write option)
sudo debugfs -R "extents -v /path/to/test-database" /dev/test-volume
Mitigation:
-
e4defragchanges file extent placement; use it only on a disposable test volume:sudo e4defrag /path/to/test-database -
For databases, consider
preallocateor use raw partitions -
Choose
noatimemount option to reduce fragmentation -
Leave enough free space for expected growth and file-system overhead
Database File Management: Why Raw I/O?
Databases like PostgreSQL and Oracle often bypass the OS file system entirely, using raw partitions or raw I/O. Understanding why:
Page cache bypass: When you write() through the OS, data goes to the page cache first. The database’s buffer pool is already a cache optimized for database access patterns. Double caching (OS page cache + database buffer pool) wastes RAM and adds CPU overhead.
fsync control: The database needs to control exactly when data is on disk. The OS may delay writes, combine them, or reorder them. For a database transaction to be durable, it needs fsync() — and the database knows exactly what needs syncing and when, without trusting the OS write-back scheduler.
Block size alignment: Database pages (typically 8KB) can be aligned to RAID stripe boundaries with raw I/O, preventing read-modify-write cycles on partial stripes.
Predictable latency: With raw I/O, I/O completion is predictable. With buffered I/O, a write might return “success” while data is still in the page cache awaiting writeback — causing durability surprises on crashes.
Implementation on Linux: posix_fallocate() for preallocation, O_DIRECT flag to bypass the page cache, and fsync() calls after critical transactions. PostgreSQL’s effective_io_concurrency setting tunes parallel I/O for raw device access.
Trade-off Table
| Aspect | Contiguous | Linked | Indexed | ext4 Extents | NTFS MFT |
|---|---|---|---|---|---|
| Sequential Read | Excellent | Good | Good | Excellent | Excellent |
| Random Access | Good | Poor | Excellent | Good | Excellent |
| Fragmentation | High | Low | Low | Low | Moderate |
| Metadata Overhead | Low | Very Low | Medium | Low | Medium |
| Large File Support | Limited | Good | Limited | Excellent | Excellent |
| Crash Recovery | Poor | Poor | Good | Excellent | Excellent |
| Complexity | Low | Low | Medium | High | High |
Implementation Snippet
Simulating Block Allocation with Bitmaps (Python)
#!/usr/bin/env python3
"""Simulate file allocation with block bitmap."""
class FileSystemSimulator:
def __init__(self, total_blocks=1000, block_size=4096):
self.total_blocks = total_blocks
self.block_size = block_size
self.block_bitmap = [0] * total_blocks # 0 = free, 1 = allocated
self.files = {}
def allocate_contiguous(self, filename, size_blocks):
"""Allocate contiguous blocks (First Fit)."""
start = self._find_contiguous_hole(size_blocks)
if start == -1:
return None
# Mark blocks as allocated
for i in range(start, start + size_blocks):
self.block_bitmap[i] = 1
self.files[filename] = {
'start': start,
'length': size_blocks,
'type': 'contiguous'
}
return start
def allocate_linked(self, filename, size_blocks):
"""Allocate using linked list approach."""
free_blocks = self._find_free_blocks(size_blocks)
if len(free_blocks) != size_blocks:
return None
# Allocate and link
for i, block in enumerate(free_blocks):
self.block_bitmap[block] = 1
if i < len(free_blocks) - 1:
# Store next pointer (simplified: store in separate structure)
pass
self.files[filename] = {
'start': free_blocks[0],
'blocks': free_blocks,
'type': 'linked'
}
return free_blocks[0]
def _find_contiguous_hole(self, size_needed):
"""Find first contiguous hole of sufficient size."""
consecutive = 0
start = -1
for i, allocated in enumerate(self.block_bitmap):
if allocated == 0:
if consecutive == 0:
start = i
consecutive += 1
if consecutive >= size_needed:
return start
else:
consecutive = 0
start = -1
return -1
def _find_free_blocks(self, count):
"""Find any free blocks."""
free = []
for i, allocated in enumerate(self.block_bitmap):
if allocated == 0:
free.append(i)
if len(free) >= count:
return free
return []
def defragment(self, filename):
"""Defragment a linked file to contiguous allocation."""
if filename not in self.files or self.files[filename]['type'] != 'linked':
return False
old_blocks = self.files[filename]['blocks']
size = len(old_blocks)
new_start = self._find_contiguous_hole(size)
if new_start == -1:
return False
# Move data (in reality, this is a complex operation)
for i in range(size):
self.block_bitmap[old_blocks[i]] = 0
self.block_bitmap[new_start + i] = 1
self.files[filename] = {
'start': new_start,
'length': size,
'type': 'contiguous'
}
return True
def print_status(self):
"""Display allocation status."""
allocated = sum(self.block_bitmap)
print(f"Total blocks: {self.total_blocks}")
print(f"Allocated: {allocated} ({100*allocated/self.total_blocks:.1f}%)")
print(f"Free: {self.total_blocks - allocated}")
print(f"\nFiles: {len(self.files)}")
for name, info in self.files.items():
print(f" {name}: start={info.get('start', 'N/A')}, type={info['type']}")
if __name__ == "__main__":
fs = FileSystemSimulator(100)
# Test contiguous allocation
fs.allocate_contiguous("video.mp4", 50)
fs.allocate_contiguous("document.txt", 5)
# Test linked allocation
fs.allocate_linked("database.db", 20)
fs.print_status()
Checking File Fragmentation with ext4
#!/bin/bash
# check_fragmentation.sh - Check file fragmentation on ext4
FILE=$1
if [ -z "$FILE" ]; then
echo "Usage: $0 <filename>"
exit 1
fi
DEVICE=$(df "$FILE" | tail -1 | awk '{print $1}')
MOUNT=$(mount | grep "$DEVICE" | awk '{print $3}')
# Use debugfs to check extent info
echo "=== Extent Information for $FILE ==="
debugfs -R "stat $FILE" "$DEVICE" 2>/dev/null | grep -E "Extent|Block|Size"
echo ""
echo "=== Fragmentation Analysis ==="
filefrag "$FILE"
echo ""
echo "=== Disk Layout ==="
ext2ls -l "$DEVICE" "$FILE" 2>/dev/null || echo "ext2ls not available"
Observability Checklist
Monitoring file allocation health:
- df -h: Check available space
- df -i: Check inode usage
- filefrag -v file: Check file fragmentation level
- e4defrag -c /mount/point: Check overall fragmentation percentage
# Comprehensive allocation monitoring script
#!/bin/bash
echo "=== Storage Allocation Report ==="
echo ""
echo "--- Space Usage ---"
df -h | grep -v tmpfs
echo ""
echo "--- Inode Usage ---"
df -i | grep -v tmpfs
echo ""
echo "--- Largest Files in /var (if exists) ---"
if [ -d /var ]; then
du -sh /var/* 2>/dev/null | sort -rh | head -10
fi
echo ""
echo "--- Fragmentation Levels (ext4) ---"
for mount in $(mount | grep ext4 | awk '{print $3}'); do
echo "Checking $mount..."
sudo e4defrag -c "$mount" 2>/dev/null | grep -E "Fragmentation|total"
done
Common Pitfalls / Anti-Patterns
Secure File Deletion
When a file is unlinked, its name is removed and its storage can be released when no references remain. How the file system records that space varies: FAT updates its allocation table, while ext file systems use allocation metadata such as block bitmaps. The old bytes may remain until storage is reused, but recovery depends on the file system, device, and workload.
Delayed allocation can postpone block assignment until writeback; it does not mean that deleted file contents are necessarily sitting in the page cache. File-system metadata and device behavior affect what remains after deletion. NTFS may retain file records for a time, but that alone does not mean the file data can be recovered.
Three approaches actually work here:
-
Overwrite before delete:
shredwrites random data over file contents several times before unlinking. The-uflag removes the file after overwriting. This works on magnetic disks but SSDs are a different story — the wear-leveling controller maps logical blocks to physical cells however it wants, so the cell you think you’re overwriting might not be the one holding your data. -
Full-disk secure deletion:
sfillfrom thesecure-deletepackage writes patterns across all free space on a mount point. Run it periodically on systems handling sensitive data. -
Encryption at rest: This is the most reliable approach for SSDs. If the whole volume is encrypted with dm-crypt/LUKS, throwing away the key makes all the data unreadable instantly. No overwriting needed, and it works uniformly regardless of wear leveling. This is why compliance frameworks increasingly list encryption as the primary data-at-rest control instead of post-deletion overwriting.
# DESTRUCTIVE: overwrites and deletes the named file; use only on a disposable image
shred -vu /path/to/file
# DESTRUCTIVE: writes across free space on the mounted volume
sfill -f /mount/point
# For ext4, encryption (dm-crypt) is more effective than overwriting on SSDs
# WRITES an image file and initializes a new encrypted file system. Use a disposable path.
set -e
IMAGE=$(mktemp /tmp/secure-lab.XXXXXX)
dd if=/dev/urandom of="$IMAGE" bs=1M count=1000
LOOP=$(sudo losetup --find --show "$IMAGE")
MAPPER="secure_lab_$$"
sudo cryptsetup luksFormat "$LOOP"
sudo cryptsetup open "$LOOP" "$MAPPER"
sudo mkfs.ext4 "/dev/mapper/$MAPPER"
sudo cryptsetup close "$MAPPER"
sudo losetup --detach "$LOOP"
rm "$IMAGE"
File System Integrity
File systems do more than just track which blocks belong to which files. They maintain several interlocking mechanisms to keep the structure consistent, and knowing what each does helps you diagnose when things go wrong.
Journaling differs across file systems and configurations. ext2 has no journal by default; ext3 uses a journal, and ext4 commonly does when its journal feature is enabled. ext4’s data mode controls how file data relates to journaled metadata. In the common data=ordered mode, ext4 writes associated file data before committing the metadata that exposes it, but the file data itself is not copied into the journal. A journal helps recover file-system structure after a crash; it is not a guarantee that every recent file write reached storage. See the kernel documentation for ext4 data modes.
Recovery behavior depends on the file system and its configuration. A consistency check may still be needed after an unclean shutdown; its scope and duration vary.
fsck consistency checks look for contradictions: inodes pointing to blocks marked free in the bitmap, directory entries referencing inodes that don’t exist, circular directory links. Running with -n does a read-only check — reported problems aren’t fixed. Run this on an unmounted filesystem to avoid the check itself changing state.
tune2fs intervals set when automatic checks fire. The filesystem increments a mount counter on each mount and a time counter daily. When either hits its limit, the next reboot triggers e2fsck. For servers that barely reboot, the mount-count threshold is more useful than time-based checks.
Block-group metadata in ext2/3/4 includes allocation bitmaps and inode tables, though feature flags can change where structures are placed. Consistency checks look for invalid references and overlapping metadata. Such problems can come from an unclean shutdown, a software fault, or failing hardware.
# READ-ONLY: -n reports errors without repairing the file system
sudo e2fsck -n /dev/test-volume # -n = read-only, no changes
# READ-ONLY: inspect current check settings
sudo tune2fs -l /dev/test-volume | grep -E "Check|state"
# Mount count: 50
# Check interval: 0 days
# MODIFIES file-system settings: run only against a disposable test volume
sudo tune2fs -c 30 /dev/test-volume # Modifies settings on the disposable test file system
sudo tune2fs -i 90d /dev/test-volume # Modifies settings on the disposable test file system
Compliance: Data Localization
Regulations like GDPR, HIPAA, and SOX require proof of where data lives, not just that it exists somewhere in a volume. Allocation metadata becomes your paper trail.
What triggers allocation tracking requirements:
Data sovereignty rules (GDPR Article 44-49) demand proof that files don’t cross jurisdictional boundaries. When a single file spans multiple physical disks across regions, auditors want to see exactly which blocks sit where.
Financial audits under SOX and PCI-DSS need documented proof that specific records were written to known locations and stayed there. Scattered allocation defeats this documentation.
Healthcare regulations under HIPAA require demonstrable retention controls. If defragmentation silently moves a patient record, can you prove it wasn’t altered?
Why allocation methods affect compliance:
Contiguous allocation makes residency proof straightforward. A file’s blocks occupy a known range, and the volume geometry determines the physical location. Linked and indexed allocation scatter blocks, complicating verification.
For regulated workloads, LVM snapshots at key timestamps create verifiable allocation snapshots. ext4’s dir_index tracks which files existed and where. Stricter requirements may need application-level logging that records file-to-block mappings independently of the file system.
# Create timestamped allocation snapshot for audit trail
sudo lvm snapshot /dev/vg0/data_vol -s audit_snap_$(date +%Y%m%d%H%M)
sudo debugfs -R "ls -l /audit_snap_20260519/data" /dev/vg0/audit_snap
# Track allocation patterns with audit tool
auditctl -w /data -p rw -k allocation_tracking
ausearch -k allocation_tracking
High Disk Utilization
As free space shrinks, an allocator has fewer choices and may have a harder time finding long contiguous runs. The effect depends on the file system, storage device, and workload. A file can use multiple extents without a visible performance problem, and there is no single utilization percentage at which fragmentation begins.
Writes can also fail before all bytes are used. For example, a file system with no free inodes cannot create another file even if data blocks remain. Other file systems may keep additional metadata or reserve space for privileged operations.
ext4’s delayed allocation can give its allocator more data to place together before assigning blocks, but it does not prevent fragmentation or guarantee available space. Set monitoring thresholds for the workload and leave room for expected growth.
# Example only: choose a warning threshold for the workload
df -h | awk '{if ($5+0 > 80) print "WARNING: "$0}'
# Set up in /etc/rc.local or cron
# Also use iostat to check for allocation stalls:
iostat -x 1 | awk '$6 ~ /[0-9]+\.[0-9]/ && $6 > 50 {print "High await: "$0}'
Using Wrong Block Size
# Creating file system with wrong block size
# Small block (4KB): Good for many small files, wastes space on large files
# Large block (8KB): Good for large files, wastes inodes for small files
# Choose based on workload:
# Database: larger blocks
# Mail server: smaller blocks (many small files)
# READ-ONLY: inspect current block size
tune2fs -l /dev/test-volume | grep "Block size"
# DESTRUCTIVE: formats the target. Never run on a live system disk.
sudo mkfs.ext4 -b 8192 /dev/test-volume
Ignoring Extent Usage in ext4
ext4 supports extent-based allocation, while ext2 and ext3 traditionally use direct and indirect block pointers. ext4 file mapping depends on the file-system features and the file; the two layouts should not be treated as one universal ext-family model.
Why extents can help. Traditional Unix inodes use direct and indirect pointers; large files may need extra mapping blocks. An extent stores a run of adjacent blocks in one entry. A 10MB file in one contiguous run can fit in one extent; a file split across many runs needs more. Extents reduce mapping metadata when they represent long runs, though the effect on reads also depends on caching and the access pattern.
When files use block pointers. An ext4 file can use the traditional block map when its inode does not have the extents feature. The mapping is a file-system feature, not a consequence of ordinary direct I/O or a particular write command.
How to inspect. debugfs can show a file’s mapping. Use it in read-only mode for inspection. e4defrag can change extent placement, but it does not guarantee a single extent or an optimal layout.
For a large file, block maps and extent trees resolve block locations differently. How much that affects reads depends on access pattern and metadata caching; do not infer query performance from the mapping format alone.
# READ-ONLY inspection with debugfs (do not add its -w write option)
debugfs -R "ex list <path>" /dev/test-volume
# MODIFIES a file attribute: use only for a file on the disposable test image
chattr +e /path/to/test-file
# Check for non-extent files or files with deep extent trees
debugfs -R "stat <path>" /dev/test-volume | grep -i extent
# MODIFIES file extent placement; use only on a disposable test volume
e4defrag /path/to/test-file
Quick Recap Checklist
- Contiguous allocation: Fast but causes fragmentation
- Linked allocation: Flexible but slow random access
- Indexed allocation: Good random access, overhead per file
- FAT: Cluster chains stored in a table; fragmentation effects depend on device and workload
- ext2/3: Block maps; ext4 supports extent trees. Free-space metadata can vary by feature.
- NTFS: MFT with runlists for flexible allocation
- Monitor inode usage (not just space usage)
- Leave headroom; no single utilization threshold prevents fragmentation across every file system and workload
Interview Questions
Contiguous allocation stores each file in consecutive blocks. Performance is excellent for sequential access, but external fragmentation becomes severe. Files can't grow if adjacent blocks are taken.
Linked allocation stores each block with a pointer to the next block. Any free block can be used, eliminating external fragmentation. However, random access requires following the entire chain, which is slow. If any pointer is corrupted, subsequent blocks are lost.
Indexed allocation stores all block pointers in an index block. Random access is fast, and blocks can be anywhere. The limitation is file size (limited by index block entries), and there's overhead (one index block per file).
These textbook models explain trade-offs, not a one-to-one map of modern file systems. FAT stores cluster chains in its allocation table; ext2/3 use block maps; ext4 can use extents; NTFS uses MFT records and data runs. See the comparison table above for the differences.
External fragmentation occurs when free disk space is split into small, non-contiguous chunks after files are created and deleted over time.
Example: You allocate a 10-block file, then delete it. Then you allocate 3 files of 3 blocks each in different areas. Delete two of them. Now you have three free blocks, but they're not adjacent. A new 5-block file can't be stored contiguously.
In contiguous allocation, this is catastrophic—you might have 100MB free but not be able to allocate a 50MB file. In linked allocation, it doesn't matter since blocks don't need to be adjacent. Indexed allocation is also immune since each block is referenced by index, not position.
Solutions: Compaction (moving files to consolidate free space), defragmentation tools, and using file systems that handle fragmentation gracefully.
Traditional Unix inodes use direct and indirect pointers (12 direct pointers, 1 single indirect, 1 double indirect, 1 triple indirect). For a large file, reading block N requires following pointer chains, potentially causing many disk I/Os.
When a file uses extents, each entry describes a range of contiguous blocks. A single contiguous file can use one entry; a fragmented file can use several. The count depends on the file's layout.
Benefits:
- Reduced metadata overhead (fewer entries per file)
- Better sequential performance (fewer seek operations)
- Less fragmentation impact (ranges still work even if scattered)
- Fewer disk reads to access file metadata
This classic puzzle has two common causes:
1. Inode exhaustion: The file system has allocated all inodes. Check with df -i. Reformatting with a different inode count is one option, but mkfs.ext4 -N <count> destroys the target's existing file system; use only with a disposable image.
2. Reserved blocks: ext2/3/4 can reserve blocks for privileged use. Check a disposable test file system with tune2fs -l /dev/test-volume | grep Reserved. Changing the reservation modifies file-system settings; on a disposable test volume, tune2fs -m 0 /dev/test-volume sets it to zero.
3. fragmentation: Not enough contiguous blocks for the allocation request (unlikely with linked/extent-based systems).
Internal fragmentation: Wasted space within allocated units. If you allocate 4KB blocks and have a 1KB file, you waste 3KB. This is unavoidable with block-based allocation—you choose a block size and accept the waste.
External fragmentation: Free space split into non-contiguous chunks. After many allocations and deletions, you might have 100MB total free space but no single hole large enough for a 50MB file. This affects contiguous allocation methods but not linked or indexed.
Trade-offs:
- Small block size: Less internal fragmentation, more external
- Large block size: Less external fragmentation, more internal
- Linked allocation: No external fragmentation, but pointer overhead
- Extent-based: Reduces external fragmentation while keeping internal waste low
NTFS stores file information in Master File Table (MFT) records. A file can use more than one record, and directory indexes and other metadata have their own structures. Records contain attributes such as:
- $STANDARD_INFORMATION: Timestamps, permissions
- $FILE_NAME: File name (multiple possible for hard links)
- $DATA: File content (resident within MFT or non-resident with runlist)
Small data may be resident in an MFT record; whether it fits depends on the record's available space and its other attributes. Non-resident data uses runs to describe its cluster ranges. The MFT can grow, and NTFS reserves space for its growth.
These records and runs are NTFS-specific metadata structures. They should not be treated as the same thing as ext inodes, block maps, or ext4 extent trees.
FAT12 and FAT16 limit directory entries to 16-bit root directory cluster counts. For FAT16 with typical cluster sizes, this limits root directories to 65,536 entries—but practical limits often enforced 512 entries per directory for compatibility.
FAT32 removed this root directory limitation (root can be anywhere, like any other directory), but FAT12/FAT16 root directories were fixed-size at format time.
Implications for modern use:
- Old floppy disk FAT12 root directories held ~112 files maximum
- Early USB drives with FAT12/16 would fail to create more than a few hundred files in the root directory
- Modern SD cards and USB drives use FAT32 with essentially unlimited directory entries
Traditional Unix inodes use block pointers:
- 12 direct pointers
- 1 single indirect (points to block of pointers)
- 1 double indirect (points to block of single indirect blocks)
- 1 triple indirect
A 1GB file with 4KB blocks needs 262,144 data blocks. With block pointers, that's one inode + 256 indirect block entries + etc.
Extent-based allocation stores contiguous ranges: {start: 4096, length: 65536} means "blocks 4096-69631, 65536 blocks (256MB)". A 1GB file might need just 4 extent entries instead of thousands of block pointers.
Benefits: Smaller metadata, fewer disk reads to access file, better sequential performance, less fragmentation impact.
ext2/3/4 commonly reserve 5% of blocks for privileged use by default; the value is configurable:
- Root can log in and repair the system even if users fill the disk
- File system operations (like fsck) have working space
- Critical daemons don't fail when disk is "full"
For large data partitions (e.g., 10TB file server), 5% is 500GB—significant waste. You can reduce or eliminate the reservation:
# View current reservation
tune2fs -l /dev/test-volume | grep Reserved
MODIFIES file-system settings: run only on the disposable test volume
Change reservation to 1%
tune2fs -m 1 /dev/test-volume
Disable entirely (not recommended for root)
tune2fs -m 0 /dev/test-volume
For non-root partitions where you manage recovery, reducing reservation saves substantial space.
Contiguous allocation with consolidation: When a file is deleted and an adjacent block becomes free, the file system merges the free blocks. This helps reduce external fragmentation but still requires allocation to find a large enough contiguous hole.
Extent-based allocation: Stores files as contiguous ranges called extents — a start block and a length. A file can span multiple extents if it grows beyond the initial allocation, but each extent is internally contiguous. This reduces the problem of finding huge contiguous holes while keeping most file access sequential.
Key difference: Contiguous allocation assigns one block range per file; extent allocation allows multiple block ranges per file but prefers to keep each range contiguous.
ext4 can represent a contiguous range with one extent entry, while a fragmented file may need several. Extents can reduce mapping metadata compared with listing every block, but the count depends on the file's layout.
ext2/3/4 organize storage into block groups. A traditional group has structures such as:
- Block bitmap (free block tracking)
- Inode bitmap (free inode tracking)
- Inode table (inode storage for the group)
- Data blocks
The allocator tries to keep related data together:
- New files get inodes in the same block group as their parent directory
- Data blocks for a file stay within the same block group when possible
- Linked files (hard links) prefer the same block group
This improves performance by ensuring related data is physically close on disk—reducing seek time during sequential access. The allocator uses heuristics and preallocation hints to maintain locality.
ext2/3/4 use block bitmaps to track free space; the exact metadata layout depends on file-system features. A bitmap uses bits to represent block allocation. To allocate:
- Scan the bitmap for a free block
- Mark it as allocated (set bit to 1)
- Return the block number
Advantages over linked allocation:
- O(1) free space check: No need to traverse chains to find free space
- Fast allocation: Bitmap operations are hardware-optimized
- No pointer corruption: Linked allocation's pointer chain isn't used; if a block is lost, the bitmap still shows it as allocated
- Easy to find contiguous blocks: Bitmap scanning finds contiguous free ranges for extent allocation
- Simple recovery: If a pointer is lost, the bitmap shows the actual allocation state
The inode bitmap works similarly for inode allocation. Both bitmaps are stored in each block group, enabling fast local allocation without scanning the entire partition.
FAT: A central table where each entry corresponds to a cluster. File cluster chains are stored in this table:
- FAT[cluster] = next cluster in file chain (or EOF)
- Directory entries store the starting cluster only
- Operating systems cache FAT data; the amount depends on volume size and implementation
Inode-based file systems (such as ext2/3/4 and XFS): each file has an inode with metadata and file-to-block mapping information. NTFS has a different design based on MFT records and attributes, so it is not inode-based.
- Directory entries map names to inode numbers
- File mapping can use pointers, extents, or another file-system-specific structure
- Free-space tracking is separate from the inode's file mapping
Key differences:
- FAT stores cluster-chain links in its allocation table; inode-based systems store mapping metadata with each inode
- Inodes do not all store simple block-pointer arrays: ext4, for example, can use extent trees
- Free-space indexes and caching policies vary by file system
- Hard links are supported by many inode-based systems; FAT does not use inode numbers for directory entries
ext2 has no journal by default, while ext3 adds journaled metadata recovery. A consistency check can still be needed after a crash, and its duration depends on the volume and damage; avoid assuming every check scans every block.
Journal details depend on the file system and its configuration. In ext3 and ext4, the journal records metadata updates; ext4's data mode controls whether file data is also journaled or ordered relative to metadata. For the common data=ordered mode, file data is written before the metadata commit, but it is not itself stored in the journal.
A simplified metadata-journal sequence is:
- Before making a metadata change, write it to the journal first
- Once the journal write is on disk (synchronized), apply the change to the actual file system
- After the change is complete, mark the journal entry as committed
After an unclean shutdown, the file system can replay committed journal transactions. This often avoids a full consistency scan, but recovery time depends on the file system and the work left to recover.
ext4 supports journal checksums and several data modes. These features affect recovery behavior, but journaling does not promise that application data from every recent write is durable.
Small block size (e.g., 4KB):
- Pros: Less internal fragmentation, efficient for small files, more flexibility in allocation
- Cons: More metadata overhead (more block pointers needed per file), worse sequential read performance (more seeks), larger bitmaps
Large block size (e.g., 8KB, 16KB):
- Pros: Better sequential read performance (fewer blocks to seek between), smaller metadata (fewer pointers), better for large files
- Cons: More internal fragmentation (wasted space in last block), inefficient for many small files, wasted i-nodes
Most file systems use 4KB as the default because it balances well for general workloads. Database workloads often use larger blocks to match their record sizes. The optimal choice depends on the typical file size in your workload.
ext4 can map file data with extents. Btrfs uses copy-on-write (COW) metadata trees and extent-based data allocation; these designs differ in more than the textbook block-pointer model:
extent-based vs block-pointer:
- ext4: inode stores pointers to data blocks (traditional)
- Btrfs: inode stores a root node of a B-tree; all block pointers are in the tree
COW semantics:
- When you modify a block, Btrfs writes a new copy rather than overwriting in place
- The old block remains until no references point to it
- This enables snapshots (reference counting on blocks), checksums (verify old data wasn't corrupted), and easy RAID integration
Allocation differences:
- Btrfs uses chunks (extents of the underlying devices) rather than fixed block groups
- Dynamic allocation: chunks are allocated from free space and can be relocated
- Integrated RAID: allocation metadata and data are checksummed and mirrored across devices
Preallocation reserves disk space for a file before data is written. Instead of allocating blocks as data arrives, the file system reserves a range of blocks upfront.
Use cases:
- Databases: Preallocate data files to avoid fragmentation as the database grows. Use
posix_fallocate()on Linux to reserve space without writing zeros. - Video recording: Reserve space for a fixed-length recording so the file doesn't fragment mid-write.
- Preventing disk full errors: Allocate space for known-size files before writing begins.
Implementation in ext4:
- extents are pre-allocated for the file
- Blocks are marked as allocated in the bitmap
- No data is written until the application writes—blocks remain sparse (read as zeros)
Caveat: Preallocating and then not using the space wastes capacity. Also, some older file systems (FAT) don't support true preallocation and may not reserve the blocks.
ext4 allocation approach:
- Block groups of fixed size (~128MB each)
- allocator tries to keep files and their metadata in the same block group
- Uses bitmap-based allocation within block groups
XFS allocation approach:
- Allocation groups (AGs): XFS partitions the filesystem into allocation groups (typically 1GB each), each with its own bitmap and inode allocator
- B+tree bitmaps: XFS uses B+trees for free space tracking (not simple bitmaps), enabling faster allocation in large filesystems
- Delayed allocation: Like ext4, XFS batches allocations and delays physical block assignment until writeback, reducing fragmentation
- Stripe-aware allocation: XFS can align allocations to RAID stripe boundaries for better performance
XFS handles parallel allocation better because multiple threads can allocate from different AGs simultaneously without contention. This makes XFS excellent for large files and high-throughput workloads.
Hard link: Multiple directory entries (dentries) pointing to the same inode. The file's data blocks are referenced by one inode, but multiple names in different directories point to it.
- Only works within the same file system (must have same inode number space)
- Cannot link to directories (would create cycles in directory tree)
- Deleting a hard link removes one name; the file persists until all hard links are removed
- No extra disk space for the link itself (just a directory entry)
Symbolic link: A special file containing a path string. The symlink's inode points to data blocks containing the target path.
- Can cross file systems and mount points
- Can link to directories
- Deleting the symlink does not affect the target
- Deleting the target leaves a "dangling" symlink
- Uses a small amount of space for the path string
From an allocation perspective: hard links share the same inode and data blocks; symbolic links allocate separate data blocks for the path content.
Fragmentation on ext4 occurs when a file's extents become scattered or when the last extent can't be extended due to adjacent allocated blocks.
Detecting fragmentation:
filefrag -v file: Shows extent list for a filee4defrag -c /mount: Shows overall fragmentation percentage
e4defrag modifies allocation: it can move file extents to reduce fragmentation when space allows. It writes data and changes metadata, so use it only on a disposable test volume. It does not guarantee one extent or an optimal layout.
Leave enough free space for expected growth. No single utilization threshold prevents fragmentation across every file system and workload.
Further Reading
- ext4 extent-tree documentation: Linux kernel documentation for ext4’s on-disk extent tree.
- NTFS Master File Table documentation: Microsoft’s overview of MFT entries and where NTFS stores file information.
- FAT File System Specification — Microsoft: Official FAT specification including FAT12, FAT16, FAT32 cluster chain formats and media descriptor bytes.
- PostgreSQL — Raw Devices and O_DIRECT: PostgreSQL documentation on bypassing the OS file system for raw I/O and fsync behavior control.
- e4defrag man page — Linux: Manual for ext4 online defragmentation tool, including fragmentation detection and extent reorganization.
- e2fsck man page — Linux: Documents the read-only
-noption and repair behavior. - Tune2fs man page — Linux: Documentation for ext2/3/4 filesystem tuning, including inode reservation and automatic check intervals.
- Btrfs Architecture — Kernel.org: Comparison of Btrfs copy-on-write allocation against traditional block-pointer approaches in ext4.
- XFS Allocation Groups — Oracle: Technical comparison of XFS allocation groups versus ext4 block groups and their implications for parallel allocation.
- File System Abstraction: /blog/technical/file-system-abstraction/ — foundational concepts of how file systems present a unified interface to applications
- Directory Implementation: /blog/technical/directory-implementation/ — how directory entries organize file metadata and name-to-inode mappings
Conclusion
File allocation methods determine how disk space gets assigned to files, with direct consequences for performance and fragmentation. Contiguous allocation delivers excellent sequential throughput but suffers from external fragmentation that eventually requires compaction. Linked allocation eliminates fragmentation but destroys random access performance. Indexed allocation balances both, though with per-file overhead.
These textbook models explain the trade-offs, but they are not a complete taxonomy of modern file systems. FAT keeps cluster-chain links in an allocation table; ext2 and ext3 map files with block pointers; ext4 can use extents; NTFS stores file attributes in MFT records and maps non-resident data with runs. Each file system also manages free space and recovery metadata separately.
For a real volume, check its file-system type and enabled features. Then consult that file system’s documentation for its mapping, free-space tracking, and recovery behavior.
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.
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.
Boolean Logic & Gates
Understanding AND, OR, NOT gates and how they combine into arithmetic logic units — the building blocks of every processor.