Coverage Report

Created: 2025-07-12 06:30

/src/util-linux/lib/loopdev.c
Line
Count
Source (jump to first uncovered line)
1
2
/*
3
 * No copyright is claimed.  This code is in the public domain; do with
4
 * it what you wish.
5
 *
6
 * Written by Karel Zak <kzak@redhat.com>
7
 *
8
 * -- based on mount/losetup.c
9
 *
10
 * Simple library for work with loop devices.
11
 *
12
 *  - requires kernel 2.6.x
13
 *  - reads info from /sys/block/loop<N>/loop/<attr> (new kernels)
14
 *  - reads info by ioctl
15
 *  - supports *unlimited* number of loop devices
16
 *  - supports /dev/loop<N> as well as /dev/loop/<N>
17
 *  - minimize overhead (fd, loopinfo, ... are shared for all operations)
18
 *  - setup (associate device and backing file)
19
 *  - delete (dis-associate file)
20
 *  - old LOOP_{SET,GET}_STATUS (32bit) ioctls are unsupported
21
 *  - extendible
22
 */
23
#include <stdio.h>
24
#include <stdint.h>
25
#include <string.h>
26
#include <ctype.h>
27
#include <fcntl.h>
28
#include <stdlib.h>
29
#include <unistd.h>
30
#include <sys/ioctl.h>
31
#include <sys/stat.h>
32
#include <sys/mman.h>
33
#include <inttypes.h>
34
#include <dirent.h>
35
36
#include "linux_version.h"
37
#include "c.h"
38
#include "sysfs.h"
39
#include "pathnames.h"
40
#include "loopdev.h"
41
#include "canonicalize.h"
42
#include "blkdev.h"
43
#include "debug.h"
44
#include "fileutils.h"
45
46
0
#define LOOPDEV_MAX_TRIES 10
47
48
/*
49
 * Debug stuff (based on include/debug.h)
50
 */
51
static UL_DEBUG_DEFINE_MASK(loopdev);
52
UL_DEBUG_DEFINE_MASKNAMES(loopdev) = UL_DEBUG_EMPTY_MASKNAMES;
53
54
0
#define LOOPDEV_DEBUG_INIT  (1 << 1)
55
0
#define LOOPDEV_DEBUG_CXT (1 << 2)
56
0
#define LOOPDEV_DEBUG_ITER  (1 << 3)
57
0
#define LOOPDEV_DEBUG_SETUP (1 << 4)
58
59
0
#define DBG(m, x)       __UL_DBG(loopdev, LOOPDEV_DEBUG_, m, x)
60
#define ON_DBG(m, x)    __UL_DBG_CALL(loopdev, LOOPDEV_DEBUG_, m, x)
61
62
0
#define UL_DEBUG_CURRENT_MASK UL_DEBUG_MASK(loopdev)
63
#include "debugobj.h"
64
65
static void loopdev_init_debug(void)
66
0
{
67
0
  if (loopdev_debug_mask)
68
0
    return;
69
0
  __UL_INIT_DEBUG_FROM_ENV(loopdev, LOOPDEV_DEBUG_, 0, LOOPDEV_DEBUG);
70
0
}
71
72
/*
73
 * see loopcxt_init()
74
 */
75
0
#define loopcxt_ioctl_enabled(_lc)  (!((_lc)->flags & LOOPDEV_FL_NOIOCTL))
76
0
#define loopcxt_sysfs_available(_lc)  (!((_lc)->flags & LOOPDEV_FL_NOSYSFS)) \
77
0
           && !loopcxt_ioctl_enabled(_lc)
78
79
/*
80
 * Calls @x and repeat on EAGAIN
81
 */
82
0
#define repeat_on_eagain(x) __extension__ ({      \
83
0
    int _c = 0, _e;         \
84
0
    do {           \
85
0
      errno = 0;        \
86
0
      _e = x;         \
87
0
      if (_e == 0 || errno != EAGAIN)   \
88
0
        break;       \
89
0
      if (_c >= LOOPDEV_MAX_TRIES)   \
90
0
        break;       \
91
0
      xusleep(250000);      \
92
0
      _c++;         \
93
0
    } while (1);          \
94
0
    _e == 0 ? 0 : errno ? -errno : -1;   \
95
0
  })
96
97
/*
98
 * @lc: context
99
 * @device: device name, absolute device path or NULL to reset the current setting
100
 *
101
 * Sets device, absolute paths (e.g. "/dev/loop<N>") are unchanged, device
102
 * names ("loop<N>") are converted to the path (/dev/loop<N> or to
103
 * /dev/loop/<N>)
104
 *
105
 * This sets the device name, but does not check if the device exists!
106
 *
107
 * Returns: <0 on error, 0 on success
108
 */
109
int loopcxt_set_device(struct loopdev_cxt *lc, const char *device)
110
0
{
111
0
  if (!lc)
112
0
    return -EINVAL;
113
114
0
  if (lc->fd >= 0) {
115
0
    close(lc->fd);
116
0
    DBG(CXT, ul_debugobj(lc, "closing old open fd"));
117
0
  }
118
0
  lc->fd = -1;
119
0
  lc->is_lost = 0;
120
0
  lc->devno = 0;
121
0
  lc->mode = O_RDONLY;
122
0
  lc->blocksize = 0;
123
0
  lc->has_info = 0;
124
0
  lc->info_failed = 0;
125
0
  *lc->device = '\0';
126
0
  memset(&lc->config, 0, sizeof(lc->config));
127
128
  /* set new */
129
0
  if (device) {
130
0
    if (*device != '/') {
131
0
      const char *dir = _PATH_DEV;
132
133
      /* compose device name for /dev/loop<n> or /dev/loop/<n> */
134
0
      if (lc->flags & LOOPDEV_FL_DEVSUBDIR) {
135
0
        if (strlen(device) < 5)
136
0
          return -1;
137
0
        device += 4;
138
0
        dir = _PATH_DEV_LOOP "/"; /* _PATH_DEV uses trailing slash */
139
0
      }
140
0
      snprintf(lc->device, sizeof(lc->device), "%s%s",
141
0
        dir, device);
142
0
    } else
143
0
      xstrncpy(lc->device, device, sizeof(lc->device));
144
145
0
    DBG(CXT, ul_debugobj(lc, "%s name assigned", device));
146
0
  }
147
148
0
  ul_unref_path(lc->sysfs);
149
0
  lc->sysfs = NULL;
150
0
  return 0;
151
0
}
152
153
int loopcxt_has_device(struct loopdev_cxt *lc)
154
0
{
155
0
  return lc && *lc->device;
156
0
}
157
158
dev_t loopcxt_get_devno(struct loopdev_cxt *lc)
159
0
{
160
0
  if (!lc || !loopcxt_has_device(lc))
161
0
    return 0;
162
0
  if (!lc->devno)
163
0
    lc->devno = sysfs_devname_to_devno(lc->device);
164
0
  return lc->devno;
165
0
}
166
167
int loopcxt_is_lost(struct loopdev_cxt *lc)
168
0
{
169
0
  if (!lc || !loopcxt_has_device(lc))
170
0
    return 0;
171
0
  if (lc->is_lost)
172
0
    return 1;
173
174
0
  lc->is_lost = access(lc->device, F_OK) != 0
175
0
      && loopcxt_get_devno(lc) != 0;
176
177
0
  return lc->is_lost;
178
0
}
179
180
/*
181
 * @lc: context
182
 * @flags: LOOPDEV_FL_* flags
183
 *
184
 * Initialize loop handler.
185
 *
186
 * We have two sets of the flags:
187
 *
188
 *  * LOOPDEV_FL_* flags control loopcxt_* API behavior
189
 *
190
 *  * LO_FLAGS_* are kernel flags used for LOOP_{SET,GET}_STAT64 ioctls
191
 *
192
 * Returns: <0 on error, 0 on success.
193
 */
194
int loopcxt_init(struct loopdev_cxt *lc, int flags)
195
0
{
196
0
  int rc;
197
0
  struct stat st;
198
0
  struct loopdev_cxt dummy = UL_LOOPDEVCXT_EMPTY;
199
200
0
  if (!lc)
201
0
    return -EINVAL;
202
203
0
  loopdev_init_debug();
204
0
  DBG(CXT, ul_debugobj(lc, "initialize context"));
205
206
0
  memcpy(lc, &dummy, sizeof(dummy));
207
0
  lc->flags = flags;
208
209
0
  rc = loopcxt_set_device(lc, NULL);
210
0
  if (rc)
211
0
    return rc;
212
213
0
  if (stat(_PATH_SYS_BLOCK, &st) || !S_ISDIR(st.st_mode)) {
214
0
    lc->flags |= LOOPDEV_FL_NOSYSFS;
215
0
    lc->flags &= ~LOOPDEV_FL_NOIOCTL;
216
0
    DBG(CXT, ul_debugobj(lc, "init: disable /sys usage"));
217
0
  }
218
219
0
  if (!(lc->flags & LOOPDEV_FL_NOSYSFS) &&
220
0
      get_linux_version() >= KERNEL_VERSION(2,6,37)) {
221
    /*
222
     * Use only sysfs for basic information about loop devices
223
     */
224
0
    lc->flags |= LOOPDEV_FL_NOIOCTL;
225
0
    DBG(CXT, ul_debugobj(lc, "init: ignore ioctls"));
226
0
  }
227
228
0
  if (!(lc->flags & LOOPDEV_FL_CONTROL) && !stat(_PATH_DEV_LOOPCTL, &st)) {
229
0
    lc->flags |= LOOPDEV_FL_CONTROL;
230
0
    DBG(CXT, ul_debugobj(lc, "init: loop-control detected "));
231
0
  }
232
233
0
  return 0;
234
0
}
235
236
/*
237
 * @lc: context
238
 *
239
 * Deinitialize loop context
240
 */
