Tue Sep 28 10:12:54 CEST 2010

qemu: bootable linux image from scratch

The key elements are dd, parted and grub.

1. Create the image.  We use a 4GB raw disk image, fits on a DVD.

zni:/qemu# dd if=/dev/zero of=linux.img seek=4000 obs=1MB count=0

2. Format and mount the partiton

Use parted:
(parted) mklabel msdos
(parted) mkpart primary ext2 0 4000
(parted) mkfs 1 ext2

3. Populate filesystem

I use plosetup[1] to create loop devices at the proper offset in the
hd image so they can be mounted.  Then you can use debootstrap or any
old filesystem to populate the partition.

zni:/qemu# plosetup linux.img
I: plosetup: partition 1 of linux.img will become /dev/loop0...
zni:/qemu# losetup /dev/loop0
/dev/loop0: [fe03]:12756230 (/qemu/linux.img), offset 32256

4. Install grub

The only remaining part is to install grub in the MBR.  Assume there
is a /boot/grub dir in the filesystem installed in step 3.  See also

Be careful with this as to not mess up your host system!

zni:/qemu# grub --device-map=/dev/null
grub> device (hd0) linux.img
grub> root (hd0,0)
grub> setup (hd0)
grub> quit

( It's also possible to use the loop devices instead of disk image,
but you need to make sure that the loop device mentioned on the first
line has an associated partition device i.e. postfixed with "1". )

[1] http://zwizwa.be/darcs/pool/bin/plosetup
[2] http://blog.quinthar.com/2008/07/building-1gb-bootable-qemu-image-using.html