TRIM Support on KVM Virtual Machines

James Young · May 31, 2016

Messing with KVM as a replacement for my Microserver setup at home.  With KVM, you can define a thin-provisioned VM image file (a qcow2 file), which is a sparse file on the filesystem.  You can then configure the guest O/S so that TRIM support works, and it can then unmap unused blocks by the guest FS and have those blocks get unmapped the whole way down the stack (released from the sparse file, and ultimately trimmed from the underlying SSD if there is one).

The best bit?  This works for Windows and Linux guests, in the same way.

First up, adjust your machine so that it uses SCSI for the QCOW files you want to enable TRIM support on.  This may require some fudging with Windows (more on this one later).

Then, edit the XML for your VM definition with “virsh edit DOMAINNAME”.  Find the disk definition, and make the changes that are bolded here;

<disk type='file' device='disk'>
 <driver name='qemu' type='qcow2' discard='unmap'/>
 <source file='/var/lib/libvirt/images/example.qcow2'/>
 <backingStore/>
 <target dev='sda' bus='scsi'/>
 <alias name='scsi0-0-0-0'/>
 <address type='drive' controller='0' bus='0' target='0' unit='0'/>
 </disk>

Also make sure that your SCSI controller is of type ‘virtio-scsi’;

<controller type='scsi' index='0' model='virtio-scsi'>
 <alias name='scsi0'/>
 <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0'/>
 </controller>

Notably, only SCSI is able to pass the commands necessary to support TRIM properly.  Boot your VM, and you should now be able to run fstrim, or on Windows defrag should show the drive as a thin provisioned volume that can be trimmed (for Windows versions that support TRIM).

Now, for Windows.  Assuming you have already installed all the drivers, the easiest way to ensure that the kernel is loading the SCSI driver when you go and change the type (which otherwise results in a blue screen), temporarily add a second, small disk using the type you’re changing C drive to.  Change C drive and boot, and it should boot fine with that type.  You can then remove the small disk.

Good luck!

Twitter, Facebook