241
void loopcxt_deinit(struct loopdev_cxt *lc)
242
0
{
243
0
  int errsv = errno;
244
245
0
  if (!lc)
246
0
    return;
247
248
0
  DBG(CXT, ul_debugobj(lc, "de-initialize"));
249
250
0
  free(lc->filename);
251
0
  lc->filename = NULL;
252
253
0
  ignore_result( loopcxt_set_device(lc, NULL) );
254
0
  loopcxt_deinit_iterator(lc);
255
256
0
  errno = errsv;
257
0
}
258
259
/*
260
 * @lc: context
261
 *
262
 * Returns newly allocated device path.
263
 */
264
char *loopcxt_strdup_device(struct loopdev_cxt *lc)
265
0
{
266
0
  if (!lc || !*lc->device)
267
0
    return NULL;
268
0
  return strdup(lc->device);
269
0
}
270
271
/*
272
 * @lc: context
273
 *
274
 * Returns pointer device name in the @lc struct.
275
 */
276
const char *loopcxt_get_device(struct loopdev_cxt *lc)
277
0
{
278
0
  return lc && *lc->device ? lc->device : NULL;
279
0
}
280
281
/*
282
 * @lc: context
283
 *
284
 * Returns pointer to the sysfs context (see lib/sysfs.c)
285
 */
286
static struct path_cxt *loopcxt_get_sysfs(struct loopdev_cxt *lc)
287
0
{
288
0
  if (!lc || !*lc->device || (lc->flags & LOOPDEV_FL_NOSYSFS))
289
0
    return NULL;
290
291
0
  if (!lc->sysfs) {
292
0
    dev_t devno = loopcxt_get_devno(lc);
293
0
    if (!devno) {
294
0
      DBG(CXT, ul_debugobj(lc, "sysfs: failed devname to devno"));
295
0
      return NULL;
296
0
    }
297
298
0
    lc->sysfs = ul_new_sysfs_path(devno, NULL, NULL);
299
0
    if (!lc->sysfs)
300
0
      DBG(CXT, ul_debugobj(lc, "sysfs: init failed"));
301
0
  }
302
303
0
  return lc->sysfs;
304
0
}
305
306
static int __loopcxt_get_fd(struct loopdev_cxt *lc, mode_t mode)
307
0
{
308
0
  int old = -1;
309
310
0
  if (!lc || !*lc->device)
311
0
    return -EINVAL;
312
313
  /* It's okay to return a FD with read-write permissions if someone
314
   * asked for read-only, but you shouldn't do the opposite.
315
   *
316
   * (O_RDONLY is a widely usable default.)
317
   */
318
0
  if (lc->fd >= 0 && mode == O_RDWR && lc->mode == O_RDONLY) {
319
0
    DBG(CXT, ul_debugobj(lc, "closing already open device (mode mismatch)"));
320
0
    old = lc->fd;
321
0
    lc->fd = -1;
322
0
  }
323
324
0
  if (lc->fd < 0) {
325
0
    lc->mode = mode;
326
0
    lc->fd = open(lc->device, lc->mode | O_CLOEXEC);
327
0
    DBG(CXT, ul_debugobj(lc, "open %s [%s]: %m", lc->device,
328
0
        mode == O_RDONLY ? "ro" :
329
0
              mode == O_RDWR ? "rw" : "??"));
330
331
0
    if (lc->fd < 0 && old >= 0) {
332
      /* restore original on error */
333
0
      lc->fd = old;
334
0
      old = -1;
335
0
    }
336
0
  }
337
338
0
  if (old >= 0)
339
0
    close(old);
340
0
  return lc->fd;
341
0
}
342
343
/* default is read-only file descriptor, it's enough for all ioctls */
344
int loopcxt_get_fd(struct loopdev_cxt *lc)
345
0
{
346
0
  return __loopcxt_get_fd(lc, O_RDONLY);
347
0
}
348
349
/*
350
 * @lc: context
351
 * @flags: LOOPITER_FL_* flags
352
 *
353
 * Iterator can be used to scan list of the free or used loop devices.
354
 *
355
 * Returns: <0 on error, 0 on success
356
 */
357
int loopcxt_init_iterator(struct loopdev_cxt *lc, int flags)
358
0
{
359
0
  struct loopdev_iter *iter;
360
0
  struct stat st;
361
362
0
  if (!lc)
363
0
    return -EINVAL;
364
365
366
0
  iter = &lc->iter;
367
0
  DBG(ITER, ul_debugobj(iter, "initialize"));
368
369
  /* always zeroize
370
   */
371
0
  memset(iter, 0, sizeof(*iter));
372
0
  iter->ncur = -1;
373
0
  iter->flags = flags;
374
0
  iter->default_check = 1;
375
376
0
  if (!lc->extra_check) {
377
    /*
378
     * Check for /dev/loop/<N> subdirectory
379
     */
380
0
    if (!(lc->flags & LOOPDEV_FL_DEVSUBDIR) &&
381
0
        stat(_PATH_DEV_LOOP, &st) == 0 && S_ISDIR(st.st_mode))
382
0
      lc->flags |= LOOPDEV_FL_DEVSUBDIR;
383
384
0
    lc->extra_check = 1;
385
0
  }
386
0
  return 0;
387
0
}
388
389
/*
390
 * @lc: context
391
 *
392
 * Returns: <0 on error, 0 on success
393
 */
394
int loopcxt_deinit_iterator(struct loopdev_cxt *lc)
395
0
{
396
0
  struct loopdev_iter *iter;
397
398
0
  if (!lc)
399
0
    return -EINVAL;
400
401
0
  iter = &lc->iter;
402
0
  DBG(ITER, ul_debugobj(iter, "de-initialize"));
403
404
0
  free(iter->minors);
405
0
  if (iter->proc)
406
0
    fclose(iter->proc);
407
0
  if (iter->sysblock)
408
0
    closedir(iter->sysblock);
409
410
0
  memset(iter, 0, sizeof(*iter));
411
0
  return 0;
412
0
}
413
414
/*
415
 * Same as loopcxt_set_device, but also checks if the device is
416
 * associated with any file.
417
 *
418
 * Returns: <0 on error, 0 on success, 1 device does not match with
419
 *         LOOPITER_FL_{USED,FREE} flags.
420
 */
421
static int loopiter_set_device(struct loopdev_cxt *lc, const char *device)
422
0
{
423
0
  int rc = loopcxt_set_device(lc, device);
424
0
  int used;
425
426
0
  if (rc)
427
0
    return rc;
428
429
0
  if (!(lc->iter.flags & LOOPITER_FL_USED) &&
430
0
      !(lc->iter.flags & LOOPITER_FL_FREE))
431
0
    return 0; /* caller does not care about device status */
432
433
0
  used = loopcxt_get_offset(lc, NULL) == 0;
434
435
0
  if ((lc->iter.flags & LOOPITER_FL_USED) && used)
436
0
    return 0;
437
438
0
  if ((lc->iter.flags & LOOPITER_FL_FREE) && !used)
439
0
    return 0;
440
441
0
  DBG(ITER, ul_debugobj(&lc->iter, "failed to use %s device", lc->device));
442
443
0
  ignore_result( loopcxt_set_device(lc, NULL) );
444
0
  return 1;
445
0
}
446
447
static int cmpnum(const void *p1, const void *p2)
448
0
{
449
0
  return (((* (const int *) p1) > (* (const int *) p2)) -
450
0
      ((* (const int *) p1) < (* (const int *) p2)));
451
0
}
452
453
/*
454
 * The classic scandir() is more expensive and less portable.
455
 * We needn't full loop device names -- loop numbers (loop<N>)
456
 * are enough.
457
 */
458
static int loop_scandir(const char *dirname, int **ary, int hasprefix)
459
0
{
460
0
  DIR *dir;
461
0
  struct dirent *d;
462
0
  unsigned int n, count = 0, arylen = 0;
463
464
0
  if (!dirname || !ary)
465
0
    return 0;
466
467
0
  DBG(ITER, ul_debug("scan dir: %s", dirname));
468
469
0
  dir = opendir(dirname);
470
0
  if (!dir)
471
0
    return 0;
472
0
  free(*ary);
473
0
  *ary = NULL;
474
475
0
  while((d = readdir(dir))) {
476
0
#ifdef _DIRENT_HAVE_D_TYPE
477
0
    if (d->d_type != DT_BLK && d->d_type != DT_UNKNOWN &&
478
0
        d->d_type != DT_LNK)
479
0
      continue;
480
0
#endif
481
0
    if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
482
0
      continue;
483
484
0
    if (hasprefix) {
485
      /* /dev/loop<N> */
486
0
      if (sscanf(d->d_name, "loop%u", &n) != 1)
487
0
        continue;
488
0
    } else {
489
      /* /dev/loop/<N> */
490
0
      char *end = NULL;
491
492
0
      errno = 0;
493
0
      n = strtol(d->d_name, &end, 10);
494
0
      if (d->d_name == end || (end && *end) || errno)
495
0
        continue;
496
0
    }
497
0
    if (n < LOOPDEV_DEFAULT_NNODES)
498
0
      continue;     /* ignore loop<0..7> */
499
500
0
    if (count + 1 > arylen) {
501
0
      int *tmp;
502
503
0
      arylen += 1;
504
505
0
      tmp = reallocarray(*ary, arylen, sizeof(int));
506
0
      if (!tmp) {
507
0
        free(*ary);
508
0
        *ary = NULL;
509
0
        closedir(dir);
510
0
        return -1;
511
0
      }
512
0
      *ary = tmp;
513
0
    }
514
0
    if (*ary)
515
0
      (*ary)[count++] = n;
516
0
  }
517
0
  if (count && *ary)
518
0
    qsort(*ary, count, sizeof(int), cmpnum);
519
520
0
  closedir(dir);
521
0
  return count;
522
0
}
523
524
/*
525
 * Set the next *used* loop device according to /proc/partitions.
526
 *
527
 * Loop devices smaller than 512 bytes are invisible for this function.
528
 */
