Filesystem defragmentation
Reorganizing a file's storage extents to reduce fragmentation while preserving its logical contents.
In a copy-on-write filesystem a rewrite of file data creates a new copy that can land far from the rest of the file, so fragmentation is inherent to the design. The cost is highest on rotating disks because the heads must move to distant locations, while on devices without seeks the remaining benefit is less metadata for tracking scattered extents. Btrfs defragmentation does not preserve extent sharing with reflink copies or snapshots, so data-space use can increase. [1]
The btrfs-progs v6.16 command requires kernel 2.6.33 or newer. Its -t value is an advisory target extent size with a kernel default of 256 KiB, and larger extents are skipped. The recursive -r option does not descend into nested subvolumes, mount points or directory symlinks. The -f option flushes each file before the next one to limit dirty data, and without it the accumulated writes can end in ENOSPC when reservations for the new copies cannot be made. [2]
The ext4 tool e4defrag works on extent-based files, and with -c it only reports a fragmentation score computed from the current and ideal extent counts without changing the file. Its manual gives 131072 KB as the maximum extent size at a 4 KB block size and excludes swap files, files in lost+found and files mapped through indirect blocks. [4]
Relations
- related
- File extent, Free-space fragmentation, Reflink, Copy-on-write (storage), Transparent filesystem compression, Btrfs filesystem du, Btrfs balance
Advantages
- Files in active use can be defragmented safely because the copy goes through the page cache, which handles synchronization. [1, 4]
Limitations
- Copying through the page cache can slow both the defragmenter and the application through contention for memory and disk bandwidth. [4]
- When free space is itself fragmented or scarce, the requested layout may not be reached. [2, 4]
Citations
- Btrfs-progs v6.16: Defragmentation, extent sharing and compression
- Btrfs-progs v6.16: filesystem defragment, traversal, extent targets and reservations
- e2fsprogs v1.47.2: e4defrag(8) manual page, options and notes
Further reading
Sources & caveats
- Btrfs behavior follows pinned btrfs-progs v6.16 documentation, and ext4 behavior follows the e4defrag manual page from e2fsprogs v1.47.2.
- Other filesystems can have different sharing and traversal contracts.
- The kernel versions, the 256 KiB default and the 131072 KB extent limit are quoted from the documentation and were not measured.