kvm | qemu | qcow2 dynamic/sparse disk allocation problem | shrink sparse qcow2 disks howto

In some recent qemu versions there is a problem while creating sparse disks using the virt-manager.
Normally the qcow2 format always allocates space dynamically (sparse), but some qemu versions fail at this, they create disks with full expected size.

Solution:
The easy way:

Backup your old qcow2 image. Then do

apt-get install libguestfs-tools
virt-sparsify kvm_backup/debian_mssql.qcow2 kvm_images/debian_mssql.qcow2

Shrinking existing images:

 # mv disk.qcow2 disk.qcow2.orig
 # qemu-img convert -O qcow2 disk.qcow2.orig disk.qcow2

This process removes blocks filled with zeros.
if you wanna shrink some old qcow2’s after cleaning up the mess inside your guest system (removing old files etc), you have to overwrite your abandones blocks with zeros. For windows use https://docs.microsoft.com/en-us/sysinternals/downloads/sdelete.

  ...> sdelete.exe -z c:

For linux: Inside your guest create a large file filled with zeros and remove it afterwards.

 # dd if=/dev/zero of=zero-file bs=1M count=40000
 # rm zero-file

This is slow and will bloat your drive to the maximum. Better way for daredevils:

kvm | linux | shrink sparse disk using zerofree

Then convert your qcow2 image again, like shown above.

Check all with

 # qemu-img info disk.qcow2

As a tough guy you create your future disks in console:

 # qemu-img create -f qcow2 /var/lib/libvirt/images/disk.qcow2 10G

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.