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

systemd / systemd / 23877209284

01 Apr 2026 05:23PM UTC coverage: 72.343% (-0.06%) from 72.404%
23877209284

push

github

bluca
hwdb/keyboard: fix enter key for X+ piccolo

The main enter key gives a code for keypad one... Map it to
regular enter key.

318395 of 440116 relevant lines covered (72.34%)

1157750.86 hits per line

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

65.09
/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,596✔
36
        if (*fd < 0)
2,596✔
37
                return;
38

39
        (void) ioctl(*fd, LOOP_CLR_FD);
×
40
        (void) safe_close(*fd);
×
41
}
42

43
static int loop_is_bound(int fd) {
2,596✔
44
        struct loop_info64 info;
2,596✔
45

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

50
                return -errno;
×
51
        }
52

53
        return true; /* bound! */
54
}
55

56
static int open_lock_fd(int primary_fd, int operation) {
2,731✔
57
        _cleanup_close_ int lock_fd = -EBADF;
2,731✔
58

59
        assert(IN_SET(operation & ~LOCK_NB, LOCK_SH, LOCK_EX));
2,731✔
60

61
        lock_fd = fd_reopen(ASSERT_FD(primary_fd), O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2,731✔
62
        if (lock_fd < 0)
2,731✔
63
                return lock_fd;
64

65
        if (flock(lock_fd, operation) < 0)
2,731✔
66
                return -errno;
×
67

68
        return TAKE_FD(lock_fd);
69
}
70

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

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

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

81
#if HAVE_VALGRIND_MEMCHECK_H
82
                VALGRIND_MAKE_MEM_DEFINED(&info, sizeof(info));
83
#endif
84

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

104
        return 0;
105
}
106

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

111
        assert(fd >= 0);
2,535✔
112
        assert(c);
2,535✔
113

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

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

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

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

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

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

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

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

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

161
        return !broken;
2,535✔
162
}
163

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

168
        assert(fd >= 0);
×
169
        assert(c);
×
170

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

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

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

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

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

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

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

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

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

219
        return loop_configure_verify_direct_io(fd, c);
×
220
}
221

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

229
        static bool loop_configure_broken = false;
2,596✔
230

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

239
        assert(nr >= 0);
2,596✔
240
        assert(c);
2,596✔
241
        assert(ret);
2,596✔
242

243
        if (asprintf(&node, "/dev/loop%i", nr) < 0)
2,596✔
244
                return log_oom_debug();
×
245

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

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

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

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

269
        log_device_debug(dev, "Acquired exclusive lock.");
2,623✔
270

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

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

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

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

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

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

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

326
                loop_with_fd = TAKE_FD(fd);
×
327

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

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

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

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

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

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

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

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

384
        assert(ret);
×
385

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

389
        if (!S_ISBLK(st.st_mode))
×
390
                return -ENOTBLK;
391

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

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

398
        return safe_atou64(buffer, ret);
×
399
}
400

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

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

408
        if (!S_ISBLK(st.st_mode))
×
409
                return -ENOTBLK;
410

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

413
        return write_string_filef(sysfs_path, WRITE_STRING_FILE_DISABLE_BUFFER, "%" PRIu64, max_discard);
×
414
}
415

416
static int loop_device_make_internal(
2,555✔
417
                const char *path,
418
                int fd,
419
                int open_flags,
420
                uint64_t offset,
421
                uint64_t size,
422
                uint32_t sector_size,
423
                uint32_t loop_flags,
424
                int lock_op,
425
                LoopDevice **ret) {
426

427
        _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
×
428
        _cleanup_close_ int reopened_fd = -EBADF, control = -EBADF;
5,110✔
429
        _cleanup_free_ char *backing_file = NULL;
2,555✔
430
        struct loop_config config;
2,555✔
431
        int r, f_flags;
2,555✔
432
        struct stat st;
2,555✔
433

434
        assert(fd >= 0);
2,555✔
435
        assert(open_flags < 0 || IN_SET(open_flags, O_RDWR, O_RDONLY));
2,555✔
436
        assert(ret);
2,555✔
437

438
        f_flags = fcntl(fd, F_GETFL);
2,555✔
439
        if (f_flags < 0)
2,555✔
440
                return -errno;
×
441

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

447
                open_flags = f_flags & O_ACCMODE_STRICT;
6✔
448
                if (!IN_SET(open_flags, O_RDWR, O_RDONLY))
6✔
449
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADFD), "Access mode of image file is write only (?)");
×
450
        }
451

452
        if (fstat(fd, &st) < 0)
2,555✔
453
                return -errno;
×
454

