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

systemd / systemd / 23990547145

04 Apr 2026 09:30PM UTC coverage: 72.373% (+0.3%) from 72.107%
23990547145

push

github

web-flow
shutdown: enforce a minimum uptime to make boot loops less annoying (#41215)

Fixes: #9453

Split out of #41016

3 of 39 new or added lines in 2 files covered. (7.69%)

2565 existing lines in 66 files now uncovered.

319531 of 441505 relevant lines covered (72.37%)

1187721.39 hits per line

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

65.43
/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,595✔
36
        assert(fd);
2,595✔
37

38
        if (*fd < 0)
2,595✔
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,595✔
46
        struct loop_info64 info;
2,595✔
47

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

52
                return -errno;
×
53
        }
54

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

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

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

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

67
        if (flock(lock_fd, operation) < 0)
2,728✔
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,537✔
74
        assert(fd >= 0);
2,537✔
75
        assert(c);
2,537✔
76

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

80
                if (ioctl(fd, LOOP_GET_STATUS64, &info) < 0)
2,536✔
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,536✔
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,537✔
110
        bool broken = false;
2,537✔
111
        int r;
2,537✔
112

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

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

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

123
                if (ssz != c->block_size) {
2,537✔
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,537✔
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,537✔
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,537✔
160
        if (r < 0)
2,537✔
161
                return r;
162

163
        return !broken;
2,537✔
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,595✔
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,595✔
232

233
        _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
2,595✔
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,190✔
236
        _cleanup_free_ char *node = NULL;
2,595✔
237
        uint64_t diskseq = 0;
2,595✔
238
        dev_t devno;
2,595✔
239
        int r;
2,595✔
240

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

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

248
        r = sd_device_new_from_devname(&dev, node);
2,595✔
249
        if (r < 0)
2,595✔
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,595✔
253
        if (r < 0)
2,595✔
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,595✔
257
        if (fd < 0)
2,595✔
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,595✔
268
        if (lock_fd < 0)
2,595✔
269
                return log_device_debug_errno(dev, lock_fd, "Failed to acquire lock: %m");
×
270

271
        log_device_debug(dev, "Acquired exclusive lock.");
2,622✔
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,595✔
276
        if (r < 0)
2,595✔
277
                return log_device_debug_errno(dev, r, "Failed to check if the loopback block device is bound: %m");
×
278
        if (r > 0)
2,595✔
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,595✔
288
        if (r < 0)
2,595✔
289
                return log_device_debug_errno(dev, r, "Failed to remove partitions on the loopback block device: %m");
×
290
        if (r > 0)
2,595✔
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,595✔
297
                if (ioctl(fd, LOOP_CONFIGURE, c) < 0) {
2,595✔
298
                        /* Do fallback only if LOOP_CONFIGURE is not supported, propagate all other errors. */
299
                        if (!ERRNO_IS_IOCTL_NOT_SUPPORTED(errno))
58✔
300
                                return log_device_debug_errno(dev, errno, "ioctl(LOOP_CONFIGURE) failed: %m");
58✔
301

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

306
                        r = loop_configure_verify(loop_with_fd, c);
2,537✔
307
                        if (r < 0)
2,537✔
308
                                return log_device_debug_errno(dev, r, "Failed to verify if loopback block device is correctly configured: %m");
×
309
                        if (r == 0) {
2,537✔
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,537✔
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,537✔
336
        if (r < 0 && r != -EOPNOTSUPP)
2,537✔
337
                return log_device_debug_errno(dev, r, "Failed to get diskseq: %m");
×
338

339
        switch (lock_op & ~LOCK_NB) {
2,537✔
340
        case LOCK_EX: /* Already in effect */
341
                break;
342
        case LOCK_SH: /* Downgrade */
2,404✔
343
                if (flock(lock_fd, lock_op) < 0)
2,404✔
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,537✔
354
        r = blockdev_get_device_size(loop_with_fd, &device_size);
2,537✔
355
        if (r < 0)
2,537✔
356
                return log_device_debug_errno(dev, r, "Failed to get loopback device size: %m");
×
357

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

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

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

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

386
        assert(ret);
×
387

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

391
        if (!S_ISBLK(st.st_mode))
×
392
                return -ENOTBLK;
393

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

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

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

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

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

410
        if (!S_ISBLK(st.st_mode))
×
411
                return -ENOTBLK;
412

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

415
        return write_string_filef(sysfs_path, WRITE_STRING_FILE_DISABLE_BUFFER, "%" PRIu64, max_discard);
×
416
}
417

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

422
        assert(fd >= 0);
2,424✔
423
        assert(ret);
2,424✔
424

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

429
        f_flags = fcntl(fd, F_GETFL);
2,424✔
430
        if (f_flags < 0)
2,424✔
431
                return -errno;
×
432

433
        if (FLAGS_SET(f_flags, O_DIRECT)) {
2,424✔
434
                non_direct_io_fd = fd_reopen(fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK);
2,417✔
435
                if (non_direct_io_fd < 0)
2,417✔
436
                        return non_direct_io_fd;
437

438
                probe_fd = non_direct_io_fd;
439
        } else
440
                probe_fd = fd;
441

442
        return probe_sector_size(probe_fd, ret);
2,424✔
443
}
444

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

456
        _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
×
457
        _cleanup_close_ int reopened_fd = -EBADF, control = -EBADF;
5,114✔
458
        _cleanup_free_ char *backing_file = NULL;
2,557✔
459
        struct loop_config config;
2,557✔
460
        int r, f_flags;
2,557✔
461
        struct stat st;
2,557✔
462

463
        assert(fd >= 0);
2,557✔
464
        assert(open_flags < 0 || IN_SET(open_flags, O_RDWR, O_RDONLY));
2,557✔
465
        assert(ret);
2,557✔
466

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

472
        f_flags = fcntl(fd, F_GETFL);
2,557✔
473
        if (f_flags < 0)
2,557✔
474
                return -errno;
×
475

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

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

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

491
                r = probe_sector_size_harder(fd, &sector_size);
2,424✔
492
                if (r < 0)
2,424✔
493
                        return r;
494
                if (r == 0)
2,424✔
495
                        sector_size = 0; /* If we can't probe anything, use default sector size. */
2,307✔
496
        }
497

498
        if (fstat(fd, &st) < 0)
2,557✔
499
                return -errno;
×
500

501
        if (S_ISBLK(st.st_mode)) {
2,557✔
502
                uint32_t device_ssz;
×
503
                r = blockdev_get_sector_size(fd, &device_ssz);
×
504
                if (r < 0)
×
505
                        return r;
×
506

507
                if (sector_size == 0)
×
508
                        sector_size = device_ssz;
×
509

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

523
                if (sector_size == 0)
2,557✔
524
                        sector_size = 512;
2,307✔
525
        }
526

527
        if (path) {
2,557✔
528
                r = path_make_absolute_cwd(path, &backing_file);
338✔
529
                if (r < 0)
338✔
530
                        return r;
531

532
                path_simplify(backing_file);
338✔
533
        } else {
534
                r = fd_get_path(fd, &backing_file);
2,219✔
535
                if (r < 0)
2,219✔
536
                        return r;
537
        }
538

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

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

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

559
        control = open("/dev/loop-control", O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
2,557✔
560
        if (control < 0)
2,557✔
561
                return -errno;
20✔
562

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

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

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

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

608
                nr = ioctl(control, LOOP_CTL_GET_FREE);
2,595✔
609
                if (nr < 0)
2,595✔
610
                        return -errno;
×
611

612
                r = loop_configure(nr, open_flags, lock_op, &config, &d);
2,595✔
613
                if (r >= 0)
2,595✔
614
                        break;
615

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

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

629
                if (++n_attempts >= 64) /* Give up eventually */
58✔
630
                        return -EBUSY;
631

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

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

645
                        safe_close(reopened_fd);
×
646
                        fd = config.fd = /* For cleanups */ reopened_fd = non_direct_io_fd;
×
647
                }
648

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

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

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

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

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

686
                info.lo_flags |= LO_FLAGS_PARTSCAN;
2,360✔
687

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

692
        d->backing_file = TAKE_PTR(backing_file);
2,537✔
693
        d->backing_inode = st.st_ino;
2,537✔
694
        d->backing_devno = st.st_dev;
2,537✔
695

696
        log_debug("Successfully acquired %s, devno=%u:%u, nr=%i, diskseq=%" PRIu64,
2,537✔
697
                  d->node,
698
                  major(d->devno), minor(d->devno),
699
                  d->nr,
700
                  d->diskseq);
701

702
        *ret = TAKE_PTR(d);
2,537✔
703
        return 0;
2,537✔
704
}
705

