1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #if HAVE_VALGRIND_MEMCHECK_H
4 #include <valgrind/memcheck.h>
9 #include <linux/blkpg.h>
11 #include <linux/loop.h>
13 #include <sys/ioctl.h>
16 #include "sd-device.h"
18 #include "alloc-util.h"
19 #include "blockdev-util.h"
20 #include "device-util.h"
21 #include "devnum-util.h"
23 #include "errno-util.h"
26 #include "loop-util.h"
27 #include "missing_loop.h"
28 #include "parse-util.h"
29 #include "random-util.h"
30 #include "stat-util.h"
31 #include "stdio-util.h"
32 #include "string-util.h"
33 #include "tmpfile-util.h"
35 static void cleanup_clear_loop_close(int *fd
) {
39 (void) ioctl(*fd
, LOOP_CLR_FD
);
40 (void) safe_close(*fd
);
43 static int loop_is_bound(int fd
) {
44 struct loop_info64 info
;
48 if (ioctl(fd
, LOOP_GET_STATUS64
, &info
) < 0) {
50 return false; /* not bound! */
55 return true; /* bound! */
58 static int get_current_uevent_seqnum(uint64_t *ret
) {
59 _cleanup_free_
char *p
= NULL
;
62 r
= read_full_virtual_file("/sys/kernel/uevent_seqnum", &p
, NULL
);
64 return log_debug_errno(r
, "Failed to read current uevent sequence number: %m");
66 r
= safe_atou64(strstrip(p
), ret
);
68 return log_debug_errno(r
, "Failed to parse current uevent sequence number: %s", p
);
73 static int device_has_block_children(sd_device
*d
) {
74 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
75 const char *main_ss
, *main_dt
;
80 /* Checks if the specified device currently has block device children (i.e. partition block
83 r
= sd_device_get_subsystem(d
, &main_ss
);
87 if (!streq(main_ss
, "block"))
90 r
= sd_device_get_devtype(d
, &main_dt
);
94 if (!streq(main_dt
, "disk")) /* Refuse invocation on partition block device, insist on "whole" device */
97 r
= sd_device_enumerator_new(&e
);
101 r
= sd_device_enumerator_allow_uninitialized(e
);
105 r
= sd_device_enumerator_add_match_parent(e
, d
);
109 r
= sd_device_enumerator_add_match_subsystem(e
, "block", /* match = */ true);
113 r
= sd_device_enumerator_add_match_property(e
, "DEVTYPE", "partition");
117 return !!sd_device_enumerator_get_device_first(e
);
120 static int loop_configure(
123 const struct loop_config
*c
,
124 bool *try_loop_configure
,
125 uint64_t *ret_seqnum_not_before
,
126 usec_t
*ret_timestamp_not_before
) {
128 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
129 _cleanup_free_
char *sysname
= NULL
;
130 _cleanup_close_
int lock_fd
= -1;
131 struct loop_info64 info_copy
;
139 assert(try_loop_configure
);
141 if (asprintf(&sysname
, "loop%i", nr
) < 0)
144 r
= sd_device_new_from_subsystem_sysname(&d
, "block", sysname
);
148 /* Let's lock the device before we do anything. We take the BSD lock on a second, separately opened
149 * fd for the device. udev after all watches for close() events (specifically IN_CLOSE_WRITE) on
150 * block devices to reprobe them, hence by having a separate fd we will later close() we can ensure
151 * we trigger udev after everything is done. If we'd lock our own fd instead and keep it open for a
152 * long time udev would possibly never run on it again, even though the fd is unlocked, simply
153 * because we never close() it. It also has the nice benefit we can use the _cleanup_close_ logic to
154 * automatically release the lock, after we are done. */
155 lock_fd
= fd_reopen(fd
, O_RDWR
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
158 if (flock(lock_fd
, LOCK_EX
) < 0)
161 /* Let's see if the device is really detached, i.e. currently has no associated partition block
162 * devices. On various kernels (such as 5.8) it is possible to have a loopback block device that
163 * superficially is detached but still has partition block devices associated for it. They only go
164 * away when the device is reattached. (Yes, LOOP_CLR_FD doesn't work then, because officially
165 * nothing is attached and LOOP_CTL_REMOVE doesn't either, since it doesn't care about partition
167 r
= device_has_block_children(d
);
171 r
= loop_is_bound(fd
);
177 return -EUCLEAN
; /* Bound but children? Tell caller to reattach something so that the
178 * partition block devices are gone too. */
181 if (*try_loop_configure
) {
182 /* Acquire uevent seqnum immediately before attaching the loopback device. This allows
183 * callers to ignore all uevents with a seqnum before this one, if they need to associate
184 * uevent with this attachment. Doing so isn't race-free though, as uevents that happen in
185 * the window between this reading of the seqnum, and the LOOP_CONFIGURE call might still be
186 * mistaken as originating from our attachment, even though might be caused by an earlier
187 * use. But doing this at least shortens the race window a bit. */
188 r
= get_current_uevent_seqnum(&seqnum
);
191 timestamp
= now(CLOCK_MONOTONIC
);
193 if (ioctl(fd
, LOOP_CONFIGURE
, c
) < 0) {
194 /* Do fallback only if LOOP_CONFIGURE is not supported, propagate all other
195 * errors. Note that the kernel is weird: non-existing ioctls currently return EINVAL
196 * rather than ENOTTY on loopback block devices. They should fix that in the kernel,
197 * but in the meantime we accept both here. */
198 if (!ERRNO_IS_NOT_SUPPORTED(errno
) && errno
!= EINVAL
)
201 *try_loop_configure
= false;
205 if (c
->info
.lo_sizelimit
!= 0) {
206 /* Kernel 5.8 vanilla doesn't properly propagate the size limit into the
207 * block device. If it's used, let's immediately check if it had the desired
208 * effect hence. And if not use classic LOOP_SET_STATUS64. */
211 if (ioctl(fd
, BLKGETSIZE64
, &z
) < 0) {
216 if (z
!= c
->info
.lo_sizelimit
) {
217 log_debug("LOOP_CONFIGURE is broken, doesn't honour .lo_sizelimit. Falling back to LOOP_SET_STATUS64.");
222 if (FLAGS_SET(c
->info
.lo_flags
, LO_FLAGS_PARTSCAN
)) {
223 /* Kernel 5.8 vanilla doesn't properly propagate the partition scanning flag
224 * into the block device. Let's hence verify if things work correctly here
225 * before returning. */
227 r
= blockdev_partscan_enabled(fd
);
231 log_debug("LOOP_CONFIGURE is broken, doesn't honour LO_FLAGS_PARTSCAN. Falling back to LOOP_SET_STATUS64.");
237 /* LOOP_CONFIGURE doesn't work. Remember that. */
238 *try_loop_configure
= false;
240 /* We return EBUSY here instead of retrying immediately with LOOP_SET_FD,
241 * because LOOP_CLR_FD is async: if the operation cannot be executed right
242 * away it just sets the autoclear flag on the device. This means there's a
243 * good chance we cannot actually reuse the loopback device right-away. Hence
244 * let's assume it's busy, avoid the trouble and let the calling loop call us
245 * again with a new, likely unused device. */
250 if (ret_seqnum_not_before
)
251 *ret_seqnum_not_before
= seqnum
;
252 if (ret_timestamp_not_before
)
253 *ret_timestamp_not_before
= timestamp
;
259 /* Let's read the seqnum again, to shorten the window. */
260 r
= get_current_uevent_seqnum(&seqnum
);
263 timestamp
= now(CLOCK_MONOTONIC
);
265 /* Since kernel commit 5db470e229e22b7eda6e23b5566e532c96fb5bc3 (kernel v5.0) the LOOP_SET_STATUS64
266 * ioctl can return EAGAIN in case we change the lo_offset field, if someone else is accessing the
267 * block device while we try to reconfigure it. This is a pretty common case, since udev might
268 * instantly start probing the device as soon as we attach an fd to it. Hence handle it in two ways:
269 * first, let's take the BSD lock to ensure that udev will not step in between the point in
270 * time where we attach the fd and where we reconfigure the device. Secondly, let's wait 50ms on
271 * EAGAIN and retry. The former should be an efficient mechanism to avoid we have to wait 50ms
272 * needlessly if we are just racing against udev. The latter is protection against all other cases,
273 * i.e. peers that do not take the BSD lock. */
275 if (ioctl(fd
, LOOP_SET_FD
, c
->fd
) < 0)
278 /* Only some of the flags LOOP_CONFIGURE can set are also settable via LOOP_SET_STATUS64, hence mask
281 info_copy
.lo_flags
&= LOOP_SET_STATUS_SETTABLE_FLAGS
;
283 for (unsigned n_attempts
= 0;;) {
284 if (ioctl(fd
, LOOP_SET_STATUS64
, &info_copy
) >= 0)
286 if (errno
!= EAGAIN
|| ++n_attempts
>= 64) {
287 r
= log_debug_errno(errno
, "Failed to configure loopback device: %m");
291 /* Sleep some random time, but at least 10ms, at most 250ms. Increase the delay the more
292 * failed attempts we see */
293 (void) usleep(UINT64_C(10) * USEC_PER_MSEC
+
294 random_u64_range(UINT64_C(240) * USEC_PER_MSEC
* n_attempts
/64));
297 /* Work around a kernel bug, where changing offset/size of the loopback device doesn't correctly
298 * invalidate the buffer cache. For details see:
300 * https://android.googlesource.com/platform/system/apex/+/bef74542fbbb4cd629793f4efee8e0053b360570
302 * This was fixed in kernel 5.0, see:
304 * https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=5db470e229e22b7eda6e23b5566e532c96fb5bc3
306 * We'll run the work-around here in the legacy LOOP_SET_STATUS64 codepath. In the LOOP_CONFIGURE
307 * codepath above it should not be necessary. */
308 if (c
->info
.lo_offset
!= 0 || c
->info
.lo_sizelimit
!= 0)
309 if (ioctl(fd
, BLKFLSBUF
, 0) < 0)
310 log_debug_errno(errno
, "Failed to issue BLKFLSBUF ioctl, ignoring: %m");
312 /* LO_FLAGS_DIRECT_IO is a flags we need to configure via explicit ioctls. */
313 if (FLAGS_SET(c
->info
.lo_flags
, LO_FLAGS_DIRECT_IO
)) {
316 if (ioctl(fd
, LOOP_SET_DIRECT_IO
, b
) < 0)
317 log_debug_errno(errno
, "Failed to enable direct IO mode on loopback device /dev/loop%i, ignoring: %m", nr
);
320 if (ret_seqnum_not_before
)
321 *ret_seqnum_not_before
= seqnum
;
322 if (ret_timestamp_not_before
)
323 *ret_timestamp_not_before
= timestamp
;
328 (void) ioctl(fd
, LOOP_CLR_FD
);
332 static int attach_empty_file(int loop
, int nr
) {
333 _cleanup_close_
int fd
= -1;
335 /* So here's the thing: on various kernels (5.8 at least) loop block devices might enter a state
336 * where they are detached but nonetheless have partitions, when used heavily. Accessing these
337 * partitions results in immediatey IO errors. There's no pretty way to get rid of them
338 * again. Neither LOOP_CLR_FD nor LOOP_CTL_REMOVE suffice (see above). What does work is to
339 * reassociate them with a new fd however. This is what we do here hence: we associate the devices
340 * with an empty file (i.e. an image that definitely has no partitions). We then immediately clear it
341 * again. This suffices to make the partitions go away. Ugly but appears to work. */
343 log_debug("Found unattached loopback block device /dev/loop%i with partitions. Attaching empty file to remove them.", nr
);
345 fd
= open_tmpfile_unlinkable(NULL
, O_RDONLY
);
349 if (flock(loop
, LOCK_EX
) < 0)
352 if (ioctl(loop
, LOOP_SET_FD
, fd
) < 0)
355 if (ioctl(loop
, LOOP_SET_STATUS64
, &(struct loop_info64
) {
356 .lo_flags
= LO_FLAGS_READ_ONLY
|
358 LO_FLAGS_PARTSCAN
, /* enable partscan, so that the partitions really go away */
362 if (ioctl(loop
, LOOP_CLR_FD
) < 0)
365 /* The caller is expected to immediately close the loopback device after this, so that the BSD lock
366 * is released, and udev sees the changes. */
370 static int loop_device_make_internal(
378 _cleanup_close_
int direct_io_fd
= -1;
379 _cleanup_free_
char *loopdev
= NULL
;
380 bool try_loop_configure
= true;
381 struct loop_config config
;
382 LoopDevice
*d
= NULL
;
383 uint64_t seqnum
= UINT64_MAX
;
384 usec_t timestamp
= USEC_INFINITY
;
385 int nr
= -1, r
, f_flags
;
390 assert(IN_SET(open_flags
, O_RDWR
, O_RDONLY
));
392 if (fstat(fd
, &st
) < 0)
395 if (S_ISBLK(st
.st_mode
)) {
396 if (ioctl(fd
, LOOP_GET_STATUS64
, &config
.info
) >= 0) {
397 /* Oh! This is a loopback device? That's interesting! */
399 #if HAVE_VALGRIND_MEMCHECK_H
400 /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
401 VALGRIND_MAKE_MEM_DEFINED(&config
.info
, sizeof(config
.info
));
403 nr
= config
.info
.lo_number
;
405 if (asprintf(&loopdev
, "/dev/loop%i", nr
) < 0)
409 if (offset
== 0 && IN_SET(size
, 0, UINT64_MAX
)) {
410 _cleanup_close_
int copy
= -1;
411 uint64_t diskseq
= 0;
413 /* If this is already a block device and we are supposed to cover the whole of it
414 * then store an fd to the original open device node — and do not actually create an
415 * unnecessary loopback device for it. Note that we reopen the inode here, instead of
416 * keeping just a dup() clone of it around, since we want to ensure that the O_DIRECT
417 * flag of the handle we keep is off, we have our own file index, and have the right
418 * read/write mode in effect. */
420 copy
= fd_reopen(fd
, open_flags
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
424 r
= fd_get_diskseq(copy
, &diskseq
);
425 if (r
< 0 && r
!= -EOPNOTSUPP
)
428 d
= new(LoopDevice
, 1);
434 .node
= TAKE_PTR(loopdev
),
435 .relinquished
= true, /* It's not allocated by us, don't destroy it when this object is freed */
438 .uevent_seqnum_not_before
= UINT64_MAX
,
439 .timestamp_not_before
= USEC_INFINITY
,
446 r
= stat_verify_regular(&st
);
451 f_flags
= fcntl(fd
, F_GETFL
);
455 if (FLAGS_SET(loop_flags
, LO_FLAGS_DIRECT_IO
) != FLAGS_SET(f_flags
, O_DIRECT
)) {
456 /* If LO_FLAGS_DIRECT_IO is requested, then make sure we have the fd open with O_DIRECT, as
457 * that's required. Conversely, if it's off require that O_DIRECT is off too (that's because
458 * new kernels will implicitly enable LO_FLAGS_DIRECT_IO if O_DIRECT is set).
460 * Our intention here is that LO_FLAGS_DIRECT_IO is the primary knob, and O_DIRECT derived
461 * from that automatically. */
463 direct_io_fd
= fd_reopen(fd
, (FLAGS_SET(loop_flags
, LO_FLAGS_DIRECT_IO
) ? O_DIRECT
: 0)|O_CLOEXEC
|O_NONBLOCK
|open_flags
);
464 if (direct_io_fd
< 0) {
465 if (!FLAGS_SET(loop_flags
, LO_FLAGS_DIRECT_IO
))
466 return log_debug_errno(errno
, "Failed to reopen file descriptor without O_DIRECT: %m");
468 /* Some file systems might not support O_DIRECT, let's gracefully continue without it then. */
469 log_debug_errno(errno
, "Failed to enable O_DIRECT for backing file descriptor for loopback device. Continuing without.");
470 loop_flags
&= ~LO_FLAGS_DIRECT_IO
;
472 fd
= direct_io_fd
; /* From now on, operate on our new O_DIRECT fd */
475 _cleanup_close_
int control
= -1;
476 _cleanup_(cleanup_clear_loop_close
) int loop_with_fd
= -1;
478 control
= open("/dev/loop-control", O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
482 config
= (struct loop_config
) {
485 /* Use the specified flags, but configure the read-only flag from the open flags, and force autoclear */
486 .lo_flags
= (loop_flags
& ~LO_FLAGS_READ_ONLY
) | ((open_flags
& O_ACCMODE
) == O_RDONLY
? LO_FLAGS_READ_ONLY
: 0) | LO_FLAGS_AUTOCLEAR
,
488 .lo_sizelimit
= size
== UINT64_MAX
? 0 : size
,
492 /* Loop around LOOP_CTL_GET_FREE, since at the moment we attempt to open the returned device it might
493 * be gone already, taken by somebody else racing against us. */
494 for (unsigned n_attempts
= 0;;) {
495 _cleanup_close_
int loop
= -1;
497 /* Let's take a lock on the control device first. On a busy system, where many programs
498 * attempt to allocate a loopback device at the same time, we might otherwise keep looping
499 * around relatively heavy operations: asking for a free loopback device, then opening it,
500 * validating it, attaching something to it. Let's serialize this whole operation, to make
501 * unnecessary busywork less likely. Note that this is just something we do to optimize our
502 * own code (and whoever else decides to use LOCK_EX locks for this), taking this lock is not
503 * necessary, it just means it's less likely we have to iterate through this loop again and
504 * again if our own code races against our own code. */
505 if (flock(control
, LOCK_EX
) < 0)
508 nr
= ioctl(control
, LOOP_CTL_GET_FREE
);
512 if (asprintf(&loopdev
, "/dev/loop%i", nr
) < 0)
515 loop
= open(loopdev
, O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
|open_flags
);
517 /* Somebody might've gotten the same number from the kernel, used the device,
518 * and called LOOP_CTL_REMOVE on it. Let's retry with a new number. */
519 if (!ERRNO_IS_DEVICE_ABSENT(errno
))
522 r
= loop_configure(loop
, nr
, &config
, &try_loop_configure
, &seqnum
, ×tamp
);
524 loop_with_fd
= TAKE_FD(loop
);
528 /* Make left-over partition disappear hack (see above) */
529 r
= attach_empty_file(loop
, nr
);
530 if (r
< 0 && r
!= -EBUSY
)
532 } else if (r
!= -EBUSY
)
536 /* OK, this didn't work, let's try again a bit later, but first release the lock on the
538 if (flock(control
, LOCK_UN
) < 0)
541 if (++n_attempts
>= 64) /* Give up eventually */
544 /* Now close the loop device explicitly. This will release any lock acquired by
545 * attach_empty_file() or similar, while we sleep below. */
546 loop
= safe_close(loop
);
547 loopdev
= mfree(loopdev
);
549 /* Wait some random time, to make collision less likely. Let's pick a random time in the
550 * range 0ms…250ms, linearly scaled by the number of failed attempts. */
551 (void) usleep(random_u64_range(UINT64_C(10) * USEC_PER_MSEC
+
552 UINT64_C(240) * USEC_PER_MSEC
* n_attempts
/64));
555 if (FLAGS_SET(loop_flags
, LO_FLAGS_DIRECT_IO
)) {
556 struct loop_info64 info
;
558 if (ioctl(loop_with_fd
, LOOP_GET_STATUS64
, &info
) < 0)
561 #if HAVE_VALGRIND_MEMCHECK_H
562 VALGRIND_MAKE_MEM_DEFINED(&info
, sizeof(info
));
565 /* On older kernels (<= 5.3) it was necessary to set the block size of the loopback block
566 * device to the logical block size of the underlying file system. Since there was no nice
567 * way to query the value, we are not bothering to do this however. On newer kernels the
568 * block size is propagated automatically and does not require intervention from us. We'll
569 * check here if enabling direct IO worked, to make this easily debuggable however.
571 * (Should anyone really care and actually wants direct IO on old kernels: it might be worth
572 * enabling direct IO with iteratively larger block sizes until it eventually works.) */
573 if (!FLAGS_SET(info
.lo_flags
, LO_FLAGS_DIRECT_IO
))
574 log_debug("Could not enable direct IO mode, proceeding in buffered IO mode.");
577 if (fstat(loop_with_fd
, &st
) < 0)
579 assert(S_ISBLK(st
.st_mode
));
581 uint64_t diskseq
= 0;
582 r
= fd_get_diskseq(loop_with_fd
, &diskseq
);
583 if (r
< 0 && r
!= -EOPNOTSUPP
)
586 d
= new(LoopDevice
, 1);
590 .fd
= TAKE_FD(loop_with_fd
),
591 .node
= TAKE_PTR(loopdev
),
595 .uevent_seqnum_not_before
= seqnum
,
596 .timestamp_not_before
= timestamp
,
599 log_debug("Successfully acquired %s, devno=%u:%u, nr=%i, diskseq=%" PRIu64
,
601 major(d
->devno
), minor(d
->devno
),
609 static uint32_t loop_flags_mangle(uint32_t loop_flags
) {
612 r
= getenv_bool("SYSTEMD_LOOP_DIRECT_IO");
613 if (r
< 0 && r
!= -ENXIO
)
614 log_debug_errno(r
, "Failed to parse $SYSTEMD_LOOP_DIRECT_IO, ignoring: %m");
616 return UPDATE_FLAG(loop_flags
, LO_FLAGS_DIRECT_IO
, r
!= 0); /* Turn on LO_FLAGS_DIRECT_IO by default, unless explicitly configured to off. */
619 int loop_device_make(
630 return loop_device_make_internal(
635 loop_flags_mangle(loop_flags
),
639 int loop_device_make_by_path(
645 int r
, basic_flags
, direct_flags
, rdwr_flags
;
646 _cleanup_close_
int fd
= -1;
651 assert(open_flags
< 0 || IN_SET(open_flags
, O_RDWR
, O_RDONLY
));
653 /* Passing < 0 as open_flags here means we'll try to open the device writable if we can, retrying
654 * read-only if we cannot. */
656 loop_flags
= loop_flags_mangle(loop_flags
);
658 /* Let's open with O_DIRECT if we can. But not all file systems support that, hence fall back to
659 * non-O_DIRECT mode automatically, if it fails. */
661 basic_flags
= O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
;
662 direct_flags
= FLAGS_SET(loop_flags
, LO_FLAGS_DIRECT_IO
) ? O_DIRECT
: 0;
663 rdwr_flags
= open_flags
>= 0 ? open_flags
: O_RDWR
;
665 fd
= open(path
, basic_flags
|direct_flags
|rdwr_flags
);
666 if (fd
< 0 && direct_flags
!= 0) /* If we had O_DIRECT on, and things failed with that, let's immediately try again without */
667 fd
= open(path
, basic_flags
|rdwr_flags
);
669 direct
= direct_flags
!= 0;
673 /* Retry read-only? */
674 if (open_flags
>= 0 || !(ERRNO_IS_PRIVILEGE(r
) || r
== -EROFS
))
677 fd
= open(path
, basic_flags
|direct_flags
|O_RDONLY
);
678 if (fd
< 0 && direct_flags
!= 0) /* as above */
679 fd
= open(path
, basic_flags
|O_RDONLY
);
681 direct
= direct_flags
!= 0;
683 return r
; /* Propagate original error */
685 open_flags
= O_RDONLY
;
686 } else if (open_flags
< 0)
689 log_debug("Opened '%s' in %s access mode%s, with O_DIRECT %s%s.",
691 open_flags
== O_RDWR
? "O_RDWR" : "O_RDONLY",
692 open_flags
!= rdwr_flags
? " (O_RDWR was requested but not allowed)" : "",
693 direct
? "enabled" : "disabled",
694 direct
!= (direct_flags
!= 0) ? " (O_DIRECT was requested but not supported)" : "");
696 return loop_device_make_internal(fd
, open_flags
, 0, 0, loop_flags
, ret
);
699 LoopDevice
* loop_device_unref(LoopDevice
*d
) {
704 /* Implicitly sync the device, since otherwise in-flight blocks might not get written */
705 if (fsync(d
->fd
) < 0)
706 log_debug_errno(errno
, "Failed to sync loop block device, ignoring: %m");
708 if (d
->nr
>= 0 && !d
->relinquished
) {
709 if (ioctl(d
->fd
, LOOP_CLR_FD
) < 0)
710 log_debug_errno(errno
, "Failed to clear loop device: %m");
717 if (d
->nr
>= 0 && !d
->relinquished
) {
718 _cleanup_close_
int control
= -1;
720 control
= open("/dev/loop-control", O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
722 log_warning_errno(errno
,
723 "Failed to open loop control device, cannot remove loop device %s: %m",
726 for (unsigned n_attempts
= 0;;) {
727 if (ioctl(control
, LOOP_CTL_REMOVE
, d
->nr
) >= 0)
729 if (errno
!= EBUSY
|| ++n_attempts
>= 64) {
730 log_warning_errno(errno
, "Failed to remove device %s: %m", strna(d
->node
));
733 (void) usleep(50 * USEC_PER_MSEC
);
741 void loop_device_relinquish(LoopDevice
*d
) {
744 /* Don't attempt to clean up the loop device anymore from this point on. Leave the clean-ing up to the kernel
745 * itself, using the loop device "auto-clear" logic we already turned on when creating the device. */
747 d
->relinquished
= true;
750 void loop_device_unrelinquish(LoopDevice
*d
) {
752 d
->relinquished
= false;
755 int loop_device_open(const char *loop_path
, int open_flags
, LoopDevice
**ret
) {
756 _cleanup_close_
int loop_fd
= -1;
757 _cleanup_free_
char *p
= NULL
;
758 struct loop_info64 info
;
764 assert(IN_SET(open_flags
, O_RDWR
, O_RDONLY
));
767 loop_fd
= open(loop_path
, O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
|open_flags
);
771 if (fstat(loop_fd
, &st
) < 0)
773 if (!S_ISBLK(st
.st_mode
))
776 if (ioctl(loop_fd
, LOOP_GET_STATUS64
, &info
) >= 0) {
777 #if HAVE_VALGRIND_MEMCHECK_H
778 /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
779 VALGRIND_MAKE_MEM_DEFINED(&info
, sizeof(info
));
785 p
= strdup(loop_path
);
789 d
= new(LoopDevice
, 1);
794 .fd
= TAKE_FD(loop_fd
),
797 .relinquished
= true, /* It's not ours, don't try to destroy it when this object is freed */
799 .uevent_seqnum_not_before
= UINT64_MAX
,
800 .timestamp_not_before
= USEC_INFINITY
,
807 static int resize_partition(int partition_fd
, uint64_t offset
, uint64_t size
) {
808 char sysfs
[STRLEN("/sys/dev/block/:/partition") + 2*DECIMAL_STR_MAX(dev_t
) + 1];
809 _cleanup_free_
char *buffer
= NULL
;
810 uint64_t current_offset
, current_size
, partno
;
811 _cleanup_close_
int whole_fd
= -1;
816 assert(partition_fd
>= 0);
818 /* Resizes the partition the loopback device refer to (assuming it refers to one instead of an actual
819 * loopback device), and changes the offset, if needed. This is a fancy wrapper around
820 * BLKPG_RESIZE_PARTITION. */
822 if (fstat(partition_fd
, &st
) < 0)
825 assert(S_ISBLK(st
.st_mode
));
827 xsprintf(sysfs
, "/sys/dev/block/%u:%u/partition", major(st
.st_rdev
), minor(st
.st_rdev
));
828 r
= read_one_line_file(sysfs
, &buffer
);
829 if (r
== -ENOENT
) /* not a partition, cannot resize */
833 r
= safe_atou64(buffer
, &partno
);
837 xsprintf(sysfs
, "/sys/dev/block/%u:%u/start", major(st
.st_rdev
), minor(st
.st_rdev
));
839 buffer
= mfree(buffer
);
840 r
= read_one_line_file(sysfs
, &buffer
);
843 r
= safe_atou64(buffer
, ¤t_offset
);
846 if (current_offset
> UINT64_MAX
/512U)
848 current_offset
*= 512U;
850 if (ioctl(partition_fd
, BLKGETSIZE64
, ¤t_size
) < 0)
853 if (size
== UINT64_MAX
&& offset
== UINT64_MAX
)
855 if (current_size
== size
&& current_offset
== offset
)
858 xsprintf(sysfs
, "/sys/dev/block/%u:%u/../dev", major(st
.st_rdev
), minor(st
.st_rdev
));
860 buffer
= mfree(buffer
);
861 r
= read_one_line_file(sysfs
, &buffer
);
864 r
= parse_devnum(buffer
, &devno
);
868 whole_fd
= r
= device_open_from_devnum(S_IFBLK
, devno
, O_RDWR
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
, NULL
);
872 struct blkpg_partition bp
= {
874 .start
= offset
== UINT64_MAX
? current_offset
: offset
,
875 .length
= size
== UINT64_MAX
? current_size
: size
,
878 struct blkpg_ioctl_arg ba
= {
879 .op
= BLKPG_RESIZE_PARTITION
,
881 .datalen
= sizeof(bp
),
884 return RET_NERRNO(ioctl(whole_fd
, BLKPG
, &ba
));
887 int loop_device_refresh_size(LoopDevice
*d
, uint64_t offset
, uint64_t size
) {
888 struct loop_info64 info
;
891 /* Changes the offset/start of the loop device relative to the beginning of the underlying file or
892 * block device. If this loop device actually refers to a partition and not a loopback device, we'll
893 * try to adjust the partition offsets instead.
895 * If either offset or size is UINT64_MAX we won't change that parameter. */
900 if (d
->nr
< 0) /* not a loopback device */
901 return resize_partition(d
->fd
, offset
, size
);
903 if (ioctl(d
->fd
, LOOP_GET_STATUS64
, &info
) < 0)
906 #if HAVE_VALGRIND_MEMCHECK_H
907 /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
908 VALGRIND_MAKE_MEM_DEFINED(&info
, sizeof(info
));
911 if (size
== UINT64_MAX
&& offset
== UINT64_MAX
)
913 if (info
.lo_sizelimit
== size
&& info
.lo_offset
== offset
)
916 if (size
!= UINT64_MAX
)
917 info
.lo_sizelimit
= size
;
918 if (offset
!= UINT64_MAX
)
919 info
.lo_offset
= offset
;
921 return RET_NERRNO(ioctl(d
->fd
, LOOP_SET_STATUS64
, &info
));
924 int loop_device_flock(LoopDevice
*d
, int operation
) {
930 return RET_NERRNO(flock(d
->fd
, operation
));
933 int loop_device_sync(LoopDevice
*d
) {
936 /* We also do this implicitly in loop_device_unref(). Doing this explicitly here has the benefit that
937 * we can check the return value though. */
942 return RET_NERRNO(fsync(d
->fd
));