455
        if (S_ISBLK(st.st_mode)) {
2,555✔
456
                if (offset == 0 && IN_SET(size, 0, UINT64_MAX))
×
457
                        /* If this is already a block device and we are supposed to cover the whole of it
458
                         * then store an fd to the original open device node — and do not actually create an
459
                         * unnecessary loopback device for it. */
460
                        return loop_device_open_from_fd(fd, open_flags, lock_op, ret);
×
461
        } else {
462
                r = stat_verify_regular(&st);
2,555✔
463
                if (r < 0)
2,555✔
464
                        return r;
465
        }
466

467
        if (path) {
2,555✔
468
                r = path_make_absolute_cwd(path, &backing_file);
336✔
469
                if (r < 0)
336✔
470
                        return r;
471

472
                path_simplify(backing_file);
336✔
473
        } else {
474
                r = fd_get_path(fd, &backing_file);
2,219✔
475
                if (r < 0)
2,219✔
476
                        return r;
477
        }
478

479
        if (FLAGS_SET(loop_flags, LO_FLAGS_DIRECT_IO) != FLAGS_SET(f_flags, O_DIRECT)) {
2,555✔
480
                /* If LO_FLAGS_DIRECT_IO is requested, then make sure we have the fd open with O_DIRECT, as
481
                 * that's required. Conversely, if it's off require that O_DIRECT is off too (that's because
482
                 * new kernels will implicitly enable LO_FLAGS_DIRECT_IO if O_DIRECT is set).
483
                 *
484
                 * Our intention here is that LO_FLAGS_DIRECT_IO is the primary knob, and O_DIRECT derived
485
                 * from that automatically. */
486

487
                reopened_fd = fd_reopen(fd, (FLAGS_SET(loop_flags, LO_FLAGS_DIRECT_IO) ? O_DIRECT : 0)|O_CLOEXEC|O_NONBLOCK|open_flags);
139✔
488
                if (reopened_fd < 0) {
139✔
489
                        if (!FLAGS_SET(loop_flags, LO_FLAGS_DIRECT_IO))
×
490
                                return log_debug_errno(reopened_fd, "Failed to reopen file descriptor without O_DIRECT: %m");
×
491

492
                        /* Some file systems might not support O_DIRECT, let's gracefully continue without it then. */
493
                        log_debug_errno(reopened_fd, "Failed to enable O_DIRECT for backing file descriptor for loopback device. Continuing without.");
×
494
                        loop_flags &= ~LO_FLAGS_DIRECT_IO;
×
495
                } else
496
                        fd = reopened_fd; /* From now on, operate on our new O_DIRECT fd */
497
        }
498

