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