Btrfs/Space Cache

From Forza's ramblings

Btrfs Space Cache[edit | edit source]

A Copy-on-Write (CoW) filesystem never overwrites existing data. Instead it writes new data on a new location. Once the data is written it updates its metadata to point to the newly written data. This means if there is a crash or power outage, the filesystem will remain intact. Either all the old data is still intact or all of the new data.

Because of CoW, it is very important that Btrfs keeps track on where there is free space to write new data. Btrfs solves this by creating a cache of all the free space on the filesystem.

There are two versions of this space cache, The original v1 and then the new modern v2. For now, the default is still V1.

Free Space Tree a.k.a "Space Cache v2"[edit | edit source]

On very large filesystems (many terabytes) or with certain workloads, the performance of the v1 space cache may degrade drastically. This is why the new v2 implementation was created. It adds a new B-tree called the free space tree.

While the default is still to use v1. This is mostly for legacy reasons. Myself and others recommend to always use v2. V2 was introduced in 13 March 2016, so it is over four years old already! Luckily there is ongoing work to switch to v2 by default.

Switch Space Cache versions[edit | edit source]

To change to space_cache v2 you have to unmount the filesystem and mount it with the space_cache=v2 mount option.

umount /mnt/btrfs
mount /mnt/btrfs -o clear_cache,space_cache=v2

If you want to change your root filesystem you have to boot with a USB stick to be able to mount the filesystem with the above options. It is also possible to add rw,clear_cache,space_cache=v2 to your kernel command line. Check with your distribution on how to do that.