499
        control = open("/dev/loop-control", O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
2,555✔
500
        if (control < 0)
2,555✔
501
                return -errno;
20✔
502

503
        if (sector_size == 0)
2,535✔
504
                /* If no sector size is specified, default to the classic default */
505
                sector_size = 512;
×
506
        else if (sector_size == UINT32_MAX) {
2,535✔
507

508
                if (S_ISBLK(st.st_mode))
2,402✔
509
                        /* If the sector size is specified as UINT32_MAX we'll propagate the sector size of
510
                         * the underlying block device. */
511
                        r = blockdev_get_sector_size(fd, &sector_size);
×
512
                else {
513
                        _cleanup_close_ int non_direct_io_fd = -EBADF;
2,555✔
514
                        int probe_fd;
2,402✔
515

516
                        assert(S_ISREG(st.st_mode));
2,402✔
517

518
                        /* If sector size is specified as UINT32_MAX, we'll try to probe the right sector
519
                         * size of the image in question by looking for the GPT partition header at various
520
                         * offsets. This of course only works if the image already has a disk label.
521
                         *
522
                         * So here we actually want to read the file contents ourselves. This is quite likely
523
                         * not going to work if we managed to enable O_DIRECT, because in such a case there
524
                         * are some pretty strict alignment requirements to offset, size and target, but
525
                         * there's no way to query what alignment specifically is actually required. Hence,
526
                         * let's avoid the mess, and temporarily open an fd without O_DIRECT for the probing
527
                         * logic. */
528

529
                        if (FLAGS_SET(loop_flags, LO_FLAGS_DIRECT_IO)) {
2,402✔
530
                                non_direct_io_fd = fd_reopen(fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK);
2,401✔
531
                                if (non_direct_io_fd < 0)
2,401✔
532
                                        return non_direct_io_fd;
×
533

534
                                probe_fd = non_direct_io_fd;
535
                        } else
536
                                probe_fd = fd;
537

538
                        r = probe_sector_size(probe_fd, &sector_size);
2,402✔
539
                }
540
                if (r < 0)
2,402✔
541
                        return r;
542
        }
543

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

556
        config = (struct loop_config) {
5,070✔
557
                .fd = fd,
558
                .block_size = sector_size,
559
                .info = {
560
                        /* Use the specified flags, but configure the read-only flag from the open flags, and force autoclear */
561
                        .lo_flags = ((loop_flags & ~(LO_FLAGS_READ_ONLY|LO_FLAGS_PARTSCAN)) |
5,070✔
562
                                     ((open_flags & O_ACCMODE_STRICT) == O_RDONLY ? LO_FLAGS_READ_ONLY : 0) |
2,535✔
563
                                     LO_FLAGS_AUTOCLEAR),
564
                        .lo_offset = offset,
565
                        .lo_sizelimit = size == UINT64_MAX ? 0 : size,
2,535✔
566
                },
567
        };
568

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

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

589
                nr = ioctl(control, LOOP_CTL_GET_FREE);
2,596✔
590
                if (nr < 0)
2,596✔
591
                        return -errno;
×
592

593
                r = loop_configure(nr, open_flags, lock_op, &config, &d);
2,596✔
594
                if (r >= 0)
2,596✔
595
                        break;
596

597
                /* -ENODEV or friends: Somebody might've gotten the same number from the kernel, used the
598
                 * device, and called LOOP_CTL_REMOVE on it. Let's retry with a new number.
599
                 * -EBUSY: a file descriptor is already bound to the loopback block device.
600
                 * -EUCLEAN: some left-over partition devices that were cleaned up.
601
                 * -ENOANO: we tried to use LO_FLAGS_DIRECT_IO but the kernel rejected it. */
602
                if (!ERRNO_IS_DEVICE_ABSENT(r) && !IN_SET(r, -EBUSY, -EUCLEAN, -ENOANO))
61✔
603
                        return r;
604

605
                /* OK, this didn't work, let's try again a bit later, but first release the lock on the
606
                 * control device */
607
                if (flock(control, LOCK_UN) < 0)
61✔
608
                        return -errno;
×
609

610
                if (++n_attempts >= 64) /* Give up eventually */
61✔
611
                        return -EBUSY;
612

613
                /* If we failed to enable direct IO mode, let's retry without it. We restart the process as
614
                 * on some combination of kernel version and storage filesystem, the kernel is very unhappy
615
                 * about a failed DIRECT_IO enablement and throws I/O errors. */
616
                if (r == -ENOANO && FLAGS_SET(config.info.lo_flags, LO_FLAGS_DIRECT_IO)) {
61✔
617
                        config.info.lo_flags &= ~LO_FLAGS_DIRECT_IO;
×
618
                        open_flags &= ~O_DIRECT;
×
619

620
                        int non_direct_io_fd = fd_reopen(config.fd, O_CLOEXEC|O_NONBLOCK|open_flags);
×
621
                        if (non_direct_io_fd < 0)
×
622
                                return log_debug_errno(
×
623
                                                non_direct_io_fd,
624
                                                "Failed to reopen file descriptor without O_DIRECT: %m");
625

626
                        safe_close(reopened_fd);
×
627
                        fd = config.fd = /* For cleanups */ reopened_fd = non_direct_io_fd;
×
628
                }
629

630
                /* Wait some random time, to make collision less likely. Let's pick a random time in the
631
                 * range 0ms…250ms, linearly scaled by the number of failed attempts. */
632
                usec = random_u64_range(UINT64_C(10) * USEC_PER_MSEC +
122✔
633
                                        UINT64_C(240) * USEC_PER_MSEC * n_attempts/64);
61✔
634
                log_debug("Trying again after %s.", FORMAT_TIMESPAN(usec, USEC_PER_MSEC));
61✔
635
                (void) usleep_safe(usec);
61✔
636
        }
637

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

645
                r = fd_get_max_discard(fd, &discard_max_bytes);
×
646
                if (r < 0)
×
647
                        log_debug_errno(r, "Failed to read 'discard_max_bytes' of backing device, ignoring: %m");
×
648
                else {
649
                        r = fd_set_max_discard(d->fd, discard_max_bytes);
×
650
                        if (r < 0)
×
651
                                log_debug_errno(r, "Failed to write 'discard_max_bytes' of loop device, ignoring: %m");
×
652
                }
653
        }
654

655
        if (deferred_partscan) {
2,535✔
656
                /* Open+close to drain GD_NEED_PART_SCAN harmlessly (GD_SUPPRESS_PART_SCAN is still
657
                 * set so no partitions appear). Then enable partscan via LOOP_SET_STATUS64. */
658
                int tmp_fd = fd_reopen(d->fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK);
2,358✔
659
                if (tmp_fd < 0)
2,358✔
660
                        return log_debug_errno(tmp_fd, "Failed to reopen loop device to drain partscan flag: %m");
×
661
                safe_close(tmp_fd);
2,358✔
662

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

667
                info.lo_flags |= LO_FLAGS_PARTSCAN;
2,358✔
668

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

673
        d->backing_file = TAKE_PTR(backing_file);
2,535✔
674
        d->backing_inode = st.st_ino;
2,535✔
675
        d->backing_devno = st.st_dev;
2,535✔
676

677
        log_debug("Successfully acquired %s, devno=%u:%u, nr=%i, diskseq=%" PRIu64,
2,535✔
678
                  d->node,
679
                  major(d->devno), minor(d->devno),
680
                  d->nr,
681
                  d->diskseq);
682

683
        *ret = TAKE_PTR(d);
2,535✔
684
        return 0;
2,535✔
685
}
686

