Defragmenting and Compressing a Btrfs File System

You can defragment the file system to increase I/O performance. You can also compress a Btrfs file system to increase its effective capacity.

You can defragment the file system or any files and directories within the file system by running the btrfs filesystem defragment command. You can automatically run defragmentation on the file system by setting the autodefrag option when you mount it. However, note that automatic defragmentation isn't recommended for large databases or for images of virtual machines.

Note:

Defragmenting a file or a subvolume with a copy-on-write copy breaks the link between the file and its copy. For example, if you defragment a subvolume that has a snapshot, the disk usage by the subvolume and its snapshot increases because the snapshot is no longer a copy-on-write image of the subvolume.

You can apply compression during a defragmentation, but compression can also be set as a mount option so that it's applied to the whole file system, or can be set as a property on a subvolume so that it's applied to a particular subvolume.
Three different compression types are supported:
  • zlib: General-purpose and widely used compression with balanced speed and compression ratio.
  • lzo: Rapid compression and decompression with a lower compression ratio than other options.
  • zstd: High compression ratio and rapid compression and decompression.
You can enable compression at any point and only the new writes are compressed unless compression is applied when defragmentation is run.
  • To defragment a Btrfs file system, run:
    sudo btrfs filesystem defragment /mnt
  • To mount a Btrfs file system with automatic defragmentation enabled, run:
    sudo mount -o autodefrag /dev/sdb /mnt
  • To apply compression to a Btrfs file system during a defragmentation operation, run:
    sudo btrfs filesystem defragment -czlib /mnt
  • To apply compression to a subvolume by setting a compression property on the subvolume, use the btrfs property set command.
    sudo btrfs property set /mnt/subvol1 compression zstd
  • To apply compression when mounting the file system, run:
    sudo mount -o compress=lzo /dev/sdb /mnt