Smokes your problems, coughs fresh air.

Tag: losetup

Growing a qcow2 image file

First, convert it to raw:

qemu-img convert system.qcow2 -O raw system.raw

Then use DD to append a zero all the way at the end of the new file. It will automatically create a hole in the file:

# Make sure the seek value is bigger than the file size, otherwise it would put a zero somewhere in the middle of the file.
dd if=/dev/zero of=temp.raw bs=1 count=1 seek=100G

Then resize the partition. I did that by binding the image to a loop device:

losetup /dev/loop0 system.raw

Then you can use fdisk on /dev/loop0 to alter the partition table. parted didn’t want to resize my file sytem because it had a journal (argh…) so I just used fdisk and made sure that the start of the partition was the same.

Then you detach the loop device and attach the partition:

losetup -d /dev/loop0
# 32256 is 63*512. 63 is the start sector, which fdisk can tell you (with the u option)
losetup -o 32256 /dev/loop0 system.raw

Then I used resize2fs on /dev/loop0 and detached it again.

Mounting partititions residing inside a disk image

When you’ve read a disk with dd or ddrescue into an image file, one of the things you want to do is mount the partitions inside it. But, how does one do that? The answer is using losetup, with a bit of knowledge of partition offsets.

First, you have to map the disk image to a loopback device:

# losetup /dev/loop/0 disk_image_file

Then use fdisk to print the partition table, displaying offsets in sectors:

# fdisk -lu /dev/loop/0

For my disk, that results in:

Disk /dev/sda: 250.0 GB, 250059350016 bytes
255 heads, 63 sectors/track, 30401 cylinders, total 488397168 sectors
Units = sectors of 1 * 512 = 512 bytes
Disk identifier: 0x00000000

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *          63   482415884   241207911   fd  Linux raid autodetect
/dev/sda2       482415885   488392064     2988090   fd  Linux raid autodetect

You can see that the first partition begins at sector 63. Now we’re going to setup a new loop device, with the proper offset. A disk sector is 512 bytes long, so an offset of 63 sectors is 32256 bytes. Therefore, you setup the first partition with this command:

# losetup -o 32256 /dev/loop/1 disk_image_file

Then you can mount that loop device:

# mount /dev/loop/1 /mnt/mountpoint

© 2024 BigSmoke

Theme by Anders NorenUp ↑