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
);
389 fputs(USAGE_OPTIONS
, out
);
390 fputs(_(" -a, --all list all used devices\n"), out
);
391 fputs(_(" -d, --detach <loopdev>... detach one or more devices\n"), out
);
392 fputs(_(" -D, --detach-all detach all used devices\n"), out
);
393 fputs(_(" -f, --find find first unused device\n"), out
);
394 fputs(_(" -c, --set-capacity <loopdev> resize the device\n"), out
);
395 fputs(_(" -j, --associated <file> list all devices associated with <file>\n"), out
);
396 fputs(_(" -L, --nooverlap avoid possible conflict between devices\n"), out
);
398 /* commands options */
399 fputs(USAGE_SEPARATOR
, out
);
400 fputs(_(" -o, --offset <num> start at offset <num> into file\n"), out
);
401 fputs(_(" --sizelimit <num> device is limited to <num> bytes of the file\n"), out
);
402 fputs(_(" -P, --partscan create a partitioned loop device\n"), out
);
403 fputs(_(" -r, --read-only set up a read-only loop device\n"), out
);
404 fputs(_(" --direct-io[=<on|off>] open backing file with O_DIRECT\n"), out
);
405 fputs(_(" --show print device name after setup (with -f)\n"), out
);
406 fputs(_(" -v, --verbose verbose mode\n"), out
);
409 fputs(USAGE_SEPARATOR
, out
);
410 fputs(_(" -J, --json use JSON --list output format\n"), out
);
411 fputs(_(" -l, --list list info about all or specified (default)\n"), out
);
412 fputs(_(" -n, --noheadings don't print headings for --list output\n"), out
);
413 fputs(_(" -O, --output <cols> specify columns to output for --list\n"), out
);
414 fputs(_(" --raw use raw --list output format\n"), out
);
416 fputs(USAGE_SEPARATOR
, out
);
417 fputs(USAGE_HELP
, out
);
418 fputs(USAGE_VERSION
, out
);
420 fputs(_("\nAvailable --output columns:\n"), out
);
421 for (i
= 0; i
< ARRAY_SIZE(infos
); i
++)
422 fprintf(out
, " %12s %s\n", infos
[i
].name
, _(infos
[i
].help
));
424 fprintf(out
, USAGE_MAN_TAIL("losetup(8)"));
426 exit(out
== stderr
? EXIT_FAILURE
: EXIT_SUCCESS
);
429 static void warn_size(const char *filename
, uint64_t size
)
434 if (stat(filename
, &st
) || S_ISBLK(st
.st_mode
))
440 warnx(_("%s: Warning: file is smaller than 512 bytes; the loop device "
441 "may be useless or invisible for system tools."),
444 warnx(_("%s: Warning: file does not fit into a 512-byte sector; "
445 "the end of the file will be ignored."),
449 static int create_loop(struct loopdev_cxt
*lc
,
450 int nooverlap
, int lo_flags
, int flags
,
451 const char *file
, uint64_t offset
, uint64_t sizelimit
)
453 int hasdev
= loopcxt_has_device(lc
);
456 /* losetup --find --noverlap file.img */
457 if (!hasdev
&& nooverlap
) {
458 rc
= loopcxt_find_overlap(lc
, file
, offset
, sizelimit
);
460 case 0: /* not found */
463 case 1: /* overlap */
465 errx(EXIT_FAILURE
, _("%s: overlapping loop device exists"), file
);
467 case 2: /* overlap -- full size and offset match (reuse) */
469 uint32_t lc_encrypt_type
;
471 /* Once a loop is initialized RO, there is no
472 * way to change its parameters. */
473 if (loopcxt_is_readonly(lc
)
474 && !(lo_flags
& LO_FLAGS_READ_ONLY
)) {
476 errx(EXIT_FAILURE
, _("%s: overlapping read-only loop device exists"), file
);
479 /* This is no more supported, but check to be safe. */
480 if (loopcxt_get_encrypt_type(lc
, &lc_encrypt_type
) == 0
481 && lc_encrypt_type
!= LO_CRYPT_NONE
) {
483 errx(EXIT_FAILURE
, _("%s: overlapping encrypted loop device exists"), file
);
486 lc
->info
.lo_flags
&= !LO_FLAGS_AUTOCLEAR
;
487 if (loopcxt_set_status(lc
)) {
489 errx(EXIT_FAILURE
, _("%s: failed to re-use loop device"), file
);
491 return 0; /* success, re-use */
495 errx(EXIT_FAILURE
, _("failed to inspect loop devices"));
500 if (hasdev
&& !is_loopdev(loopcxt_get_device(lc
)))
501 loopcxt_add_device(lc
);
503 /* losetup --noverlap /dev/loopN file.img */
504 if (hasdev
&& nooverlap
) {
505 struct loopdev_cxt lc2
;
507 if (loopcxt_init(&lc2
, 0)) {
509 err(EXIT_FAILURE
, _("failed to initialize loopcxt"));
511 rc
= loopcxt_find_overlap(&lc2
, file
, offset
, sizelimit
);
512 loopcxt_deinit(&lc2
);
517 errx(EXIT_FAILURE
, _("%s: overlapping loop device exists"), file
);
518 err(EXIT_FAILURE
, _("%s: failed to check for conflicting loop devices"), file
);
522 /* Create a new device */
526 /* Note that loopcxt_{find_unused,set_device}() resets
529 if (!hasdev
&& (rc
= loopcxt_find_unused(lc
))) {
530 warnx(_("cannot find an unused loop device"));
533 if (flags
& LOOPDEV_FL_OFFSET
)
534 loopcxt_set_offset(lc
, offset
);
535 if (flags
& LOOPDEV_FL_SIZELIMIT
)
536 loopcxt_set_sizelimit(lc
, sizelimit
);
538 loopcxt_set_flags(lc
, lo_flags
);
539 if ((rc
= loopcxt_set_backing_file(lc
, file
))) {
540 warn(_("%s: failed to use backing file"), file
);
544 rc
= loopcxt_setup_device(lc
);
547 if (errno
== EBUSY
&& !hasdev
)
551 errpre
= hasdev
&& loopcxt_get_fd(lc
) < 0 ?
552 loopcxt_get_device(lc
) : file
;
553 warn(_("%s: failed to set up loop device"), errpre
);
555 } while (hasdev
== 0);
560 int main(int argc
, char **argv
)
562 struct loopdev_cxt lc
;
563 int act
= 0, flags
= 0, no_overlap
= 0, c
;
565 uint64_t offset
= 0, sizelimit
= 0;
566 int res
= 0, showdev
= 0, lo_flags
= 0;
569 unsigned long use_dio
= 0, set_dio
= 0;
572 OPT_SIZELIMIT
= CHAR_MAX
+ 1,
577 static const struct option longopts
[] = {
578 { "all", no_argument
, NULL
, 'a' },
579 { "set-capacity", required_argument
, NULL
, 'c' },
580 { "detach", required_argument
, NULL
, 'd' },
581 { "detach-all", no_argument
, NULL
, 'D' },
582 { "find", no_argument
, NULL
, 'f' },
583 { "nooverlap", no_argument
, NULL
, 'L' },
584 { "help", no_argument
, NULL
, 'h' },
585 { "associated", required_argument
, NULL
, 'j' },
586 { "json", no_argument
, NULL
, 'J' },
587 { "list", no_argument
, NULL
, 'l' },
588 { "noheadings", no_argument
, NULL
, 'n' },
589 { "offset", required_argument
, NULL
, 'o' },
590 { "output", required_argument
, NULL
, 'O' },
591 { "sizelimit", required_argument
, NULL
, OPT_SIZELIMIT
},
592 { "partscan", no_argument
, NULL
, 'P' },
593 { "read-only", no_argument
, NULL
, 'r' },
594 { "direct-io", optional_argument
, NULL
, OPT_DIO
},
595 { "raw", no_argument
, NULL
, OPT_RAW
},
596 { "show", no_argument
, NULL
, OPT_SHOW
},
597 { "verbose", no_argument
, NULL
, 'v' },
598 { "version", no_argument
, NULL
, 'V' },
602 static const ul_excl_t excl
[] = { /* rows and cols in ASCII order */
603 { 'D','a','c','d','f','j' },
604 { 'D','c','d','f','l' },
605 { 'D','c','d','f','O' },
609 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
611 setlocale(LC_ALL
, "");
612 bindtextdomain(PACKAGE
, LOCALEDIR
);
614 atexit(close_stdout
);
616 if (loopcxt_init(&lc
, 0))
617 err(EXIT_FAILURE
, _("failed to initialize loopcxt"));
619 while ((c
= getopt_long(argc
, argv
, "ac:d:Dfhj:JlLno:O:PrvV",
620 longopts
, NULL
)) != -1) {
622 err_exclusive_options(c
, longopts
, excl
, excl_st
);
629 act
= A_SET_CAPACITY
;
630 if (!is_loopdev(optarg
) ||
631 loopcxt_set_device(&lc
, optarg
))
632 err(EXIT_FAILURE
, _("%s: failed to use device"),
636 lo_flags
|= LO_FLAGS_READ_ONLY
;
640 if (!is_loopdev(optarg
) ||
641 loopcxt_set_device(&lc
, optarg
))
642 err(EXIT_FAILURE
, _("%s: failed to use device"),
674 offset
= strtosize_or_err(optarg
, _("failed to parse offset"));
675 flags
|= LOOPDEV_FL_OFFSET
;
682 lo_flags
|= LO_FLAGS_PARTSCAN
;
688 use_dio
= set_dio
= 1;
690 use_dio
= parse_switch(optarg
, _("argument error"), "on", "off", NULL
);
695 printf(UTIL_LINUX_VERSION
);
697 case OPT_SIZELIMIT
: /* --sizelimit */
698 sizelimit
= strtosize_or_err(optarg
, _("failed to parse size"));
699 flags
|= LOOPDEV_FL_SIZELIMIT
;
702 errtryhelp(EXIT_FAILURE
);
706 /* default is --list --all */
712 if (!act
&& argc
== 2 && (raw
|| json
)) {
717 /* default --list output columns */
718 if (list
&& !ncolumns
) {
719 columns
[ncolumns
++] = COL_NAME
;
720 columns
[ncolumns
++] = COL_SIZELIMIT
;
721 columns
[ncolumns
++] = COL_OFFSET
;
722 columns
[ncolumns
++] = COL_AUTOCLR
;
723 columns
[ncolumns
++] = COL_RO
;
724 columns
[ncolumns
++] = COL_BACK_FILE
;
725 columns
[ncolumns
++] = COL_DIO
;
728 if (act
== A_FIND_FREE
&& optind
< argc
) {
730 * losetup -f <backing_file>
733 file
= argv
[optind
++];
736 if (list
&& !act
&& optind
== argc
)
738 * losetup --list defaults to --all
742 if (!act
&& optind
+ 1 == argc
) {
744 * losetup [--list] <device>
746 * losetup --direct-io[=off] <device>
751 act
= A_SET_DIRECT_IO
;
752 if (!is_loopdev(argv
[optind
]) ||
753 loopcxt_set_device(&lc
, argv
[optind
]))
754 err(EXIT_FAILURE
, _("%s: failed to use device"),
760 * losetup <loopdev> <backing_file>
765 errx(EXIT_FAILURE
, _("no loop device specified"));
766 /* don't use is_loopdev() here, the device does not have exist yet */
767 if (loopcxt_set_device(&lc
, argv
[optind
]))
768 err(EXIT_FAILURE
, _("%s: failed to use device"),
773 errx(EXIT_FAILURE
, _("no file specified"));
774 file
= argv
[optind
++];
777 if (act
!= A_CREATE
&&
778 (sizelimit
|| lo_flags
|| showdev
))
780 _("the options %s are allowed during loop device setup only"),
781 "--{sizelimit,read-only,show}");
783 if ((flags
& LOOPDEV_FL_OFFSET
) &&
784 act
!= A_CREATE
&& (act
!= A_SHOW
|| !file
))
785 errx(EXIT_FAILURE
, _("the option --offset is not allowed in this context"));
787 if (outarg
&& string_add_to_idarray(outarg
, columns
, ARRAY_SIZE(columns
),
788 &ncolumns
, column_name_to_id
) < 0)
793 res
= create_loop(&lc
, no_overlap
, lo_flags
, flags
, file
, offset
, sizelimit
);
796 printf("%s\n", loopcxt_get_device(&lc
));
797 warn_size(file
, sizelimit
);
803 res
= delete_loop(&lc
);
804 while (optind
< argc
) {
805 if (!is_loopdev(argv
[optind
]) ||
806 loopcxt_set_device(&lc
, argv
[optind
]))
807 warn(_("%s: failed to use device"),
810 res
+= delete_loop(&lc
);
814 res
= delete_all_loops(&lc
);
817 res
= loopcxt_find_unused(&lc
);
821 if (access(_PATH_DEV_LOOPCTL
, F_OK
) == 0 &&
822 access(_PATH_DEV_LOOPCTL
, W_OK
) != 0)
827 warn(_("cannot find an unused loop device"));
829 printf("%s\n", loopcxt_get_device(&lc
));
833 res
= show_table(&lc
, file
, offset
, flags
);
835 res
= show_all_loops(&lc
, file
, offset
, flags
);
839 res
= show_table(&lc
, NULL
, 0, 0);
841 res
= printf_loopdev(&lc
);
843 warn("%s", loopcxt_get_device(&lc
));
846 res
= loopcxt_set_capacity(&lc
);
848 warn(_("%s: set capacity failed"),
849 loopcxt_get_device(&lc
));
851 case A_SET_DIRECT_IO
:
853 res
= loopcxt_set_dio(&lc
, use_dio
);
855 warn(_("%s: set direct io failed"),
856 loopcxt_get_device(&lc
));
864 return res
? EXIT_FAILURE
: EXIT_SUCCESS
;