2 * Copyright (C) 2011 Karel Zak <kzak@redhat.com>
3 * Originally from Ted's losetup.c
5 * losetup.c - setup and control loop devices
13 #include <sys/ioctl.h>
18 #include <libsmartcols.h>
24 #include "closestream.h"
27 #include "canonicalize.h"
28 #include "pathnames.h"
31 A_CREATE
= 1, /* setup a new device */
32 A_DELETE
, /* delete given device(s) */
33 A_DELETE_ALL
, /* delete all devices */
34 A_SHOW
, /* list devices */
35 A_SHOW_ONE
, /* print info about one device */
36 A_FIND_FREE
, /* find first unused */
37 A_SET_CAPACITY
, /* set device capacity */
38 A_SET_DIRECT_IO
, /* set accessing backing file by direct io */
55 /* basic output flags */
56 static int no_headings
;
67 static struct colinfo infos
[] = {
68 [COL_AUTOCLR
] = { "AUTOCLEAR", 1, SCOLS_FL_RIGHT
, N_("autoclear flag set")},
69 [COL_BACK_FILE
] = { "BACK-FILE", 0.3, 0, N_("device backing file")},
70 [COL_BACK_INO
] = { "BACK-INO", 4, SCOLS_FL_RIGHT
, N_("backing file inode number")},
71 [COL_BACK_MAJMIN
] = { "BACK-MAJ:MIN", 6, 0, N_("backing file major:minor device number")},
72 [COL_NAME
] = { "NAME", 0.25, 0, N_("loop device name")},
73 [COL_OFFSET
] = { "OFFSET", 5, SCOLS_FL_RIGHT
, N_("offset from the beginning")},
74 [COL_PARTSCAN
] = { "PARTSCAN", 1, SCOLS_FL_RIGHT
, N_("partscan flag set")},
75 [COL_RO
] = { "RO", 1, SCOLS_FL_RIGHT
, N_("read-only device")},
76 [COL_SIZELIMIT
] = { "SIZELIMIT", 5, SCOLS_FL_RIGHT
, N_("size limit of the file in bytes")},
77 [COL_MAJMIN
] = { "MAJ:MIN", 3, 0, N_("loop device major:minor number")},
78 [COL_DIO
] = { "DIO", 1, SCOLS_FL_RIGHT
, N_("access backing file with direct-io")},
81 static int columns
[ARRAY_SIZE(infos
) * 2] = {-1};
82 static size_t ncolumns
;
84 static int get_column_id(int num
)
87 assert((size_t) num
< ncolumns
);
88 assert(columns
[num
] < (int) ARRAY_SIZE(infos
));
92 static struct colinfo
*get_column_info(int num
)
94 return &infos
[ get_column_id(num
) ];
97 static int column_name_to_id(const char *name
, size_t namesz
)
101 for (i
= 0; i
< ARRAY_SIZE(infos
); i
++) {
102 const char *cn
= infos
[i
].name
;
104 if (!strncasecmp(name
, cn
, namesz
) && !*(cn
+ namesz
))
107 warnx(_("unknown column: %s"), name
);
111 static int printf_loopdev(struct loopdev_cxt
*lc
)
119 fname
= loopcxt_get_backing_file(lc
);
123 if (loopcxt_get_backing_devno(lc
, &dev
) == 0)
124 loopcxt_get_backing_inode(lc
, &ino
);
128 * Probably non-root user (no permissions to
129 * call LOOP_GET_STATUS ioctls).
131 printf("%s: []: (%s)",
132 loopcxt_get_device(lc
), fname
);
134 if (loopcxt_get_offset(lc
, &x
) == 0 && x
)
135 printf(_(", offset %ju"), x
);
137 if (loopcxt_get_sizelimit(lc
, &x
) == 0 && x
)
138 printf(_(", sizelimit %ju"), x
);
143 printf("%s: [%04d]:%" PRIu64
" (%s)",
144 loopcxt_get_device(lc
), (int) dev
, ino
, fname
);
146 if (loopcxt_get_offset(lc
, &x
) == 0 && x
)
147 printf(_(", offset %ju"), x
);
149 if (loopcxt_get_sizelimit(lc
, &x
) == 0 && x
)
150 printf(_(", sizelimit %ju"), x
);
152 if (loopcxt_get_encrypt_type(lc
, &type
) == 0) {
153 const char *e
= loopcxt_get_crypt_name(lc
);
155 if ((!e
|| !*e
) && type
== 1)
158 printf(_(", encryption %s (type %u)"), e
, type
);
164 static int show_all_loops(struct loopdev_cxt
*lc
, const char *file
,
165 uint64_t offset
, int flags
)
167 struct stat sbuf
, *st
= &sbuf
;
168 char *cn_file
= NULL
;
170 if (loopcxt_init_iterator(lc
, LOOPITER_FL_USED
))
173 if (!file
|| stat(file
, st
))
176 while (loopcxt_next(lc
) == 0) {
179 const char *bf
= cn_file
? cn_file
: file
;
181 used
= loopcxt_is_used(lc
, st
, bf
, offset
, 0, flags
);
182 if (!used
&& !cn_file
) {
183 bf
= cn_file
= canonicalize_path(file
);
184 used
= loopcxt_is_used(lc
, st
, bf
, offset
, 0, flags
);
191 loopcxt_deinit_iterator(lc
);
196 static int delete_loop(struct loopdev_cxt
*lc
)
198 if (loopcxt_delete_device(lc
))
199 warn(_("%s: detach failed"), loopcxt_get_device(lc
));
206 static int delete_all_loops(struct loopdev_cxt
*lc
)
210 if (loopcxt_init_iterator(lc
, LOOPITER_FL_USED
))
213 while (loopcxt_next(lc
) == 0)
214 res
+= delete_loop(lc
);
216 loopcxt_deinit_iterator(lc
);
220 static int set_scols_data(struct loopdev_cxt
*lc
, struct libscols_line
*ln
)
224 for (i
= 0; i
< ncolumns
; i
++) {
225 const char *p
= NULL
; /* external data */
226 char *np
= NULL
; /* allocated here */
229 switch(get_column_id(i
)) {
231 p
= loopcxt_get_device(lc
);
234 p
= loopcxt_get_backing_file(lc
);
237 if (loopcxt_get_offset(lc
, &x
) == 0)
238 xasprintf(&np
, "%jd", x
);
241 if (loopcxt_get_sizelimit(lc
, &x
) == 0)
242 xasprintf(&np
, "%jd", x
);
244 case COL_BACK_MAJMIN
:
247 if (loopcxt_get_backing_devno(lc
, &dev
) == 0 && dev
)
248 xasprintf(&np
, "%8u:%-3u", major(dev
), minor(dev
));
255 if (loopcxt_get_device(lc
)
256 && stat(loopcxt_get_device(lc
), &st
) == 0
257 && S_ISBLK(st
.st_mode
)
258 && major(st
.st_rdev
) == LOOPDEV_MAJOR
)
259 xasprintf(&np
, "%3u:%-3u", major(st
.st_rdev
),
266 if (loopcxt_get_backing_inode(lc
, &ino
) == 0 && ino
)
267 xasprintf(&np
, "%ju", ino
);
271 p
= loopcxt_is_autoclear(lc
) ? "1" : "0";
274 p
= loopcxt_is_readonly(lc
) ? "1" : "0";
277 p
= loopcxt_is_dio(lc
) ? "1" : "0";
280 p
= loopcxt_is_partscan(lc
) ? "1" : "0";
288 scols_line_set_data(ln
, i
, p
); /* calls strdup() */
290 scols_line_refer_data(ln
, i
, np
); /* only refers */
296 static int show_table(struct loopdev_cxt
*lc
,
301 struct stat sbuf
, *st
= &sbuf
;
302 struct libscols_table
*tb
;
303 struct libscols_line
*ln
;
309 if (!(tb
= scols_new_table()))
310 err(EXIT_FAILURE
, _("failed to initialize output table"));
311 scols_table_enable_raw(tb
, raw
);
312 scols_table_enable_json(tb
, json
);
313 scols_table_enable_noheadings(tb
, no_headings
);
316 scols_table_set_name(tb
, "loopdevices");
318 for (i
= 0; i
< ncolumns
; i
++) {
319 struct colinfo
*ci
= get_column_info(i
);
321 if (!scols_table_new_column(tb
, ci
->name
, ci
->whint
, ci
->flags
))
322 err(EXIT_FAILURE
, _("failed to initialize output column"));
325 /* only one loopdev requested (already assigned to loopdev_cxt) */
326 if (loopcxt_get_device(lc
)) {
327 ln
= scols_table_new_line(tb
, NULL
);
329 err(EXIT_FAILURE
, _("failed to initialize output line"));
330 rc
= set_scols_data(lc
, ln
);
332 /* list all loopdevs */
334 char *cn_file
= NULL
;
336 rc
= loopcxt_init_iterator(lc
, LOOPITER_FL_USED
);
339 if (!file
|| stat(file
, st
))
342 while (loopcxt_next(lc
) == 0) {
345 const char *bf
= cn_file
? cn_file
: file
;
347 used
= loopcxt_is_used(lc
, st
, bf
, offset
, 0, flags
);
348 if (!used
&& !cn_file
) {
349 bf
= cn_file
= canonicalize_path(file
);
350 used
= loopcxt_is_used(lc
, st
, bf
, offset
, 0, flags
);
356 ln
= scols_table_new_line(tb
, NULL
);
358 err(EXIT_FAILURE
, _("failed to initialize output column"));
359 rc
= set_scols_data(lc
, ln
);
364 loopcxt_deinit_iterator(lc
);
369 rc
= scols_print_table(tb
);
370 scols_unref_table(tb
);
374 static void usage(FILE *out
)
378 fputs(USAGE_HEADER
, out
);
381 _(" %1$s [options] [<loopdev>]\n"
382 " %1$s [options] -f | <loopdev> <file>\n"),
383 program_invocation_short_name
);
385 fputs(USAGE_SEPARATOR
, out
);
386 fputs(_("Set up and control loop devices.\n"), out
);
388 fputs(USAGE_OPTIONS
, out
);
389 fputs(_(" -a, --all list all used devices\n"), out
);
390 fputs(_(" -d, --detach <loopdev>... detach one or more devices\n"), out
);
391 fputs(_(" -D, --detach-all detach all used devices\n"), out
);
392 fputs(_(" -f, --find find first unused device\n"), out
);
393 fputs(_(" -c, --set-capacity <loopdev> resize the device\n"), out
);
394 fputs(_(" -j, --associated <file> list all devices associated with <file>\n"), out
);
395 fputs(_(" -L, --nooverlap avoid possible conflict between devices\n"), out
);
397 fputs(USAGE_SEPARATOR
, out
);
399 fputs(_(" -o, --offset <num> start at offset <num> into file\n"), out
);
400 fputs(_(" --sizelimit <num> device is limited to <num> bytes of the file\n"), out
);
401 fputs(_(" -P, --partscan create a partitioned loop device\n"), out
);
402 fputs(_(" -r, --read-only set up a read-only loop device\n"), out
);
403 fputs(_(" --direct-io[=<on|off>] open backing file with O_DIRECT\n"), out
);
404 fputs(_(" --show print device name after setup (with -f)\n"), out
);
405 fputs(_(" -v, --verbose verbose mode\n"), out
);
407 fputs(USAGE_SEPARATOR
, out
);
409 fputs(_(" -l, --list list info about all or specified (default)\n"), out
);
410 fputs(_(" -O, --output <cols> specify columns to output for --list\n"), out
);
411 fputs(_(" -n, --noheadings don't print headings for --list output\n"), out
);
412 fputs(_(" --raw use raw --list output format\n"), out
);
413 fputs(_(" -J, --json use JSON --list output format\n"), out
);
415 fputs(USAGE_SEPARATOR
, out
);
416 fputs(USAGE_HELP
, out
);
417 fputs(USAGE_VERSION
, out
);
419 fputs(_("\nAvailable --list columns:\n"), out
);
420 for (i
= 0; i
< ARRAY_SIZE(infos
); i
++)
421 fprintf(out
, " %12s %s\n", infos
[i
].name
, _(infos
[i
].help
));
423 fprintf(out
, USAGE_MAN_TAIL("losetup(8)"));
425 exit(out
== stderr
? EXIT_FAILURE
: EXIT_SUCCESS
);
428 static void warn_size(const char *filename
, uint64_t size
)
433 if (stat(filename
, &st
) || S_ISBLK(st
.st_mode
))
439 warnx(_("%s: Warning: file is smaller than 512 bytes; the loop device "
440 "may be useless or invisible for system tools."),
443 warnx(_("%s: Warning: file does not fit into a 512-byte sector; "
444 "the end of the file will be ignored."),
448 static int create_loop(struct loopdev_cxt
*lc
,
449 int nooverlap
, int lo_flags
, int flags
,
450 const char *file
, uint64_t offset
, uint64_t sizelimit
)
452 int hasdev
= loopcxt_has_device(lc
);
455 /* losetup --find --noverlap file.img */
456 if (!hasdev
&& nooverlap
) {
457 rc
= loopcxt_find_overlap(lc
, file
, offset
, sizelimit
);
459 case 0: /* not found */
462 case 1: /* overlap */
464 errx(EXIT_FAILURE
, _("%s: overlapping loop device exists"), file
);
466 case 2: /* overlap -- full size and offset match (reuse) */
468 uint32_t lc_encrypt_type
;
470 /* Once a loop is initialized RO, there is no
471 * way to change its parameters. */
472 if (loopcxt_is_readonly(lc
)
473 && !(lo_flags
& LO_FLAGS_READ_ONLY
)) {
475 errx(EXIT_FAILURE
, _("%s: overlapping read-only loop device exists"), file
);
478 /* This is no more supported, but check to be safe. */
479 if (loopcxt_get_encrypt_type(lc
, &lc_encrypt_type
) == 0
480 && lc_encrypt_type
!= LO_CRYPT_NONE
) {
482 errx(EXIT_FAILURE
, _("%s: overlapping encrypted loop device exists"), file
);
485 lc
->info
.lo_flags
&= !LO_FLAGS_AUTOCLEAR
;
486 if (loopcxt_set_status(lc
)) {
488 errx(EXIT_FAILURE
, _("%s: failed to re-use loop device"), file
);
490 return 0; /* success, re-use */
494 errx(EXIT_FAILURE
, _("failed to inspect loop devices"));
499 if (hasdev
&& !is_loopdev(loopcxt_get_device(lc
)))
500 loopcxt_add_device(lc
);
502 /* losetup --noverlap /dev/loopN file.img */
503 if (hasdev
&& nooverlap
) {
504 struct loopdev_cxt lc2
;
506 if (loopcxt_init(&lc2
, 0)) {
508 err(EXIT_FAILURE
, _("failed to initialize loopcxt"));
510 rc
= loopcxt_find_overlap(&lc2
, file
, offset
, sizelimit
);
511 loopcxt_deinit(&lc2
);
516 errx(EXIT_FAILURE
, _("%s: overlapping loop device exists"), file
);
517 err(EXIT_FAILURE
, _("%s: failed to check for conflicting loop devices"), file
);
521 /* Create a new device */
525 /* Note that loopcxt_{find_unused,set_device}() resets
528 if (!hasdev
&& (rc
= loopcxt_find_unused(lc
))) {
529 warnx(_("cannot find an unused loop device"));
532 if (flags
& LOOPDEV_FL_OFFSET
)
533 loopcxt_set_offset(lc
, offset
);
534 if (flags
& LOOPDEV_FL_SIZELIMIT
)
535 loopcxt_set_sizelimit(lc
, sizelimit
);
537 loopcxt_set_flags(lc
, lo_flags
);
538 if ((rc
= loopcxt_set_backing_file(lc
, file
))) {
539 warn(_("%s: failed to use backing file"), file
);
543 rc
= loopcxt_setup_device(lc
);
546 if (errno
== EBUSY
&& !hasdev
)
550 errpre
= hasdev
&& loopcxt_get_fd(lc
) < 0 ?
551 loopcxt_get_device(lc
) : file
;
552 warn(_("%s: failed to set up loop device"), errpre
);
554 } while (hasdev
== 0);
559 int main(int argc
, char **argv
)
561 struct loopdev_cxt lc
;
562 int act
= 0, flags
= 0, no_overlap
= 0, c
;
564 uint64_t offset
= 0, sizelimit
= 0;
565 int res
= 0, showdev
= 0, lo_flags
= 0;
568 unsigned long use_dio
= 0, set_dio
= 0;
571 OPT_SIZELIMIT
= CHAR_MAX
+ 1,
576 static const struct option longopts
[] = {
577 { "all", 0, 0, 'a' },
578 { "set-capacity", 1, 0, 'c' },
579 { "detach", 1, 0, 'd' },
580 { "detach-all", 0, 0, 'D' },
581 { "find", 0, 0, 'f' },
582 { "nooverlap", 0, 0, 'L' },
583 { "help", 0, 0, 'h' },
584 { "associated", 1, 0, 'j' },
585 { "json", 0, 0, 'J' },
586 { "list", 0, 0, 'l' },
587 { "noheadings", 0, 0, 'n' },
588 { "offset", 1, 0, 'o' },
589 { "output", 1, 0, 'O' },
590 { "sizelimit", 1, 0, OPT_SIZELIMIT
},
591 { "partscan", 0, 0, 'P' },
592 { "read-only", 0, 0, 'r' },
593 { "direct-io", 2, 0, OPT_DIO
},
594 { "raw", 0, 0, OPT_RAW
},
595 { "show", 0, 0, OPT_SHOW
},
596 { "verbose", 0, 0, 'v' },
597 { "version", 0, 0, 'V' },
601 static const ul_excl_t excl
[] = { /* rows and cols in ASCII order */
602 { 'D','a','c','d','f','j' },
603 { 'D','c','d','f','l' },
604 { 'D','c','d','f','O' },
608 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
610 setlocale(LC_ALL
, "");
611 bindtextdomain(PACKAGE
, LOCALEDIR
);
613 atexit(close_stdout
);
615 if (loopcxt_init(&lc
, 0))
616 err(EXIT_FAILURE
, _("failed to initialize loopcxt"));
618 while ((c
= getopt_long(argc
, argv
, "ac:d:Dfhj:JlLno:O:PrvV",
619 longopts
, NULL
)) != -1) {
621 err_exclusive_options(c
, longopts
, excl
, excl_st
);
628 act
= A_SET_CAPACITY
;
629 if (!is_loopdev(optarg
) ||
630 loopcxt_set_device(&lc
, optarg
))
631 err(EXIT_FAILURE
, _("%s: failed to use device"),
635 lo_flags
|= LO_FLAGS_READ_ONLY
;
639 if (!is_loopdev(optarg
) ||
640 loopcxt_set_device(&lc
, optarg
))
641 err(EXIT_FAILURE
, _("%s: failed to use device"),
673 offset
= strtosize_or_err(optarg
, _("failed to parse offset"));
674 flags
|= LOOPDEV_FL_OFFSET
;
681 lo_flags
|= LO_FLAGS_PARTSCAN
;
687 use_dio
= set_dio
= 1;
689 use_dio
= parse_switch(optarg
, _("argument error"), "on", "off", NULL
);
694 printf(UTIL_LINUX_VERSION
);
696 case OPT_SIZELIMIT
: /* --sizelimit */
697 sizelimit
= strtosize_or_err(optarg
, _("failed to parse size"));
698 flags
|= LOOPDEV_FL_SIZELIMIT
;
701 errtryhelp(EXIT_FAILURE
);
705 /* default is --list --all */
711 if (!act
&& argc
== 2 && (raw
|| json
)) {
716 /* default --list output columns */
717 if (list
&& !ncolumns
) {
718 columns
[ncolumns
++] = COL_NAME
;
719 columns
[ncolumns
++] = COL_SIZELIMIT
;
720 columns
[ncolumns
++] = COL_OFFSET
;
721 columns
[ncolumns
++] = COL_AUTOCLR
;
722 columns
[ncolumns
++] = COL_RO
;
723 columns
[ncolumns
++] = COL_BACK_FILE
;
724 columns
[ncolumns
++] = COL_DIO
;
727 if (act
== A_FIND_FREE
&& optind
< argc
) {
729 * losetup -f <backing_file>
732 file
= argv
[optind
++];
735 if (list
&& !act
&& optind
== argc
)
737 * losetup --list defaults to --all
741 if (!act
&& optind
+ 1 == argc
) {
743 * losetup [--list] <device>
745 * losetup --direct-io[=off] <device>
750 act
= A_SET_DIRECT_IO
;
751 if (!is_loopdev(argv
[optind
]) ||
752 loopcxt_set_device(&lc
, argv
[optind
]))
753 err(EXIT_FAILURE
, _("%s: failed to use device"),
759 * losetup <loopdev> <backing_file>
764 errx(EXIT_FAILURE
, _("no loop device specified"));
765 /* don't use is_loopdev() here, the device does not have exist yet */
766 if (loopcxt_set_device(&lc
, argv
[optind
]))
767 err(EXIT_FAILURE
, _("%s: failed to use device"),
772 errx(EXIT_FAILURE
, _("no file specified"));
773 file
= argv
[optind
++];
776 if (act
!= A_CREATE
&&
777 (sizelimit
|| lo_flags
|| showdev
))
779 _("the options %s are allowed during loop device setup only"),
780 "--{sizelimit,read-only,show}");
782 if ((flags
& LOOPDEV_FL_OFFSET
) &&
783 act
!= A_CREATE
&& (act
!= A_SHOW
|| !file
))
784 errx(EXIT_FAILURE
, _("the option --offset is not allowed in this context"));
786 if (outarg
&& string_add_to_idarray(outarg
, columns
, ARRAY_SIZE(columns
),
787 &ncolumns
, column_name_to_id
) < 0)
792 res
= create_loop(&lc
, no_overlap
, lo_flags
, flags
, file
, offset
, sizelimit
);
795 printf("%s\n", loopcxt_get_device(&lc
));
796 warn_size(file
, sizelimit
);
802 res
= delete_loop(&lc
);
803 while (optind
< argc
) {
804 if (!is_loopdev(argv
[optind
]) ||
805 loopcxt_set_device(&lc
, argv
[optind
]))
806 warn(_("%s: failed to use device"),
809 res
+= delete_loop(&lc
);
813 res
= delete_all_loops(&lc
);
816 res
= loopcxt_find_unused(&lc
);
820 if (access(_PATH_DEV_LOOPCTL
, F_OK
) == 0 &&
821 access(_PATH_DEV_LOOPCTL
, W_OK
) != 0)
826 warn(_("cannot find an unused loop device"));
828 printf("%s\n", loopcxt_get_device(&lc
));
832 res
= show_table(&lc
, file
, offset
, flags
);
834 res
= show_all_loops(&lc
, file
, offset
, flags
);
838 res
= show_table(&lc
, NULL
, 0, 0);
840 res
= printf_loopdev(&lc
);
842 warn("%s", loopcxt_get_device(&lc
));
845 res
= loopcxt_set_capacity(&lc
);
847 warn(_("%s: set capacity failed"),
848 loopcxt_get_device(&lc
));
850 case A_SET_DIRECT_IO
:
852 res
= loopcxt_set_dio(&lc
, use_dio
);
854 warn(_("%s: set direct io failed"),
855 loopcxt_get_device(&lc
));
863 return res
? EXIT_FAILURE
: EXIT_SUCCESS
;