How to run SSD trim fstrim on btrfs when mounted multiple subvolumes

btrfsssdtrim

I am using btrfs and have mounted several subvolumes (but not btrfs root). It resides on SSD partition, so I would like to use fstrim. Should I call fstrim on each mountpoint (corresponding with different subvolume each) ? Or do I need to have btrfs root mounted and run fstrim on this mountpoint?

Best Answer

fstrim should run on "mountpoint", so you need to have devices mounted. But you only need to call it once per physical device. So if 2 mountpoints are on the same device with btrfs, you only need to call fstrim on one mountpoint.

Finding this answer: https://forums.gentoo.org/viewtopic-t-1003980-view-previous.html?sid=a51dab49787e5b7b6c2fa4aa7c1a5e44

I do it like this :

#!/bin/sh
LOG=/var/log/fstrim.log
echo "===" $(date -R) "===" >> $LOG
for d in $(lsblk -o MOUNTPOINT,FSTYPE | grep -E 'btrfs' | awk '{print $1}'); do
    fstrim -v $d 2>&1 >> $LOG
done

This script is placed in /etc/cron.weekly/fstrim and set executable:

sudo chmod +x /etc/cron.weekly/fstrim

The script makes use of lsblk that list block devices. I'm searching "btrfs" devices and I launch fstrim on it.

Related Question