]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/loop-util.c
dissect-image: add probe_sector_size() helper for detecting sector size of a GPT...
[thirdparty/systemd.git] / src / shared / loop-util.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
8c1be37e 2
10c1b188
LP
3#if HAVE_VALGRIND_MEMCHECK_H
4#include <valgrind/memcheck.h>
5#endif
6
dccca82b 7#include <errno.h>
8c1be37e 8#include <fcntl.h>
f1443709
LP
9#include <linux/blkpg.h>
10#include <linux/fs.h>
8c1be37e 11#include <linux/loop.h>
441ec804 12#include <sys/file.h>
8c1be37e 13#include <sys/ioctl.h>
f2d9213f 14#include <unistd.h>
8c1be37e 15
021bf175
LP
16#include "sd-device.h"
17
8c1be37e 18#include "alloc-util.h"
86c1c1f3 19#include "blockdev-util.h"
fcd8a19d 20#include "data-fd-util.h"
021bf175 21#include "device-util.h"
7176f06c 22#include "devnum-util.h"
e8c7c4d9 23#include "env-util.h"
b0a94268 24#include "errno-util.h"
8c1be37e 25#include "fd-util.h"
f1443709 26#include "fileio.h"
8c1be37e 27#include "loop-util.h"
86c1c1f3 28#include "missing_loop.h"
f1443709 29#include "parse-util.h"
e77cab82 30#include "path-util.h"
b202ec20 31#include "random-util.h"
3cc44114 32#include "stat-util.h"
f1443709 33#include "stdio-util.h"
f2d9213f 34#include "string-util.h"
021bf175 35#include "tmpfile-util.h"
8c1be37e 36
e8af3bfd 37static void cleanup_clear_loop_close(int *fd) {
86c1c1f3
LP
38 if (*fd < 0)
39 return;
40
41 (void) ioctl(*fd, LOOP_CLR_FD);
42 (void) safe_close(*fd);
43}
44
021bf175
LP
45static int loop_is_bound(int fd) {
46 struct loop_info64 info;
47
48 assert(fd >= 0);
49
50 if (ioctl(fd, LOOP_GET_STATUS64, &info) < 0) {
51 if (errno == ENXIO)
52 return false; /* not bound! */
53
54 return -errno;
55 }
56
57 return true; /* bound! */
58}
59
31c75fcc
LP
60static int get_current_uevent_seqnum(uint64_t *ret) {
61 _cleanup_free_ char *p = NULL;
62 int r;
63
64 r = read_full_virtual_file("/sys/kernel/uevent_seqnum", &p, NULL);
65 if (r < 0)
66 return log_debug_errno(r, "Failed to read current uevent sequence number: %m");
67
a145f8c0 68 r = safe_atou64(strstrip(p), ret);
31c75fcc
LP
69 if (r < 0)
70 return log_debug_errno(r, "Failed to parse current uevent sequence number: %s", p);
71
72 return 0;
73}
74
7f52206a 75static int open_lock_fd(int primary_fd, int operation) {
254d1313 76 _cleanup_close_ int lock_fd = -EBADF;
7f52206a
LP
77
78 assert(primary_fd >= 0);
10719a6f 79 assert(IN_SET(operation & ~LOCK_NB, LOCK_SH, LOCK_EX));
7f52206a 80
3e6b7d26 81 lock_fd = fd_reopen(primary_fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
7f52206a
LP
82 if (lock_fd < 0)
83 return lock_fd;
10719a6f 84
7f52206a
LP
85 if (flock(lock_fd, operation) < 0)
86 return -errno;
87
10719a6f 88 return TAKE_FD(lock_fd);
7f52206a
LP
89}
90
54ba7daf
YW
91static int loop_configure_verify_direct_io(int fd, const struct loop_config *c) {
92 assert(fd);
93 assert(c);
94
95 if (FLAGS_SET(c->info.lo_flags, LO_FLAGS_DIRECT_IO)) {
96 struct loop_info64 info;
97
98 if (ioctl(fd, LOOP_GET_STATUS64, &info) < 0)
99 return log_debug_errno(errno, "Failed to issue LOOP_GET_STATUS64: %m");
100
101#if HAVE_VALGRIND_MEMCHECK_H
102 VALGRIND_MAKE_MEM_DEFINED(&info, sizeof(info));
103#endif
104
105 /* On older kernels (<= 5.3) it was necessary to set the block size of the loopback block
106 * device to the logical block size of the underlying file system. Since there was no nice
107 * way to query the value, we are not bothering to do this however. On newer kernels the
108 * block size is propagated automatically and does not require intervention from us. We'll
109 * check here if enabling direct IO worked, to make this easily debuggable however.
110 *
111 * (Should anyone really care and actually wants direct IO on old kernels: it might be worth
112 * enabling direct IO with iteratively larger block sizes until it eventually works.) */
113 if (!FLAGS_SET(info.lo_flags, LO_FLAGS_DIRECT_IO))
114 log_debug("Could not enable direct IO mode, proceeding in buffered IO mode.");
115 }
116
117 return 0;
118}
119
120static int loop_configure_verify(int fd, const struct loop_config *c) {
121 bool broken = false;
122 int r;
123
124 assert(fd >= 0);
125 assert(c);
126
fd83c98e 127 if (c->block_size != 0) {
65046b92 128 uint32_t ssz;
fd83c98e 129
65046b92
LP
130 r = blockdev_get_sector_size(fd, &ssz);
131 if (r < 0)
132 return r;
fd83c98e 133
1163ddb3 134 if (ssz != c->block_size) {
65046b92 135 log_debug("LOOP_CONFIGURE didn't honour requested block size %" PRIu32 ", got %" PRIu32 " instead. Ignoring.", c->block_size, ssz);
1163ddb3
LP
136 broken = true;
137 }
fd83c98e
AD
138 }
139
54ba7daf
YW
140 if (c->info.lo_sizelimit != 0) {
141 /* Kernel 5.8 vanilla doesn't properly propagate the size limit into the
142 * block device. If it's used, let's immediately check if it had the desired
143 * effect hence. And if not use classic LOOP_SET_STATUS64. */
144 uint64_t z;
145
146 if (ioctl(fd, BLKGETSIZE64, &z) < 0)
147 return -errno;
148
149 if (z != c->info.lo_sizelimit) {
fd83c98e 150 log_debug("LOOP_CONFIGURE is broken, doesn't honour .info.lo_sizelimit. Falling back to LOOP_SET_STATUS64.");
54ba7daf
YW
151 broken = true;
152 }
153 }
154
155 if (FLAGS_SET(c->info.lo_flags, LO_FLAGS_PARTSCAN)) {
156 /* Kernel 5.8 vanilla doesn't properly propagate the partition scanning flag
157 * into the block device. Let's hence verify if things work correctly here
158 * before returning. */
159
160 r = blockdev_partscan_enabled(fd);
161 if (r < 0)
162 return r;
163 if (r == 0) {
164 log_debug("LOOP_CONFIGURE is broken, doesn't honour LO_FLAGS_PARTSCAN. Falling back to LOOP_SET_STATUS64.");
165 broken = true;
166 }
167 }
168
169 r = loop_configure_verify_direct_io(fd, c);
170 if (r < 0)
171 return r;
172
173 return !broken;
174}
175
176static int loop_configure_fallback(int fd, const struct loop_config *c) {
177 struct loop_info64 info_copy;
1163ddb3 178 int r;
54ba7daf
YW
179
180 assert(fd >= 0);
181 assert(c);
182
183 /* Only some of the flags LOOP_CONFIGURE can set are also settable via LOOP_SET_STATUS64, hence mask
184 * them out. */
185 info_copy = c->info;
186 info_copy.lo_flags &= LOOP_SET_STATUS_SETTABLE_FLAGS;
187
188 /* Since kernel commit 5db470e229e22b7eda6e23b5566e532c96fb5bc3 (kernel v5.0) the LOOP_SET_STATUS64
fd83c98e 189 * ioctl can return EAGAIN in case we change the info.lo_offset field, if someone else is accessing the
54ba7daf
YW
190 * block device while we try to reconfigure it. This is a pretty common case, since udev might
191 * instantly start probing the device as soon as we attach an fd to it. Hence handle it in two ways:
192 * first, let's take the BSD lock to ensure that udev will not step in between the point in
193 * time where we attach the fd and where we reconfigure the device. Secondly, let's wait 50ms on
194 * EAGAIN and retry. The former should be an efficient mechanism to avoid we have to wait 50ms
195 * needlessly if we are just racing against udev. The latter is protection against all other cases,
196 * i.e. peers that do not take the BSD lock. */
197
198 for (unsigned n_attempts = 0;;) {
199 if (ioctl(fd, LOOP_SET_STATUS64, &info_copy) >= 0)
200 break;
201
202 if (errno != EAGAIN || ++n_attempts >= 64)
203 return log_debug_errno(errno, "Failed to configure loopback block device: %m");
204
205 /* Sleep some random time, but at least 10ms, at most 250ms. Increase the delay the more
206 * failed attempts we see */
207 (void) usleep(UINT64_C(10) * USEC_PER_MSEC +
208 random_u64_range(UINT64_C(240) * USEC_PER_MSEC * n_attempts/64));
209 }
210
211 /* Work around a kernel bug, where changing offset/size of the loopback device doesn't correctly
212 * invalidate the buffer cache. For details see:
213 *
214 * https://android.googlesource.com/platform/system/apex/+/bef74542fbbb4cd629793f4efee8e0053b360570
215 *
216 * This was fixed in kernel 5.0, see:
217 *
218 * https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=5db470e229e22b7eda6e23b5566e532c96fb5bc3
219 *
220 * We'll run the work-around here in the legacy LOOP_SET_STATUS64 codepath. In the LOOP_CONFIGURE
221 * codepath above it should not be necessary. */
222 if (c->info.lo_offset != 0 || c->info.lo_sizelimit != 0)
223 if (ioctl(fd, BLKFLSBUF, 0) < 0)
224 log_debug_errno(errno, "Failed to issue BLKFLSBUF ioctl, ignoring: %m");
225
1163ddb3
LP
226 /* If a block size is requested then try to configure it. If that doesn't work, ignore errors, but
227 * afterwards, let's validate what is in effect, and if it doesn't match what we want, fail */
228 if (c->block_size != 0) {
229 uint32_t ssz;
230
231 if (ioctl(fd, LOOP_SET_BLOCK_SIZE, (unsigned long) c->block_size) < 0)
232 log_debug_errno(errno, "Failed to set sector size, ignoring: %m");
233
234 r = blockdev_get_sector_size(fd, &ssz);
235 if (r < 0)
236 return log_debug_errno(r, "Failed to read sector size: %m");
237 if (ssz != c->block_size)
238 return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Sector size of loopback device doesn't match what we requested, refusing.");
239 }
240
54ba7daf
YW
241 /* LO_FLAGS_DIRECT_IO is a flags we need to configure via explicit ioctls. */
242 if (FLAGS_SET(c->info.lo_flags, LO_FLAGS_DIRECT_IO))
243 if (ioctl(fd, LOOP_SET_DIRECT_IO, 1UL) < 0)
244 log_debug_errno(errno, "Failed to enable direct IO mode, ignoring: %m");
245
246 return loop_configure_verify_direct_io(fd, c);
247}
248
95c50092 249static int loop_configure(
021bf175 250 int nr,
da4fd288
YW
251 int open_flags,
252 int lock_op,
95c50092 253 const struct loop_config *c,
da4fd288 254 LoopDevice **ret) {
95c50092 255
bb273a51
YW
256 static bool loop_configure_broken = false;
257
da4fd288 258 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
254d1313
ZJS
259 _cleanup_(cleanup_clear_loop_close) int loop_with_fd = -EBADF; /* This must be declared before lock_fd. */
260 _cleanup_close_ int fd = -EBADF, lock_fd = -EBADF;
da4fd288
YW
261 _cleanup_free_ char *node = NULL;
262 uint64_t diskseq = 0, seqnum = UINT64_MAX;
263 usec_t timestamp = USEC_INFINITY;
264 dev_t devno;
86c1c1f3
LP
265 int r;
266
021bf175 267 assert(nr >= 0);
86c1c1f3 268 assert(c);
da4fd288
YW
269 assert(ret);
270
271 if (asprintf(&node, "/dev/loop%i", nr) < 0)
272 return -ENOMEM;
273
274 r = sd_device_new_from_devname(&dev, node);
275 if (r < 0)
276 return r;
277
278 r = sd_device_get_devnum(dev, &devno);
279 if (r < 0)
280 return r;
281
282 fd = sd_device_open(dev, O_CLOEXEC|O_NONBLOCK|O_NOCTTY|open_flags);
283 if (fd < 0)
284 return fd;
95c50092 285
021bf175
LP
286 /* Let's lock the device before we do anything. We take the BSD lock on a second, separately opened
287 * fd for the device. udev after all watches for close() events (specifically IN_CLOSE_WRITE) on
288 * block devices to reprobe them, hence by having a separate fd we will later close() we can ensure
289 * we trigger udev after everything is done. If we'd lock our own fd instead and keep it open for a
290 * long time udev would possibly never run on it again, even though the fd is unlocked, simply
291 * because we never close() it. It also has the nice benefit we can use the _cleanup_close_ logic to
292 * automatically release the lock, after we are done. */
7f52206a 293 lock_fd = open_lock_fd(fd, LOCK_EX);
021bf175
LP
294 if (lock_fd < 0)
295 return lock_fd;
021bf175 296
53274fdb
YW
297 /* Let's see if backing file is really unattached. Someone may already attach a backing file without
298 * taking BSD lock. */
299 r = loop_is_bound(fd);
300 if (r < 0)
301 return r;
302 if (r > 0)
303 return -EBUSY;
304
021bf175
LP
305 /* Let's see if the device is really detached, i.e. currently has no associated partition block
306 * devices. On various kernels (such as 5.8) it is possible to have a loopback block device that
247738b4
LP
307 * superficially is detached but still has partition block devices associated for it. Let's then
308 * manually remove the partitions via BLKPG, and tell the caller we did that via EUCLEAN, so they try
309 * again. */
833106b8 310 r = block_device_remove_all_partitions(dev, fd);
021bf175
LP
311 if (r < 0)
312 return r;
833106b8
YW
313 if (r > 0)
314 /* Removed all partitions. Let's report this to the caller, to try again, and count this as
53274fdb 315 * an attempt. */
247738b4 316 return -EUCLEAN;
021bf175 317
bb273a51 318 if (!loop_configure_broken) {
31c75fcc
LP
319 /* Acquire uevent seqnum immediately before attaching the loopback device. This allows
320 * callers to ignore all uevents with a seqnum before this one, if they need to associate
321 * uevent with this attachment. Doing so isn't race-free though, as uevents that happen in
322 * the window between this reading of the seqnum, and the LOOP_CONFIGURE call might still be
323 * mistaken as originating from our attachment, even though might be caused by an earlier
324 * use. But doing this at least shortens the race window a bit. */
325 r = get_current_uevent_seqnum(&seqnum);
326 if (r < 0)
327 return r;
54ba7daf 328
8ede1e86 329 timestamp = now(CLOCK_MONOTONIC);
31c75fcc 330
95c50092
LP
331 if (ioctl(fd, LOOP_CONFIGURE, c) < 0) {
332 /* Do fallback only if LOOP_CONFIGURE is not supported, propagate all other
333 * errors. Note that the kernel is weird: non-existing ioctls currently return EINVAL
334 * rather than ENOTTY on loopback block devices. They should fix that in the kernel,
335 * but in the meantime we accept both here. */
336 if (!ERRNO_IS_NOT_SUPPORTED(errno) && errno != EINVAL)
337 return -errno;
86c1c1f3 338
bb273a51 339 loop_configure_broken = true;
95c50092 340 } else {
da4fd288
YW
341 loop_with_fd = TAKE_FD(fd);
342
343 r = loop_configure_verify(loop_with_fd, c);
54ba7daf 344 if (r < 0)
da4fd288 345 return r;
54ba7daf 346 if (r == 0) {
95c50092 347 /* LOOP_CONFIGURE doesn't work. Remember that. */
bb273a51 348 loop_configure_broken = true;
95c50092
LP
349
350 /* We return EBUSY here instead of retrying immediately with LOOP_SET_FD,
351 * because LOOP_CLR_FD is async: if the operation cannot be executed right
352 * away it just sets the autoclear flag on the device. This means there's a
353 * good chance we cannot actually reuse the loopback device right-away. Hence
354 * let's assume it's busy, avoid the trouble and let the calling loop call us
355 * again with a new, likely unused device. */
da4fd288 356 return -EBUSY;
bb2551bd 357 }
95c50092 358 }
86c1c1f3
LP
359 }
360
bb273a51
YW
361 if (loop_configure_broken) {
362 /* Let's read the seqnum again, to shorten the window. */
363 r = get_current_uevent_seqnum(&seqnum);
364 if (r < 0)
365 return r;
31c75fcc 366
bb273a51 367 timestamp = now(CLOCK_MONOTONIC);
738f29cb 368
bb273a51
YW
369 if (ioctl(fd, LOOP_SET_FD, c->fd) < 0)
370 return -errno;
86c1c1f3 371
da4fd288
YW
372 loop_with_fd = TAKE_FD(fd);
373
374 r = loop_configure_fallback(loop_with_fd, c);
bb273a51 375 if (r < 0)
da4fd288 376 return r;
bb273a51 377 }
e8c7c4d9 378
da4fd288
YW
379 r = fd_get_diskseq(loop_with_fd, &diskseq);
380 if (r < 0 && r != -EOPNOTSUPP)
381 return r;
31c75fcc 382
da4fd288
YW
383 switch (lock_op & ~LOCK_NB) {
384 case LOCK_EX: /* Already in effect */
385 break;
386 case LOCK_SH: /* Downgrade */
387 if (flock(lock_fd, lock_op) < 0)
388 return -errno;
389 break;
390 case LOCK_UN: /* Release */
391 lock_fd = safe_close(lock_fd);
392 break;
393 default:
394 assert_not_reached();
395 }
396
397 LoopDevice *d = new(LoopDevice, 1);
398 if (!d)
399 return -ENOMEM;
400
401 *d = (LoopDevice) {
36d5eb0b 402 .n_ref = 1,
da4fd288
YW
403 .fd = TAKE_FD(loop_with_fd),
404 .lock_fd = TAKE_FD(lock_fd),
405 .node = TAKE_PTR(node),
406 .nr = nr,
407 .devno = devno,
408 .dev = TAKE_PTR(dev),
409 .diskseq = diskseq,
410 .uevent_seqnum_not_before = seqnum,
411 .timestamp_not_before = timestamp,
412 };
86c1c1f3 413
da4fd288
YW
414 *ret = TAKE_PTR(d);
415 return 0;
e8af3bfd
ZJS
416}
417
e8c7c4d9 418static int loop_device_make_internal(
e77cab82 419 const char *path,
ed9eeb7b
LP
420 int fd,
421 int open_flags,
422 uint64_t offset,
423 uint64_t size,
fd83c98e 424 uint32_t block_size,
ed9eeb7b 425 uint32_t loop_flags,
7f52206a 426 int lock_op,
ed9eeb7b 427 LoopDevice **ret) {
8c1be37e 428
da4fd288 429 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
254d1313 430 _cleanup_close_ int direct_io_fd = -EBADF, control = -EBADF;
da4fd288 431 _cleanup_free_ char *backing_file = NULL;
86c1c1f3 432 struct loop_config config;
da4fd288 433 int r, f_flags;
8c1be37e 434 struct stat st;
8c1be37e
LP
435
436 assert(fd >= 0);
437 assert(ret);
438 assert(IN_SET(open_flags, O_RDWR, O_RDONLY));
439
440 if (fstat(fd, &st) < 0)
441 return -errno;
442
443 if (S_ISBLK(st.st_mode)) {
1996ad28 444 if (offset == 0 && IN_SET(size, 0, UINT64_MAX))
d7654742
LP
445 /* If this is already a block device and we are supposed to cover the whole of it
446 * then store an fd to the original open device node — and do not actually create an
1996ad28 447 * unnecessary loopback device for it. */
de3b7f16 448 return loop_device_open_from_fd(fd, open_flags, lock_op, ret);
ed9eeb7b
LP
449 } else {
450 r = stat_verify_regular(&st);
451 if (r < 0)
452 return r;
8c1be37e
LP
453 }
454
e77cab82
YW
455 if (path) {
456 r = path_make_absolute_cwd(path, &backing_file);
457 if (r < 0)
458 return r;
459
460 path_simplify(backing_file);
461 } else {
462 r = fd_get_path(fd, &backing_file);
463 if (r < 0)
464 return r;
465 }
466
e8c7c4d9
LP
467 f_flags = fcntl(fd, F_GETFL);
468 if (f_flags < 0)
469 return -errno;
470
471 if (FLAGS_SET(loop_flags, LO_FLAGS_DIRECT_IO) != FLAGS_SET(f_flags, O_DIRECT)) {
472 /* If LO_FLAGS_DIRECT_IO is requested, then make sure we have the fd open with O_DIRECT, as
473 * that's required. Conversely, if it's off require that O_DIRECT is off too (that's because
474 * new kernels will implicitly enable LO_FLAGS_DIRECT_IO if O_DIRECT is set).
475 *
476 * Our intention here is that LO_FLAGS_DIRECT_IO is the primary knob, and O_DIRECT derived
477 * from that automatically. */
478
479 direct_io_fd = fd_reopen(fd, (FLAGS_SET(loop_flags, LO_FLAGS_DIRECT_IO) ? O_DIRECT : 0)|O_CLOEXEC|O_NONBLOCK|open_flags);
480 if (direct_io_fd < 0) {
481 if (!FLAGS_SET(loop_flags, LO_FLAGS_DIRECT_IO))
482 return log_debug_errno(errno, "Failed to reopen file descriptor without O_DIRECT: %m");
483
484 /* Some file systems might not support O_DIRECT, let's gracefully continue without it then. */
485 log_debug_errno(errno, "Failed to enable O_DIRECT for backing file descriptor for loopback device. Continuing without.");
486 loop_flags &= ~LO_FLAGS_DIRECT_IO;
487 } else
488 fd = direct_io_fd; /* From now on, operate on our new O_DIRECT fd */
489 }
490
8c1be37e
LP
491 control = open("/dev/loop-control", O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
492 if (control < 0)
493 return -errno;
494
86c1c1f3
LP
495 config = (struct loop_config) {
496 .fd = fd,
fd83c98e 497 .block_size = block_size,
86c1c1f3
LP
498 .info = {
499 /* Use the specified flags, but configure the read-only flag from the open flags, and force autoclear */
0950526a 500 .lo_flags = (loop_flags & ~LO_FLAGS_READ_ONLY) | ((open_flags & O_ACCMODE) == O_RDONLY ? LO_FLAGS_READ_ONLY : 0) | LO_FLAGS_AUTOCLEAR,
86c1c1f3
LP
501 .lo_offset = offset,
502 .lo_sizelimit = size == UINT64_MAX ? 0 : size,
503 },
504 };
505
0f6519d4
LP
506 /* Loop around LOOP_CTL_GET_FREE, since at the moment we attempt to open the returned device it might
507 * be gone already, taken by somebody else racing against us. */
e8af3bfd 508 for (unsigned n_attempts = 0;;) {
da4fd288 509 int nr;
e8af3bfd 510
cc530466
LP
511 /* Let's take a lock on the control device first. On a busy system, where many programs
512 * attempt to allocate a loopback device at the same time, we might otherwise keep looping
513 * around relatively heavy operations: asking for a free loopback device, then opening it,
514 * validating it, attaching something to it. Let's serialize this whole operation, to make
515 * unnecessary busywork less likely. Note that this is just something we do to optimize our
516 * own code (and whoever else decides to use LOCK_EX locks for this), taking this lock is not
517 * necessary, it just means it's less likely we have to iterate through this loop again and
4c1d50e6
LP
518 * again if our own code races against our own code.
519 *
520 * Note: our lock protocol is to take the /dev/loop-control lock first, and the block device
521 * lock second, if both are taken, and always in this order, to avoid ABBA locking issues. */
cc530466
LP
522 if (flock(control, LOCK_EX) < 0)
523 return -errno;
524
0f6519d4
LP
525 nr = ioctl(control, LOOP_CTL_GET_FREE);
526 if (nr < 0)
527 return -errno;
8c1be37e 528
da4fd288
YW
529 r = loop_configure(nr, open_flags, lock_op, &config, &d);
530 if (r >= 0)
531 break;
cc5bae6c 532
da4fd288
YW
533 /* -ENODEV or friends: Somebody might've gotten the same number from the kernel, used the
534 * device, and called LOOP_CTL_REMOVE on it. Let's retry with a new number.
535 * -EBUSY: a file descriptor is already bound to the loopback block device.
536 * -EUCLEAN: some left-over partition devices that were cleaned up. */
537 if (!ERRNO_IS_DEVICE_ABSENT(errno) && !IN_SET(r, -EBUSY, -EUCLEAN))
538 return -errno;
01813148 539
cc530466
LP
540 /* OK, this didn't work, let's try again a bit later, but first release the lock on the
541 * control device */
542 if (flock(control, LOCK_UN) < 0)
543 return -errno;
544
e8af3bfd
ZJS
545 if (++n_attempts >= 64) /* Give up eventually */
546 return -EBUSY;
0f6519d4 547
b202ec20
LP
548 /* Wait some random time, to make collision less likely. Let's pick a random time in the
549 * range 0ms…250ms, linearly scaled by the number of failed attempts. */
b0dbffd8
LP
550 (void) usleep(random_u64_range(UINT64_C(10) * USEC_PER_MSEC +
551 UINT64_C(240) * USEC_PER_MSEC * n_attempts/64));
0f6519d4 552 }
8c1be37e 553
da4fd288 554 d->backing_file = TAKE_PTR(backing_file);
8c1be37e 555
3b195f63
LP
556 log_debug("Successfully acquired %s, devno=%u:%u, nr=%i, diskseq=%" PRIu64,
557 d->node,
558 major(d->devno), minor(d->devno),
559 d->nr,
560 d->diskseq);
561
da4fd288
YW
562 *ret = TAKE_PTR(d);
563 return 0;
8c1be37e
LP
564}
565
e8c7c4d9
LP
566static uint32_t loop_flags_mangle(uint32_t loop_flags) {
567 int r;
568
569 r = getenv_bool("SYSTEMD_LOOP_DIRECT_IO");
570 if (r < 0 && r != -ENXIO)
571 log_debug_errno(r, "Failed to parse $SYSTEMD_LOOP_DIRECT_IO, ignoring: %m");
572
bfd08445 573 return UPDATE_FLAG(loop_flags, LO_FLAGS_DIRECT_IO, r != 0); /* Turn on LO_FLAGS_DIRECT_IO by default, unless explicitly configured to off. */
e8c7c4d9
LP
574}
575
576int loop_device_make(
577 int fd,
578 int open_flags,
579 uint64_t offset,
580 uint64_t size,
fd83c98e 581 uint32_t block_size,
e8c7c4d9 582 uint32_t loop_flags,
7f52206a 583 int lock_op,
e8c7c4d9
LP
584 LoopDevice **ret) {
585
586 assert(fd >= 0);
587 assert(ret);
e8c7c4d9
LP
588
589 return loop_device_make_internal(
e77cab82 590 NULL,
e8c7c4d9
LP
591 fd,
592 open_flags,
593 offset,
594 size,
fd83c98e 595 block_size,
bfd08445 596 loop_flags_mangle(loop_flags),
7f52206a 597 lock_op,
e8c7c4d9
LP
598 ret);
599}
600
79e8393a
LP
601int loop_device_make_by_path(
602 const char *path,
603 int open_flags,
604 uint32_t loop_flags,
7f52206a 605 int lock_op,
79e8393a
LP
606 LoopDevice **ret) {
607
e8c7c4d9 608 int r, basic_flags, direct_flags, rdwr_flags;
254d1313 609 _cleanup_close_ int fd = -EBADF;
aa4d3aa3 610 bool direct = false;
8c1be37e
LP
611
612 assert(path);
613 assert(ret);
b0a94268 614 assert(open_flags < 0 || IN_SET(open_flags, O_RDWR, O_RDONLY));
8c1be37e 615
b0a94268
LP
616 /* Passing < 0 as open_flags here means we'll try to open the device writable if we can, retrying
617 * read-only if we cannot. */
618
e8c7c4d9
LP
619 loop_flags = loop_flags_mangle(loop_flags);
620
621 /* Let's open with O_DIRECT if we can. But not all file systems support that, hence fall back to
622 * non-O_DIRECT mode automatically, if it fails. */
623
624 basic_flags = O_CLOEXEC|O_NONBLOCK|O_NOCTTY;
625 direct_flags = FLAGS_SET(loop_flags, LO_FLAGS_DIRECT_IO) ? O_DIRECT : 0;
626 rdwr_flags = open_flags >= 0 ? open_flags : O_RDWR;
627
628 fd = open(path, basic_flags|direct_flags|rdwr_flags);
629 if (fd < 0 && direct_flags != 0) /* If we had O_DIRECT on, and things failed with that, let's immediately try again without */
630 fd = open(path, basic_flags|rdwr_flags);
aa4d3aa3
LP
631 else
632 direct = direct_flags != 0;
b0a94268
LP
633 if (fd < 0) {
634 r = -errno;
635
636 /* Retry read-only? */
637 if (open_flags >= 0 || !(ERRNO_IS_PRIVILEGE(r) || r == -EROFS))
638 return r;
639
e8c7c4d9
LP
640 fd = open(path, basic_flags|direct_flags|O_RDONLY);
641 if (fd < 0 && direct_flags != 0) /* as above */
642 fd = open(path, basic_flags|O_RDONLY);
aa4d3aa3
LP
643 else
644 direct = direct_flags != 0;
b0a94268
LP
645 if (fd < 0)
646 return r; /* Propagate original error */
647
648 open_flags = O_RDONLY;
649 } else if (open_flags < 0)
650 open_flags = O_RDWR;
8c1be37e 651
aa4d3aa3
LP
652 log_debug("Opened '%s' in %s access mode%s, with O_DIRECT %s%s.",
653 path,
654 open_flags == O_RDWR ? "O_RDWR" : "O_RDONLY",
655 open_flags != rdwr_flags ? " (O_RDWR was requested but not allowed)" : "",
656 direct ? "enabled" : "disabled",
657 direct != (direct_flags != 0) ? " (O_DIRECT was requested but not supported)" : "");
658
fd83c98e 659 return loop_device_make_internal(path, fd, open_flags, 0, 0, 0, loop_flags, lock_op, ret);
8c1be37e
LP
660}
661
fcd8a19d
LP
662int loop_device_make_by_path_memory(
663 const char *path,
664 int open_flags,
665 uint32_t loop_flags,
666 int lock_op,
667 LoopDevice **ret) {
668
669 _cleanup_close_ int fd = -EBADF, mfd = -EBADF;
670 _cleanup_free_ char *fn = NULL;
671 struct stat st;
672 int r;
673
674 assert(path);
675 assert(IN_SET(open_flags, O_RDWR, O_RDONLY));
676 assert(ret);
677
678 loop_flags &= ~LO_FLAGS_DIRECT_IO; /* memfds don't support O_DIRECT, hence LO_FLAGS_DIRECT_IO can't be used either */
679
680 fd = open(path, O_CLOEXEC|O_NONBLOCK|O_NOCTTY|O_RDONLY);
681 if (fd < 0)
682 return -errno;
683
684 if (fstat(fd, &st) < 0)
685 return -errno;
686
687 if (!S_ISREG(st.st_mode) && !S_ISBLK(st.st_mode))
688 return -EBADF;
689
690 r = path_extract_filename(path, &fn);
691 if (r < 0)
692 return r;
693
694 mfd = memfd_clone_fd(fd, fn, open_flags|O_CLOEXEC);
695 if (mfd < 0)
696 return mfd;
697
698 fd = safe_close(fd); /* Let's close the original early */
699
700 return loop_device_make_internal(NULL, mfd, open_flags, 0, 0, 0, loop_flags, lock_op, ret);
701}
702
36d5eb0b 703static LoopDevice* loop_device_free(LoopDevice *d) {
5bb1d7fb 704 _cleanup_close_ int control = -EBADF;
3a6ed1e1
LP
705 int r;
706
8c1be37e
LP
707 if (!d)
708 return NULL;
709
4c1d50e6
LP
710 /* Release any lock we might have on the device first. We want to open+lock the /dev/loop-control
711 * device below, but our lock protocol says that if both control and block device locks are taken,
712 * the control lock needs to be taken first, the block device lock second — in order to avoid ABBA
713 * locking issues. Moreover, we want to issue LOOP_CLR_FD on the block device further down, and that
714 * would fail if we had another fd open to the device. */
7f52206a
LP
715 d->lock_fd = safe_close(d->lock_fd);
716
4c1d50e6
LP
717 /* Let's open the control device early, and lock it, so that we can release our block device and
718 * delete it in a synchronized fashion, and allocators won't needlessly see the block device as free
719 * while we are about to delete it. */
7cb349f0 720 if (!LOOP_DEVICE_IS_FOREIGN(d) && !d->relinquished) {
4c1d50e6
LP
721 control = open("/dev/loop-control", O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
722 if (control < 0)
723 log_debug_errno(errno, "Failed to open loop control device, cannot remove loop device '%s', ignoring: %m", strna(d->node));
724 else if (flock(control, LOCK_EX) < 0)
725 log_debug_errno(errno, "Failed to lock loop control device, ignoring: %m");
726 }
727
728 /* Then let's release the loopback block device */
8c1be37e 729 if (d->fd >= 0) {
cae1e8fb
LP
730 /* Implicitly sync the device, since otherwise in-flight blocks might not get written */
731 if (fsync(d->fd) < 0)
732 log_debug_errno(errno, "Failed to sync loop block device, ignoring: %m");
733
7cb349f0 734 if (!LOOP_DEVICE_IS_FOREIGN(d) && !d->relinquished) {
3a6ed1e1
LP
735 /* We are supposed to clear the loopback device. Let's do this synchronously: lock
736 * the device, manually remove all partitions and then clear it. This should ensure
737 * udev doesn't concurrently access the devices, and we can be reasonably sure that
738 * once we are done here the device is cleared and all its partition children
739 * removed. Note that we lock our primary device fd here (and not a separate locking
740 * fd, as we do during allocation, since we want to keep the lock all the way through
741 * the LOOP_CLR_FD, but that call would fail if we had more than one fd open.) */
8c1be37e 742
3a6ed1e1
LP
743 if (flock(d->fd, LOCK_EX) < 0)
744 log_debug_errno(errno, "Failed to lock loop block device, ignoring: %m");
745
46c3a288 746 r = block_device_remove_all_partitions(d->dev, d->fd);
3a6ed1e1
LP
747 if (r < 0)
748 log_debug_errno(r, "Failed to remove partitions of loopback block device, ignoring: %m");
749
750 if (ioctl(d->fd, LOOP_CLR_FD) < 0)
751 log_debug_errno(errno, "Failed to clear loop device, ignoring: %m");
8c1be37e
LP
752 }
753
754 safe_close(d->fd);
755 }
756
4c1d50e6
LP
757 /* Now that the block device is released, let's also try to remove it */
758 if (control >= 0)
759 for (unsigned n_attempts = 0;;) {
760 if (ioctl(control, LOOP_CTL_REMOVE, d->nr) >= 0)
761 break;
762 if (errno != EBUSY || ++n_attempts >= 64) {
763 log_debug_errno(errno, "Failed to remove device %s: %m", strna(d->node));
764 break;
f2d9213f 765 }
4c1d50e6
LP
766 (void) usleep(50 * USEC_PER_MSEC);
767 }
8c1be37e
LP
768
769 free(d->node);
cc5bae6c 770 sd_device_unref(d->dev);
e77cab82 771 free(d->backing_file);
5fecf46d 772 return mfree(d);
8c1be37e 773}
a2ea3b2f 774
36d5eb0b
YW
775DEFINE_TRIVIAL_REF_UNREF_FUNC(LoopDevice, loop_device, loop_device_free);
776
a2ea3b2f
LP
777void loop_device_relinquish(LoopDevice *d) {
778 assert(d);
779
780 /* Don't attempt to clean up the loop device anymore from this point on. Leave the clean-ing up to the kernel
781 * itself, using the loop device "auto-clear" logic we already turned on when creating the device. */
782
783 d->relinquished = true;
784}
9dabc4fd 785
24d59aee
DDM
786void loop_device_unrelinquish(LoopDevice *d) {
787 assert(d);
788 d->relinquished = false;
789}
790
4f0ad43e
YW
791int loop_device_open(
792 sd_device *dev,
7f52206a
LP
793 int open_flags,
794 int lock_op,
795 LoopDevice **ret) {
796
254d1313 797 _cleanup_close_ int fd = -EBADF, lock_fd = -EBADF;
4f0ad43e 798 _cleanup_free_ char *node = NULL, *backing_file = NULL;
b26c39ad 799 struct loop_info64 info;
ffcb3324 800 uint64_t diskseq = 0;
9dabc4fd 801 LoopDevice *d;
4f0ad43e
YW
802 const char *s;
803 dev_t devnum;
a8d8a619 804 int r, nr = -1;
9dabc4fd 805
4f0ad43e 806 assert(dev);
e8c7c4d9 807 assert(IN_SET(open_flags, O_RDWR, O_RDONLY));
9dabc4fd
LP
808 assert(ret);
809
4f0ad43e
YW
810 /* Even if fd is provided through the argument in loop_device_open_from_fd(), we reopen the inode
811 * here, instead of keeping just a dup() clone of it around, since we want to ensure that the
812 * O_DIRECT flag of the handle we keep is off, we have our own file index, and have the right
813 * read/write mode in effect. */
814 fd = sd_device_open(dev, O_CLOEXEC|O_NONBLOCK|O_NOCTTY|open_flags);
815 if (fd < 0)
816 return fd;
cc5bae6c 817
4f0ad43e
YW
818 if ((lock_op & ~LOCK_NB) != LOCK_UN) {
819 lock_fd = open_lock_fd(fd, lock_op);
820 if (lock_fd < 0)
821 return lock_fd;
a8d8a619
YW
822 }
823
4f0ad43e 824 if (ioctl(fd, LOOP_GET_STATUS64, &info) >= 0) {
10c1b188
LP
825#if HAVE_VALGRIND_MEMCHECK_H
826 /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
827 VALGRIND_MAKE_MEM_DEFINED(&info, sizeof(info));
828#endif
b26c39ad 829 nr = info.lo_number;
e77cab82
YW
830
831 if (sd_device_get_sysattr_value(dev, "loop/backing_file", &s) >= 0) {
832 backing_file = strdup(s);
833 if (!backing_file)
834 return -ENOMEM;
835 }
a8d8a619 836 }
b26c39ad 837
4f0ad43e 838 r = fd_get_diskseq(fd, &diskseq);
ffcb3324
YW
839 if (r < 0 && r != -EOPNOTSUPP)
840 return r;
841
4f0ad43e
YW
842 r = sd_device_get_devnum(dev, &devnum);
843 if (r < 0)
844 return r;
7f52206a 845
4f0ad43e 846 r = sd_device_get_devname(dev, &s);
cc5bae6c
YW
847 if (r < 0)
848 return r;
849
4f0ad43e
YW
850 node = strdup(s);
851 if (!node)
cc5bae6c 852 return -ENOMEM;
9dabc4fd
LP
853
854 d = new(LoopDevice, 1);
855 if (!d)
856 return -ENOMEM;
857
858 *d = (LoopDevice) {
36d5eb0b 859 .n_ref = 1,
a8d8a619 860 .fd = TAKE_FD(fd),
7f52206a 861 .lock_fd = TAKE_FD(lock_fd),
b26c39ad 862 .nr = nr,
4f0ad43e
YW
863 .node = TAKE_PTR(node),
864 .dev = sd_device_ref(dev),
e77cab82 865 .backing_file = TAKE_PTR(backing_file),
9dabc4fd 866 .relinquished = true, /* It's not ours, don't try to destroy it when this object is freed */
4f0ad43e 867 .devno = devnum,
ffcb3324 868 .diskseq = diskseq,
31c75fcc 869 .uevent_seqnum_not_before = UINT64_MAX,
8ede1e86 870 .timestamp_not_before = USEC_INFINITY,
9dabc4fd
LP
871 };
872
873 *ret = d;
4f0ad43e
YW
874 return 0;
875}
876
877int loop_device_open_from_fd(
878 int fd,
879 int open_flags,
880 int lock_op,
881 LoopDevice **ret) {
882
883 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
884 int r;
885
886 assert(fd >= 0);
887
888 r = block_device_new_from_fd(fd, 0, &dev);
889 if (r < 0)
890 return r;
891
892 return loop_device_open(dev, open_flags, lock_op, ret);
893}
894
895int loop_device_open_from_path(
896 const char *path,
897 int open_flags,
898 int lock_op,
899 LoopDevice **ret) {
900
901 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
902 int r;
903
904 assert(path);
905
906 r = block_device_new_from_path(path, 0, &dev);
907 if (r < 0)
908 return r;
909
910 return loop_device_open(dev, open_flags, lock_op, ret);
9dabc4fd
LP
911}
912
f1443709
LP
913static int resize_partition(int partition_fd, uint64_t offset, uint64_t size) {
914 char sysfs[STRLEN("/sys/dev/block/:/partition") + 2*DECIMAL_STR_MAX(dev_t) + 1];
ca822829 915 _cleanup_free_ char *buffer = NULL;
f1443709 916 uint64_t current_offset, current_size, partno;
254d1313 917 _cleanup_close_ int whole_fd = -EBADF;
f1443709
LP
918 struct stat st;
919 dev_t devno;
920 int r;
921
922 assert(partition_fd >= 0);
923
924 /* Resizes the partition the loopback device refer to (assuming it refers to one instead of an actual
925 * loopback device), and changes the offset, if needed. This is a fancy wrapper around
926 * BLKPG_RESIZE_PARTITION. */
927
928 if (fstat(partition_fd, &st) < 0)
929 return -errno;
930
931 assert(S_ISBLK(st.st_mode));
932
ed13feff 933 xsprintf(sysfs, "/sys/dev/block/" DEVNUM_FORMAT_STR "/partition", DEVNUM_FORMAT_VAL(st.st_rdev));
f1443709
LP
934 r = read_one_line_file(sysfs, &buffer);
935 if (r == -ENOENT) /* not a partition, cannot resize */
936 return -ENOTTY;
937 if (r < 0)
938 return r;
939 r = safe_atou64(buffer, &partno);
940 if (r < 0)
941 return r;
942
ed13feff 943 xsprintf(sysfs, "/sys/dev/block/" DEVNUM_FORMAT_STR "/start", DEVNUM_FORMAT_VAL(st.st_rdev));
f1443709
LP
944
945 buffer = mfree(buffer);
946 r = read_one_line_file(sysfs, &buffer);
947 if (r < 0)
948 return r;
949 r = safe_atou64(buffer, &current_offset);
950 if (r < 0)
951 return r;
952 if (current_offset > UINT64_MAX/512U)
953 return -EINVAL;
954 current_offset *= 512U;
955
956 if (ioctl(partition_fd, BLKGETSIZE64, &current_size) < 0)
957 return -EINVAL;
958
959 if (size == UINT64_MAX && offset == UINT64_MAX)
960 return 0;
961 if (current_size == size && current_offset == offset)
962 return 0;
963
ed13feff 964 xsprintf(sysfs, "/sys/dev/block/" DEVNUM_FORMAT_STR "/../dev", DEVNUM_FORMAT_VAL(st.st_rdev));
f1443709
LP
965
966 buffer = mfree(buffer);
967 r = read_one_line_file(sysfs, &buffer);
968 if (r < 0)
969 return r;
7176f06c 970 r = parse_devnum(buffer, &devno);
f1443709
LP
971 if (r < 0)
972 return r;
973
ca822829 974 whole_fd = r = device_open_from_devnum(S_IFBLK, devno, O_RDWR|O_CLOEXEC|O_NONBLOCK|O_NOCTTY, NULL);
f1443709
LP
975 if (r < 0)
976 return r;
977
91e1ce1a
LP
978 return block_device_resize_partition(
979 whole_fd,
980 partno,
981 offset == UINT64_MAX ? current_offset : offset,
982 size == UINT64_MAX ? current_size : size);
f1443709
LP
983}
984
c37878fc
LP
985int loop_device_refresh_size(LoopDevice *d, uint64_t offset, uint64_t size) {
986 struct loop_info64 info;
ff27ef4b 987
9dabc4fd 988 assert(d);
ff27ef4b 989 assert(d->fd >= 0);
9dabc4fd 990
f1443709
LP
991 /* Changes the offset/start of the loop device relative to the beginning of the underlying file or
992 * block device. If this loop device actually refers to a partition and not a loopback device, we'll
993 * try to adjust the partition offsets instead.
994 *
995 * If either offset or size is UINT64_MAX we won't change that parameter. */
996
f1443709
LP
997 if (d->nr < 0) /* not a loopback device */
998 return resize_partition(d->fd, offset, size);
999
c37878fc
LP
1000 if (ioctl(d->fd, LOOP_GET_STATUS64, &info) < 0)
1001 return -errno;
1002
10c1b188
LP
1003#if HAVE_VALGRIND_MEMCHECK_H
1004 /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
1005 VALGRIND_MAKE_MEM_DEFINED(&info, sizeof(info));
1006#endif
1007
c37878fc
LP
1008 if (size == UINT64_MAX && offset == UINT64_MAX)
1009 return 0;
1010 if (info.lo_sizelimit == size && info.lo_offset == offset)
1011 return 0;
1012
1013 if (size != UINT64_MAX)
1014 info.lo_sizelimit = size;
1015 if (offset != UINT64_MAX)
1016 info.lo_offset = offset;
1017
7c248223 1018 return RET_NERRNO(ioctl(d->fd, LOOP_SET_STATUS64, &info));
9dabc4fd 1019}
441ec804
LP
1020
1021int loop_device_flock(LoopDevice *d, int operation) {
7f52206a 1022 assert(IN_SET(operation & ~LOCK_NB, LOCK_UN, LOCK_SH, LOCK_EX));
441ec804
LP
1023 assert(d);
1024
7f52206a
LP
1025 /* When unlocking just close the lock fd */
1026 if ((operation & ~LOCK_NB) == LOCK_UN) {
1027 d->lock_fd = safe_close(d->lock_fd);
1028 return 0;
1029 }
1030
1031 /* If we had no lock fd so far, create one and lock it right-away */
1032 if (d->lock_fd < 0) {
1033 assert(d->fd >= 0);
1034
1035 d->lock_fd = open_lock_fd(d->fd, operation);
1036 if (d->lock_fd < 0)
1037 return d->lock_fd;
1038
1039 return 0;
1040 }
441ec804 1041
7f52206a
LP
1042 /* Otherwise change the current lock mode on the existing fd */
1043 return RET_NERRNO(flock(d->lock_fd, operation));
441ec804 1044}
8dbc208c
LP
1045
1046int loop_device_sync(LoopDevice *d) {
1047 assert(d);
ff27ef4b 1048 assert(d->fd >= 0);
8dbc208c
LP
1049
1050 /* We also do this implicitly in loop_device_unref(). Doing this explicitly here has the benefit that
1051 * we can check the return value though. */
1052
7c248223 1053 return RET_NERRNO(fsync(d->fd));
8dbc208c 1054}