687
static uint32_t loop_flags_mangle(uint32_t loop_flags) {
2,555✔
688
        int r;
2,555✔
689

690
        r = getenv_bool("SYSTEMD_LOOP_DIRECT_IO");
2,555✔
691
        if (r < 0 && r != -ENXIO)
2,555✔
692
                log_debug_errno(r, "Failed to parse $SYSTEMD_LOOP_DIRECT_IO, ignoring: %m");
×
693

694
        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✔
695
}
696

697
int loop_device_make(
139✔
698
                int fd,
699
                int open_flags,
700
                uint64_t offset,
701
                uint64_t size,
702
                uint32_t sector_size,
703
                uint32_t loop_flags,
704
                int lock_op,
705
                LoopDevice **ret) {
706

707
        assert(fd >= 0);
139✔
708
        assert(ret);
139✔
709

710
        return loop_device_make_internal(
139✔
711
                        NULL,
712
                        fd,
713
                        open_flags,
714
                        offset,
715
                        size,
716
                        sector_size,
717
                        loop_flags_mangle(loop_flags),
718
                        lock_op,
719
                        ret);
720
}
721

722
int loop_device_make_by_path_at(
2,416✔
723
                int dir_fd,
724
                const char *path,
725
                int open_flags,
726
                uint32_t sector_size,
727
                uint32_t loop_flags,
728
                int lock_op,
729
                LoopDevice **ret) {
730

731
        int r, basic_flags, direct_flags, rdwr_flags;
2,416✔
732
        _cleanup_close_ int fd = -EBADF;
2,416✔
733
        bool direct = false;
2,416✔
734

735
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
2,416✔
736
        assert(ret);
2,416✔
737
        assert(open_flags < 0 || IN_SET(open_flags, O_RDWR, O_RDONLY));
2,416✔
738

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

742
        loop_flags = loop_flags_mangle(loop_flags);
2,416✔
743

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

747
        basic_flags = O_CLOEXEC|O_NONBLOCK|O_NOCTTY;
2,416✔
748
        direct_flags = FLAGS_SET(loop_flags, LO_FLAGS_DIRECT_IO) ? O_DIRECT : 0;
2,416✔
749
        rdwr_flags = open_flags >= 0 ? open_flags : O_RDWR;
2,416✔
750

751
        fd = xopenat(dir_fd, path, basic_flags|direct_flags|rdwr_flags);
2,416✔
752
        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✔
753
                fd = xopenat(dir_fd, path, basic_flags|rdwr_flags);
1✔
754
        else
755
                direct = direct_flags != 0;
×
756
        if (fd < 0) {
2,416✔
757
                r = fd;
1✔
758

759
                /* Retry read-only? */
760
                if (open_flags >= 0 || !ERRNO_IS_NEG_FS_WRITE_REFUSED(r))
2,417✔
761
                        return r;
762

763
                fd = xopenat(dir_fd, path, basic_flags|direct_flags|O_RDONLY);
×
764
                if (fd < 0 && direct_flags != 0) /* as above */
×
765
                        fd = xopenat(dir_fd, path, basic_flags|O_RDONLY);
×
766
                else
767
                        direct = direct_flags != 0;
×
768
                if (fd < 0)
×
769
                        return r; /* Propagate original error */
770

771
                open_flags = O_RDONLY;
772
        } else if (open_flags < 0)
2,415✔
773
                open_flags = O_RDWR;
143✔
774

775
        log_debug("Opened %s in %s access mode%s, with O_DIRECT %s%s.",
11,542✔
776
                  path ?: "loop device",
777
                  open_flags == O_RDWR ? "O_RDWR" : "O_RDONLY",
778
                  open_flags != rdwr_flags ? " (O_RDWR was requested but not allowed)" : "",
779
                  direct ? "enabled" : "disabled",
780
                  direct != (direct_flags != 0) ? " (O_DIRECT was requested but not supported)" : "");
781

782
        return loop_device_make_internal(
4,494✔
783
                        dir_fd == AT_FDCWD ? path : NULL,
784
                        fd,
785
                        open_flags,
786
                        /* offset= */ 0,
787
                        /* size= */ 0,
788
                        sector_size,
789
                        loop_flags,
790
                        lock_op,
791
                        ret);
792
}
793

