• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 24429739682

14 Apr 2026 10:26PM UTC coverage: 72.318% (+0.03%) from 72.291%
24429739682

push

github

bluca
mkosi: update fedora commit reference to 207e2d004

* 207e2d0044 Stop building support for openssl engines
* 36a234147f Upload sources
* 3681163f81 Version 260.1
* 8f4f0f58e3 Version 260
* e3fab23aa0 Version 260~rc4
* e4c1c2100b Version 260~rc3
* 453696813e Fix typo in unit name in %post scriptlet
* 154edb7cdb Silence false positive "HWID match failed, no DT blob" error (rhbz#2444759)
* 03b6637c35 riscv64 port has LTO disabled
* ce1dec6a40 Version 260~rc2
* 809049777c Add patch for symlink creation error
* 6ff27708f7 Enable getty@.service through presets
* ba7807fbce Drop scriptlet for upgrades from versions <253
* 455f277188 Move support for tpm2 to systemd-udev subpackage
* 0183bc784e Version 260~rc1

321299 of 444286 relevant lines covered (72.32%)

1183364.59 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

63.36
/src/shared/loop-util.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#if HAVE_VALGRIND_MEMCHECK_H
4
#include <valgrind/memcheck.h>
5
#endif
6

7
#include <fcntl.h>
8
#include <linux/loop.h>
9
#include <sys/file.h>
10
#include <sys/ioctl.h>
11
#include <unistd.h>
12

13
#include "sd-device.h"
14

15
#include "alloc-util.h"
16
#include "blockdev-util.h"
17
#include "data-fd-util.h"
18
#include "device-util.h"
19
#include "devnum-util.h"
20
#include "dissect-image.h"
21
#include "env-util.h"
22
#include "errno-util.h"
23
#include "fd-util.h"
24
#include "fileio.h"
25
#include "fs-util.h"
26
#include "loop-util.h"
27
#include "parse-util.h"
28
#include "path-util.h"
29
#include "random-util.h"
30
#include "stat-util.h"
31
#include "stdio-util.h"
32
#include "string-util.h"
33
#include "time-util.h"
34

35
static void cleanup_clear_loop_close(int *fd) {
2,535✔
36
        assert(fd);
2,535✔
37

38
        if (*fd < 0)
2,535✔
39
                return;
40

41
        (void) ioctl(*fd, LOOP_CLR_FD);
×
42
        (void) safe_close(*fd);
×
43
}
44

45
static int loop_is_bound(int fd) {
2,535✔
46
        struct loop_info64 info;
2,535✔
47

48
        if (ioctl(ASSERT_FD(fd), LOOP_GET_STATUS64, &info) < 0) {
2,535✔
49
                if (errno == ENXIO)
2,535✔
50
                        return false; /* not bound! */
2,535✔
51

52
                return -errno;
×
53
        }
54

55
        return true; /* bound! */
56
}
57

58
static int open_lock_fd(int primary_fd, int operation) {
2,668✔
59
        _cleanup_close_ int lock_fd = -EBADF;
2,668✔
60

61
        assert(IN_SET(operation & ~LOCK_NB, LOCK_SH, LOCK_EX));
2,668✔
62

63
        lock_fd = fd_reopen(ASSERT_FD(primary_fd), O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2,668✔
64
        if (lock_fd < 0)
2,668✔
65
                return lock_fd;
66

67
        if (flock(lock_fd, operation) < 0)
2,668✔
68
                return -errno;
×
69

70
        return TAKE_FD(lock_fd);
71
}
72

73
static int loop_configure_verify_direct_io(int fd, const struct loop_config *c) {
2,535✔
74
        assert(fd >= 0);
2,535✔
75
        assert(c);
2,535✔
76

77
        if (FLAGS_SET(c->info.lo_flags, LO_FLAGS_DIRECT_IO)) {
2,535✔
78
                struct loop_info64 info;
2,534✔
79

80
                if (ioctl(fd, LOOP_GET_STATUS64, &info) < 0)
2,534✔
81
                        return log_debug_errno(errno, "Failed to issue LOOP_GET_STATUS64: %m");
×
82

83
#if HAVE_VALGRIND_MEMCHECK_H
84
                VALGRIND_MAKE_MEM_DEFINED(&info, sizeof(info));
85
#endif
86

87
                /* On older kernels (<= 5.3) it was necessary to set the block size of the loopback block
88
                 * device to the logical block size of the underlying file system. Since there was no nice
89
                 * way to query the value, we are not bothering to do this however. On newer kernels the
90
                 * block size is propagated automatically and does not require intervention from us. We'll
91
                 * check here if enabling direct IO worked, to make this easily debuggable however.
92
                 *
93
                 * (Should anyone really care and actually wants direct IO on old kernels: it might be worth
94
                 * enabling direct IO with iteratively larger block sizes until it eventually works.)
95
                 *
96
                 * On older kernels (e.g.: 5.10) when this is attempted on a file stored on a dm-crypt
97
                 * backed partition the kernel will start returning I/O errors when accessing the mounted
98
                 * loop device, so return a recognizable error that causes the operation to be started
99
                 * from scratch without the LO_FLAGS_DIRECT_IO flag. */
100
                if (!FLAGS_SET(info.lo_flags, LO_FLAGS_DIRECT_IO))
2,534✔
101
                        return log_debug_errno(
×
102
                                        SYNTHETIC_ERRNO(ENOANO),
103
                                        "Could not enable direct IO mode, retrying in buffered IO mode.");
104
        }
105

106
        return 0;
107
}
108

109
static int loop_configure_verify(int fd, const struct loop_config *c) {
2,535✔
110
        bool broken = false;
2,535✔
111
        int r;
2,535✔
112

113
        assert(fd >= 0);
2,535✔
114
        assert(c);
2,535✔
115

116
        if (c->block_size != 0) {
2,535✔
117
                uint32_t ssz;
2,535✔
118

119
                r = blockdev_get_sector_size(fd, &ssz);
2,535✔
120
                if (r < 0)
2,535✔
121
                        return r;
×
122

123
                if (ssz != c->block_size) {
2,535✔
124
                        log_debug("LOOP_CONFIGURE didn't honour requested block size %" PRIu32 ", got %" PRIu32 " instead. Ignoring.", c->block_size, ssz);
×
125
                        broken = true;
126
                }
127
        }
128

129
        if (c->info.lo_sizelimit != 0) {
2,535✔
130
                /* Kernel 5.8 vanilla doesn't properly propagate the size limit into the
131
                 * block device. If it's used, let's immediately check if it had the desired
132
                 * effect hence. And if not use classic LOOP_SET_STATUS64. */
133
                uint64_t z;
99✔
134

135
                r = blockdev_get_device_size(fd, &z);
99✔
136
                if (r < 0)
99✔
137
                        return r;
×
138

139
                if (z != c->info.lo_sizelimit) {
99✔
140
                        log_debug("LOOP_CONFIGURE is broken, doesn't honour .info.lo_sizelimit. Falling back to LOOP_SET_STATUS64.");
×
141
                        broken = true;
142
                }
143
        }
144

145
        if (FLAGS_SET(c->info.lo_flags, LO_FLAGS_PARTSCAN)) {
2,535✔
146
                /* Kernel 5.8 vanilla doesn't properly propagate the partition scanning flag
147
                 * into the block device. Let's hence verify if things work correctly here
148
                 * before returning. */
149

150
                r = blockdev_partscan_enabled_fd(fd);
×
151
                if (r < 0)
×
152
                        return r;
153
                if (r == 0) {
×
154
                        log_debug("LOOP_CONFIGURE is broken, doesn't honour LO_FLAGS_PARTSCAN. Falling back to LOOP_SET_STATUS64.");
×
155
                        broken = true;
156
                }
157
        }
158

159
        r = loop_configure_verify_direct_io(fd, c);
2,535✔
160
        if (r < 0)
2,535✔
161
                return r;
162

163
        return !broken;
2,535✔
164
}
165

166
static int loop_configure_fallback(int fd, const struct loop_config *c) {
×
167
        struct loop_info64 info_copy;
×
168
        int r;
×
169

170
        assert(fd >= 0);
×
171
        assert(c);
×
172

173
        /* Only some of the flags LOOP_CONFIGURE can set are also settable via LOOP_SET_STATUS64, hence mask
174
         * them out. */
175
        info_copy = c->info;
×
176
        info_copy.lo_flags &= LOOP_SET_STATUS_SETTABLE_FLAGS;
×
177

178
        /* Since kernel commit 5db470e229e22b7eda6e23b5566e532c96fb5bc3 (kernel v5.0) the LOOP_SET_STATUS64
179
         * ioctl can return EAGAIN in case we change the info.lo_offset field, if someone else is accessing the
180
         * block device while we try to reconfigure it. This is a pretty common case, since udev might
181
         * instantly start probing the device as soon as we attach an fd to it. Hence handle it in two ways:
182
         * first, let's take the BSD lock to ensure that udev will not step in between the point in
183
         * time where we attach the fd and where we reconfigure the device. Secondly, let's wait 50ms on
184
         * EAGAIN and retry. The former should be an efficient mechanism to avoid we have to wait 50ms
185
         * needlessly if we are just racing against udev. The latter is protection against all other cases,
186
         * i.e. peers that do not take the BSD lock. */
187

188
        for (unsigned n_attempts = 0;;) {
×
189
                if (ioctl(fd, LOOP_SET_STATUS64, &info_copy) >= 0)
×
190
                        break;
191

192
                if (errno != EAGAIN || ++n_attempts >= 64)
×
193
                        return log_debug_errno(errno, "Failed to configure loopback block device: %m");
×
194

195
                /* Sleep some random time, but at least 10ms, at most 250ms. Increase the delay the more
196
                 * failed attempts we see */
197
                (void) usleep_safe(UINT64_C(10) * USEC_PER_MSEC +
×
198
                              random_u64_range(UINT64_C(240) * USEC_PER_MSEC * n_attempts/64));
×
199
        }
200

201
        /* If a block size is requested then try to configure it. If that doesn't work, ignore errors, but
202
         * afterwards, let's validate what is in effect, and if it doesn't match what we want, fail */
203
        if (c->block_size != 0) {
×
204
                uint32_t ssz;
×
205

206
                if (ioctl(fd, LOOP_SET_BLOCK_SIZE, (unsigned long) c->block_size) < 0)
×
207
                        log_debug_errno(errno, "Failed to set sector size, ignoring: %m");
×
208

209
                r = blockdev_get_sector_size(fd, &ssz);
×
210
                if (r < 0)
×
211
                        return log_debug_errno(r, "Failed to read sector size: %m");
×
212
                if (ssz != c->block_size)
×
213
                        return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Sector size of loopback device doesn't match what we requested, refusing.");
×
214
        }
215

216
        /* LO_FLAGS_DIRECT_IO is a flags we need to configure via explicit ioctls. */
217
        if (FLAGS_SET(c->info.lo_flags, LO_FLAGS_DIRECT_IO))
×
218
                if (ioctl(fd, LOOP_SET_DIRECT_IO, 1UL) < 0)
×
219
                        log_debug_errno(errno, "Failed to enable direct IO mode, ignoring: %m");
×
220

221
        return loop_configure_verify_direct_io(fd, c);
×
222
}
223

224
static int loop_configure(
2,535✔
225
                int nr,
226
                int open_flags,
227
                int lock_op,
228
                const struct loop_config *c,
229
                LoopDevice **ret) {
230

231
        static bool loop_configure_broken = false;
2,535✔
232

233
        _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
2,535✔
234
        _cleanup_(cleanup_clear_loop_close) int loop_with_fd = -EBADF; /* This must be declared before lock_fd. */
×
235
        _cleanup_close_ int fd = -EBADF, lock_fd = -EBADF;
5,070✔
236
        _cleanup_free_ char *node = NULL;
2,535✔
237
        uint64_t diskseq = 0;
2,535✔
238
        dev_t devno;
2,535✔
239
        int r;
2,535✔
240

241
        assert(nr >= 0);
2,535✔
242
        assert(c);
2,535✔
243
        assert(ret);
2,535✔
244

245
        if (asprintf(&node, "/dev/loop%i", nr) < 0)
2,535✔
246
                return log_oom_debug();
×
247

248
        r = sd_device_new_from_devname(&dev, node);
2,535✔
249
        if (r < 0)
2,535✔
250
                return log_debug_errno(r, "Failed to create sd_device object for \"%s\": %m", node);
×
251

252
        r = sd_device_get_devnum(dev, &devno);
2,535✔
253
        if (r < 0)
2,535✔
254
                return log_device_debug_errno(dev, r, "Failed to get devnum: %m");
×
255

256
        fd = sd_device_open(dev, O_CLOEXEC|O_NONBLOCK|O_NOCTTY|open_flags);
2,535✔
257
        if (fd < 0)
2,535✔
258
                return log_device_debug_errno(dev, fd, "Failed to open device: %m");
×
259

260
        /* Let's lock the device before we do anything. We take the BSD lock on a second, separately opened
261
         * fd for the device. udev after all watches for close() events (specifically IN_CLOSE_WRITE) on
262
         * block devices to reprobe them, hence by having a separate fd we will later close() we can ensure
263
         * we trigger udev after everything is done. If we'd lock our own fd instead and keep it open for a
264
         * long time udev would possibly never run on it again, even though the fd is unlocked, simply
265
         * because we never close() it. It also has the nice benefit we can use the _cleanup_close_ logic to
266
         * automatically release the lock, after we are done. */
267
        lock_fd = open_lock_fd(fd, LOCK_EX);
2,535✔
268
        if (lock_fd < 0)
2,535✔
269
                return log_device_debug_errno(dev, lock_fd, "Failed to acquire lock: %m");
×
270

271
        log_device_debug(dev, "Acquired exclusive lock.");
2,562✔
272

273
        /* Let's see if backing file is really unattached. Someone may already attach a backing file without
274
         * taking BSD lock. */
275
        r = loop_is_bound(fd);
2,535✔
276
        if (r < 0)
2,535✔
277
                return log_device_debug_errno(dev, r, "Failed to check if the loopback block device is bound: %m");
×
278
        if (r > 0)
2,535✔
279
                return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EBUSY),
×
280
                                              "The loopback block device is already bound, ignoring.");
281

282
        /* Let's see if the device is really detached, i.e. currently has no associated partition block
283
         * devices. On various kernels (such as 5.8) it is possible to have a loopback block device that
284
         * superficially is detached but still has partition block devices associated for it. Let's then
285
         * manually remove the partitions via BLKPG, and tell the caller we did that via EUCLEAN, so they try
286
         * again. */
287
        r = block_device_remove_all_partitions(dev, fd);
2,535✔
288
        if (r < 0)
2,535✔
289
                return log_device_debug_errno(dev, r, "Failed to remove partitions on the loopback block device: %m");
×
290
        if (r > 0)
2,535✔
291
                /* Removed all partitions. Let's report this to the caller, to try again, and count this as
292
                 * an attempt. */
293
                return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EUCLEAN),
