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