Hero Image

How to easily make qemu qcow2 thin provisoned images smaller w/o the dd zero trick with virsh

As an ongoing saga of how to reduce the size of my qcow images smaller, I found a very nice solution. Basically you create a 'scsi' type disk, and then a virtio-scsi with discard turned on as 'zero'. This causes the fstrim utility to be able to reclaim used space due to the design of virsh. Its much easer than virtio-sparsify, or doing the old 'dd' trick. Just delete all the things you want to, and then an fstrim -a -v. VOILA the image is ready for the next step, (after shutting down the vm) for a qemu-img convert. Online is possible, but I don't because I transfer things with rsync, and don't want to deal with the differences.

fstrim -av

The hardest part is editing the configuration for an existing VM (which is what I did.) first edit the controller in virt-manager:

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

The next step is to edit the disk:

<disk type="file" device="disk">
  <driver name="qemu" type="qcow2" discard="unmap"/>
  <source file="/path/to/your/qcow2/file.qcow2" index="2"/>
  <target dev="vda" bus="scsi"/>
  <alias name="scsi0-0-0-0"/>
  <address type="drive" controller="0" bus="0" target="0" unit="0"/>

This has to be done while the vm is OFF. The FSTRIM operation in fact worked (only on a 'copy' of the original via a qemu-img convert command,) reducing the new copy by a factor of what I deleted from the original disk. I thought I would document this, since not many