×
294
                                              "Removed partitions on the loopback block device.");
295

296
        if (!loop_configure_broken) {
2,535✔
297
                if (ioctl(fd, LOOP_CONFIGURE, c) < 0) {
2,535✔
298
                        /* Do fallback only if LOOP_CONFIGURE is not supported, propagate all other errors. */
299
                        if (!ERRNO_IS_IOCTL_NOT_SUPPORTED(errno))
×
300
                                return log_device_debug_errno(dev, errno, "ioctl(LOOP_CONFIGURE) failed: %m");
×
301

302
                        loop_configure_broken = true;
×
303
                } else {
304
                        loop_with_fd = TAKE_FD(fd);
2,535✔
305

306
                        r = loop_configure_verify(loop_with_fd, c);
2,535✔
307
                        if (r < 0)
2,535✔
308
                                return log_device_debug_errno(dev, r, "Failed to verify if loopback block device is correctly configured: %m");
×
309
                        if (r == 0) {
2,535✔
310
                                /* LOOP_CONFIGURE doesn't work. Remember that. */
311
                                loop_configure_broken = true;
×
312

313
                                /* We return EBUSY here instead of retrying immediately with LOOP_SET_FD,
314
                                 * because LOOP_CLR_FD is async: if the operation cannot be executed right
315
                                 * away it just sets the autoclear flag on the device. This means there's a
316
                                 * good chance we cannot actually reuse the loopback device right-away. Hence
317
                                 * let's assume it's busy, avoid the trouble and let the calling loop call us
318
                                 * again with a new, likely unused device. */
319
                                return -EBUSY;
×
320
                        }
321
                }
322
        }
