User Tools

Site Tools


linux:btrfs:trim

Guide to enable TRIM on a Btrfs filesystem

Enable TRIM on your Btrfs filesystem, either through continuous or periodic TRIM operations.

Check Your SSD

Ensure your SSD is recognized and has Btrfs installed. You can check connected drives using:

lsblk

Mount the Btrfs Filesystem with TRIM Option

You can enable TRIM either during mounting or set it up for periodic trimming.


Option A: Enable TRIM During Mounting

Mount with the discard Option: Replace /dev/sdX1 and /mnt/mybtrfs with your actual device identifier and mount point.

sudo mount -o discard /dev/sdX1 /mnt/mybtrfs

Add to /etc/fstab: To make the change persistent across reboots, add the following line to your /etc/fstab file:

/dev/sdX1 /mnt/mybtrfs btrfs defaults,discard 0 0

Option B: Schedule Periodic TRIM

In this guide I will schedule the trim-script with systemd, you could instead run the script periodically using a simple cronjob, with some tradeoffs, explained in this table:

Feature cron systemd timer
Ease of setup โœ”๏ธ Easier โŒ More involved
Logging โŒ Manual (unless set) โœ”๏ธ Via journalctl
Missed job handling โŒ Not handled โœ”๏ธ Persistent=true
Service dependencies โŒ None โœ”๏ธ Fully supported
Portability โœ”๏ธ Highly portable โŒ Linux only (with systemd)

Unmount the Filesystem (if needed): If you want to remove the discard option and use periodic TRIM instead:

sudo umount /mnt/mybtrfs

Re-mount without discard: Mount the filesystem normally:

sudo mount /dev/sdX1 /mnt/mybtrfs

Create a TRIM Script: Create a simple script for periodic TRIM. For example, create a file named btrfs-trim.sh:

sudo vim /usr/local/bin/btrfs-trim.sh

Add the following lines:

#!/bin/bash
btrfs filesystem df /mnt/hd1
sudo btrfs device stats /mnt/hd1
sudo fstrim /mnt/hd1

Make the Script Executable:

sudo chmod +x /usr/local/bin/btrfs-trim.sh

Schedule the Script with systemd: Create a systemd service and timer to run the script regularly.

Create the Service File:

sudo vim /etc/systemd/system/btrfs-trim.service

Add the following:

[Unit]
Description=Run Btrfs TRIM

[Service]
Type=oneshot
ExecStart=/usr/local/bin/btrfs-trim.sh

Create the Timer File:

sudo vim /etc/systemd/system/btrfs-trim.timer

Add the following:

[Unit]
Description=Run Btrfs TRIM weekly

[Timer]
OnCalendar=weekly
Persistent=true

[Install]
WantedBy=timers.target

Enable and Start the Timer:

sudo systemctl enable btrfs-trim.timer
sudo systemctl start btrfs-trim.timer

Verify TRIM

You can check if TRIM is functioning by monitoring your SSDโ€™s performance and usage over time. You can also look at the output of the TRIM command you scheduled to see if it executes without errors.


snippet.cpp
by:
โ––     โ–˜โ––โ––
โ–Œ โ–Œโ–Œโ–›โ–˜โ–Œโ–™โ–Œ
โ–™โ––โ–™โ–Œโ–™โ––โ–Œ โ–Œ
 
written: a while ago. Edited: June 8 2025
linux/btrfs/trim.txt ยท Last modified: by luci4