794
int loop_device_make_by_path_memory(
1✔
795
                const char *path,
796
                int open_flags,
797
                uint32_t sector_size,
798
                uint32_t loop_flags,
799
                int lock_op,
800
                LoopDevice **ret) {
801

802
        _cleanup_close_ int fd = -EBADF, mfd = -EBADF;
1✔
803
        _cleanup_free_ char *fn = NULL;
1✔
804
        struct stat st;
1✔
805
        int r;
1✔
806

807
        assert(path);
1✔
808
        assert(open_flags < 0 || IN_SET(open_flags, O_RDWR, O_RDONLY));
1✔
809
        assert(ret);
1✔
810

811
        /* memfds are always writable, so default to O_RDWR when auto-detecting. */
812
        if (open_flags < 0)
1✔
813
                open_flags = O_RDWR;
1✔
814

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

817
        fd = open(path, O_CLOEXEC|O_NONBLOCK|O_NOCTTY|O_RDONLY);
1✔
818
        if (fd < 0)
1✔
819
                return -errno;
×
820

821
        if (fstat(fd, &st) < 0)
1✔
822
                return -errno;
×
823

824
        if (!S_ISREG(st.st_mode) && !S_ISBLK(st.st_mode))
1✔
825
                return -EBADF;
826

827
        r = path_extract_filename(path, &fn);
1✔
828
        if (r < 0)
1✔
829
                return r;
830

831
        mfd = memfd_clone_fd(fd, fn, open_flags|O_CLOEXEC);
1✔
832
        if (mfd < 0)
1✔
833
                return mfd;
834

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

837
        return loop_device_make_internal(NULL, mfd, open_flags, 0, 0, sector_size, loop_flags, lock_op, ret);
1✔
838
}
839

840
static LoopDevice* loop_device_free(LoopDevice *d) {
2,571✔
841
        _cleanup_close_ int control = -EBADF;
2,571✔
842
        int r;
2,571✔
843

844
        if (!d)
2,571✔
845
                return NULL;
846

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

854
        /* Let's open the control device early, and lock it, so that we can release our block device and
855
         * delete it in a synchronized fashion, and allocators won't needlessly see the block device as free
856
         * while we are about to delete it. */
857
        if (!LOOP_DEVICE_IS_FOREIGN(d) && !d->relinquished) {
2,571✔
858
                control = open("/dev/loop-control", O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
2,262✔
859
                if (control < 0)
2,262✔
860
                        log_debug_errno(errno, "Failed to open loop control device, cannot remove loop device '%s', ignoring: %m", strna(d->node));
×
861
                else if (flock(control, LOCK_EX) < 0)
2,262✔
862
                        log_debug_errno(errno, "Failed to lock loop control device, ignoring: %m");
×
863
        }
864

865
        /* Then let's release the loopback block device */
866
        if (d->fd >= 0) {
2,571✔
867
                /* Implicitly sync the device, since otherwise in-flight blocks might not get written */
868
                if (fsync(d->fd) < 0)
2,571✔
869
                        log_debug_errno(errno, "Failed to sync loop block device, ignoring: %m");
×
870

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

880
                        if (flock(d->fd, LOCK_EX) < 0)
2,262✔
881
                                log_debug_errno(errno, "Failed to lock loop block device, ignoring: %m");
×
882

883
                        r = block_device_remove_all_partitions(d->dev, d->fd);
2,262✔
884
                        if (r < 0)
2,262✔
885
                                log_debug_errno(r, "Failed to remove partitions of loopback block device, ignoring: %m");
×
886

887
                        if (ioctl(d->fd, LOOP_CLR_FD) < 0)
2,262✔
888
                                log_debug_errno(errno, "Failed to clear loop device, ignoring: %m");
×
889
                }
890

891
                safe_close(d->fd);
2,571✔
892
        }
893

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

899
                for (unsigned attempt = 1;; attempt++) {
430✔
900
                        if (ioctl(control, LOOP_CTL_REMOVE, d->nr) >= 0)
2,692✔
901
                                break;
902
                        if (errno != EBUSY || attempt > 38) {
431✔
903
                                log_debug_errno(errno, "Failed to remove device %s: %m", strna(d->node));
1✔
904
                                break;
905
                        }
906
                        if (attempt % 5 == 0) {
430✔
907
                                log_debug("Device is still busy after %u attempts…", attempt);
68✔
908
                                delay *= 2;
68✔
909
                        }
910

911
                        (void) usleep_safe(delay);
430✔
912
                }
913
        }
914

915
        free(d->node);
2,571✔
916
        sd_device_unref(d->dev);
2,571✔
917
        free(d->backing_file);