529
static int loopcxt_next_from_proc(struct loopdev_cxt *lc)
530
0
{
531
0
  struct loopdev_iter *iter = &lc->iter;
532
0
  char buf[BUFSIZ];
533
534
0
  DBG(ITER, ul_debugobj(iter, "scan /proc/partitions"));
535
536
0
  if (!iter->proc)
537
0
    iter->proc = fopen(_PATH_PROC_PARTITIONS, "r" UL_CLOEXECSTR);
538
0
  if (!iter->proc)
539
0
    return 1;
540
541
0
  while (fgets(buf, sizeof(buf), iter->proc)) {
542
0
    unsigned int m;
543
0
    char name[128 + 1];
544
545
546
0
    if (sscanf(buf, " %u %*s %*s %128[^\n ]",
547
0
         &m, name) != 2 || m != LOOPDEV_MAJOR)
548
0
      continue;
549
550
0
    DBG(ITER, ul_debugobj(iter, "checking %s", name));
551
552
0
    if (loopiter_set_device(lc, name) == 0)
553
0
      return 0;
554
0
  }
555
556
0
  return 1;
557
0
}
558
559
/*
560
 * Set the next *used* loop device according to
561
 * /sys/block/loopN/loop/backing_file (kernel >= 2.6.37 is required).
562
 *
563
 * This is preferred method.
564
 */
565
static int loopcxt_next_from_sysfs(struct loopdev_cxt *lc)
566
0
{
567
0
  struct loopdev_iter *iter = &lc->iter;
568
0
  struct dirent *d;
569
0
  int fd;
570
571
0
  DBG(ITER, ul_debugobj(iter, "scanning /sys/block"));
572
573
0
  if (!iter->sysblock)
574
0
    iter->sysblock = opendir(_PATH_SYS_BLOCK);
575
576
0
  if (!iter->sysblock)
577
0
    return 1;
578
579
0
  fd = dirfd(iter->sysblock);
580
581
0
  while ((d = readdir(iter->sysblock))) {
582
0
    char name[NAME_MAX + 18 + 1];
583
0
    struct stat st;
584
585
0
    DBG(ITER, ul_debugobj(iter, "check %s", d->d_name));
586
587
0
    if (strcmp(d->d_name, ".") == 0
588
0
        || strcmp(d->d_name, "..") == 0
589
0
        || strncmp(d->d_name, "loop", 4) != 0)
590
0
      continue;
591
592
0
    snprintf(name, sizeof(name), "%s/loop/backing_file", d->d_name);
593
0
    if (fstatat(fd, name, &st, 0) != 0)
594
0
      continue;
595
596
0
    if (loopiter_set_device(lc, d->d_name) == 0)
597
0
      return 0;
598
0
  }
599
600
0
  return 1;
601
0
}
602
603
/*
604
 * @lc: context, has to initialized by loopcxt_init_iterator()
605
 *
606
 * Returns: 0 on success, < 0 on error, 1 at the end of scanning. The details
607
 *          about the current loop device are available by
608
 *          loopcxt_get_{fd,backing_file,device,offset, ...} functions.
609
 */
610
int loopcxt_next(struct loopdev_cxt *lc)
611
0
{
612
0
  struct loopdev_iter *iter;
613
614
0
  if (!lc)
615
0
    return -EINVAL;
616
617
618
0
  iter = &lc->iter;
619
0
  if (iter->done)
620
0
    return 1;
621
622
0
  DBG(ITER, ul_debugobj(iter, "next"));
623
624
  /* A) Look for used loop devices in /proc/partitions ("losetup -a" only)
625
   */
626
0
  if (iter->flags & LOOPITER_FL_USED) {
627
0
    int rc;
628
629
0
    if (loopcxt_sysfs_available(lc))
630
0
      rc = loopcxt_next_from_sysfs(lc);
631
0
    else
632
0
      rc = loopcxt_next_from_proc(lc);
633
0
    if (rc == 0)
634
0
      return 0;
635
0
    goto done;
636
0
  }
637
638
  /* B) Classic way, try first eight loop devices (default number
639
   *    of loop devices). This is enough for 99% of all cases.
640
   */
641
0
  if (iter->default_check) {
642
0
    DBG(ITER, ul_debugobj(iter, "next: default check"));
643
0
    for (++iter->ncur; iter->ncur < LOOPDEV_DEFAULT_NNODES;
644
0
              iter->ncur++) {
645
0
      char name[16];
646
0
      snprintf(name, sizeof(name), "loop%d", iter->ncur);
647
648
0
      if (loopiter_set_device(lc, name) == 0)
649
0
        return 0;
650
0
    }
651
0
    iter->default_check = 0;
652
0
  }
653
654
  /* C) the worst possibility, scan whole /dev or /dev/loop/<N>
655
   */
656
0
  if (!iter->minors) {
657
0
    DBG(ITER, ul_debugobj(iter, "next: scanning /dev"));
658
0
    iter->nminors = (lc->flags & LOOPDEV_FL_DEVSUBDIR) ?
659
0
      loop_scandir(_PATH_DEV_LOOP, &iter->minors, 0) :
660
0
      loop_scandir(_PATH_DEV, &iter->minors, 1);
661
0
    iter->ncur = -1;
662
0
  }
663
0
  for (++iter->ncur; iter->ncur < iter->nminors; iter->ncur++) {
664
0
    char name[16];
665
0
    snprintf(name, sizeof(name), "loop%d", iter->minors[iter->ncur]);
666
667
0
    if (loopiter_set_device(lc, name) == 0)
668
0
      return 0;
669
0
  }
670
0
done:
671
0
  loopcxt_deinit_iterator(lc);
672
0
  return 1;
673
0
}
674
675
/*
676
 * @device: path to device
677
 */
678
int is_loopdev(const char *device)
679
0
{
680
0
  struct stat st;
681
0
  int rc = 0;
682
683
0
  if (!device || stat(device, &st) != 0 || !S_ISBLK(st.st_mode))
684
0
    rc = 0;
685
0
  else if (major(st.st_rdev) == LOOPDEV_MAJOR)
686
0
    rc = 1;
687
0
  else if (sysfs_devno_is_wholedisk(st.st_rdev)) {
688
    /* It's possible that kernel creates a device with a different
689
     * major number ... check by /sys it's really loop device.
690
     */
691
0
    char name[PATH_MAX], *cn, *p = NULL;
692
693
0
    snprintf(name, sizeof(name), _PATH_SYS_DEVBLOCK "/%d:%d",
694
0
        major(st.st_rdev), minor(st.st_rdev));
695
0
    cn = canonicalize_path(name);
696
0
    if (cn)
697
0
      p = stripoff_last_component(cn);
698
0
    rc = p && ul_startswith(p, "loop");
699
0
    free(cn);
700
0
  }
701
702
0
  if (rc == 0)
703
0
    errno = ENODEV;
704
0
  return rc;
705
0
}
706
707
/*
708
 * @lc: context
709
 *
710
 * Returns result from LOOP_GET_STAT64 ioctl or NULL on error.
711
 */
712
struct loop_info64 *loopcxt_get_info(struct loopdev_cxt *lc)
713
0
{
714
0
  int fd;
715
716
0
  if (!lc || lc->info_failed) {
717
0
    errno = EINVAL;
718
0
    return NULL;
719
0
  }
720
0
  errno = 0;
721
0
  if (lc->has_info)
722
0
    return &lc->config.info;
723
724
0
  fd = loopcxt_get_fd(lc);
725
0
  if (fd < 0)
726
0
    return NULL;
727
728
0
  if (ioctl(fd, LOOP_GET_STATUS64, &lc->config.info) == 0) {
729
0
    lc->has_info = 1;
730
0
    lc->info_failed = 0;
731
0
    DBG(CXT, ul_debugobj(lc, "reading loop_info64 OK"));
732
0
    return &lc->config.info;
733
0
  }
734
735
0
  lc->info_failed = 1;
736
0
  DBG(CXT, ul_debugobj(lc, "reading loop_info64 FAILED"));
737
738
0
  return NULL;
739
0
}
740
741
/*
742
 * @lc: context
743
 *
744
 * Returns (allocated) string with path to the file associated
745
 * with the current loop device.
746
 */
747
char *loopcxt_get_backing_file(struct loopdev_cxt *lc)
748
0
{
749
0
  struct path_cxt *sysfs = loopcxt_get_sysfs(lc);
750
0
  char *res = NULL;
751
752
0
  if (sysfs)
753
    /*
754
     * This is always preferred, the loop_info64
755
     * has too small buffer for the filename.
756
     */
757
0
    ul_path_read_string(sysfs, &res, "loop/backing_file");
758
759
0
  if (!res && loopcxt_ioctl_enabled(lc)) {
760
0
    struct loop_info64 *lo = loopcxt_get_info(lc);
761
762
0
    if (lo) {
763
0
      lo->lo_file_name[LO_NAME_SIZE - 2] = '*';
764
0
      lo->lo_file_name[LO_NAME_SIZE - 1] = '\0';
765
0
      res = strdup((char *) lo->lo_file_name);
766
0
    }
767
0
  }
768
769
0
  DBG(CXT, ul_debugobj(lc, "get_backing_file [%s]", res));
770
0
  return res;
771
0
}
772
773
/*
774
 * @lc: context
775
 *
776
 * Returns (allocated) string with loop reference. The same as backing file by
777
 * default.
778
 */