323

324
        if (loop_configure_broken) {
2,535✔
325
                if (ioctl(fd, LOOP_SET_FD, c->fd) < 0)
×
326
                        return log_device_debug_errno(dev, errno, "ioctl(LOOP_SET_FD) failed: %m");
×
327

328
                loop_with_fd = TAKE_FD(fd);
×
329

330
                r = loop_configure_fallback(loop_with_fd, c);
×
331
                if (r < 0)
×
332
                        return r;
333
        }
334

335
        r = fd_get_diskseq(loop_with_fd, &diskseq);
2,535✔
336
        if (r < 0 && r != -EOPNOTSUPP)
2,535✔
337
                return log_device_debug_errno(dev, r, "Failed to get diskseq: %m");
×
338

339
        switch (lock_op & ~LOCK_NB) {
2,535✔
340
        case LOCK_EX: /* Already in effect */
341
                break;
342
        case LOCK_SH: /* Downgrade */
2,402✔
343
                if (flock(lock_fd, lock_op) < 0)
2,402✔
344
                        return log_device_debug_errno(dev, errno, "Failed to downgrade lock level: %m");
×
345
                break;
346
        case LOCK_UN: /* Release */
×
347
                lock_fd = safe_close(lock_fd);
×
348
                break;
349
        default:
×
350
                assert_not_reached();
×
351
        }
352

353
        uint64_t device_size;
2,535✔
354
        r = blockdev_get_device_size(loop_with_fd, &device_size);
2,535✔
355
        if (r < 0)
2,535✔
356
                return log_device_debug_errno(dev, r, "Failed to get loopback device size: %m");
×
357

358
        LoopDevice *d = new(LoopDevice, 1);
2,535✔
359
        if (!d)
2,535✔
360
                return log_oom_debug();
×
361

362
        *d = (LoopDevice) {
2,535✔
363
                .n_ref = 1,
364
                .fd = TAKE_FD(loop_with_fd),
2,535✔
365
                .lock_fd = TAKE_FD(lock_fd),
2,535✔
366
                .node = TAKE_PTR(node),
2,535✔
367
                .nr = nr,
368
                .devno = devno,
369
                .dev = TAKE_PTR(dev),
2,535✔
370
                .diskseq = diskseq,
371
                .sector_size = c->block_size,
2,535✔
372
                .device_size = device_size,
373
                .created = true,
374
        };
375

376
        *ret = TAKE_PTR(d);
2,535✔
377
        return 0;
2,535✔
378
}
379

380
static int fd_get_max_discard(int fd, uint64_t *ret) {
×
381
        char sysfs_path[STRLEN("/sys/dev/block/" ":" "/queue/discard_max_bytes") + DECIMAL_STR_MAX(dev_t) * 2 + 1];
×
382
        _cleanup_free_ char *buffer = NULL;
×
383
        struct stat st;
×
384
        int r;
×
385

386
        assert(ret);
×
387

388
        if (fstat(ASSERT_FD(fd), &st) < 0)
×
389
                return -errno;
×
390

391
        r = stat_verify_block(&st);
×
392
        if (r < 0)
×
393
                return r;
394

395
        xsprintf(sysfs_path, "/sys/dev/block/" DEVNUM_FORMAT_STR "/queue/discard_max_bytes", DEVNUM_FORMAT_VAL(st.st_rdev));
×
396

397
        r = read_one_line_file(sysfs_path, &buffer);
×
398
        if (r < 0)
×
399
                return r;
400

401
        return safe_atou64(buffer, ret);
×
402
}
403

404
static int fd_set_max_discard(int fd, uint64_t max_discard) {
×
405
        char sysfs_path[STRLEN("/sys/dev/block/" ":" "/queue/discard_max_bytes") + DECIMAL_STR_MAX(dev_t) * 2 + 1];
×
406
        struct stat st;
×
407
        int r;
×
408

409
        if (fstat(ASSERT_FD(fd), &st) < 0)
×
410
                return -errno;
×
411

412
        r = stat_verify_block(&st);
×
413
        if (r < 0)
×
414
                return r;
415

416
        xsprintf(sysfs_path, "/sys/dev/block/" DEVNUM_FORMAT_STR "/queue/discard_max_bytes", DEVNUM_FORMAT_VAL(st.st_rdev));
×
417

418
        return write_string_filef(sysfs_path, WRITE_STRING_FILE_DISABLE_BUFFER, "%" PRIu64, max_discard);
×
419
}
420

421
static int probe_sector_size_harder(int fd, uint32_t *ret) {
2,422✔
422
        _cleanup_close_ int non_direct_io_fd = -EBADF;
2,422✔
423
        int probe_fd, f_flags;
2,422✔
424

425
        assert(fd >= 0);
2,422✔
426
        assert(ret);
2,422✔
427

428
        /* Wraps probe_sector_size() but handles O_DIRECT: if the fd is opened with O_DIRECT there are
429
         * strict alignment requirements for reads, so we temporarily reopen it without O_DIRECT for the
430
         * probing logic. */
431

432
        f_flags = fcntl(fd, F_GETFL);
2,422✔
433
        if (f_flags < 0)
2,422✔
434
                return -errno;
×
435

436
        if (FLAGS_SET(f_flags, O_DIRECT)) {
2,422✔
437
                non_direct_io_fd = fd_reopen(fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK);
2,415✔
438
                if (non_direct_io_fd < 0)
2,415✔
439
                        return non_direct_io_fd;
440

441
                probe_fd = non_direct_io_fd;
442
        } else
443
                probe_fd = fd;
444

445
        return probe_sector_size(probe_fd, ret);
2,422✔
446
}
447

448
static int loop_device_make_internal(
2,555✔
449
                const char *path,
450
                int fd,
451
                int open_flags,
452
                uint64_t offset,
453
                uint64_t size,
454
                uint32_t sector_size,
455
                uint32_t loop_flags,
456
                int lock_op,
457
                LoopDevice **ret) {
458

459
        _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
×
460
        _cleanup_close_ int reopened_fd = -EBADF, control = -EBADF;
5,110✔
461
        _cleanup_free_ char *backing_file = NULL;
2,555✔
462
        struct loop_config config;
2,555✔
463
        int r, f_flags;
2,555✔
464
        struct stat st;
2,555✔
465

466
        assert(fd >= 0);
2,555✔
467
        assert(open_flags < 0 || IN_SET(open_flags, O_RDWR, O_RDONLY));
2,555✔
468
        assert(ret);
2,555✔
469

470
        /* sector_size interpretation:
471
         *   0          → use device sector size for block devices, 512 for regular files
472
         *   UINT32_MAX → probe GPT header to find the right sector size, fall back to 0 behavior
473
         *   other      → use the specified sector size explicitly */
474

475
        f_flags = fcntl(fd, F_GETFL);
2,555✔
476
        if (f_flags < 0)
2,555✔
477
                return -errno;
×
478

479
        if (open_flags < 0) {
2,555✔
480
                /* If open_flags is unset, initialize it from the open fd */
481
                if (FLAGS_SET(f_flags, O_PATH))
6✔
482
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADFD), "Access mode of image file indicates O_PATH, cannot determine read/write flags.");
×
483