2,571✔
918
        return mfree(d);
2,571✔
919
}
920

921
DEFINE_TRIVIAL_REF_UNREF_FUNC(LoopDevice, loop_device, loop_device_free);
8,030✔
922

923
void loop_device_relinquish(LoopDevice *d) {
196✔
924
        assert(d);
196✔
925

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

929
        d->relinquished = true;
196✔
930
}
196✔
931

932
void loop_device_unrelinquish(LoopDevice *d) {
22✔
933
        assert(d);
22✔
934
        d->relinquished = false;
22✔
935
}
22✔
936

937
int loop_device_open(
134✔
938
                sd_device *dev,
939
                int open_flags,
940
                int lock_op,
941
                LoopDevice **ret) {
942

943
        _cleanup_close_ int fd = -EBADF, lock_fd = -EBADF;
134✔
944
        _cleanup_free_ char *node = NULL, *backing_file = NULL;
134✔
945
        dev_t devnum, backing_devno = 0;
134✔
946
        struct loop_info64 info;
134✔
947
        ino_t backing_inode = 0;
134✔
948
        uint64_t diskseq = 0;
134✔
949
        LoopDevice *d;
134✔
950
        const char *s;
134✔
951
        int r, nr = -1;
134✔
952

953
        assert(dev);
134✔
954
        assert(IN_SET(open_flags, O_RDWR, O_RDONLY));
134✔
955
        assert(ret);
134✔
956

957
        /* Even if fd is provided through the argument in loop_device_open_from_fd(), we reopen the inode
958
         * here, instead of keeping just a dup() clone of it around, since we want to ensure that the
959
         * O_DIRECT flag of the handle we keep is off, we have our own file index, and have the right
960
         * read/write mode in effect. */
961
        fd = sd_device_open(dev, O_CLOEXEC|O_NONBLOCK|O_NOCTTY|open_flags);
134✔
962
        if (fd < 0)
134✔
963
                return fd;
964

965
        if ((lock_op & ~LOCK_NB) != LOCK_UN) {
134✔
966
                lock_fd = open_lock_fd(fd, lock_op);
134✔
967
                if (lock_fd < 0)
134✔
968
                        return lock_fd;
969
        }
970

971
        if (ioctl(fd, LOOP_GET_STATUS64, &info) >= 0) {
134✔
972
#if HAVE_VALGRIND_MEMCHECK_H
973
                /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
974
                VALGRIND_MAKE_MEM_DEFINED(&info, sizeof(info));
975
#endif
976
                nr = info.lo_number;
26✔
977

978
                if (sd_device_get_sysattr_value(dev, "loop/backing_file", &s) >= 0) {
26✔
979
                        backing_file = strdup(s);
17✔
980
                        if (!backing_file)
17✔
981
                                return -ENOMEM;
982
                }
983

984
                backing_devno = info.lo_device;
26✔
985
                backing_inode = info.lo_inode;
26✔
986
        }
987

988
        r = fd_get_diskseq(fd, &diskseq);
134✔
989
        if (r < 0 && r != -EOPNOTSUPP)
134✔
990
                return r;
991

992
        uint32_t sector_size;
134✔
993
        r = blockdev_get_sector_size(fd, &sector_size);
134✔
994
        if (r < 0)
134✔
995
                return r;
996

997
        uint64_t device_size;
134✔
998
        r = blockdev_get_device_size(fd, &device_size);
134✔
999
        if (r < 0)
134✔
1000
                return r;
1001

1002
        r = sd_device_get_devnum(dev, &devnum);
134✔
1003
        if (r < 0)
134✔
1004
                return r;
1005

1006
        r = sd_device_get_devname(dev, &s);
134✔
1007
        if (r < 0)
134✔
1008
                return r;
1009

1010
        node = strdup(s);
134✔
1011
        if (!node)
134✔
1012
                return -ENOMEM;
1013

1014
        d = new(LoopDevice, 1);
134✔
1015
        if (!d)
134✔
1016
                return -ENOMEM;
1017

1018
        *d = (LoopDevice) {
268✔
1019
                .n_ref = 1,
1020
                .fd = TAKE_FD(fd),
134✔
1021
                .lock_fd = TAKE_FD(lock_fd),
134✔
1022
                .nr = nr,
1023
                .node = TAKE_PTR(node),
134✔
1024
                .dev = sd_device_ref(dev),
134✔
1025
                .backing_file = TAKE_PTR(backing_file),
134✔
1026
                .backing_inode = backing_inode,
1027
                .backing_devno = backing_devno,
1028
                .relinquished = true, /* It's not ours, don't try to destroy it when this object is freed */
1029
                .devno = devnum,
1030
                .diskseq = diskseq,
1031
                .sector_size = sector_size,
1032
                .device_size = device_size,
1033
                .created = false,
1034
        };
1035

1036
        *ret = d;
134✔
1037
        return 0;
134✔
1038
}
1039