779
char *loopcxt_get_refname(struct loopdev_cxt *lc)
780
0
{
781
0
  char *res = NULL;
782
0
  struct loop_info64 *lo = loopcxt_get_info(lc);
783
784
0
  if (lo) {
785
0
    lo->lo_file_name[LO_NAME_SIZE - 1] = '\0';
786
0
    res = strdup((char *) lo->lo_file_name);
787
0
  }
788
789
0
  DBG(CXT, ul_debugobj(lc, "get_refname [%s]", res));
790
0
  return res;
791
0
}
792
793
/*
794
 * @lc: context
795
 * @offset: returns offset number for the given device
796
 *
797
 * Returns: <0 on error, 0 on success
798
 */
799
int loopcxt_get_offset(struct loopdev_cxt *lc, uint64_t *offset)
800
0
{
801
0
  struct path_cxt *sysfs = loopcxt_get_sysfs(lc);
802
0
  int rc = -EINVAL;
803
804
0
  if (sysfs)
805
0
    if (ul_path_read_u64(sysfs, offset, "loop/offset") == 0)
806
0
      rc = 0;
807
808
0
  if (rc && loopcxt_ioctl_enabled(lc)) {
809
0
    struct loop_info64 *lo = loopcxt_get_info(lc);
810
0
    if (lo) {
811
0
      if (offset)
812
0
        *offset = lo->lo_offset;
813
0
      rc = 0;
814
0
    } else
815
0
      rc = -errno;
816
0
  }
817
818
0
  DBG(CXT, ul_debugobj(lc, "get_offset [rc=%d]", rc));
819
0
  return rc;
820
0
}
821
822
/*
823
 * @lc: context
824
 * @blocksize: returns logical blocksize for the given device
825
 *
826
 * Returns: <0 on error, 0 on success
827
 */
828
int loopcxt_get_blocksize(struct loopdev_cxt *lc, uint64_t *blocksize)
829
0
{
830
0
  struct path_cxt *sysfs = loopcxt_get_sysfs(lc);
831
0
  int rc = -EINVAL;
832
833
0
  if (sysfs)
834
0
    if (ul_path_read_u64(sysfs, blocksize, "queue/logical_block_size") == 0)
835
0
      rc = 0;
836
837
  /* Fallback based on BLKSSZGET ioctl */
838
0
  if (rc) {
839
0
    int fd = loopcxt_get_fd(lc);
840
0
    int sz = 0;
841
842
0
    if (fd < 0)
843
0
      return -EINVAL;
844
0
    rc = blkdev_get_sector_size(fd, &sz);
845
0
    if (rc)
846
0
      return rc;
847
848
0
    *blocksize = sz;
849
0
  }
850
851
0
  DBG(CXT, ul_debugobj(lc, "get_blocksize [rc=%d]", rc));
852
0
  return rc;
853
0
}
854
855
/*
856
 * @lc: context
857
 * @sizelimit: returns size limit for the given device
858
 *
859
 * Returns: <0 on error, 0 on success
860
 */
861
int loopcxt_get_sizelimit(struct loopdev_cxt *lc, uint64_t *size)
862
0
{
863
0
  struct path_cxt *sysfs = loopcxt_get_sysfs(lc);
864
0
  int rc = -EINVAL;
865
866
0
  if (sysfs)
867
0
    if (ul_path_read_u64(sysfs, size, "loop/sizelimit") == 0)
868
0
      rc = 0;
869
870
0
  if (rc && loopcxt_ioctl_enabled(lc)) {
871
0
    struct loop_info64 *lo = loopcxt_get_info(lc);
872
0
    if (lo) {
873
0
      if (size)
874
0
        *size = lo->lo_sizelimit;
875
0
      rc = 0;
876
0
    } else
877
0
      rc = -errno;
878
0
  }
879
880
0
  DBG(CXT, ul_debugobj(lc, "get_sizelimit [rc=%d]", rc));
881
0
  return rc;
882
0
}
883
884
/*
885
 * @lc: context
886
 * @type: returns encryption type
887
 *
888
 * Cryptoloop is DEPRECATED!
889
 *
890
 * Returns: <0 on error, 0 on success
891
 */
892
int loopcxt_get_encrypt_type(struct loopdev_cxt *lc, uint32_t *type)
893
0
{
894
0
  struct loop_info64 *lo = loopcxt_get_info(lc);
895
0
  int rc;
896
897
  /* not provided by sysfs */
898
0
  if (lo) {
899
0
    if (type)
900
0
      *type = lo->lo_encrypt_type;
901
0
    rc = 0;
902
0
  } else
903
0
    rc = -errno;
904
905
0
  DBG(CXT, ul_debugobj(lc, "get_encrypt_type [rc=%d]", rc));
906
0
  return rc;
907
0
}
908
909
/*
910
 * @lc: context
911
 *
912
 * Cryptoloop is DEPRECATED!
913
 *
914
 * Returns: <0 on error, 0 on success
915
 */
916
const char *loopcxt_get_crypt_name(struct loopdev_cxt *lc)
917
0
{
918
0
  struct loop_info64 *lo = loopcxt_get_info(lc);
919
920
0
  if (lo)
921
0
    return (char *) lo->lo_crypt_name;
922
923
0
  DBG(CXT, ul_debugobj(lc, "get_crypt_name failed"));
924
0
  return NULL;
925
0
}
926
927
/*
928
 * @lc: context
929
 * @devno: returns backing file devno
930
 *
931
 * Returns: <0 on error, 0 on success
932
 */
933
int loopcxt_get_backing_devno(struct loopdev_cxt *lc, dev_t *devno)
934
0
{
935
0
  struct loop_info64 *lo = loopcxt_get_info(lc);
936
0
  int rc;
937
938
0
  if (lo) {
939
0
    if (devno)
940
0
      *devno = lo->lo_device;
941
0
    rc = 0;
942
0
  } else
943
0
    rc = -errno;
944
945
0
  DBG(CXT, ul_debugobj(lc, "get_backing_devno [rc=%d]", rc));
946
0
  return rc;
947
0
}
948
949
/*
950
 * @lc: context
951
 * @ino: returns backing file inode
952
 *
953
 * Returns: <0 on error, 0 on success
954
 */
955
int loopcxt_get_backing_inode(struct loopdev_cxt *lc, ino_t *ino)
956
0
{
957
0
  struct loop_info64 *lo = loopcxt_get_info(lc);
958
0
  int rc;
959
960
0
  if (lo) {
961
0
    if (ino)
962
0
      *ino = lo->lo_inode;
963
0
    rc = 0;
964
0
  } else
965
0
    rc = -errno;
966
967
0
  DBG(CXT, ul_debugobj(lc, "get_backing_inode [rc=%d]", rc));
968
0
  return rc;
969
0
}
970
971
/*
972
 * Check if the kernel supports partitioned loop devices.
973
 *
974
 * Notes:
975
 *   - kernels < 3.2 support partitioned loop devices and PT scanning
976
 *     only if max_part= module parameter is non-zero
977
 *
978
 *   - kernels >= 3.2 always support partitioned loop devices
979
 *
980
 *   - kernels >= 3.2 always support BLKPG_{ADD,DEL}_PARTITION ioctls
981
 *
982
 *   - kernels >= 3.2 enable PT scanner only if max_part= is non-zero or if the
983
 *     LO_FLAGS_PARTSCAN flag is set for the device. The PT scanner is disabled
984
 *     by default.
985
 *
986
 *  See kernel commit e03c8dd14915fabc101aa495828d58598dc5af98.
987
 */
988
int loopmod_supports_partscan(void)
989
0
{
990
0
  int rc, ret = 0;
991
0
  FILE *f;
992
993
0
  if (get_linux_version() >= KERNEL_VERSION(3,2,0))
994
0
    return 1;
995
996
0
  f = fopen("/sys/module/loop/parameters/max_part", "r" UL_CLOEXECSTR);
997
0
  if (!f)
998
0
    return 0;
999
0
  rc = fscanf(f, "%d", &ret);
1000
0
  fclose(f);
1001
0
  return rc == 1 ? ret : 0;
1002
0
}
1003
1004
/*
1005
 * @lc: context
1006
 *
1007
 * Returns: 1 if the partscan flags is set *or* (for old kernels) partitions
1008
 * scanning is enabled for all loop devices.
1009
 */
1010
int loopcxt_is_partscan(struct loopdev_cxt *lc)
1011
0
{
1012
0
  struct path_cxt *sysfs = loopcxt_get_sysfs(lc);
1013
1014
0
  if (sysfs) {
1015
    /* kernel >= 3.2 */
1016
0
    int fl;
1017
0
    if (ul_path_read_s32(sysfs, &fl, "loop/partscan") == 0)
1018
0
      return fl;
1019
0
  }
1020
1021
  /* old kernels (including kernels without loopN/loop/<flags> directory */
1022
0
  return loopmod_supports_partscan();
1023
0
}
1024
1025
/*
1026
 * @lc: context
1027
 *
1028
 * Returns: 1 if the autoclear flags is set.
1029
 */
1030
int loopcxt_is_autoclear(struct loopdev_cxt *lc)
1031
0
{
1032
0
  struct path_cxt *sysfs = loopcxt_get_sysfs(lc);
1033
1034
0
  if (sysfs) {
1035
0
    int fl;
1036
0
    if (ul_path_read_s32(sysfs, &fl, "loop/autoclear") == 0)
1037
0
      return fl;
1038
0
  }
1039
1040
0
  if (loopcxt_ioctl_enabled(lc)) {
1041
0
    struct loop_info64 *lo = loopcxt_get_info(lc);
1042
0
    if (lo)
1043
0
      return lo->lo_flags & LO_FLAGS_AUTOCLEAR;
1044
0
  }
1045
0
  return 0;
1046
0
}
1047
1048
/*
1049
 * @lc: context
1050
 *
1051
 * Returns: 1 if the readonly flags is set.
1052
 */
