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