706
static uint32_t loop_flags_mangle(uint32_t loop_flags) {
2,557✔
707
        int r;
2,557✔
708

709
        r = getenv_bool("SYSTEMD_LOOP_DIRECT_IO");
2,557✔
710
        if (r < 0 && r != -ENXIO)
2,557✔
711
                log_debug_errno(r, "Failed to parse $SYSTEMD_LOOP_DIRECT_IO, ignoring: %m");
×
712

713
        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,557✔
714
}
715

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

726
        assert(fd >= 0);
139✔
727
        assert(ret);
139✔
728

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

741
int loop_device_make_by_path_at(
2,418✔
742
                int dir_fd,
743
                const char *path,
744
                int open_flags,
745
                uint32_t sector_size,
746
                uint32_t loop_flags,
747
                int lock_op,
748
                LoopDevice **ret) {
749

750
        int r, basic_flags, direct_flags, rdwr_flags;
2,418✔
751
        _cleanup_close_ int fd = -EBADF;
2,418✔
752
        bool direct = false;
2,418✔
753

754
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
2,418✔
755
        assert(ret);
2,418✔
756
        assert(open_flags < 0 || IN_SET(open_flags, O_RDWR, O_RDONLY));
2,418✔
757

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

761
        loop_flags = loop_flags_mangle(loop_flags);
2,418✔
762

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

766
        basic_flags = O_CLOEXEC|O_NONBLOCK|O_NOCTTY;
2,418✔
767
        direct_flags = FLAGS_SET(loop_flags, LO_FLAGS_DIRECT_IO) ? O_DIRECT : 0;
2,418✔
768
        rdwr_flags = open_flags >= 0 ? open_flags : O_RDWR;
2,418✔
769

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

778
                /* Retry read-only? */
779
                if (open_flags >= 0 || !ERRNO_IS_NEG_FS_WRITE_REFUSED(r))
2,419✔
780
                        return r;
781

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

790
                open_flags = O_RDONLY;
791
        } else if (open_flags < 0)