1040
int loop_device_open_from_fd(
2✔
1041
                int fd,
1042
                int open_flags,
1043
                int lock_op,
1044
                LoopDevice **ret) {
1045

1046
        _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
2✔
1047
        int r;
2✔
1048

1049
        r = block_device_new_from_fd(ASSERT_FD(fd), 0, &dev);
2✔
1050
        if (r < 0)
2✔
1051
                return r;
1052

1053
        return loop_device_open(dev, open_flags, lock_op, ret);
2✔
1054
}
1055

1056
int loop_device_open_from_path(
×
1057
                const char *path,
1058
                int open_flags,
1059
                int lock_op,
1060
                LoopDevice **ret) {
1061

1062
        _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
×
1063
        int r;
×
1064

1065
        assert(path);
×
1066

1067
        r = block_device_new_from_path(path, 0, &dev);
×
1068
        if (r < 0)
×
1069
                return r;
1070

1071
        return loop_device_open(dev, open_flags, lock_op, ret);
×
1072
}
1073

1074
static int resize_partition(int partition_fd, uint64_t offset, uint64_t size) {
×
1075
        char sysfs[STRLEN("/sys/dev/block/:/partition") + 2*DECIMAL_STR_MAX(dev_t) + 1];
×
1076
        _cleanup_free_ char *buffer = NULL;
×
1077
        uint64_t current_offset, current_size, partno;
×
1078
        _cleanup_close_ int whole_fd = -EBADF;
×
1079
        struct stat st;
×
1080
        dev_t devno;
×
1081
        int r;
×
1082

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

1087
        if (fstat(ASSERT_FD(partition_fd), &st) < 0)
×
1088
                return -errno;
×
1089

1090
        assert(S_ISBLK(st.st_mode));
×
1091

1092
        xsprintf(sysfs, "/sys/dev/block/" DEVNUM_FORMAT_STR "/partition", DEVNUM_FORMAT_VAL(st.st_rdev));
×
1093
        r = read_one_line_file(sysfs, &buffer);
×
1094
        if (r == -ENOENT) /* not a partition, cannot resize */
×
1095
                return -ENOTTY;
1096
        if (r < 0)
×
1097
                return r;
1098
        r = safe_atou64(buffer, &partno);
×
1099
        if (r < 0)
×
1100
                return r;
1101

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

1104
        buffer = mfree(buffer);
×
1105
        r = read_one_line_file(sysfs, &buffer);
×
1106
        if (r < 0)
×
1107
                return r;
1108
        r = safe_atou64(buffer, &current_offset);
×
1109
        if (r < 0)
×
1110
                return r;
1111
        if (current_offset > UINT64_MAX/512U)
×
1112
                return -EINVAL;
1113
        current_offset *= 512U;
×
1114

1115
        r = blockdev_get_device_size(partition_fd, &current_size);
×
1116
        if (r < 0)
×
1117
                return r;
1118

1119
        if (size == UINT64_MAX && offset == UINT64_MAX)
×
1120
                return 0;
1121
        if (current_size == size && current_offset == offset)
×
1122
                return 0;
1123

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

1126
        buffer = mfree(buffer);
×
1127
        r = read_one_line_file(sysfs, &buffer);
×
1128
        if (r < 0)
×
1129
                return r;
1130
        r = parse_devnum(buffer, &devno);
×
1131
        if (r < 0)
×
1132
                return r;
1133

1134
        whole_fd = r = device_open_from_devnum(S_IFBLK, devno, O_RDWR|O_CLOEXEC|O_NONBLOCK|O_NOCTTY, NULL);
×
1135
        if (r < 0)
×
1136
                return r;
1137

1138
        return block_device_resize_partition(
×
1139
                        whole_fd,
1140
                        partno,
1141
                        offset == UINT64_MAX ? current_offset : offset,
1142
                        size == UINT64_MAX ? current_size : size);
1143
}
1144

