systemd service to trim free SSD cells at boot

I mount all ext4 partitions on my solid-state disks with the discard option; this tells the filesystem to use SSD-specific low-level TRIM operations instead of normal erases (which are essentially just block re-writes). As I use my SSDs quite heavily, I like to perform batch discards every so often as well.

Here’s a systemd service which will batch discard all unused cells on an SSD at boot time, /usr/lib/systemd/system/fstrim.service:

[Unit]
Description=Trim free cells on the SSD
After=local-fs.target

[Service]
ExecStart=/sbin/fstrim /home/aorth/android
Type=oneshot

[Install]
WantedBy=multi-user.target

Don’t forget to install fstrim and edit the service to point to the directory where your SSD is mounted!

Enable the service:

[root@smalls ~]# systemctl enable fstrim.service
ln -s '/usr/lib/systemd/system/fstrim.service' '/etc/systemd/system/multi-user.target.wants/fstrim.service'

After a restart, check the service status:

[root@smalls ~]# systemctl status fstrim
fstrim.service - Trim free cells on the SSD
          Loaded: loaded (/usr/lib/systemd/system/fstrim.service; enabled)
          Active: inactive (dead) since Sun 2013-04-07 18:13:33 EAT; 4h 34min ago
         Process: 302 ExecStart=/sbin/fstrim /home/aorth/android (code=exited, status=0/SUCCESS)

Apr 07 18:13:33 smalls systemd[1]: Started Trim free cells on the SSD.

This helps keep my SSD nice and fast. Also, it was a learning experience for me in writing systemd service files.

3 thoughts on “systemd service to trim free SSD cells at boot

  1. Using the mount option and doing it manually is useless. Even more on modern SSDs with a good garbage collection. Snakeoil like in Wondows.

    1. Yeah, you’re right; running it manually when your filesystem is mounted using discard is pointless. I think the reason I like doing it manually from time to time is to see the amount of data discarded… there’s something gratifying about it. But yes, it’s pointless.

Leave a Reply

Your email address will not be published. Required fields are marked *