1053
int loopcxt_is_readonly(struct loopdev_cxt *lc)
1054
0
{
1055
0
  struct path_cxt *sysfs = loopcxt_get_sysfs(lc);
1056
1057
0
  if (sysfs) {
1058
0
    int fl;
1059
0
    if (ul_path_read_s32(sysfs, &fl, "ro") == 0)
1060
0
      return fl;
1061
0
  }
1062
1063
0
  if (loopcxt_ioctl_enabled(lc)) {
1064
0
    struct loop_info64 *lo = loopcxt_get_info(lc);
1065
0
    if (lo)
1066
0
      return lo->lo_flags & LO_FLAGS_READ_ONLY;
1067
0
  }
1068
0
  return 0;
1069
0
}
1070
1071
/*
1072
 * @lc: context
1073
 *
1074
 * Returns: 1 if the dio flags is set.
1075
 */
1076
int loopcxt_is_dio(struct loopdev_cxt *lc)
1077
0
{
1078
0
  struct path_cxt *sysfs = loopcxt_get_sysfs(lc);
1079
1080
0
  if (sysfs) {
1081
0
    int fl;
1082
0
    if (ul_path_read_s32(sysfs, &fl, "loop/dio") == 0)
1083
0
      return fl;
1084
0
  }
1085
0
  if (loopcxt_ioctl_enabled(lc)) {
1086
0
    struct loop_info64 *lo = loopcxt_get_info(lc);
1087
0
    if (lo)
1088
0
      return lo->lo_flags & LO_FLAGS_DIRECT_IO;
1089
0
  }
1090
0
  return 0;
1091
0
}
1092
1093
/*
1094
 * @lc: context
1095
 * @st: backing file stat or NULL
1096
 * @backing_file: filename
1097
 * @offset: offset (use LOOPDEV_FL_OFFSET if specified)
1098
 * @sizelimit: size limit (use LOOPDEV_FL_SIZELIMIT if specified)
1099
 * @flags: LOOPDEV_FL_{OFFSET,SIZELIMIT}
1100
 *
1101
 * Returns 1 if the current @lc loopdev is associated with the given backing
1102
 * file. Note that the preferred way is to use devno and inode number rather
1103
 * than filename. The @backing_file filename is poor solution usable in case
1104
 * that you don't have rights to call stat().
1105
 *
1106
 * LOOPDEV_FL_SIZELIMIT requires LOOPDEV_FL_OFFSET being set as well.
1107
 *
1108
 * Don't forget that old kernels provide very restricted (in size) backing
1109
 * filename by LOOP_GET_STAT64 ioctl only.
1110
 */
1111
int loopcxt_is_used(struct loopdev_cxt *lc,
1112
        struct stat *st,
1113
        const char *backing_file,
1114
        uint64_t offset,
1115
        uint64_t sizelimit,
1116
        int flags)
1117
0
{
1118
0
  ino_t ino = 0;
1119
0
  dev_t dev = 0;
1120
1121
0
  if (!lc)
1122
0
    return 0;
1123
1124
0
  DBG(CXT, ul_debugobj(lc, "checking %s vs. %s",
1125
0
        loopcxt_get_device(lc),
1126
0
        backing_file));
1127
1128
0
  if (st && loopcxt_get_backing_inode(lc, &ino) == 0 &&
1129
0
      loopcxt_get_backing_devno(lc, &dev) == 0) {
1130
1131
0
    if (ino == st->st_ino && dev == st->st_dev)
1132
0
      goto found;
1133
1134
    /* don't use filename if we have devno and inode */
1135
0
    return 0;
1136
0
  }
1137
1138
  /* poor man's solution */
1139
0
  if (backing_file) {
1140
0
    char *name = loopcxt_get_backing_file(lc);
1141
0
    int rc = name && strcmp(name, backing_file) == 0;
1142
1143
0
    free(name);
1144
0
    if (rc)
1145
0
      goto found;
1146
0
  }
1147
1148
0
  return 0;
1149
0
found:
1150
0
  if (flags & LOOPDEV_FL_OFFSET) {
1151
0
    uint64_t off = 0;
1152
1153
0
    int rc = loopcxt_get_offset(lc, &off) == 0 && off == offset;
1154
1155
0
    if (rc && flags & LOOPDEV_FL_SIZELIMIT) {
1156
0
      uint64_t sz = 0;
1157
1158
0
      return loopcxt_get_sizelimit(lc, &sz) == 0 && sz == sizelimit;
1159
0
    }
1160
0
    return rc;
1161
0
  }
1162
0
  return 1;
1163
0
}
1164
1165
/*
1166
 * The setting is removed by loopcxt_set_device() loopcxt_next()!
1167
 */
1168
int loopcxt_set_offset(struct loopdev_cxt *lc, uint64_t offset)
1169
0
{
1170
0
  if (!lc)
1171
0
    return -EINVAL;
1172
0
  lc->config.info.lo_offset = offset;
1173
1174
0
  DBG(CXT, ul_debugobj(lc, "set offset=%jd", offset));
1175
0
  return 0;
1176
0
}
1177
1178
/*
1179
 * The setting is removed by loopcxt_set_device() loopcxt_next()!
1180
 */
1181
int loopcxt_set_sizelimit(struct loopdev_cxt *lc, uint64_t sizelimit)
1182
0
{
1183
0
  if (!lc)
1184
0
    return -EINVAL;
1185
0
  lc->config.info.lo_sizelimit = sizelimit;
1186
1187
0
  DBG(CXT, ul_debugobj(lc, "set sizelimit=%jd", sizelimit));
1188
0
  return 0;
1189
0
}
1190
1191
/*
1192
 * The blocksize will be used by loopcxt_set_device(). For already exiting
1193
 * devices use  loopcxt_ioctl_blocksize().
1194
 *
1195
 * The setting is removed by loopcxt_set_device() loopcxt_next()!
1196
 */
1197
int loopcxt_set_blocksize(struct loopdev_cxt *lc, uint64_t blocksize)
1198
0
{
1199
0
  if (!lc)
1200
0
    return -EINVAL;
1201
0
  lc->blocksize = blocksize;
1202
1203
0
  DBG(CXT, ul_debugobj(lc, "set blocksize=%jd", blocksize));
1204
0
  return 0;
1205
0
}
1206
1207
/*
1208
 * @lc: context
1209
 * @flags: kernel LO_FLAGS_{READ_ONLY,USE_AOPS,AUTOCLEAR} flags
1210
 *
1211
 * The setting is removed by loopcxt_set_device() loopcxt_next()!
1212
 *
1213
 * Returns: 0 on success, <0 on error.
1214
 */
1215
int loopcxt_set_flags(struct loopdev_cxt *lc, uint32_t flags)
1216
0
{
1217
0
  if (!lc)
1218
0
    return -EINVAL;
1219
0
  lc->config.info.lo_flags = flags;
1220
1221
0
  DBG(CXT, ul_debugobj(lc, "set flags=%u", (unsigned) flags));
1222
0
  return 0;
1223
0
}
1224
1225
/*
1226
 * @lc: context
1227
 * @refname: reference name (used to overwrite lo_file_name where is backing
1228
 *           file by default)
1229
 *
1230
 * The setting is removed by loopcxt_set_device() loopcxt_next()!
1231
 *
1232
 * Returns: 0 on success, <0 on error.
1233
 */
1234
int loopcxt_set_refname(struct loopdev_cxt *lc, const char *refname)
1235
0
{
1236
0
  if (!lc)
1237
0
    return -EINVAL;
1238
1239
0
  memset(lc->config.info.lo_file_name, 0, sizeof(lc->config.info.lo_file_name));
1240
0
  if (refname)
1241
0
    xstrncpy((char *)lc->config.info.lo_file_name, refname, LO_NAME_SIZE);
1242
1243
0
  DBG(CXT, ul_debugobj(lc, "set refname=%s", (char *)lc->config.info.lo_file_name));
1244
0
  return 0;
1245
0
}
1246
1247
/*
1248
 * @lc: context
1249
 * @filename: backing file path (the path will be canonicalized)
1250
 *
1251
 * The setting is removed by loopcxt_set_device() loopcxt_next()!
1252
 *
1253
 * Returns: 0 on success, <0 on error.
1254
 */
1255
int loopcxt_set_backing_file(struct loopdev_cxt *lc, const char *filename)
1256
0
{
1257
0
  if (!lc)
1258
0
    return -EINVAL;
1259
1260
0
  lc->filename = canonicalize_path(filename);
1261
0
  if (!lc->filename)
1262
0
    return -errno;
1263
1264
0
  if (!lc->config.info.lo_file_name[0])
1265
0
    loopcxt_set_refname(lc, lc->filename);
1266
1267
0
  DBG(CXT, ul_debugobj(lc, "set backing file=%s", lc->filename));
1268
0
  return 0;
1269
0
}
1270
1271
/*
1272
 * In kernels prior to v3.9, if the offset or sizelimit options
1273
 * are used, the block device's size won't be synced automatically.
1274
 * blockdev --getsize64 and filesystems will use the backing
1275
 * file size until the block device has been re-opened or the
1276
 * LOOP_SET_CAPACITY ioctl is called to sync the sizes.
1277
 *
1278
 * Since mount -oloop uses the LO_FLAGS_AUTOCLEAR option and passes
1279
 * the open file descriptor to the mount system call, we need to use
1280
 * the ioctl. Calling losetup directly doesn't have this problem since
1281
 * it closes the device when it exits and whatever consumes the device
1282
 * next will re-open it, causing the resync.
1283
 */
