I have some image files that I often use for cross-compilation work via chroot. My usual deal is to create a loop device with it, mount its main partition, bind mount /dev, /proc, /sys, and maybe /etc/resolv.conf (I don't actually know what else is necessary for a proper chroot, but this seems to work fine), and chroot in to do work. All this seems to work, but then the loop device fails to actually detach via losetup -d $LOOP_DEVICE after unmounting everything. Instead, the AUTOCLEAR flag seems to get set, and that's about it. I tried to delete the underlying file (which succeeded), in an attempt to trick it into letting go, but all that did was add (deleted) to the end of the corresponding line in the output of losetup -d $LOOP_DEVICE. For a more concrete example, here's approximately what I did.

# Pretend this never fails
LOOP_DEVICE=$(sudo losetup --partscan --file --show $SOME_IMAGE_FILE)

# Mount the desired partition for chrooting

# Recursive bind mount and rslave, so it can be easily unmounted
for DIRECTORY in dev proc sys
    sudo mount --rbind /$DIRECTORY $MOUNT_POINT/$DIRECTORY
    sudo mount --make-rslave $MOUNT_POINT/$DIRECTORY

# Do what needs to be done in there

# Clean up, unmount, and detach
sudo umount -R $MOUNT_POINT
sudo losetup -d $LOOP_DEVICE

# At this point, $LOOP_DEVICE still shows up, for some reason,
# even if $SOME_IMAGE_FILE is deleted
sudo losetup -l

I've also tried unmounting things individually, in case umount -R does not properly unmount everything, but that didn't resolve the issue. To reproduce this, perhaps try using a Raspberry Pi image or something, and running the above commands. Beware that it's just a rough list of commands to illustrate what I did, and is not really a script.

I've looked around for answers to this, but they're either old (e.g. one points to a kernel bug from a decade ago), unanswered, vague, or not as close to my case. I can't tell whether it's something wrong with what I'm doing that would cause the loop device to be undetachable, whether it really is a kernel bug that hasn't been fixed in a decade, or whether this question really is a duplicate of something I missed in my search. For context, I'm on Ubuntu 18.04 on kernel 5.4.0, but I think this happened to me on Ubuntu 20.04 on kernel 5.8.0, too.



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.