How to find which images belong to which /dev/loop

disk-imageloop-device

I work a lot with imaged drives, meaning a do a dd-copy of the drive in question and then work on the image instead of the drive itself.

For most work, I use kpartx to map the drive's partitions to a device under /dev/mapper/. What I'm wondering here is if there's a way to find which of the mapping belong to which image.

Consider this:

root@vyvyan:/tmp# kpartx -a -v Image1 
add map loop1p1 (254:4): 0 10240 linear /dev/loop1 2048
add map loop1p2 (254:5): 0 10240 linear /dev/loop1 12288
add map loop1p3 (254:6): 0 52848 linear /dev/loop1 22528
root@vyvyan:/tmp# kpartx -a -v Image2
add map loop2p1 (254:7): 0 33508 linear /dev/loop2 2048
add map loop2p2 (254:8): 0 39820 linear /dev/loop2 35556

Now, let's say I forget which image went to which mapping. Is there a way to let kpartx – or the kernel, or anything else – tell me which image goes where?

EDIT Also, if I accidentally rm the image-file while kpartx has added the mappings, how do you remove the mappings? kpartx wants the actual image to be present.

Best Answer

losetup (the command normally used to set them up) will tell you:

$ /sbin/losetup --list
NAME       SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE
/dev/loop0         0      0         0  0 /var/tmp/jigdo/debian-7.6.0-amd64-CD-1.iso

Note that with older versions you may hat to use use -a instead of --list, and this outputs in a different and now deprecated format.

The information comes from /sys:

$ cat /sys/class/block/loop0/loop/backing_file 
/var/tmp/jigdo/debian-7.6.0-amd64-CD-1.iso

Another, possibly more portable, option is to get it from udisks:

$ udisksctl info -b /dev/loop0
/org/freedesktop/UDisks2/block_devices/loop0:
⋮
  org.freedesktop.UDisks2.Loop:
    Autoclear:          false
    BackingFile:        /var/tmp/jigdo/debian-7.6.0-amd64-CD-1.iso
    SetupByUID:         1000
⋮

losetup will also happily remove them for you, using the -d option. That just requires the loop device as a parameter; it doesn't care about the backing file/device.

Related Question