Utility to TRIM unallocated space on drive
If you have a recent enough version of util-linux
, it contains the tool blkdiscard
which is able to TRIM entire devices, or ranges within a device using --offset
and --length
options.
Please note: blkdiscard
is dangerous, if you let it TRIM the wrong regions, your data is gone!
So you can figure out the unpartitioned (free) regions of your partition table and then TRIM them using this tool. For msdos
and gpt
partitions, parted
provides the free regions like so:
# parted -m /dev/sda unit b print free | grep ':free;'
1:17408B:1048575B:1031168B:free;
1:64022904832B:64023240191B:335360B:free;
Add a loop to it...
while IFS=: read -ra FREE
do
echo blkdiscard --offset ${FREE[1]%%B} --length ${FREE[3]%%B} /dev/sda
done < <(parted -m /dev/sda unit b print free | grep ':free;')
which prints
blkdiscard --offset 17408 --length 1031168 /dev/sda
blkdiscard --offset 64022904832 --length 335360 /dev/sda
Verify that this output is correct for you, add additional options if you like (verbose?), and finally remove the echo
so it will be actually executed, and you should be set.
The second command of that example actually fails because the length is too small - it may be worth checking inside the loop, ignore regions smaller than 1MB as they're unlikely to be successfully trimmed.
If you are using LVM instead of partitions, you can create a LV for the unoccupied space and trim that:
lvcreate -l100%FREE -n blkdiscard SSD-VG
blkdiscard -v /dev/SSD-VG/blkdiscard
lvremove SSD-VG/blkdiscard
If you set issue_discards = 1
in your lvm.conf
, you can skip the blkdiscard
call as LVM will issue the TRIM on lvremove
by itself.
hdparm --trim-sector-ranges
can trim a range. The man page warns to use it, so you better be sure you got the right range and syntax.
I think sending a trim for all data outside a partition would be dangerous, as there is some hidden data there sometimes like bootloader code or second partition tables. You'd need to know exaclty, which areas outside of partitions are really unused.