1284
static int loopcxt_check_size(struct loopdev_cxt *lc, int file_fd)
1285
0
{
1286
0
  uint64_t size, expected_size;
1287
0
  int dev_fd;
1288
0
  struct stat st;
1289
1290
0
  if (!lc->config.info.lo_offset && !lc->config.info.lo_sizelimit)
1291
0
    return 0;
1292
1293
0
  if (fstat(file_fd, &st)) {
1294
0
    DBG(CXT, ul_debugobj(lc, "failed to fstat backing file"));
1295
0
    return -errno;
1296
0
  }
1297
0
  if (S_ISBLK(st.st_mode)) {
1298
0
    if (blkdev_get_size(file_fd,
1299
0
        (unsigned long long *) &expected_size)) {
1300
0
      DBG(CXT, ul_debugobj(lc, "failed to determine device size"));
1301
0
      return -errno;
1302
0
    }
1303
0
  } else
1304
0
    expected_size = st.st_size;
1305
1306
0
  if (expected_size == 0 || expected_size <= lc->config.info.lo_offset) {
1307
0
    DBG(CXT, ul_debugobj(lc, "failed to determine expected size"));
1308
0
    return 0; /* ignore this error */
1309
0
  }
1310
1311
0
  if (lc->config.info.lo_offset > 0)
1312
0
    expected_size -= lc->config.info.lo_offset;
1313
1314
0
  if (lc->config.info.lo_sizelimit > 0 && lc->config.info.lo_sizelimit < expected_size)
1315
0
    expected_size = lc->config.info.lo_sizelimit;
1316
1317
0
  dev_fd = loopcxt_get_fd(lc);
1318
0
  if (dev_fd < 0) {
1319
0
    DBG(CXT, ul_debugobj(lc, "failed to get loop FD"));
1320
0
    return -errno;
1321
0
  }
1322
1323
0
  if (blkdev_get_size(dev_fd, (unsigned long long *) &size)) {
1324
0
    DBG(CXT, ul_debugobj(lc, "failed to determine loopdev size"));
1325
0
    return -errno;
1326
0
  }
1327
1328
  /* It's block device, so, align to 512-byte sectors */
1329
0
  if (expected_size % 512) {
1330
0
    DBG(CXT, ul_debugobj(lc, "expected size misaligned to 512-byte sectors"));
1331
0
    expected_size = (expected_size >> 9) << 9;
1332
0
  }
1333
1334
0
  if (expected_size != size) {
1335
0
    DBG(CXT, ul_debugobj(lc, "warning: loopdev and expected "
1336
0
              "size mismatch (%ju/%ju)",
1337
0
              size, expected_size));
1338
1339
0
    if (loopcxt_ioctl_capacity(lc)) {
1340
      /* ioctl not available */
1341
0
      if (errno == ENOTTY || errno == EINVAL)
1342
0
        errno = ERANGE;
1343
0
      return -errno;
1344
0
    }
1345
1346
0
    if (blkdev_get_size(dev_fd, (unsigned long long *) &size))
1347
0
      return -errno;
1348
1349
0
    if (expected_size != size) {
1350
0
      errno = ERANGE;
1351
0
      DBG(CXT, ul_debugobj(lc, "failed to set loopdev size, "
1352
0
          "size: %ju, expected: %ju",
1353
0
          size, expected_size));
1354
0
      return -errno;
1355
0
    }
1356
0
  }
1357
1358
0
  return 0;
1359
0
}
1360
1361
1362
/*
1363
 * @lc: context
1364
 *
1365
 * Associate the current device (see loopcxt_{set,get}_device()) with
1366
 * a file (see loopcxt_set_backing_file()).
1367
 *
1368
 * The device is initialized read-write by default. If you want read-only
1369
 * device then set LO_FLAGS_READ_ONLY by loopcxt_set_flags(). The LOOPDEV_FL_*
1370
 * flags are ignored and modified according to LO_FLAGS_*.
1371
 *
1372
 * If the device is already open by loopcxt_get_fd() then this setup device
1373
 * function will re-open the device to fix read/write mode.
1374
 *
1375
 * The device is also initialized read-only if the backing file is not
1376
 * possible to open read-write (e.g. read-only FS).
1377
 *
1378
 * Returns: <0 on error, 0 on success.
1379
 */
1380
int loopcxt_setup_device(struct loopdev_cxt *lc)
1381
0
{
1382
0
  int file_fd, dev_fd;
1383
0
  mode_t flags = O_CLOEXEC, mode = O_RDWR;
1384
0
  int rc = -1, cnt = 0;
1385
0
  int errsv = 0;
1386
0
  int fallback = 0;
1387
1388
0
  if (!lc || !*lc->device || !lc->filename)
1389
0
    return -EINVAL;
1390
1391
0
  DBG(SETUP, ul_debugobj(lc, "device setup requested"));
1392
1393
  /*
1394
   * Open backing file and device
1395
   */
1396
0
  if (lc->config.info.lo_flags & LO_FLAGS_READ_ONLY)
1397
0
    mode = O_RDONLY;
1398
1399
0
  if (lc->config.info.lo_flags & LO_FLAGS_DIRECT_IO)
1400
0
    flags |= O_DIRECT;
1401
1402
0
  if ((file_fd = open(lc->filename, mode | flags)) < 0) {
1403
0
    if (mode != O_RDONLY && (errno == EROFS || errno == EACCES))
1404
0
      file_fd = open(lc->filename, (mode = O_RDONLY) | flags);
1405
1406
0
    if (file_fd < 0) {
1407
0
      DBG(SETUP, ul_debugobj(lc, "open backing file failed: %m"));
1408
0
      return -errno;
1409
0
    }
1410
0
  }
1411
0
  DBG(SETUP, ul_debugobj(lc, "backing file open: OK"));
1412
1413
0
  if (mode == O_RDONLY)
1414
0
    lc->config.info.lo_flags |= LO_FLAGS_READ_ONLY; /* kernel loopdev mode */
1415
0
  else
1416
0
    lc->config.info.lo_flags &= ~LO_FLAGS_READ_ONLY;
1417
1418
0
  do {
1419
0
    errno = 0;
1420
1421
0
    dev_fd = __loopcxt_get_fd(lc, mode);
1422
0
    if (dev_fd >= 0 || lc->control_ok == 0)
1423
0
      break;
1424
0
    if (errno != EACCES && errno != ENOENT)
1425
0
      break;
1426
    /* We have permissions to open /dev/loop-control, but open
1427
     * /dev/loopN failed with EACCES, it's probably because udevd
1428
     * does not applied chown yet. Let's wait a moment. */
1429
0
    xusleep(25000);
1430
0
  } while (cnt++ < 16);
1431
1432
0
  if (dev_fd < 0) {
1433
0
    rc = -errno;
1434
0
    goto err;
1435
0
  }
1436
1437
0
  DBG(SETUP, ul_debugobj(lc, "device open: OK"));
1438
1439
  /*
1440
   * Atomic way to configure all by one ioctl call
1441
   * -- since Linux v5.8-rc1, commit 3448914e8cc550ba792d4ccc74471d1ca4293aae
1442
   */
1443
0
  lc->config.fd = file_fd;
1444
0
  if (lc->blocksize > 0)
1445
0
    lc->config.block_size = lc->blocksize;
1446
1447
0
  rc = repeat_on_eagain( ioctl(dev_fd, LOOP_CONFIGURE, &lc->config) );
1448
0
  if (rc != 0) {
1449
0
    errsv = errno;
1450
0
    if (errno != EINVAL && errno != ENOTTY && errno != ENOSYS) {
1451
0
      DBG(SETUP, ul_debugobj(lc, "LOOP_CONFIGURE failed: %m"));
1452
0
      goto err;
1453
0
    }
1454
0
    fallback = 1;
1455
0
  } else {
1456
0
    DBG(SETUP, ul_debugobj(lc, "LOOP_CONFIGURE: OK"));
1457
0
  }
1458
1459
  /*
1460
   * Old deprecated way; first assign backing file FD and then in the
1461
   * second step set loop device properties.
1462
   */
1463
0
  if (fallback) {
1464
0
    if (ioctl(dev_fd, LOOP_SET_FD, file_fd) < 0) {
1465
0
      rc = -errno;
1466
0
      errsv = errno;
1467
0
      DBG(SETUP, ul_debugobj(lc, "LOOP_SET_FD failed: %m"));
1468
0
      goto err;
1469
0
    }
1470
1471
0
    DBG(SETUP, ul_debugobj(lc, "LOOP_SET_FD: OK"));
1472
1473
0
    if (lc->blocksize > 0
1474
0
      && (rc = loopcxt_ioctl_blocksize(lc, lc->blocksize)) < 0) {
1475
0
      errsv = -rc;
1476
0
      goto err;
1477
0
    }
1478
1479
0
    if ((rc = loopcxt_ioctl_status(lc)) < 0) {
1480
0
      errsv = -rc;
1481
0
      goto err;
1482
0
    }
1483
0
  }
1484
1485
0
  if ((rc = loopcxt_check_size(lc, file_fd)))
1486
0
    goto err;
1487
1488
0
  close(file_fd);
1489
1490
0
  memset(&lc->config, 0, sizeof(lc->config));
1491
0
  lc->has_info = 0;
1492
0
  lc->info_failed = 0;
1493
1494
0
  DBG(SETUP, ul_debugobj(lc, "success [rc=0]"));
1495
0
  return 0;
1496
0
err:
1497
0
  if (file_fd >= 0)
1498
0
    close(file_fd);
1499
0
  if (dev_fd >= 0 && rc != -EBUSY)
1500
0
    ioctl(dev_fd, LOOP_CLR_FD, 0);
1501
0
  if (errsv)
1502
0
    errno = errsv;
1503
1504
0
  DBG(SETUP, ul_debugobj(lc, "failed [rc=%d]", rc));
1505
0
  return rc;
1506
0
}
1507
1508
1509
/*
1510
 * @lc: context
1511
 *
1512
 * Update status of the current device (see loopcxt_{set,get}_device()).
1513
 *
1514
 * Note that once initialized, kernel accepts only selected changes:
1515
 * LO_FLAGS_AUTOCLEAR and LO_FLAGS_PARTSCAN
1516
 * For more see linux/drivers/block/loop.c:loop_set_status()
1517
 *
1518
 * Returns: <0 on error, 0 on success.
1519
 */
