When it comes to file-based block devices, the major difficulty is the extremely bad kernel API. The only fully safe way to use loop devices is to use LOOP_CONFIGURE with LO_FLAGS_AUTOCLEAR and hold a file descriptor open to the device until another piece of code (either another userspace program or the kernel) has grabbed a reference to it. Everything else risks either using a freed loop device (that might now be attached to a different file) or risks leaking them on unclean exit. The only exception is if one can make certain assumptions, such as no other program freeing loop devices for the file in question. This is a reasonable assumption for Qubes dom0, but neither for Qubes domU nor for Xen dom0 in general. Nevertheless, this is effectively what the current block script does: if I understand the code correctly, there is a race where badly timed calls to losetup by another process could result in the block script freeing the wrong loop device. Worse, writes to XenStore only cause Linux to take a reference to the device at some unspecified point in the future, rather than synchronously. It takes a major and minor number, which means we need to hold a reference to the relevant loop device ourselves. FreeBSD solves this by having XenStore include a path to the device and/or regular file, but on Linux this leads to awkward issues with namespaces. Instead, I recommend that Linux gain an ioctl-based interface in the future, which takes a file descriptor to the device to use. The kernel would then do the writes itself. Thankfully, not all hope is lost, even with the current kernel API. We can use sd_pid_notify_with_fds to stash the file descriptors in PID 1, which will never exit. We can give those file descriptors a name, so that we know which is which if we are restarted. And we can close devices that we know are not in use by any VMs. The cache will allow us to avoid duplicating devices, which is actually quite important ― QubesOS doesn’t want each qube to have a separate file descriptor for its kernel, for example. Initially, I recommend focusing on handle the case where the process using libxl is not restarted. That is the simpler case, by far. I suggest starting by just setting up a loop device prior to attaching it, and destroying it when the device is detached. Caching can be added as the next step. -- Demi Marie Obenour she/her/hers QubesOS Developer, Invisible Things Lab