484
                open_flags = f_flags & O_ACCMODE_STRICT;
6✔
485
                if (!IN_SET(open_flags, O_RDWR, O_RDONLY))
6✔
486
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADFD), "Access mode of image file is write only (?)");
×
487
        }
488

489
        if (sector_size == UINT32_MAX) {
2,555✔
490
                /* If sector size is specified as UINT32_MAX, we'll try to probe the right sector size
491
                 * by looking for the GPT partition header at various offsets. This of course only works
492
                 * if the image already has a disk label. */
493

494
                r = probe_sector_size_harder(fd, &sector_size);
2,422✔
495
                if (r < 0)
2,422✔
496
                        return r;
497
                if (r == 0)
2,422✔
498
                        sector_size = 0; /* If we can't probe anything, use default sector size. */
2,305✔
499
        }
500

501
        if (fstat(fd, &st) < 0)
2,555✔
502
                return -errno;
×
503

504
        if (S_ISBLK(st.st_mode)) {
2,555✔
505
                uint32_t device_ssz;
×
506
                r = blockdev_get_sector_size(fd, &device_ssz);
×
507
                if (r < 0)
×
508
                        return r;
×
509

510
                if (sector_size == 0)
×
511
                        sector_size = device_ssz;
×
512

513
                if (offset == 0 && IN_SET(size, 0, UINT64_MAX) && sector_size == device_ssz)
×
514
                        /* If this is already a block device and we are supposed to cover the whole of it
515
                         * then store an fd to the original open device node — and do not actually create
516
                         * an unnecessary loopback device for it. If an explicit sector size was requested
517
                         * that differs from the device sector size, or if the probed GPT sector size
518
                         * differs (e.g. CD-ROMs with 2048-byte blocks but a 512-byte sector GPT), create
519
                         * a real loop device to change the sector size. */
520
                        return loop_device_open_from_fd(fd, open_flags, lock_op, ret);
×
521
        } else {
522
                r = stat_verify_regular(&st);
2,555✔
523
                if (r < 0)
2,555✔
524
                        return r;
525

526
                if (sector_size == 0)
2,555✔
527
                        sector_size = 512;
2,305✔
528
        }
529

530
        if (path) {
2,555✔
531
                r = path_make_absolute_cwd(path, &backing_file);
336✔
532
                if (r < 0)
336✔
533
                        return r;
534

535
                path_simplify(backing_file);
336✔
536
        } else {
537
                r = fd_get_path(fd, &backing_file);
2,219✔
538
                if (r < 0)
2,219✔
539
                        return r;
540
        }
541

542
        if (FLAGS_SET(loop_flags, LO_FLAGS_DIRECT_IO) != FLAGS_SET(f_flags, O_DIRECT)) {
2,555✔
543
                /* If LO_FLAGS_DIRECT_IO is requested, then make sure we have the fd open with O_DIRECT, as
544
                 * that's required. Conversely, if it's off require that O_DIRECT is off too (that's because
545
                 * new kernels will implicitly enable LO_FLAGS_DIRECT_IO if O_DIRECT is set).
546
                 *
547
                 * Our intention here is that LO_FLAGS_DIRECT_IO is the primary knob, and O_DIRECT derived
548
                 * from that automatically. */
549

550
                reopened_fd = fd_reopen(fd, (FLAGS_SET(loop_flags, LO_FLAGS_DIRECT_IO) ? O_DIRECT : 0)|O_CLOEXEC|O_NONBLOCK|open_flags);
139✔
551
                if (reopened_fd < 0) {
139✔
552
                        if (!FLAGS_SET(loop_flags, LO_FLAGS_DIRECT_IO))
×
553
                                return log_debug_errno(reopened_fd, "Failed to reopen file descriptor without O_DIRECT: %m");
×
554

555
                        /* Some file systems might not support O_DIRECT, let's gracefully continue without it then. */
556
                        log_debug_errno(reopened_fd, "Failed to enable O_DIRECT for backing file descriptor for loopback device. Continuing without.");
×
557
                        loop_flags &= ~LO_FLAGS_DIRECT_IO;
×
558
                } else
559
                        fd = reopened_fd; /* From now on, operate on our new O_DIRECT fd */
560
        }
561