2,417✔
792
                open_flags = O_RDWR;
142✔
793

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

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

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

821
        _cleanup_close_ int fd = -EBADF, mfd = -EBADF;
1✔
822
        _cleanup_free_ char *fn = NULL;
1✔
823
        struct stat st;
1✔
824
        int r;
1✔
825

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

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

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

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

840
        if (fstat(fd, &st) < 0)
1✔
841
                return -errno;
×
842

843
        if (!S_ISREG(st.st_mode) && !S_ISBLK(st.st_mode))
1✔
844
                return -EBADF;
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,571✔
860
        _cleanup_close_ int control = -EBADF;
2,571✔
861
        int r;
2,571✔
862

863
        if (!d)
2,571✔
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,571✔
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,571✔
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,571✔
886
                /* Implicitly sync the device, since otherwise in-flight blocks might not get written */
887
                if (fsync(d->fd) < 0)
2,571✔
888
                        log_debug_errno(errno, "Failed to sync loop block device, ignoring: %m");
×
889

890
                if (!LOOP_DEVICE_IS_FOREIGN(d) && !d->relinquished) {
2,571✔
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,571✔
911
        }
912

913
        /* Now that the block device is released, let's also try to remove it */
914
        if (control >= 0) {
2,571✔
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++) {
163✔
919
                        if (ioctl(control, LOOP_CTL_REMOVE, d->nr) >= 0)
2,428✔
920
                                break;
921
                        if (errno != EBUSY || attempt > 38) {
164✔
922
                                log_debug_errno(errno, "Failed to remove device %s: %m", strna(d->node));
1✔
923
                                break;
924
                        }
925
                        if (attempt % 5 == 0) {
163✔
926
                                log_debug("Device is still busy after %u attempts…", attempt);
24✔
927
                                delay *= 2;
24✔
928
                        }
929

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

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

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

942
void loop_device_relinquish(LoopDevice *d) {
195✔
943
        assert(d);
195✔
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;
195✔
949
}
195✔
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) {
157✔
1200
        assert(IN_SET(operation & ~LOCK_NB, LOCK_UN, LOCK_SH, LOCK_EX));
157✔
1201
        assert(d);
157✔
1202

1203
        /* When unlocking just close the lock fd */
1204
        if ((operation & ~LOCK_NB) == LOCK_UN) {
157✔
1205
                d->lock_fd = safe_close(d->lock_fd);
155✔
1206
                return 0;
155✔
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✔
UNCOV
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✔
UNCOV
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✔
UNCOV
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✔
UNCOV
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