1145
int loop_device_refresh_size(LoopDevice *d, uint64_t offset, uint64_t size) {
22✔
1146
        struct loop_info64 info;
22✔
1147

1148
        assert(d);
22✔
1149
        assert(d->fd >= 0);
22✔
1150

1151
        /* Changes the offset/start of the loop device relative to the beginning of the underlying file or
1152
         * block device. If this loop device actually refers to a partition and not a loopback device, we'll
1153
         * try to adjust the partition offsets instead.
1154
         *
1155
         * If either offset or size is UINT64_MAX we won't change that parameter. */
1156

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

1160
        if (ioctl(d->fd, LOOP_GET_STATUS64, &info) < 0)
22✔
1161
                return -errno;
×
1162

1163
#if HAVE_VALGRIND_MEMCHECK_H
1164
        /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
1165
        VALGRIND_MAKE_MEM_DEFINED(&info, sizeof(info));
1166
#endif
1167

1168
        if ((size == UINT64_MAX || info.lo_sizelimit == size) &&
22✔
1169
            (offset == UINT64_MAX || info.lo_offset == offset))
×
1170
                return 0;
1171

1172
        if (size != UINT64_MAX)
22✔
1173
                info.lo_sizelimit = size;
22✔
1174
        if (offset != UINT64_MAX)
22✔
1175
                info.lo_offset = offset;
×
1176

1177
        return RET_NERRNO(ioctl(d->fd, LOOP_SET_STATUS64, &info));
22✔
1178
}
1179

1180
int loop_device_flock(LoopDevice *d, int operation) {
158✔
1181
        assert(IN_SET(operation & ~LOCK_NB, LOCK_UN, LOCK_SH, LOCK_EX));
158✔
1182
        assert(d);
158✔
1183

1184
        /* When unlocking just close the lock fd */
1185
        if ((operation & ~LOCK_NB) == LOCK_UN) {
158✔
1186
                d->lock_fd = safe_close(d->lock_fd);
156✔
1187
                return 0;
156✔
1188
        }
1189

1190
        /* If we had no lock fd so far, create one and lock it right-away */
1191
        if (d->lock_fd < 0) {
2✔
1192
                d->lock_fd = open_lock_fd(ASSERT_FD(d->fd), operation);
1✔
1193
                if (d->lock_fd < 0)
1✔
1194
                        return d->lock_fd;
1195

1196
                return 0;
1✔
1197
        }
1198

1199
        /* Otherwise change the current lock mode on the existing fd */
1200
        return RET_NERRNO(flock(d->lock_fd, operation));
1✔
1201
}
1202

1203
int loop_device_sync(LoopDevice *d) {
78✔
1204
        assert(d);
78✔
1205

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

1209
        return RET_NERRNO(fsync(ASSERT_FD(d->fd)));
78✔
1210
}
1211

1212
int loop_device_set_autoclear(LoopDevice *d, bool autoclear) {
8✔
1213
        struct loop_info64 info;
8✔
1214

1215
        assert(d);
8✔
1216

1217
        if (ioctl(ASSERT_FD(d->fd), LOOP_GET_STATUS64, &info) < 0)
8✔
1218
                return -errno;
×
1219

1220
        if (autoclear == FLAGS_SET(info.lo_flags, LO_FLAGS_AUTOCLEAR))
8✔
1221
                return 0;
1222

1223
        SET_FLAG(info.lo_flags, LO_FLAGS_AUTOCLEAR, autoclear);
8✔
1224

1225
        if (ioctl(d->fd, LOOP_SET_STATUS64, &info) < 0)
8✔
1226
                return -errno;
×
1227

1228
        return 1;
1229
}
1230

1231
int loop_device_set_filename(LoopDevice *d, const char *name) {
4✔
1232
        struct loop_info64 info;
4✔
1233

1234
        assert(d);
4✔
1235

1236
        /* Sets the .lo_file_name of the loopback device. This is supposed to contain the path to the file
1237
         * backing the block device, but is actually just a free-form string you can pass to the kernel. Most
1238
         * tools that actually care for the backing file path use the sysfs attribute file loop/backing_file
1239
         * which is a kernel generated string, subject to file system namespaces and such.
1240
         *
1241
         * .lo_file_name is useful since userspace can select it freely when creating a loopback block
1242
         * device, and we can use it for /dev/disk/by-loop-ref/ symlinks, and similar, so that apps can
1243
         * recognize their own loopback files. */
1244

1245
        if (name && strlen(name) >= sizeof(info.lo_file_name))
4✔
1246
                return -ENOBUFS;
4✔
1247

1248
        if (ioctl(ASSERT_FD(d->fd), LOOP_GET_STATUS64, &info) < 0)
4✔
1249
                return -errno;
×
1250

1251
        if (strneq((char*) info.lo_file_name, strempty(name), sizeof(info.lo_file_name)))
4✔
1252
                return 0;
1253

1254
        if (name) {
4✔
1255
                strncpy((char*) info.lo_file_name, name, sizeof(info.lo_file_name)-1);
4✔
1256
                info.lo_file_name[sizeof(info.lo_file_name)-1] = 0;
4✔
1257
        } else
1258
                memzero(info.lo_file_name, sizeof(info.lo_file_name));
×
1259

1260
        if (ioctl(d->fd, LOOP_SET_STATUS64, &info) < 0)
4✔
1261
                return -errno;
×
1262

1263
        return 1;
1264
}
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