562
        control = open("/dev/loop-control", O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
2,555✔
563
        if (control < 0)
2,555✔
564
                return -errno;
20✔
565

566
        /* Strip LO_FLAGS_PARTSCAN from LOOP_CONFIGURE and enable it afterwards via
567
         * LOOP_SET_STATUS64 to work around a kernel race: LOOP_CONFIGURE sends a uevent with
568
         * GD_NEED_PART_SCAN set before calling loop_reread_partitions(). If udev opens the device in
569
         * response, blkdev_get_whole() triggers a first scan, then loop_reread_partitions() does a
570
         * second scan that briefly drops all partitions. By configuring without partscan,
571
         * GD_SUPPRESS_PART_SCAN stays set, making any concurrent open harmless. LOOP_SET_STATUS64
572
         * doesn't call disk_force_media_change() so it doesn't set GD_NEED_PART_SCAN.
573
         *
574
         * See: https://lore.kernel.org/linux-block/20260330081819.652890-1-daan@amutable.com/T/#u
575
         * Drop this workaround once the kernel fix is widely available. */
576
        bool deferred_partscan = FLAGS_SET(loop_flags, LO_FLAGS_PARTSCAN);
2,535✔
577

578
        config = (struct loop_config) {
5,070✔
579
                .fd = fd,
580
                .block_size = sector_size,
581
                .info = {
582
                        /* Use the specified flags, but configure the read-only flag from the open flags, and force autoclear */
583
                        .lo_flags = ((loop_flags & ~(LO_FLAGS_READ_ONLY|LO_FLAGS_PARTSCAN)) |
5,070✔
584
                                     ((open_flags & O_ACCMODE_STRICT) == O_RDONLY ? LO_FLAGS_READ_ONLY : 0) |
2,535✔
585
                                     LO_FLAGS_AUTOCLEAR),
586
                        .lo_offset = offset,
587
                        .lo_sizelimit = size == UINT64_MAX ? 0 : size,
2,535✔
588
                },
589
        };
590

591
        /* Loop around LOOP_CTL_GET_FREE, since at the moment we attempt to open the returned device it might
592
         * be gone already, taken by somebody else racing against us. */
593
        for (unsigned n_attempts = 0;;) {
2,535✔
594
                usec_t usec;
2,535✔
595
                int nr;
2,535✔
596

597
                /* Let's take a lock on the control device first. On a busy system, where many programs
598
                 * attempt to allocate a loopback device at the same time, we might otherwise keep looping
599
                 * around relatively heavy operations: asking for a free loopback device, then opening it,
600
                 * validating it, attaching something to it. Let's serialize this whole operation, to make
601
                 * unnecessary busywork less likely. Note that this is just something we do to optimize our
602
                 * own code (and whoever else decides to use LOCK_EX locks for this), taking this lock is not
603
                 * necessary, it just means it's less likely we have to iterate through this loop again and
604
                 * again if our own code races against our own code.
605
                 *
606
                 * Note: our lock protocol is to take the /dev/loop-control lock first, and the block device
607
                 * lock second, if both are taken, and always in this order, to avoid ABBA locking issues. */
608
                if (flock(control, LOCK_EX) < 0)
2,535✔
609
                        return -errno;
×
610

611
                nr = ioctl(control, LOOP_CTL_GET_FREE);
2,535✔
612
                if (nr < 0)
2,535✔
613
                        return -errno;
×
614

615
                r = loop_configure(nr, open_flags, lock_op, &config, &d);
2,535✔
616
                if (r >= 0)
2,535✔
617
                        break;
618

619
                /* -ENODEV or friends: Somebody might've gotten the same number from the kernel, used the
620
                 * device, and called LOOP_CTL_REMOVE on it. Let's retry with a new number.
621
                 * -EBUSY: a file descriptor is already bound to the loopback block device.
622
                 * -EUCLEAN: some left-over partition devices that were cleaned up.
623
                 * -ENOANO: we tried to use LO_FLAGS_DIRECT_IO but the kernel rejected it. */
624
                if (!ERRNO_IS_DEVICE_ABSENT(r) && !IN_SET(r, -EBUSY, -EUCLEAN, -ENOANO))
×
625
                        return r;
626

627
                /* OK, this didn't work, let's try again a bit later, but first release the lock on the
628
                 * control device */
629
                if (flock(control, LOCK_UN) < 0)
×
630
                        return -errno;
×
631

632
                if (++n_attempts >= 64) /* Give up eventually */
×
633
                        return -EBUSY;
634

635
                /* If we failed to enable direct IO mode, let's retry without it. We restart the process as
636
                 * on some combination of kernel version and storage filesystem, the kernel is very unhappy
637
                 * about a failed DIRECT_IO enablement and throws I/O errors. */
638
                if (r == -ENOANO && FLAGS_SET(config.info.lo_flags, LO_FLAGS_DIRECT_IO)) {
×
639
                        config.info.lo_flags &= ~LO_FLAGS_DIRECT_IO;
×
640
                        open_flags &= ~O_DIRECT;
×
641

642
                        int non_direct_io_fd = fd_reopen(config.fd, O_CLOEXEC|O_NONBLOCK|open_flags);
×
643
                        if (non_direct_io_fd < 0)
×
644
                                return log_debug_errno(
×
645
                                                non_direct_io_fd,
646
                                                "Failed to reopen file descriptor without O_DIRECT: %m");
647

648
                        safe_close(reopened_fd);
×
649
                        fd = config.fd = /* For cleanups */ reopened_fd = non_direct_io_fd;
×
650
                }
651

652
                /* Wait some random time, to make collision less likely. Let's pick a random time in the
653
                 * range 0ms…250ms, linearly scaled by the number of failed attempts. */
654
                usec = random_u64_range(UINT64_C(10) * USEC_PER_MSEC +
×
655
                                        UINT64_C(240) * USEC_PER_MSEC * n_attempts/64);
×
656
                log_debug("Trying again after %s.", FORMAT_TIMESPAN(usec, USEC_PER_MSEC));
×
657
                (void) usleep_safe(usec);
×
658
        }
659

660
        if (S_ISBLK(st.st_mode)) {
2,535✔
661
                /* Propagate backing device's discard byte limit to our loopback block device. We do this in
662
                 * order to avoid that (supposedly quick) discard requests on the loopback device get turned
663
                 * into (likely slow) zero-out requests on backing devices that do not support discarding
664
                 * natively, but do support zero-out. */
665
                uint64_t discard_max_bytes;
×
666

667
                r = fd_get_max_discard(fd, &discard_max_bytes);
×
668
                if (r < 0)
×
669
                        log_debug_errno(r, "Failed to read 'discard_max_bytes' of backing device, ignoring: %m");
×
670
                else {
671
                        r = fd_set_max_discard(d->fd, discard_max_bytes);
×
672
                        if (r < 0)
×
673
                                log_debug_errno(r, "Failed to write 'discard_max_bytes' of loop device, ignoring: %m");
×
674
                }
675
        }
676

677
        if (deferred_partscan) {
2,535✔
678
                /* Open+close to drain GD_NEED_PART_SCAN harmlessly (GD_SUPPRESS_PART_SCAN is still
679
                 * set so no partitions appear). Then enable partscan via LOOP_SET_STATUS64. */
680
                int tmp_fd = fd_reopen(d->fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK);
2,358✔
681
                if (tmp_fd < 0)
2,358✔
682
                        return log_debug_errno(tmp_fd, "Failed to reopen loop device to drain partscan flag: %m");
×
683
                safe_close(tmp_fd);
2,358✔
684

685
                struct loop_info64 info;
2,358✔
686
                if (ioctl(d->fd, LOOP_GET_STATUS64, &info) < 0)
2,358✔
687
                        return log_debug_errno(errno, "Failed to get loop device status: %m");
×
688

689
                info.lo_flags |= LO_FLAGS_PARTSCAN;
2,358✔
690

691
                if (ioctl(d->fd, LOOP_SET_STATUS64, &info) < 0)
2,358✔
692
                        return log_debug_errno(errno, "Failed to enable partscan on loop device: %m");
×
693
        }
694

695
        d->backing_file = TAKE_PTR(backing_file);
2,535✔
696
        d->backing_inode = st.st_ino;
2,535✔
697
        d->backing_devno = st.st_dev;
2,535✔
698

699
        log_debug("Successfully acquired %s, devno=%u:%u, nr=%i, diskseq=%" PRIu64,
2,535✔
700
                  d->node,
701
                  major(d->devno), minor(d->devno),
702
                  d->nr,
703
                  d->diskseq);
704

705
        *ret = TAKE_PTR(d);
2,535✔
706
        return 0;
2,535✔
707
}
708

709
static uint32_t loop_flags_mangle(uint32_t loop_flags) {
2,555✔
710
        int r;
2,555✔
711

712
        r = getenv_bool("SYSTEMD_LOOP_DIRECT_IO");
2,555✔
713
        if (r < 0 && r != -ENXIO)
2,555✔
714
                log_debug_errno(r, "Failed to parse $SYSTEMD_LOOP_DIRECT_IO, ignoring: %m");
×
715

716
        return UPDATE_FLAG(loop_flags, LO_FLAGS_DIRECT_IO, r != 0); /* Turn on LO_FLAGS_DIRECT_IO by default, unless explicitly configured to off. */
2,555✔
717
}
718

719
int loop_device_make(
139✔
720
                int fd,
721
                int open_flags,
722
                uint64_t offset,
723
                uint64_t size,
724
                uint32_t sector_size,
725
                uint32_t loop_flags,
726
                int lock_op,
727
                LoopDevice **ret) {
728

729
        assert(fd >= 0);
139✔
730
        assert(ret);
139✔
731

732
        return loop_device_make_internal(
139✔
733
                        NULL,
734
                        fd,
735
                        open_flags,
736
                        offset,
737
                        size,
738
                        sector_size,
739
                        loop_flags_mangle(loop_flags),
740
                        lock_op,
741
                        ret);
742
}
743

