Filesystems – Why Use a Loop Device?

block-devicefilesystemsloop-devicemount

I previously used to create image files using dd, set up a filesystem on them using mkfsand mount them to access them as mounted partitions. Later on, I have seen on the internet that many examples use losetup beforehand to make a loop device entry under /dev, and then mount it. I could not tell why one would practically need an image file to behave as a loop device and have its own /dev entry while the same behaviour can be obtained without all the hassle.

Summary: In a real-life scenario, why do we need a /dev/loopXentry to be present at all, when we can just mount the fs image without it? What's the use of a loop device?

Best Answer

Mounts, typically, must be done on block devices. The loop driver puts a block device front-end onto your data file.

If you do a loop mount without losetup then the OS does one in the background.

eg

$ dd if=/dev/zero of=/tmp/foo bs=1M count=100
100+0 records in
100+0 records out
104857600 bytes (105 MB) copied, 0.0798775 s, 1.3 GB/s
$ mke2fs /tmp/foo
mke2fs 1.42.9 (28-Dec-2013)
....


$ losetup    
$ mount -o loop /tmp/foo /mnt1    
$ losetup
NAME       SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE
/dev/loop0         0      0         1  0 /tmp/foo
$ umount /mnt1
$ losetup
$ 

You may need to call losetup directly if your file image has embedded partitions in it.

eg if I have this image:

$ fdisk -l /tmp/foo2      

Disk /tmp/foo2: 104 MB, 104857600 bytes, 204800 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x1f25ff39

     Device Boot      Start         End      Blocks   Id  System
/tmp/foo2p1            2048      204799      101376   83  Linux

I can't mount that directly

$ mount -o loop /tmp/foo2 /mnt1
mount: /dev/loop0 is write-protected, mounting read-only
mount: wrong fs type, bad option, bad superblock on /dev/loop0,
       missing codepage or helper program, or other error

But if I use losetup and kpartx then I can access the partitions:

$ losetup -f /tmp/foo2
$ losetup
NAME       SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE
/dev/loop0         0      0         0  0 /tmp/foo2
$ kpartx -a /dev/loop0
$ mount /dev/mapper/loop0p1 /mnt1
$
Related Question