1520
int loopcxt_ioctl_status(struct loopdev_cxt *lc)
1521
0
{
1522
0
  int dev_fd, rc;
1523
1524
0
  errno = 0;
1525
0
  dev_fd = loopcxt_get_fd(lc);
1526
1527
0
  if (dev_fd < 0)
1528
0
    return -errno;
1529
1530
0
  DBG(SETUP, ul_debugobj(lc, "calling LOOP_SET_STATUS64"));
1531
1532
0
  rc = repeat_on_eagain( ioctl(dev_fd, LOOP_SET_STATUS64, &lc->config.info) );
1533
0
  if (rc != 0) {
1534
0
    DBG(SETUP, ul_debugobj(lc, "LOOP_SET_STATUS64 failed: %m"));
1535
0
    return rc;
1536
0
  }
1537
1538
0
  DBG(SETUP, ul_debugobj(lc, "LOOP_SET_STATUS64: OK"));
1539
0
  return 0;
1540
0
}
1541
1542
int loopcxt_ioctl_capacity(struct loopdev_cxt *lc)
1543
0
{
1544
0
  int rc, fd = loopcxt_get_fd(lc);
1545
1546
0
  if (fd < 0)
1547
0
    return -EINVAL;
1548
1549
0
  DBG(SETUP, ul_debugobj(lc, "calling LOOP_SET_CAPACITY"));
1550
1551
  /* Kernels prior to v2.6.30 don't support this ioctl */
1552
0
  rc = repeat_on_eagain( ioctl(fd, LOOP_SET_CAPACITY, 0) );
1553
0
  if (rc != 0) {
1554
0
    DBG(CXT, ul_debugobj(lc, "LOOP_SET_CAPACITY failed: %m"));
1555
0
    return rc;
1556
0
  }
1557
1558
0
  DBG(CXT, ul_debugobj(lc, "capacity set"));
1559
0
  return 0;
1560
0
}
1561
1562
int loopcxt_ioctl_dio(struct loopdev_cxt *lc, unsigned long use_dio)
1563
0
{
1564
0
  int rc, fd = loopcxt_get_fd(lc);
1565
1566
0
  if (fd < 0)
1567
0
    return -EINVAL;
1568
1569
0
  DBG(SETUP, ul_debugobj(lc, "calling LOOP_SET_DIRECT_IO"));
1570
1571
  /* Kernels prior to v4.4 don't support this ioctl */
1572
0
  rc = repeat_on_eagain( ioctl(fd, LOOP_SET_DIRECT_IO, use_dio) );
1573
0
  if (rc != 0) {
1574
0
    DBG(CXT, ul_debugobj(lc, "LOOP_SET_DIRECT_IO failed: %m"));
1575
0
    return rc;
1576
0
  }
1577
1578
0
  DBG(CXT, ul_debugobj(lc, "direct io set"));
1579
0
  return 0;
1580
0
}
1581
1582
/*
1583
 * Kernel uses "unsigned long" as ioctl arg, but we use u64 for all sizes to
1584
 * keep loopdev internal API simple.
1585
 */
1586
int loopcxt_ioctl_blocksize(struct loopdev_cxt *lc, uint64_t blocksize)
1587
0
{
1588
0
  int rc, fd = loopcxt_get_fd(lc);
1589
1590
0
  if (fd < 0)
1591
0
    return -EINVAL;
1592
1593
0
  DBG(SETUP, ul_debugobj(lc, "calling LOOP_SET_BLOCK_SIZE"));
1594
1595
0
  rc = repeat_on_eagain(
1596
0
    ioctl(fd, LOOP_SET_BLOCK_SIZE, (unsigned long) blocksize) );
1597
0
  if (rc != 0) {
1598
0
    DBG(CXT, ul_debugobj(lc, "LOOP_SET_BLOCK_SIZE failed: %m"));
1599
0
    return rc;
1600
0
  }
1601
1602
0
  DBG(CXT, ul_debugobj(lc, "logical block size set"));
1603
0
  return 0;
1604
0
}
1605
1606
int loopcxt_delete_device(struct loopdev_cxt *lc)
1607
0
{
1608
0
  int rc, fd = loopcxt_get_fd(lc);
1609
1610
0
  if (fd < 0)
1611
0
    return -EINVAL;
1612
1613
0
  DBG(SETUP, ul_debugobj(lc, "calling LOOP_SET_CLR_FD"));
1614
1615
0
  rc = repeat_on_eagain( ioctl(fd, LOOP_CLR_FD, 0) );
1616
0
  if (rc != 0) {
1617
0
    DBG(CXT, ul_debugobj(lc, "LOOP_CLR_FD failed: %m"));
1618
0
    return rc;
1619
0
  }
1620
1621
0
  DBG(CXT, ul_debugobj(lc, "device removed"));
1622
0
  return 0;
1623
0
}
1624
1625
int loopcxt_add_device(struct loopdev_cxt *lc)
1626
0
{
1627
0
  int rc = -EINVAL;
1628
0
  int ctl, nr = -1;
1629
0
  const char *p, *dev = loopcxt_get_device(lc);
1630
1631
0
  if (!dev)
1632
0
    goto done;
1633
1634
0
  if (!(lc->flags & LOOPDEV_FL_CONTROL)) {
1635
0
    rc = -ENOSYS;
1636
0
    goto done;
1637
0
  }
1638
1639
0
  p = strrchr(dev, '/');
1640
0
  if (!p || (sscanf(p, "/loop%d", &nr) != 1 && sscanf(p, "/%d", &nr) != 1)
1641
0
         || nr < 0)
1642
0
    goto done;
1643
1644
0
  ctl = open(_PATH_DEV_LOOPCTL, O_RDWR|O_CLOEXEC);
1645
0
  if (ctl >= 0) {
1646
0
    DBG(CXT, ul_debugobj(lc, "add_device %d", nr));
1647
0
    rc = ioctl(ctl, LOOP_CTL_ADD, nr);
1648
0
    close(ctl);
1649
0
  }
1650
0
  lc->control_ok = rc >= 0 ? 1 : 0;
1651
0
done:
1652
0
  DBG(CXT, ul_debugobj(lc, "add_device done [rc=%d]", rc));
1653
0
  return rc;
1654
0
}
1655
1656
/*
1657
 * Note that LOOP_CTL_GET_FREE ioctl is supported since kernel 3.1. In older
1658
 * kernels we have to check all loop devices to found unused one.
1659
 *
1660
 * See kernel commit 770fe30a46a12b6fb6b63fbe1737654d28e8484.
1661
 *
1662
 * Returns: 0 = success, < 0 error
1663
 */
1664
int loopcxt_find_unused(struct loopdev_cxt *lc)
1665
0
{
1666
0
  int rc = -1;
1667
1668
0
  DBG(CXT, ul_debugobj(lc, "find_unused requested"));
1669
1670
0
  if (lc->flags & LOOPDEV_FL_CONTROL) {
1671
0
    int ctl;
1672
1673
0
    DBG(CXT, ul_debugobj(lc, "using loop-control"));
1674
1675
0
    ctl = open(_PATH_DEV_LOOPCTL, O_RDWR|O_CLOEXEC);
1676
0
    if (ctl >= 0)
1677
0
      rc = ioctl(ctl, LOOP_CTL_GET_FREE);
1678
0
    else
1679
0
      rc = -errno;
1680
0
    if (rc >= 0) {
1681
0
      char name[16];
1682
0
      snprintf(name, sizeof(name), "loop%d", rc);
1683
1684
0
      rc = loopiter_set_device(lc, name);
1685
0
    }
1686
0
    lc->control_ok = ctl >= 0 && rc == 0 ? 1 : 0;
1687
0
    if (ctl >= 0)
1688
0
      close(ctl);
1689
0
    DBG(CXT, ul_debugobj(lc, "find_unused by loop-control [rc=%d]", rc));
1690
0
  }
1691
1692
0
  if (rc < 0) {
1693
0
    DBG(CXT, ul_debugobj(lc, "using loop scan"));
1694
0
    rc = loopcxt_init_iterator(lc, LOOPITER_FL_FREE);
1695
0
    if (rc)
1696
0
      return rc;
1697
1698
0
    rc = loopcxt_next(lc);
1699
0
    loopcxt_deinit_iterator(lc);
1700
0
    DBG(CXT, ul_debugobj(lc, "find_unused by scan [rc=%d]", rc));
1701
0
    if (rc)
1702
0
      return -ENOENT;
1703
0
  }
1704
0
  return rc;
1705
0
}
1706
1707
1708
1709
/*
1710
 * Return: TRUE/FALSE
1711
 */