744
int loop_device_make_by_path_at(
2,416✔
745
                int dir_fd,
746
                const char *path,
747
                int open_flags,
748
                uint32_t sector_size,
749
                uint32_t loop_flags,
750
                int lock_op,
751
                LoopDevice **ret) {
752

753
        int r, basic_flags, direct_flags, rdwr_flags;
2,416✔
754
        _cleanup_close_ int fd = -EBADF;
2,416✔
755
        bool direct = false;
2,416✔
756

757
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
2,416✔
758
        assert(ret);
2,416✔
759
        assert(open_flags < 0 || IN_SET(open_flags, O_RDWR, O_RDONLY));
2,416✔
760

761
        /* Passing < 0 as open_flags here means we'll try to open the device writable if we can, retrying
762
         * read-only if we cannot. */
763

764
        loop_flags = loop_flags_mangle(loop_flags);
2,416✔
765

766
        /* Let's open with O_DIRECT if we can. But not all file systems support that, hence fall back to
767
         * non-O_DIRECT mode automatically, if it fails. */
768

769
        basic_flags = O_CLOEXEC|O_NONBLOCK|O_NOCTTY;
2,416✔
770
        direct_flags = FLAGS_SET(loop_flags, LO_FLAGS_DIRECT_IO) ? O_DIRECT : 0;
2,416✔
771
        rdwr_flags = open_flags >= 0 ? open_flags : O_RDWR;
2,416✔
772

773
        fd = xopenat(dir_fd, path, basic_flags|direct_flags|rdwr_flags);
2,416✔
774
        if (fd < 0 && direct_flags != 0) /* If we had O_DIRECT on, and things failed with that, let's immediately try again without */
2,416✔
775
                fd = xopenat(dir_fd, path, basic_flags|rdwr_flags);
1✔
776
        else
777
                direct = direct_flags != 0;
×
778
        if (fd < 0) {
2,416✔
779
                r = fd;
1✔
780

781
                /* Retry read-only? */
782
                if (open_flags >= 0 || !ERRNO_IS_NEG_FS_WRITE_REFUSED(r))
2,417✔
783
                        return r;
784

785
                fd = xopenat(dir_fd, path, basic_flags|direct_flags|O_RDONLY);
×
786
                if (fd < 0 && direct_flags != 0) /* as above */
×
787
                        fd = xopenat(dir_fd, path, basic_flags|O_RDONLY);
×
788
                else
789
                        direct = direct_flags != 0;
×
790
                if (fd < 0)
×
791
                        return r; /* Propagate original error */
792

793
                open_flags = O_RDONLY;
794
        } else if (open_flags < 0)
2,415✔
795
                open_flags = O_RDWR;
140✔
796

797
        log_debug("Opened %s in %s access mode%s, with O_DIRECT %s%s.",
11,545✔
798
                  path ?: "loop device",
799
                  open_flags == O_RDWR ? "O_RDWR" : "O_RDONLY",
800
                  open_flags != rdwr_flags ? " (O_RDWR was requested but not allowed)" : "",
801
                  direct ? "enabled" : "disabled",
802
                  direct != (direct_flags != 0) ? " (O_DIRECT was requested but not supported)" : "");
803

804
        return loop_device_make_internal(
4,494✔
805
                        dir_fd == AT_FDCWD ? path : NULL,
806
                        fd,
807
                        open_flags,
808
                        /* offset= */ 0,
809
                        /* size= */ 0,
810
                        sector_size,
811
                        loop_flags,
812
                        lock_op,
813
                        ret);
814
}
815

816
int loop_device_make_by_path_memory(
1✔
817
                const char *path,
818
                int open_flags,
819
                uint32_t sector_size,
820
                uint32_t loop_flags,
821
                int lock_op,
822
                LoopDevice **ret) {
823

824
        _cleanup_close_ int fd = -EBADF, mfd = -EBADF;
1✔
825
        _cleanup_free_ char *fn = NULL;
1✔
826
        int r;
1✔
827

828
        assert(path);
1✔
829
        assert(open_flags < 0 || IN_SET(open_flags, O_RDWR, O_RDONLY));
1✔
830
        assert(ret);
1✔
831

832
        /* memfds are always writable, so default to O_RDWR when auto-detecting. */
833
        if (open_flags < 0)
1✔
834
                open_flags = O_RDWR;
1✔
835

836
        loop_flags &= ~LO_FLAGS_DIRECT_IO; /* memfds don't support O_DIRECT, hence LO_FLAGS_DIRECT_IO can't be used either */
1✔
837

838
        fd = open(path, O_CLOEXEC|O_NONBLOCK|O_NOCTTY|O_RDONLY);
1✔
839
        if (fd < 0)
1✔
840
                return -errno;
×
841

842
        r = fd_verify_regular_or_block(fd);
1✔
843
        if (r < 0)
1✔
844
                return r;
845

846
        r = path_extract_filename(path, &fn);
1✔
847
        if (r < 0)
1✔
848
                return r;
849

850
        mfd = memfd_clone_fd(fd, fn, open_flags|O_CLOEXEC);
1✔
851
        if (mfd < 0)
1✔
852
                return mfd;
853

854
        fd = safe_close(fd); /* Let's close the original early */
1✔
855

856
        return loop_device_make_internal(NULL, mfd, open_flags, 0, 0, sector_size, loop_flags, lock_op, ret);
1✔
857
}
858

