Compacting a Linux Hyper-V, Virtual PC 2004 or 2007 Dynamic VHD/VHDX file

System Requirements:

  • Virtual PC 2004, SP1
  • Virtual PC 2007, SP1
  • Hyper-V

The Problem:

The Windows Integration components ISO contains a tool for performing a VHD pre-compact. Once completed, this tool allows you to shut down a VHD and compact it to reclaim disk space previously used by the VM which has actually marked as being free space by the VHD FAT/MFT.

More Info

As Linux operating systems do not formally include integration components for Virtual PC, there is no standard Microsoft way to pre-compact the VHD. The fundamental process behind pre-compaction is however simple: write 0’s all sectors of the hard drive that the FAT/MFT claim to be free (available) space.

Once you have done this, the Virtual PC/Hyper-V management UI will flush the contents of the VHD into a new VHD, skipping any 0’d sectors from the migration process, thus reducing the size of the VHD as seen by the hypervisors host partition.

The Fix

I’ve used two different methods to achieve Linux pre-compaction.

Note: This was written against the steps that need to be performed on Debian. Other distributions may require additional steps to install software.

Open Terminal and execute the following:

su
cd /
cat /dev/zero > zero.dat ; sync ; sleep 1 ; sync ; rm -f zero.dat

Although simpler and not requring any software installation, the compaction rate achieved using the method was a little hit and miss, often resulting in a large VHD file after the compaction process.

A higher success rate was achieved by installing a small app package called secure-delete. To install and use this issue the following commands from a shell.

su
apt-get install secure-delete
sfill -f -z /

While I have realised better results from this, the process takes far longer as the secure-delete packages sfill is in fact performing an “insecure” erase on the hard drive, not simple zeroing sectors. This means that it actually passes over the disk more than once, with the concluding pass being the zero pass. The cumulative effect of the multiple passes means that it takes far longer to complete. The last time that I ran with this method, a 16 GB Debian 6 VHD was reduced by 1.2 GB. Small change given the size of today’s hard drive, but a significant percentage of the 16GB disk none the less.

Please also note that there are other elements to the secure-delete package, including tools to wipe the SWAP partition (which may further reduce the size of the VHD if used) as well as tools to perform a full, secure disk erase (not just empty sector erasing). So do ensure that you use this package carefully.