How to TRIM the whole partition in FreeBSD to save space in VirtualBox

I am running FreeBSD 11 amd64 in VirtualBox 5.1.12.

I have enabled TRIM in VirtualBox (nonrotational="true" discard="true"):

    <StorageControllers>
      <StorageController name="SCSI" type="LsiLogic" PortCount="16" useHostIOCache="true" Bootable="true">
        <AttachedDevice nonrotational="true" discard="true" type="HardDisk" hotpluggable="false" port="0" device="0">
          <Image uuid="{44ac75b7-286c-4178-b8e3-db597418908f}"/>
        </AttachedDevice>
        <AttachedDevice passthrough="false" type="DVD" hotpluggable="false" port="1" device="0"/>
      </StorageController>
    </StorageControllers>

And in FreeBSD:

>tunefs -p /dev/da0p3
...
tunefs: trim: (-t)                enabled
...

It is working fine, the .VDI image grows and shrinks as I add or delete files inside the VM.

But I enabled TRIM after installing FreeBSD, and I am guessing there are blocks on the filesystem which are unused since before I enabled TRIM.

So my question is - is there a command to TRIM the whole partition so that all of unused blocks are released?


You can use fsck_ffs -E:

Clear unallocated blocks, notifying the underlying device that they are not used and that their contents may be discarded. This is useful for filesystems which have been mounted on systems without TRIM support, or with TRIM support disabled, as well as filesystems which have been copied from one device to another.

See the -E and -t flags of newfs(8), and the -t flag of tunefs(8).

It’ll also check the filesystem, so the performance will be a lot worse than fstrim on Linux.