Mounting and using KVM raw image files on the host system

Boldly stolen from David Champion at the University of Chicago, and archived for personal reference. All credits to that page.

kpartx will scan a block device — e.g., your /dev/loop0 — and create device-mapped specials under /dev/mapper for the partitions. Then you can address individual partitions. (N.B.: When done, before you can losetup -d the greater block device, you have to delete the device-mapped specials!)

Here’s a bit of terminal action to illustrate:

# First map the loop device to your KVM disk image. Note that some older versions of losetup don't have the --show option, and will output the used loop device upon being given -v only
$ losetup -fv --show /kvm/watercooler.mwt2.org.img 
Loop device is /dev/loop0

# No partitions!    
$ ls /dev/loop0* /dev/mapper/loop0*
ls: /dev/mapper/loop0*: No such file or directory
/dev/loop0

# Use kpartx -a to discover and device-map the partitions.
$ kpartx -av /dev/loop0
add map loop0p1 : 0 204800 linear /dev/loop0 2048
add map loop0p2 : 0 16930816 linear /dev/loop0 206848
add map loop0p3 : 0 16416768 linear /dev/loop0 17137664

# Look, partitions.
$ ls /dev/loop0* /dev/mapper/loop0*
/dev/loop0  /dev/mapper/loop0p1  /dev/mapper/loop0p2  /dev/mapper/loop0p3

# Fiddle with /dev/loop0p1 et al.

# Try to un-loop the file.  You can't, because kpartx's partition devices are still mapped.
$ losetup -d /dev/loop0
ioctl: LOOP_CLR_FD: Device or resource busy

# Ask kpartx to unmap.
$ kpartx -dv /dev/loop0
del devmap : loop0p1
del devmap : loop0p2
del devmap : loop0p3

# Now you can un-loop.
$ losetup -d /dev/loop0

Leave a Reply

Your email address will not be published. Required fields are marked *