1712
int loopdev_is_autoclear(const char *device)
1713
0
{
1714
0
  struct loopdev_cxt lc;
1715
0
  int rc;
1716
1717
0
  if (!device)
1718
0
    return 0;
1719
1720
0
  rc = loopcxt_init(&lc, 0);
1721
0
  if (!rc)
1722
0
    rc = loopcxt_set_device(&lc, device);
1723
0
  if (!rc)
1724
0
    rc = loopcxt_is_autoclear(&lc);
1725
1726
0
  loopcxt_deinit(&lc);
1727
0
  return rc;
1728
0
}
1729
1730
char *loopdev_get_backing_file(const char *device)
1731
0
{
1732
0
  struct loopdev_cxt lc;
1733
0
  char *res = NULL;
1734
1735
0
  if (!device)
1736
0
    return NULL;
1737
0
  if (loopcxt_init(&lc, 0))
1738
0
    return NULL;
1739
0
  if (loopcxt_set_device(&lc, device) == 0)
1740
0
    res = loopcxt_get_backing_file(&lc);
1741
1742
0
  loopcxt_deinit(&lc);
1743
0
  return res;
1744
0
}
1745
1746
/*
1747
 * Returns: TRUE/FALSE
1748
 */
1749
int loopdev_has_backing_file(const char *device)
1750
0
{
1751
0
  char *tmp = loopdev_get_backing_file(device);
1752
1753
0
  if (tmp) {
1754
0
    free(tmp);
1755
0
    return 1;
1756
0
  }
1757
0
  return 0;
1758
0
}
1759
1760
/*
1761
 * Returns: TRUE/FALSE
1762
 */
1763
int loopdev_is_used(const char *device, const char *filename,
1764
        uint64_t offset, uint64_t sizelimit, int flags)
1765
0
{
1766
0
  struct loopdev_cxt lc;
1767
0
  struct stat st;
1768
0
  int rc = 0;
1769
1770
0
  if (!device || !filename)
1771
0
    return 0;
1772
1773
0
  rc = loopcxt_init(&lc, 0);
1774
0
  if (!rc)
1775
0
    rc = loopcxt_set_device(&lc, device);
1776
0
  if (rc)
1777
0
    return rc;
1778
1779
0
  rc = !stat(filename, &st);
1780
0
  rc = loopcxt_is_used(&lc, rc ? &st : NULL, filename, offset, sizelimit, flags);
1781
1782
0
  loopcxt_deinit(&lc);
1783
0
  return rc;
1784
0
}
1785
1786
/*
1787
 * Returns: 0 = success, < 0 error
1788
 */
1789
int loopdev_delete(const char *device)
1790
0
{
1791
0
  struct loopdev_cxt lc;
1792
0
  int rc;
1793
1794
0
  if (!device)
1795
0
    return -EINVAL;
1796
1797
0
  rc = loopcxt_init(&lc, 0);
1798
0
  if (!rc)
1799
0
    rc = loopcxt_set_device(&lc, device);
1800
0
  if (!rc)
1801
0
    rc = loopcxt_delete_device(&lc);
1802
0
  loopcxt_deinit(&lc);
1803
0
  return rc;
1804
0
}
1805
1806
/*
1807
 * Returns: 0 = success, < 0 error, 1 not found
1808
 */
1809
int loopcxt_find_by_backing_file(struct loopdev_cxt *lc, const char *filename,
1810
         uint64_t offset, uint64_t sizelimit, int flags)
1811
0
{
1812
0
  int rc, hasst;
1813
0
  struct stat st;
1814
1815
0
  if (!filename)
1816
0
    return -EINVAL;
1817
1818
0
  hasst = !stat(filename, &st);
1819
1820
0
  rc = loopcxt_init_iterator(lc, LOOPITER_FL_USED);
1821
0
  if (rc)
1822
0
    return rc;
1823
1824
0
  while ((rc = loopcxt_next(lc)) == 0) {
1825
1826
0
    if (loopcxt_is_used(lc, hasst ? &st : NULL,
1827
0
            filename, offset, sizelimit, flags))
1828
0
      break;
1829
0
  }
1830
1831
0
  loopcxt_deinit_iterator(lc);
1832
0
  return rc;
1833
0
}
1834
1835
/*
1836
 * Returns: 0 = not found, < 0 error, 1 found, 2 found full size and offset match
1837
 */
1838
int loopcxt_find_overlap(struct loopdev_cxt *lc, const char *filename,
1839
         uint64_t offset, uint64_t sizelimit)
1840
0
{
1841
0
  int rc, hasst;
1842
0
  struct stat st;
1843
1844
0
  if (!filename)
1845
0
    return -EINVAL;
1846
1847
0
  DBG(CXT, ul_debugobj(lc, "find_overlap requested"));
1848
0
  hasst = !stat(filename, &st);
1849
1850
0
  rc = loopcxt_init_iterator(lc, LOOPITER_FL_USED);
1851
0
  if (rc)
1852
0
    return rc;
1853
1854
0
  while ((rc = loopcxt_next(lc)) == 0) {
1855
0
    uint64_t lc_sizelimit, lc_offset;
1856
1857
0
    rc = loopcxt_is_used(lc, hasst ? &st : NULL,
1858
0
             filename, offset, sizelimit, 0);
1859
    /*
1860
     * Either the loopdev is unused or we've got an error which can
1861
     * happen when we are racing with device autoclear. Just ignore
1862
     * this loopdev...
1863
     */
1864
0
    if (rc <= 0)
1865
0
      continue;
1866
1867
0
    DBG(CXT, ul_debugobj(lc, "found %s backed by %s",
1868
0
      loopcxt_get_device(lc), filename));
1869
1870
0
    rc = loopcxt_get_offset(lc, &lc_offset);
1871
0
    if (rc) {
1872
0
      DBG(CXT, ul_debugobj(lc, "failed to get offset for device %s",
1873
0
        loopcxt_get_device(lc)));
1874
0
      continue;
1875
0
    }
1876
0
    rc = loopcxt_get_sizelimit(lc, &lc_sizelimit);
1877
0
    if (rc) {
1878
0
      DBG(CXT, ul_debugobj(lc, "failed to get sizelimit for device %s",
1879
0
        loopcxt_get_device(lc)));
1880
0
      continue;
1881
0
    }
1882
1883
    /* full match */
1884
0
    if (lc_sizelimit == sizelimit && lc_offset == offset) {
1885
0
      DBG(CXT, ul_debugobj(lc, "overlapping loop device %s (full match)",
1886
0
            loopcxt_get_device(lc)));
1887
0
      rc = 2;
1888
0
      goto found;
1889
0
    }
1890
1891
    /* overlap */
1892
0
    if (lc_sizelimit != 0 && offset >= lc_offset + lc_sizelimit)
1893
0
      continue;
1894
0
    if (sizelimit != 0 && offset + sizelimit <= lc_offset)
1895
0
      continue;
1896
1897
0
    DBG(CXT, ul_debugobj(lc, "overlapping loop device %s",
1898
0
      loopcxt_get_device(lc)));
1899
0
      rc = 1;
1900
0
      goto found;
1901
0
  }
1902
1903
0
  if (rc == 1)
1904
0
    rc = 0; /* not found */
1905
0
found:
1906
0
  loopcxt_deinit_iterator(lc);
1907
0
  DBG(CXT, ul_debugobj(lc, "find_overlap done [rc=%d]", rc));
1908
0
  return rc;
1909
0
}
1910
1911
/*
1912
 * Returns allocated string with device name
1913
 */
1914
char *loopdev_find_by_backing_file(const char *filename, uint64_t offset, uint64_t sizelimit, int flags)
1915
0
{
1916
0
  struct loopdev_cxt lc;
1917
0
  char *res = NULL;
1918
1919
0
  if (!filename)
1920
0
    return NULL;
1921
1922
0
  if (loopcxt_init(&lc, 0))
1923
0
    return NULL;
1924
0
  if (loopcxt_find_by_backing_file(&lc, filename, offset, sizelimit, flags) == 0)
1925
0
    res = loopcxt_strdup_device(&lc);
1926
0
  loopcxt_deinit(&lc);
1927
1928
0
  return res;
1929
0
}
1930
1931
/*
1932
 * Returns number of loop devices associated with @file, if only one loop
1933
 * device is associated with the given @filename and @loopdev is not NULL then
1934
 * @loopdev returns name of the device.
1935
 */
1936
int loopdev_count_by_backing_file(const char *filename, char **loopdev)
1937
0
{
1938
0
  struct loopdev_cxt lc;
1939
0
  int count = 0, rc;
1940
1941
0
  if (!filename)
1942
0
    return -1;
1943
1944
0
  rc = loopcxt_init(&lc, 0);
1945
0
  if (rc)
1946
0
    return rc;
1947
0
  if (loopcxt_init_iterator(&lc, LOOPITER_FL_USED))
1948
0
    return -1;
1949
1950
0
  while(loopcxt_next(&lc) == 0) {
1951
0
    char *backing = loopcxt_get_backing_file(&lc);
1952
1953
0
    if (!backing || strcmp(backing, filename) != 0) {
1954
0
      free(backing);
1955
0
      continue;
1956
0
    }
1957
1958
0
    free(backing);
1959
0
    if (loopdev && count == 0)
1960
0
      *loopdev = loopcxt_strdup_device(&lc);
1961
0
    count++;
1962
0
  }
1963
1964
0
  loopcxt_deinit(&lc);
1965
1966
0
  if (loopdev && count > 1) {
1967
0
    free(*loopdev);
1968
0
    *loopdev = NULL;
1969
0
  }
1970
0
  return count;
1971
0
}
1972
1973
#ifdef TEST_PROGRAM_LOOPDEV
1974
int main(int argc, char *argv[])
1975
{
1976
  if (argc < 2)
1977
    goto usage;
1978
1979
  if (strcmp(argv[1], "--is-loopdev") == 0 && argc == 3)
1980
    printf("%s: %s\n", argv[2], is_loopdev(argv[2]) ? "OK" : "FAIL");
1981
  else
1982
    goto usage;
1983
1984
  return EXIT_SUCCESS;
1985
usage:
1986
  fprintf(stderr, "usage: %1$s --is-loopdev <dev>\n",
1987
      program_invocation_short_name);
1988
  return EXIT_FAILURE;
1989
}
1990
#endif
1991