detach_device: Wait until the kernel frees the loop device

On systems employing the "lazy loop device removal",
commit a1ecac3b0656 ("loop: Make explicit loop device destruction lazy"),
ioctl(LOOP_CLR_FD) may return 0 when the loop device is in use,
for example by udev.

Therefore, there is a chance that a quick attach/detach may not
give udev enough time to complete, like this:

open("file.img", O_RDWR)           = 4
ioctl(3, LOOP_SET_FD, 0x4)         = 0
close(3)                           = 0
close(4)                           = 0
open("/dev/loop0", O_RDONLY)       = 3
ioctl(3, LOOP_CLR_FD, 0)           = 0
close(3)                           = 0
open("/dev/loop0", O_RDWR)         = 3
open("file.img", O_RDWR)           = 4
ioctl(3, LOOP_SET_FD, 0x4)         = -1 EBUSY (Device or resource busy)

So let's wait until the kernel frees the loop device, i.e.
when ioctl(LOOP_CLR_FD) starts failing with ENXIO.

Signed-off-by: Stanislav Kholmanskikh <stanislav.kholmanskikh@oracle.com>
Acked-by: Cyril Hrubis <chrubis@suse.cz>
1 file changed