TRIM on Debian Jessie with LVM on dm-crypt/LUKS

I installed Debian Jessie on my Thinkpad T410 with a new SSD last month. To prevent disk performance degradation, I had to enable the TRIM functionality. TRIM tells the SSD that it can clean clusters that are unalocated by the file system.

When using simple configuration with only one file system directly on disk, it is very easy to enable TRIM. One can manually execute the fstrim command on the desired partition. It's also possible to allow the file system to do it automatically by adding the discard option to /etc/fstab, provided that the file system supports the option. Most modern file systems like ext4, btrfs and xfs support this option.

My setup is a bit less straightforward. I use dm-crypt/LUKS to encrypt my partitions with a passphrase. On top of that, I use LVM on the dm-crypt volume to unlock all the partitions using only one passphrase provided at boot time. The command fstrim fails to pass the TRIM function to the disk since LVM and dm-crypt do not relay it automatically. However, it is easy to adjust such a configuration.

First, we need to make dm-crypt 'trim aware' by modifying /etc/crypttab:

sda5_crypt /dev/sda5 none luks,discard

Then we do the same for LVM by modifying the devices section of the file /etc/lvm/lvm.conf:

devices {
    [...]
    issue_discards = 1
}

Finally, for the normal partitions like /, /home and swap, you need to modify /etc/fstab:

# <file system> <mount point>   <type>  <options>   <dump> <pass>
/dev/mapper/ssd-root    /       ext4    relatime,errors=remount-ro,discard  0 1
/dev/mapper/ssd-home    /home   ext4    relatime,discard                    0 2
/dev/mapper/ssd-swap    none    swap    sw,discard                          0 0

After doing these modifications, you need to create a new initramfs that will allow the new options for the encrypted volume.

Update-initramfs -u -k $(uname -r)

After a reboot, you can verify that everything is working correctly by manually executing the TRIM command (fstrim) on one of your partitions.

References :