KVM: virtualize a single partition

A nice feature in XEN that I miss in KVM is the ability to use a single partition as a disk image. In XEN you can do
disk = [ 'file:/dev/vg0/img_root,sda1,r' ]

and you can also safely mount /dev/vg0/img_root when the virtual machine is not powered on.
With KVM you're out of luck, or at least my googling returned lots of questions and no solutions.

Well, there is a not so hard way of working around the issue.

For the example I'll use ttylinux. Get the binary package from the download page. Download, unpack, you'll get a file called rootfs which is the root file system, and which we'll be booting kvm from.


  • A host kernel with loop device and device mapper (linear) support

  • A guest kernel with virtio support

Prepare the partition table

We need an empty file to hold the partition table. You can create one with
dd if=/dev/zero of=disk.pt count=63

Next, create the partition table itself:
sfdisk -C999 -uS disk.pt <<EOF
63,(size of rootfs/512),L

Now disk.pt has a partition table that defines a single partition starting after sector 63 on the disk.

Prepare the loop devices

Next, we have to bind the files to loop devices because dmsetup can only operate on block devices. So, run the following and remember the output.
$ sudo losetup -f -s disk.pt
$ sudo losetup -f -s rootfs

Now you can check what the major and minor numbers of the loop devices in the output above are:
$ ls -l /dev/loop[01]
brw-r----- 1 root disk 7, 0 2008-07-17 00:28 /dev/loop0
brw-r----- 1 root disk 7, 1 2008-07-17 00:28 /dev/loop1

In our example the major number is 7, and minors are 0 and 1.

Create the device mapper device

This is the last step. First you need to create a table file for the device mapper.
$ cat > dm-table <<EOF
0 63 linear 7:0 0
63 [size of rootfs / 512] linear 7:1 0

Then create the device mapper device itself and maybe give yourself ownership to the device
$ sudo dmsetup create full_disk dm-table
$ sudo chown $USER /dev/mapper/full_disk

Boot a KVM virtual machine using the mapper device

And you are ready to boot. A sample command would be
$ kvm -m 128M \
-drive file=/dev/mapper/full_disk,if=virtio,format=raw,boot=on \
-kernel /boot/bzImage -append root=/dev/vda1 -curses


Popular posts from this blog

Installing Gentoo with full disk encryption

ADSL Router Model CT-5367 user and pass (VIVACOM)

FreeIPA cluster with containers