859
static LoopDevice* loop_device_free(LoopDevice *d) {
2,569✔
860
        _cleanup_close_ int control = -EBADF;
2,569✔
861
        int r;
2,569✔
862

863
        if (!d)
2,569✔
864
                return NULL;
865

866
        /* Release any lock we might have on the device first. We want to open+lock the /dev/loop-control
867
         * device below, but our lock protocol says that if both control and block device locks are taken,
868
         * the control lock needs to be taken first, the block device lock second — in order to avoid ABBA
869
         * locking issues. Moreover, we want to issue LOOP_CLR_FD on the block device further down, and that
870
         * would fail if we had another fd open to the device. */
871
        d->lock_fd = safe_close(d->lock_fd);
2,569✔
872

873
        /* Let's open the control device early, and lock it, so that we can release our block device and
874
         * delete it in a synchronized fashion, and allocators won't needlessly see the block device as free
875
         * while we are about to delete it. */
876
        if (!LOOP_DEVICE_IS_FOREIGN(d) && !d->relinquished) {
2,569✔
877
                control = open("/dev/loop-control", O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
2,265✔
878
                if (control < 0)
2,265✔
879
                        log_debug_errno(errno, "Failed to open loop control device, cannot remove loop device '%s', ignoring: %m", strna(d->node));
×
880
                else if (flock(control, LOCK_EX) < 0)
2,265✔
881
                        log_debug_errno(errno, "Failed to lock loop control device, ignoring: %m");
×
882
        }
883

884
        /* Then let's release the loopback block device */
885
        if (d->fd >= 0) {
2,569✔
886
                /* Implicitly sync the device, since otherwise in-flight blocks might not get written */
887
                if (fsync(d->fd) < 0)
2,569✔
888
                        log_debug_errno(errno, "Failed to sync loop block device, ignoring: %m");
×
889

890
                if (!LOOP_DEVICE_IS_FOREIGN(d) && !d->relinquished) {
2,569✔
891
                        /* We are supposed to clear the loopback device. Let's do this synchronously: lock
892
                         * the device, manually remove all partitions and then clear it. This should ensure
893
                         * udev doesn't concurrently access the devices, and we can be reasonably sure that
894
                         * once we are done here the device is cleared and all its partition children
895
                         * removed. Note that we lock our primary device fd here (and not a separate locking
896
                         * fd, as we do during allocation, since we want to keep the lock all the way through
897
                         * the LOOP_CLR_FD, but that call would fail if we had more than one fd open.) */
898

899
                        if (flock(d->fd, LOCK_EX) < 0)
2,265✔
900
                                log_debug_errno(errno, "Failed to lock loop block device, ignoring: %m");
×
901

902
                        r = block_device_remove_all_partitions(d->dev, d->fd);
2,265✔
903
                        if (r < 0)
2,265✔
904
                                log_debug_errno(r, "Failed to remove partitions of loopback block device, ignoring: %m");
×
905

906
                        if (ioctl(d->fd, LOOP_CLR_FD) < 0)
2,265✔
907
                                log_debug_errno(errno, "Failed to clear loop device, ignoring: %m");
×
908
                }
909

910
                safe_close(d->fd);
2,569✔
911
        }
912

913
        /* Now that the block device is released, let's also try to remove it */
914
        if (control >= 0) {
2,569✔
915
                useconds_t delay = 5 * USEC_PER_MSEC;  /* A total delay of 5090 ms between 39 attempts,
916
                                                        * (4*5 + 5*10 + 5*20 + … + 3*640) = 5090. */
917

918
                for (unsigned attempt = 1;; attempt++) {
124✔
919
                        if (ioctl(control, LOOP_CTL_REMOVE, d->nr) >= 0)
2,389✔
920
                                break;
921
                        if (errno != EBUSY || attempt > 38) {
125✔
922
                                log_debug_errno(errno, "Failed to remove device %s: %m", strna(d->node));
1✔
923
                                break;
924
                        }
925
                        if (attempt % 5 == 0) {
124✔
926
                                log_debug("Device is still busy after %u attempts…", attempt);
16✔
927
                                delay *= 2;
16✔
928
                        }
929

930
                        (void) usleep_safe(delay);
124✔
931
                }
932
        }
933

934
        free(d->node);
2,569✔
935
        sd_device_unref(d->dev);
2,569✔
936
        free(d->backing_file);
2,569✔
937
        return mfree(d);
2,569✔
938
}
939

940
DEFINE_TRIVIAL_REF_UNREF_FUNC(LoopDevice, loop_device, loop_device_free);
8,024✔
941

942
void loop_device_relinquish(LoopDevice *d) {
193✔
943
        assert(d);
193✔
944

945
        /* Don't attempt to clean up the loop device anymore from this point on. Leave the clean-ing up to the kernel
946
         * itself, using the loop device "auto-clear" logic we already turned on when creating the device. */
947

948
        d->relinquished = true;
193✔
949
}
193✔
950

951
void loop_device_unrelinquish(LoopDevice *d) {
22✔
952
        assert(d);
22✔
953
        d->relinquished = false;
22✔
954
}
22✔
955

956
int loop_device_open(
132✔
957
                sd_device *dev,
958
                int open_flags,
959
                int lock_op,
960
                LoopDevice **ret) {
961

962
        _cleanup_close_ int fd = -EBADF, lock_fd = -EBADF;
132✔
963
        _cleanup_free_ char *node = NULL, *backing_file = NULL;
132✔
964
        dev_t devnum, backing_devno = 0;
132✔
965
        struct loop_info64 info;
132✔
966
        ino_t backing_inode = 0;
132✔
967
        uint64_t diskseq = 0;
132✔
968
        LoopDevice *d;
132✔
969
        const char *s;
132✔
970
        int r, nr = -1;
132✔
971

972
        assert(dev);
132✔
973
        assert(IN_SET(open_flags, O_RDWR, O_RDONLY));
132✔
974
        assert(ret);
132✔
975

976
        /* Even if fd is provided through the argument in loop_device_open_from_fd(), we reopen the inode
977
         * here, instead of keeping just a dup() clone of it around, since we want to ensure that the
978
         * O_DIRECT flag of the handle we keep is off, we have our own file index, and have the right
979
         * read/write mode in effect. */
980
        fd = sd_device_open(dev, O_CLOEXEC|O_NONBLOCK|O_NOCTTY|open_flags);
132✔
981
        if (fd < 0)
132✔
982
                return fd;
983

984
        if ((lock_op & ~LOCK_NB) != LOCK_UN) {
132✔
985
                lock_fd = open_lock_fd(fd, lock_op);
132✔
986
                if (lock_fd < 0)
132✔
987
                        return lock_fd;
988
        }
989

990
        if (ioctl(fd, LOOP_GET_STATUS64, &info) >= 0) {
132✔
991
#if HAVE_VALGRIND_MEMCHECK_H
992
                /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
993
                VALGRIND_MAKE_MEM_DEFINED(&info, sizeof(info));
994
#endif
995
                nr = info.lo_number;
26✔
996

997
                if (sd_device_get_sysattr_value(dev, "loop/backing_file", &s) >= 0) {
26✔
998
                        backing_file = strdup(s);
17✔
999
                        if (!backing_file)
17✔
1000
                                return -ENOMEM;
1001
                }
1002

1003
                backing_devno = info.lo_device;
26✔
1004
                backing_inode = info.lo_inode;
26✔
1005
        }
1006

1007
        r = fd_get_diskseq(fd, &diskseq);
132✔
1008
        if (r < 0 && r != -EOPNOTSUPP)
132✔
1009
                return r;
1010

1011
        uint32_t sector_size;
132✔
1012
        r = blockdev_get_sector_size(fd, &sector_size);
132✔
1013
        if (r < 0)
132✔
1014
                return r;
1015

1016
        uint64_t device_size;
132✔
1017
        r = blockdev_get_device_size(fd, &device_size);
132✔
1018
        if (r < 0)
132✔
1019
                return r;
1020

1021
        r = sd_device_get_devnum(dev, &devnum);
132✔
1022
        if (r < 0)
132✔
1023
                return r;
1024

1025
        r = sd_device_get_devname(dev, &s);
132✔
1026
        if (r < 0)
132✔
1027
                return r;
1028

1029
        node = strdup(s);
132✔
1030
        if (!node)
132✔
1031
                return -ENOMEM;
1032

1033
        d = new(LoopDevice, 1);
132✔
1034
        if (!d)
132✔
1035
                return -ENOMEM;
1036

1037
        *d = (LoopDevice) {
264✔
1038
                .n_ref = 1,
1039
                .fd = TAKE_FD(fd),
132✔
1040
                .lock_fd = TAKE_FD(lock_fd),
132✔
1041
                .nr = nr,
1042
                .node = TAKE_PTR(node),
132✔
1043
                .dev = sd_device_ref(dev),
132✔
1044
                .backing_file = TAKE_PTR(backing_file),
132✔
1045
                .backing_inode = backing_inode,
1046
                .backing_devno = backing_devno,
1047
                .relinquished = true, /* It's not ours, don't try to destroy it when this object is freed */
1048
                .devno = devnum,
1049
                .diskseq = diskseq,
1050
                .sector_size = sector_size,
1051
                .device_size = device_size,
1052
                .created = false,
1053
        };
1054

1055
        *ret = d;
132✔
1056
        return 0;
132✔
1057
}
1058

1059
int loop_device_open_from_fd(
2✔
1060
                int fd,
1061
                int open_flags,
1062
                int lock_op,
1063
                LoopDevice **ret) {
1064

1065
        _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
2✔
1066
        int r;
2✔
1067

1068
        r = block_device_new_from_fd(ASSERT_FD(fd), 0, &dev);
2✔
1069
        if (r < 0)
2✔
1070
                return r;
1071

1072
        return loop_device_open(dev, open_flags, lock_op, ret);
2✔
1073
}
1074

1075
int loop_device_open_from_path(
×
1076
                const char *path,
1077
                int open_flags,
1078
                int lock_op,
1079
                LoopDevice **ret) {
1080

1081
        _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
×
1082
        int r;
×
1083

1084
        assert(path);
×
1085

1086
        r = block_device_new_from_path(path, 0, &dev);
×
1087
        if (r < 0)
×
1088
                return r;
1089

1090
        return loop_device_open(dev, open_flags, lock_op, ret);
×
1091
}
1092

1093
static int resize_partition(int partition_fd, uint64_t offset, uint64_t size) {
×
1094
        char sysfs[STRLEN("/sys/dev/block/:/partition") + 2*DECIMAL_STR_MAX(dev_t) + 1];
×
1095
        _cleanup_free_ char *buffer = NULL;
×
1096
        uint64_t current_offset, current_size, partno;
×
1097
        _cleanup_close_ int whole_fd = -EBADF;
×
1098
        struct stat st;
×
1099
        dev_t devno;
×
1100
        int r;
×
1101

1102
        /* Resizes the partition the loopback device refer to (assuming it refers to one instead of an actual
1103
         * loopback device), and changes the offset, if needed. This is a fancy wrapper around
1104
         * BLKPG_RESIZE_PARTITION. */
1105

1106
        if (fstat(ASSERT_FD(partition_fd), &st) < 0)
×
1107
                return -errno;
×
1108

1109
        assert(S_ISBLK(st.st_mode));
×
1110

1111
        xsprintf(sysfs, "/sys/dev/block/" DEVNUM_FORMAT_STR "/partition", DEVNUM_FORMAT_VAL(st.st_rdev));
×
1112
        r = read_one_line_file(sysfs, &buffer);
×
1113
        if (r == -ENOENT) /* not a partition, cannot resize */
×
1114
                return -ENOTTY;
1115
        if (r < 0)
×
1116
                return r;
1117
        r = safe_atou64(buffer, &partno);
×
1118
        if (r < 0)
×
1119
                return r;
1120

1121
        xsprintf(sysfs, "/sys/dev/block/" DEVNUM_FORMAT_STR "/start", DEVNUM_FORMAT_VAL(st.st_rdev));
×
1122

1123
        buffer = mfree(buffer);
×
1124
        r = read_one_line_file(sysfs, &buffer);
×
1125
        if (r < 0)
×
1126
                return r;
1127
        r = safe_atou64(buffer, &current_offset);
×
1128
        if (r < 0)
×
1129
                return r;
1130
        if (current_offset > UINT64_MAX/512U)
×
1131
                return -EINVAL;
1132
        current_offset *= 512U;
×
1133

1134
        r = blockdev_get_device_size(partition_fd, &current_size);
×
1135
        if (r < 0)
×
1136
                return r;
1137

1138
        if (size == UINT64_MAX && offset == UINT64_MAX)
×
1139
                return 0;
1140
        if (current_size == size && current_offset == offset)
×
1141
                return 0;
1142

1143
        xsprintf(sysfs, "/sys/dev/block/" DEVNUM_FORMAT_STR "/../dev", DEVNUM_FORMAT_VAL(st.st_rdev));
×
1144

1145
        buffer = mfree(buffer);
×
1146
        r = read_one_line_file(sysfs, &buffer);
×
1147
        if (r < 0)
×
1148
                return r;
1149
        r = parse_devnum(buffer, &devno);
×
1150
        if (r < 0)
×
1151
                return r;
1152

1153
        whole_fd = r = device_open_from_devnum(S_IFBLK, devno, O_RDWR|O_CLOEXEC|O_NONBLOCK|O_NOCTTY, NULL);
×
1154
        if (r < 0)
×
1155
                return r;
1156

1157
        return block_device_resize_partition(
×
1158
                        whole_fd,
1159
                        partno,
1160
                        offset == UINT64_MAX ? current_offset : offset,
1161
                        size == UINT64_MAX ? current_size : size);
1162
}
1163

1164
int loop_device_refresh_size(LoopDevice *d, uint64_t offset, uint64_t size) {
22✔
1165
        struct loop_info64 info;
22✔
1166

1167
        assert(d);
22✔
1168
        assert(d->fd >= 0);
22✔
1169

1170
        /* Changes the offset/start of the loop device relative to the beginning of the underlying file or
1171
         * block device. If this loop device actually refers to a partition and not a loopback device, we'll
1172
         * try to adjust the partition offsets instead.
1173
         *
1174
         * If either offset or size is UINT64_MAX we won't change that parameter. */
1175

1176
        if (d->nr < 0) /* not a loopback device */
22✔
1177
                return resize_partition(d->fd, offset, size);
×
1178

1179
        if (ioctl(d->fd, LOOP_GET_STATUS64, &info) < 0)
22✔
1180
                return -errno;
×
1181

1182
#if HAVE_VALGRIND_MEMCHECK_H
1183
        /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
1184
        VALGRIND_MAKE_MEM_DEFINED(&info, sizeof(info));
1185
#endif
1186

1187
        if ((size == UINT64_MAX || info.lo_sizelimit == size) &&
22✔
1188
            (offset == UINT64_MAX || info.lo_offset == offset))
×
1189
                return 0;
1190

1191
        if (size != UINT64_MAX)
22✔
1192
                info.lo_sizelimit = size;
22✔
1193
        if (offset != UINT64_MAX)
22✔
1194
                info.lo_offset = offset;
×
1195

1196
        return RET_NERRNO(ioctl(d->fd, LOOP_SET_STATUS64, &info));
22✔
1197
}
1198

1199
int loop_device_flock(LoopDevice *d, int operation) {
155✔
1200
        assert(IN_SET(operation & ~LOCK_NB, LOCK_UN, LOCK_SH, LOCK_EX));
155✔
1201
        assert(d);
155✔
1202

1203
        /* When unlocking just close the lock fd */
1204
        if ((operation & ~LOCK_NB) == LOCK_UN) {
155✔
1205
                d->lock_fd = safe_close(d->lock_fd);
153✔
1206
                return 0;
153✔
1207
        }
1208

1209
        /* If we had no lock fd so far, create one and lock it right-away */
1210
        if (d->lock_fd < 0) {
2✔
1211
                d->lock_fd = open_lock_fd(ASSERT_FD(d->fd), operation);
1✔
1212
                if (d->lock_fd < 0)
1✔
1213
                        return d->lock_fd;
1214

1215
                return 0;
1✔
1216
        }
1217

1218
        /* Otherwise change the current lock mode on the existing fd */
1219
        return RET_NERRNO(flock(d->lock_fd, operation));
1✔
1220
}
1221

1222
int loop_device_sync(LoopDevice *d) {
78✔
1223
        assert(d);
78✔
1224

1225
        /* We also do this implicitly in loop_device_unref(). Doing this explicitly here has the benefit that
1226
         * we can check the return value though. */
1227

1228
        return RET_NERRNO(fsync(ASSERT_FD(d->fd)));
78✔
1229
}
1230

1231
int loop_device_set_autoclear(LoopDevice *d, bool autoclear) {
8✔
1232
        struct loop_info64 info;
8✔
1233

1234
        assert(d);
8✔
1235

1236
        if (LOOP_DEVICE_IS_FOREIGN(d))
8✔
1237
                return 0;
8✔
1238

1239
        if (ioctl(ASSERT_FD(d->fd), LOOP_GET_STATUS64, &info) < 0)
8✔
1240
                return -errno;
×
1241

1242
        if (autoclear == FLAGS_SET(info.lo_flags, LO_FLAGS_AUTOCLEAR))
8✔
1243
                return 0;
1244

1245
        SET_FLAG(info.lo_flags, LO_FLAGS_AUTOCLEAR, autoclear);
8✔
1246

1247
        if (ioctl(d->fd, LOOP_SET_STATUS64, &info) < 0)
8✔
1248
                return -errno;
×
1249

1250
        return 1;
1251
}
1252

1253
int loop_device_set_filename(LoopDevice *d, const char *name) {
4✔
1254
        struct loop_info64 info;
4✔
1255

1256
        assert(d);
4✔
1257

1258
        /* Sets the .lo_file_name of the loopback device. This is supposed to contain the path to the file
1259
         * backing the block device, but is actually just a free-form string you can pass to the kernel. Most
1260
         * tools that actually care for the backing file path use the sysfs attribute file loop/backing_file
1261
         * which is a kernel generated string, subject to file system namespaces and such.
1262
         *
1263
         * .lo_file_name is useful since userspace can select it freely when creating a loopback block
1264
         * device, and we can use it for /dev/disk/by-loop-ref/ symlinks, and similar, so that apps can
1265
         * recognize their own loopback files. */
1266

1267
        if (name && strlen(name) >= sizeof(info.lo_file_name))
4✔
1268
                return -ENOBUFS;
4✔
1269

1270
        if (ioctl(ASSERT_FD(d->fd), LOOP_GET_STATUS64, &info) < 0)
4✔
1271
                return -errno;
×
1272

1273
        if (strneq((char*) info.lo_file_name, strempty(name), sizeof(info.lo_file_name)))
4✔
1274
                return 0;
1275

1276
        if (name) {
4✔
1277
                strncpy((char*) info.lo_file_name, name, sizeof(info.lo_file_name)-1);
4✔
1278
                info.lo_file_name[sizeof(info.lo_file_name)-1] = 0;
4✔
1279
        } else
1280
                memzero(info.lo_file_name, sizeof(info.lo_file_name));
×
1281

1282
        if (ioctl(d->fd, LOOP_SET_STATUS64, &info) < 0)
4✔
1283
                return -errno;
×
1284

1285
        return 1;
1286
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc