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