FStrim for dir driver CTs and VMs

How to fstrim on CTs and VMs using the dir driver regularly?

I can manually stop a VM and fstrim it via

  1. kpartx -av root.img (see which one of the listed partitions is the one you want to trim)
  2. mount /dev/mapper/loopXpX /mnt/vm-disk
  3. fstrim -v /mnt/vm-disk
  4. kpartx -d root.img (delete the loop device)

but how do I fstrim CTs and VMs on schedule?

For containers, it’s not relevant as it just needs to happen once per filesystem, so the regular fstrim from the host will take care of it.

For VMs, usually you’d just want the VM itself to run fstrim on schedule inside of the VM.

It’s usually considered bad practice to map and mount a VM’s disk on the host as an untrusted guest could have altered the VM’s disk to exploit a kernel/filesystem bug when mounted on the host.