loop devices

Thu 14 January 2016
Deutsch: Hondaknoten, als Auge für Lassoschlin...

Loop device (Photo credit: Wikipedia)

Loop devices are used to acces any file as if it were a block device such as a disk. On GNU/linux, the canonical command to interact with loop devices is losetup . To list the next usable loop device : losetup -f

disk image loop mount

The most spread usage of loop devices is mounting a file such as an iso or a img file as if it were a disk.

newloop = $( losetup -f )
losetup $newloop /path/to/iso
mount $newloop /mnt

freebsd md

On UNIX, loop device interaction is different. On freeBSD (since freeBSD 5) you may use mdconfig . To mount an iso file:

unit=$( mdconfig -t vnode -f /path/to/iso ) mount -t cd9660 /dev/$unit /mnt # -t mandatory

swap file over any filesystem

swap can be either into a dedicated partition or into a file. In the second case, the file cannot reside anywhere. I understand (but I may be mistaken) that the kernel will try to access the swap file without using VFS . Thus, the number of filesystem a swap can reside on is limited and does not include network filesystem . One way to avoid this limitation is to create a loop device. The kernel will access a block device (the loop device). You may expect a dramatic fall in performance (due to number of abstraction layers).

Donnot forget that swap can host cached information in an unencrypted way (such as RAM , but in a more persistent way).

create file

First of all, you may create a file. The most obvious way is to use dd:

dd if=/dev/zero of=/path/to/file bs=1M count=512

But one can also use truncate:

truncate -s 512M /path/to/file

Do not forget to format it as a swap partition ( man mkswap ) if you use it a partition or to check permissions if you use it as a swapfile; and to activate this swap ( man swapon ).

mount file

This section is greatly inspired by this post .

swapfile=$(losetup -f)
truncate -s 8G /path/to/file       # create 8G sparse swap file
losetup $swapfile /path/to/file    # mount file to loop
mkswap $swapfile
swapon $swapfile

Related articles (or not):

Category: how to Tagged: FAQs Help and Tutorials Linux tools Unix how to unix-like