Defragmenting an XFS File System

Use the xfs_fsr command to defragment whole XFS file systems or individual files within an XFS file system.

Fragmentation occurs when a file is stored on the disk in a non-contiguous manner. Fragmentation can be caused by several factors, including:

  • Frequent Creation and Deletion of Small Files: When small files are created and deleted often, the free space on the disk becomes scattered across many locations. This dispersed free space can cause new or large files to be stored in non-contiguous chunks.
  • High Levels of File Modification and Growth: As files are changed and grow, their data might not fit into the originally allocated space. This can lead to fragmentation as the file's data is spread across different parts of the disk.
  • Copy-on-Write Operations: Features that take advantage of copy-on-write functionality can contribute to fragmentation. For example, when a file is reflinked and its contents are changed, the extents can be split or altered, which can further fragment the file system.

Fragmentation can impact performance resulting in slower access time and increased reflink creation time.

Defragmentation of the file system is managed using the xfs_fsr command. For more information, see the xfs_fsr(8) manual page.

  • To defragment an individual file, use the following command to specify the name of the file as the argument to xfs_fsr.
    sudo xfs_fsr file_path
  • To defragment all mounted XFS file systems, run the xfs_fsr command without specifying a path.
    sudo xfs_fsr
    Running the xfs_fsr command without any options defragments all the mounted and writeable XFS file systems that are listed in /etc/mtab. The defragmentation process runs for two hours and defragments the top 10 percent of files with the greatest number of extents. After two hours, the command records its progress in the /var/tmp/.fsrlast_xfs file. If you run the command again, the process is resumed from that point.