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