Wednesday, 11 August 2010

loop devices, device mapper and kpartx

Recently I copied a hard disk image onto a backup drive using dd and later on needed to mount the third partition from this image. Usually I figure out the partition offset and mount using mount -oloop,offset=xxxx but I just could not be bothered this time around to figure out the offsets especially as I have several partitions in the image. Instead, I used the following runes:

1. Associate a loop device with the drive image:

losetup --show --find image-of-drive.img

..the --show option prints out the name of the loop device being used. In my case it was /dev/loop0

2. Create a device mapper device associated with the loop device:

echo "0 `blockdev --getsize /dev/loop0` linear /dev/loop0 0" | dmsetup create sdX

..this will create /dev/mapper/sdX

3. Use kpartx to create device maps from the partition tables on the mapper device:

kpartx -a /dev/mapper/sdX

4. And lo and behold this creates device maps over the detected partition segments. You can then mount the partitions as usual, e.g. partition #3:

mount /dev/mapper/sdX3 /mnt

..I should really put this now into a bash script for next time I need this...


  1. Neat. This sounds like it might be a more elegant solution to the problem I solved here:

  2. You can call the kpartx on the loop device.

    So it will create the dev file for your partitions:
    [root@server ~]# kpartx -a /dev/loop0
    [root@server ~]# ll /dev/mapper/loop0p1
    lrwxrwxrwx 1 root root 7 Mar 11 19:01 /dev/mapper/loop0p1 -> ../dm-4