What to do when the Linux loop module is mysteriously busy

Created: 21 Jun 2013

I am writing down what to do when this happens, because it’s happened to me twice now and if it happens a third time I’d like to be able to find a webpage that explains exactly what to do.

I was trying to mount a DVD image in the form of an ISO file on a Linux system and I got this error message:

 $ sudo mount /var/lib/tftpboot/ubuntu/lucid-amd64/iso
 mount: could not find any free loop device

This indicates that the maximum number of loop devices has been used. By default 10 are allowed.

I needed to tell the Linux loop kernel module, that’s used for loopback filesystem mounts to allow more loopback devices. To do this, I created a file called /etc/modprobe.d/loop.conf with these contents:

options loop max_loop=20

This file is only read when the module is loaded by modprobe, so that means I first need to unload it. Before I could unload it I needed to un-mount all the filesystems that were mounted via loopback devices and print what was mounted so that I could put everything back. Obviously, I use a fancy pants one-liner for this, here broken into multiple lines for legibility.

for mnt in $(mount | grep 'loop=/dev/loop' | awk '{print $3};')
do sudo umount "$mnt"; echo "sudo mount ${mnt}"
done

This prints a list of commands I will copy and paste later to remount everything.

Now I can unload the loop module from the kernel:

$ sudo rmmod loop
ERROR: Module loop is in use
$ lsmod | grep loop
loop                   21508  4 

Apparently it’s still in use. But by what? I’ve unmounted everything that uses it. Finding out what is using it is the part that took me a while to work out, since losetup isn’t obviously the name of a utility to mamage loop devices and doesn’t appear when you type ‘loop[Tab]’.

$ sudo losetup -a
/dev/loop4: [fe01]:1744904 (/var/lib/scalefactory/iso/ubuntu-10.04.2-server-amd64.iso)
/dev/loop7: [fe01]:319793 (/var/lib/scalefactory/iso/ubuntu-12.04.2-server-amd64.iso)

Some loop devices have been left behind after filesystems were unmounted. So I deleted them. As far as I can tell this is safe; it warns you if the devices are actually mounted.

$ sudo losetup -d /dev/loop4
$ sudo losetup -d /dev/loop7

And this allowed me to unload the loop kernel module:

$ sudo rmmod loop

Then I pasted the commands to remount all the filesystems that we un-mounted and mounted the filesystem I was originally prevented from mounting due to the limit on the number of loop devices.

And finally I reflected on the fact that, had I known that two loop devices weren’t actually being used by mounted filesystems, I could have simply deleted those loop devices and mounted the filesystem, without needing to unload the kernel module.