Create raw disk image

From Ability
Jump to: navigation, search


This page describes how to create a raw disk image for qemu installating grub bootloader + kernel + filesystem.

Create disk

# dd if=/dev/zero of=hda.img bs=1M count=1014


# qemu-img create -f raw hda.img 1G

Create partitions

$ fdisk hda.img <<< '
$ > o
$ > n
$ > p
$ > 1
$ >
$ >
$ > a
$ > 1
$ > w'

Make the partitions available as loopback devices. The rest of the instructions will assume that the loopback device created for hda.img is /dev/loop0, but it will be a higher number if you already have set up loop devices.

# sudo losetup -f --show hda.img


Find major and minor number for the loop device and check disk size

# ls -l /dev/loop0
brw-rw---- 1 root disk 7, 0 2009-07-18 11:27 /dev/loop0

# ls -l hda.img
-rw-r--r-- 1 paolodoz paolodoz 1063256064 Apr  8 10:48 hda.img

Take size and divide by 512 (byte per sector) and using create an appropriate link using dmsetup

echo '0 2076672 linear 7:0 0' | sudo dmsetup create hda

Use kpartx to create device-mapper nodes for the partitions on the disk image

# sudo kpartx -a /dev/mapper/hda
# ls -l /dev/mapper/hda*
lrwxrwxrwx 1 root root 7 Apr  8 09:37 /dev/mapper/hda -> ../dm-2
lrwxrwxrwx 1 root root 7 Apr  8 09:22 /dev/mapper/hda1 -> ../dm-6

Beware: GRUB2 will not install correctly to the disk image unless the partition loopback device is created through the device mapper (using kpartx).

Format and installation

Format the only partition you created with previous steps

# sudo mkfs.ext4 /dev/mapper/hda1

Create a temp folder and extract the rootfs and kernel and its modules

# mkdir /tmp/rootfs
# mount /dev/mapper/hda1 /tmp/rootfs
# cd /tmp/rootfs
# tar -xf /tmp/gemini-image-qemux86-20140330142316.rootfs.tar.bz2
# tar -xf /tmp/modules--3.10.11+git0+dad2b7e1ce_e1aa804148-r2-qemux86-20140330142316.tgz
# cp /tmp/bzImage--3.10.11+git0+dad2b7e1ce_e1aa804148-r2-qemux86-20140330142316.bin boot/bzImage

Create the file needed by GRUB2 for its installation. Use the physical device created by dmsetup and not its link to /dev/mapper/hda

# sudo mkdir /tmp/rootfs/boot/grub
# echo '(hd0) /dev/dm-2 ' | sudo tee /tmp/rootfs/boot/grub/

Install grub

Install grub on the fake disk, using the physical device dm-2 in this case

# sudo grub-install --root-directory=/tmp/roots/ /dev/dm-2

This step should be not necessary. Edit and change from /dev/dm-2 to /dev/mapper/hda

Final step, copy /boot/grub/grub.cfg from your pc on the disk image under boot/grub/grub.cfg and edit it according to your virtual system conf (for example remove unused GRUB menu entries and point to right bzImage and root device in the kernel commandline

Unmount the disk

# sudo umount /tmp/rootfs

Start qemu

# qemu -m 256 -hda hda.img


  • Create disk image [1]
  • Install grub on a disk [2]
  • Install grub2 on raw disk image [3]