Enable TRIM with LVM and LUKS on ArchLinux

Fri 10 October 2014
By momo

To allow linux to issue discards through lvm and luks a few steps need to be performed.
I'm running the following setup:

sda
|__sda1 /boot
|__sda2
    |___ LUKS
         |_____ LVM
                |___ /
                |___ /home
                |___ ...

Therefore the discards need to be issued through the filesystem, the LVM and the LUKS down to the SSD. Let's start with the ext4 filesystem:
We need to append the discard option to the other filesystem options like so:

#/etc/fstab
UUID=40c66951-6148-4816-b8c7-090f7978f8a0       /               ext4            rw,relatime,data=ordered,discard        0 1

Do this for every mountpoint you have on your SSD.

Next up is the LVM:

#/etc/lvm/lvm.conf
[...]
issue_discards = 1

Now we have to add a line to /etc/crypttab:

#/etc/crypttab
<name>     /dev/sda2   none            luks,discard

Now we have to update our initrd: mkinitcpio -p linux

And last but not least my good old friend grub2:

#/etc/default/grub
GRUB_CMDLINE_LINUX_DEFAULT="cryptdevice=/dev/sda2:cryptvg:allow-discards root=/dev/mapper/pool0-root root_trim=yes"

Now rewrite grubs configuration: grub-mkconfig -o /boot/grub/grub.cfg
That's it, now you'll have to reboot for all changes to take effect.

You can test this by executing fstrim -v /. If it doesn't throw an error you're good.

Now we want to trim our filesystem every week, we therefore have to add the file /etc/cron.weekly/fstrim:

#!/bin/sh
#
# To find which FS support trim, we check that DISC-MAX (discard max bytes)
# is great than zero. Check discard_max_bytes documentation at
# https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
#
for fs in $(lsblk -o MOUNTPOINT,DISC-MAX,FSTYPE | grep -E '^/.* [1-9]+.* ' | awk '{print $1}'); do
    fstrim "$fs"
done

And make it executable using chmod +x /etc/cron.weekly/fstrim.
That's it, for a more technical writeup visit neutrino.es. Big thanks to their author.

Pages

Categories

Tags