qemu-img: Add --start-offset and --max-length to map
[qemu.git] / qemu-img.c
blob947bf8b34b3d766e60fbf4b3fdb875d473d0fcff
1 /*
2 * QEMU disk image utility
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
26 #include <getopt.h>
28 #include "qemu-common.h"
29 #include "qemu-version.h"
30 #include "qapi/error.h"
31 #include "qapi/qapi-visit-block-core.h"
32 #include "qapi/qobject-output-visitor.h"
33 #include "qapi/qmp/qjson.h"
34 #include "qapi/qmp/qdict.h"
35 #include "qapi/qmp/qstring.h"
36 #include "qemu/cutils.h"
37 #include "qemu/config-file.h"
38 #include "qemu/option.h"
39 #include "qemu/error-report.h"
40 #include "qemu/log.h"
41 #include "qemu/main-loop.h"
42 #include "qemu/module.h"
43 #include "qemu/units.h"
44 #include "qom/object_interfaces.h"
45 #include "sysemu/block-backend.h"
46 #include "block/block_int.h"
47 #include "block/blockjob.h"
48 #include "block/qapi.h"
49 #include "crypto/init.h"
50 #include "trace/control.h"
52 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
53 "\n" QEMU_COPYRIGHT "\n"
55 typedef struct img_cmd_t {
56 const char *name;
57 int (*handler)(int argc, char **argv);
58 } img_cmd_t;
60 enum {
61 OPTION_OUTPUT = 256,
62 OPTION_BACKING_CHAIN = 257,
63 OPTION_OBJECT = 258,
64 OPTION_IMAGE_OPTS = 259,
65 OPTION_PATTERN = 260,
66 OPTION_FLUSH_INTERVAL = 261,
67 OPTION_NO_DRAIN = 262,
68 OPTION_TARGET_IMAGE_OPTS = 263,
69 OPTION_SIZE = 264,
70 OPTION_PREALLOCATION = 265,
71 OPTION_SHRINK = 266,
72 OPTION_SALVAGE = 267,
73 OPTION_TARGET_IS_ZERO = 268,
76 typedef enum OutputFormat {
77 OFORMAT_JSON,
78 OFORMAT_HUMAN,
79 } OutputFormat;
81 /* Default to cache=writeback as data integrity is not important for qemu-img */
82 #define BDRV_DEFAULT_CACHE "writeback"
84 static void format_print(void *opaque, const char *name)
86 printf(" %s", name);
89 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
91 va_list ap;
93 va_start(ap, fmt);
94 error_vreport(fmt, ap);
95 va_end(ap);
97 error_printf("Try 'qemu-img --help' for more information\n");
98 exit(EXIT_FAILURE);
101 static void QEMU_NORETURN missing_argument(const char *option)
103 error_exit("missing argument for option '%s'", option);
106 static void QEMU_NORETURN unrecognized_option(const char *option)
108 error_exit("unrecognized option '%s'", option);
111 /* Please keep in synch with qemu-img.texi */
112 static void QEMU_NORETURN help(void)
114 const char *help_msg =
115 QEMU_IMG_VERSION
116 "usage: qemu-img [standard options] command [command options]\n"
117 "QEMU disk image utility\n"
118 "\n"
119 " '-h', '--help' display this help and exit\n"
120 " '-V', '--version' output version information and exit\n"
121 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
122 " specify tracing options\n"
123 "\n"
124 "Command syntax:\n"
125 #define DEF(option, callback, arg_string) \
126 " " arg_string "\n"
127 #include "qemu-img-cmds.h"
128 #undef DEF
129 "\n"
130 "Command parameters:\n"
131 " 'filename' is a disk image filename\n"
132 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
133 " manual page for a description of the object properties. The most common\n"
134 " object type is a 'secret', which is used to supply passwords and/or\n"
135 " encryption keys.\n"
136 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
137 " 'cache' is the cache mode used to write the output disk image, the valid\n"
138 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
139 " 'directsync' and 'unsafe' (default for convert)\n"
140 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
141 " options are the same as for the 'cache' option\n"
142 " 'size' is the disk image size in bytes. Optional suffixes\n"
143 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
144 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
145 " supported. 'b' is ignored.\n"
146 " 'output_filename' is the destination disk image filename\n"
147 " 'output_fmt' is the destination format\n"
148 " 'options' is a comma separated list of format specific options in a\n"
149 " name=value format. Use -o ? for an overview of the options supported by the\n"
150 " used format\n"
151 " 'snapshot_param' is param used for internal snapshot, format\n"
152 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
153 " '[ID_OR_NAME]'\n"
154 " '-c' indicates that target image must be compressed (qcow format only)\n"
155 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
156 " new backing file match exactly. The image doesn't need a working\n"
157 " backing file before rebasing in this case (useful for renaming the\n"
158 " backing file). For image creation, allow creating without attempting\n"
159 " to open the backing file.\n"
160 " '-h' with or without a command shows this help and lists the supported formats\n"
161 " '-p' show progress of command (only certain commands)\n"
162 " '-q' use Quiet mode - do not print any output (except errors)\n"
163 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
164 " contain only zeros for qemu-img to create a sparse image during\n"
165 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
166 " unallocated or zero sectors, and the destination image will always be\n"
167 " fully allocated\n"
168 " '--output' takes the format in which the output must be done (human or json)\n"
169 " '-n' skips the target volume creation (useful if the volume is created\n"
170 " prior to running qemu-img)\n"
171 "\n"
172 "Parameters to check subcommand:\n"
173 " '-r' tries to repair any inconsistencies that are found during the check.\n"
174 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
175 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
176 " hiding corruption that has already occurred.\n"
177 "\n"
178 "Parameters to convert subcommand:\n"
179 " '-m' specifies how many coroutines work in parallel during the convert\n"
180 " process (defaults to 8)\n"
181 " '-W' allow to write to the target out of order rather than sequential\n"
182 "\n"
183 "Parameters to snapshot subcommand:\n"
184 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
185 " '-a' applies a snapshot (revert disk to saved state)\n"
186 " '-c' creates a snapshot\n"
187 " '-d' deletes a snapshot\n"
188 " '-l' lists all snapshots in the given image\n"
189 "\n"
190 "Parameters to compare subcommand:\n"
191 " '-f' first image format\n"
192 " '-F' second image format\n"
193 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
194 "\n"
195 "Parameters to dd subcommand:\n"
196 " 'bs=BYTES' read and write up to BYTES bytes at a time "
197 "(default: 512)\n"
198 " 'count=N' copy only N input blocks\n"
199 " 'if=FILE' read from FILE\n"
200 " 'of=FILE' write to FILE\n"
201 " 'skip=N' skip N bs-sized blocks at the start of input\n";
203 printf("%s\nSupported formats:", help_msg);
204 bdrv_iterate_format(format_print, NULL, false);
205 printf("\n\n" QEMU_HELP_BOTTOM "\n");
206 exit(EXIT_SUCCESS);
209 static QemuOptsList qemu_object_opts = {
210 .name = "object",
211 .implied_opt_name = "qom-type",
212 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
213 .desc = {
218 static bool qemu_img_object_print_help(const char *type, QemuOpts *opts)
220 if (user_creatable_print_help(type, opts)) {
221 exit(0);
223 return true;
227 * Is @optarg safe for accumulate_options()?
228 * It is when multiple of them can be joined together separated by ','.
229 * To make that work, @optarg must not start with ',' (or else a
230 * separating ',' preceding it gets escaped), and it must not end with
231 * an odd number of ',' (or else a separating ',' following it gets
232 * escaped), or be empty (or else a separating ',' preceding it can
233 * escape a separating ',' following it).
236 static bool is_valid_option_list(const char *optarg)
238 size_t len = strlen(optarg);
239 size_t i;
241 if (!optarg[0] || optarg[0] == ',') {
242 return false;
245 for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
247 if ((len - i) % 2) {
248 return false;
251 return true;
254 static int accumulate_options(char **options, char *optarg)
256 char *new_options;
258 if (!is_valid_option_list(optarg)) {
259 error_report("Invalid option list: %s", optarg);
260 return -1;
263 if (!*options) {
264 *options = g_strdup(optarg);
265 } else {
266 new_options = g_strdup_printf("%s,%s", *options, optarg);
267 g_free(*options);
268 *options = new_options;
270 return 0;
273 static QemuOptsList qemu_source_opts = {
274 .name = "source",
275 .implied_opt_name = "file",
276 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
277 .desc = {
282 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
284 int ret = 0;
285 if (!quiet) {
286 va_list args;
287 va_start(args, fmt);
288 ret = vprintf(fmt, args);
289 va_end(args);
291 return ret;
295 static int print_block_option_help(const char *filename, const char *fmt)
297 BlockDriver *drv, *proto_drv;
298 QemuOptsList *create_opts = NULL;
299 Error *local_err = NULL;
301 /* Find driver and parse its options */
302 drv = bdrv_find_format(fmt);
303 if (!drv) {
304 error_report("Unknown file format '%s'", fmt);
305 return 1;
308 if (!drv->create_opts) {
309 error_report("Format driver '%s' does not support image creation", fmt);
310 return 1;
313 create_opts = qemu_opts_append(create_opts, drv->create_opts);
314 if (filename) {
315 proto_drv = bdrv_find_protocol(filename, true, &local_err);
316 if (!proto_drv) {
317 error_report_err(local_err);
318 qemu_opts_free(create_opts);
319 return 1;
321 if (!proto_drv->create_opts) {
322 error_report("Protocol driver '%s' does not support image creation",
323 proto_drv->format_name);
324 qemu_opts_free(create_opts);
325 return 1;
327 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
330 if (filename) {
331 printf("Supported options:\n");
332 } else {
333 printf("Supported %s options:\n", fmt);
335 qemu_opts_print_help(create_opts, false);
336 qemu_opts_free(create_opts);
338 if (!filename) {
339 printf("\n"
340 "The protocol level may support further options.\n"
341 "Specify the target filename to include those options.\n");
344 return 0;
348 static BlockBackend *img_open_opts(const char *optstr,
349 QemuOpts *opts, int flags, bool writethrough,
350 bool quiet, bool force_share)
352 QDict *options;
353 Error *local_err = NULL;
354 BlockBackend *blk;
355 options = qemu_opts_to_qdict(opts, NULL);
356 if (force_share) {
357 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
358 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
359 error_report("--force-share/-U conflicts with image options");
360 qobject_unref(options);
361 return NULL;
363 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
365 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
366 if (!blk) {
367 error_reportf_err(local_err, "Could not open '%s': ", optstr);
368 return NULL;
370 blk_set_enable_write_cache(blk, !writethrough);
372 return blk;
375 static BlockBackend *img_open_file(const char *filename,
376 QDict *options,
377 const char *fmt, int flags,
378 bool writethrough, bool quiet,
379 bool force_share)
381 BlockBackend *blk;
382 Error *local_err = NULL;
384 if (!options) {
385 options = qdict_new();
387 if (fmt) {
388 qdict_put_str(options, "driver", fmt);
391 if (force_share) {
392 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
394 blk = blk_new_open(filename, NULL, options, flags, &local_err);
395 if (!blk) {
396 error_reportf_err(local_err, "Could not open '%s': ", filename);
397 return NULL;
399 blk_set_enable_write_cache(blk, !writethrough);
401 return blk;
405 static int img_add_key_secrets(void *opaque,
406 const char *name, const char *value,
407 Error **errp)
409 QDict *options = opaque;
411 if (g_str_has_suffix(name, "key-secret")) {
412 qdict_put_str(options, name, value);
415 return 0;
419 static BlockBackend *img_open(bool image_opts,
420 const char *filename,
421 const char *fmt, int flags, bool writethrough,
422 bool quiet, bool force_share)
424 BlockBackend *blk;
425 if (image_opts) {
426 QemuOpts *opts;
427 if (fmt) {
428 error_report("--image-opts and --format are mutually exclusive");
429 return NULL;
431 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
432 filename, true);
433 if (!opts) {
434 return NULL;
436 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
437 force_share);
438 } else {
439 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
440 force_share);
442 return blk;
446 static int add_old_style_options(const char *fmt, QemuOpts *opts,
447 const char *base_filename,
448 const char *base_fmt)
450 Error *err = NULL;
452 if (base_filename) {
453 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
454 if (err) {
455 error_report("Backing file not supported for file format '%s'",
456 fmt);
457 error_free(err);
458 return -1;
461 if (base_fmt) {
462 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
463 if (err) {
464 error_report("Backing file format not supported for file "
465 "format '%s'", fmt);
466 error_free(err);
467 return -1;
470 return 0;
473 static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
474 int64_t max)
476 int err;
477 uint64_t res;
479 err = qemu_strtosz(value, NULL, &res);
480 if (err < 0 && err != -ERANGE) {
481 error_report("Invalid %s specified. You may use "
482 "k, M, G, T, P or E suffixes for", name);
483 error_report("kilobytes, megabytes, gigabytes, terabytes, "
484 "petabytes and exabytes.");
485 return err;
487 if (err == -ERANGE || res > max || res < min) {
488 error_report("Invalid %s specified. Must be between %" PRId64
489 " and %" PRId64 ".", name, min, max);
490 return -ERANGE;
492 return res;
495 static int64_t cvtnum(const char *name, const char *value)
497 return cvtnum_full(name, value, 0, INT64_MAX);
500 static int img_create(int argc, char **argv)
502 int c;
503 uint64_t img_size = -1;
504 const char *fmt = "raw";
505 const char *base_fmt = NULL;
506 const char *filename;
507 const char *base_filename = NULL;
508 char *options = NULL;
509 Error *local_err = NULL;
510 bool quiet = false;
511 int flags = 0;
513 for(;;) {
514 static const struct option long_options[] = {
515 {"help", no_argument, 0, 'h'},
516 {"object", required_argument, 0, OPTION_OBJECT},
517 {0, 0, 0, 0}
519 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
520 long_options, NULL);
521 if (c == -1) {
522 break;
524 switch(c) {
525 case ':':
526 missing_argument(argv[optind - 1]);
527 break;
528 case '?':
529 unrecognized_option(argv[optind - 1]);
530 break;
531 case 'h':
532 help();
533 break;
534 case 'F':
535 base_fmt = optarg;
536 break;
537 case 'b':
538 base_filename = optarg;
539 break;
540 case 'f':
541 fmt = optarg;
542 break;
543 case 'o':
544 if (accumulate_options(&options, optarg) < 0) {
545 goto fail;
547 break;
548 case 'q':
549 quiet = true;
550 break;
551 case 'u':
552 flags |= BDRV_O_NO_BACKING;
553 break;
554 case OPTION_OBJECT: {
555 QemuOpts *opts;
556 opts = qemu_opts_parse_noisily(&qemu_object_opts,
557 optarg, true);
558 if (!opts) {
559 goto fail;
561 } break;
565 /* Get the filename */
566 filename = (optind < argc) ? argv[optind] : NULL;
567 if (options && has_help_option(options)) {
568 g_free(options);
569 return print_block_option_help(filename, fmt);
572 if (optind >= argc) {
573 error_exit("Expecting image file name");
575 optind++;
577 if (qemu_opts_foreach(&qemu_object_opts,
578 user_creatable_add_opts_foreach,
579 qemu_img_object_print_help, &error_fatal)) {
580 goto fail;
583 /* Get image size, if specified */
584 if (optind < argc) {
585 int64_t sval;
587 sval = cvtnum("image size", argv[optind++]);
588 if (sval < 0) {
589 goto fail;
591 img_size = (uint64_t)sval;
593 if (optind != argc) {
594 error_exit("Unexpected argument: %s", argv[optind]);
597 bdrv_img_create(filename, fmt, base_filename, base_fmt,
598 options, img_size, flags, quiet, &local_err);
599 if (local_err) {
600 error_reportf_err(local_err, "%s: ", filename);
601 goto fail;
604 g_free(options);
605 return 0;
607 fail:
608 g_free(options);
609 return 1;
612 static void dump_json_image_check(ImageCheck *check, bool quiet)
614 QString *str;
615 QObject *obj;
616 Visitor *v = qobject_output_visitor_new(&obj);
618 visit_type_ImageCheck(v, NULL, &check, &error_abort);
619 visit_complete(v, &obj);
620 str = qobject_to_json_pretty(obj);
621 assert(str != NULL);
622 qprintf(quiet, "%s\n", qstring_get_str(str));
623 qobject_unref(obj);
624 visit_free(v);
625 qobject_unref(str);
628 static void dump_human_image_check(ImageCheck *check, bool quiet)
630 if (!(check->corruptions || check->leaks || check->check_errors)) {
631 qprintf(quiet, "No errors were found on the image.\n");
632 } else {
633 if (check->corruptions) {
634 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
635 "Data may be corrupted, or further writes to the image "
636 "may corrupt it.\n",
637 check->corruptions);
640 if (check->leaks) {
641 qprintf(quiet,
642 "\n%" PRId64 " leaked clusters were found on the image.\n"
643 "This means waste of disk space, but no harm to data.\n",
644 check->leaks);
647 if (check->check_errors) {
648 qprintf(quiet,
649 "\n%" PRId64
650 " internal errors have occurred during the check.\n",
651 check->check_errors);
655 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
656 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
657 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
658 check->allocated_clusters, check->total_clusters,
659 check->allocated_clusters * 100.0 / check->total_clusters,
660 check->fragmented_clusters * 100.0 / check->allocated_clusters,
661 check->compressed_clusters * 100.0 /
662 check->allocated_clusters);
665 if (check->image_end_offset) {
666 qprintf(quiet,
667 "Image end offset: %" PRId64 "\n", check->image_end_offset);
671 static int collect_image_check(BlockDriverState *bs,
672 ImageCheck *check,
673 const char *filename,
674 const char *fmt,
675 int fix)
677 int ret;
678 BdrvCheckResult result;
680 ret = bdrv_check(bs, &result, fix);
681 if (ret < 0) {
682 return ret;
685 check->filename = g_strdup(filename);
686 check->format = g_strdup(bdrv_get_format_name(bs));
687 check->check_errors = result.check_errors;
688 check->corruptions = result.corruptions;
689 check->has_corruptions = result.corruptions != 0;
690 check->leaks = result.leaks;
691 check->has_leaks = result.leaks != 0;
692 check->corruptions_fixed = result.corruptions_fixed;
693 check->has_corruptions_fixed = result.corruptions_fixed != 0;
694 check->leaks_fixed = result.leaks_fixed;
695 check->has_leaks_fixed = result.leaks_fixed != 0;
696 check->image_end_offset = result.image_end_offset;
697 check->has_image_end_offset = result.image_end_offset != 0;
698 check->total_clusters = result.bfi.total_clusters;
699 check->has_total_clusters = result.bfi.total_clusters != 0;
700 check->allocated_clusters = result.bfi.allocated_clusters;
701 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
702 check->fragmented_clusters = result.bfi.fragmented_clusters;
703 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
704 check->compressed_clusters = result.bfi.compressed_clusters;
705 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
707 return 0;
711 * Checks an image for consistency. Exit codes:
713 * 0 - Check completed, image is good
714 * 1 - Check not completed because of internal errors
715 * 2 - Check completed, image is corrupted
716 * 3 - Check completed, image has leaked clusters, but is good otherwise
717 * 63 - Checks are not supported by the image format
719 static int img_check(int argc, char **argv)
721 int c, ret;
722 OutputFormat output_format = OFORMAT_HUMAN;
723 const char *filename, *fmt, *output, *cache;
724 BlockBackend *blk;
725 BlockDriverState *bs;
726 int fix = 0;
727 int flags = BDRV_O_CHECK;
728 bool writethrough;
729 ImageCheck *check;
730 bool quiet = false;
731 bool image_opts = false;
732 bool force_share = false;
734 fmt = NULL;
735 output = NULL;
736 cache = BDRV_DEFAULT_CACHE;
738 for(;;) {
739 int option_index = 0;
740 static const struct option long_options[] = {
741 {"help", no_argument, 0, 'h'},
742 {"format", required_argument, 0, 'f'},
743 {"repair", required_argument, 0, 'r'},
744 {"output", required_argument, 0, OPTION_OUTPUT},
745 {"object", required_argument, 0, OPTION_OBJECT},
746 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
747 {"force-share", no_argument, 0, 'U'},
748 {0, 0, 0, 0}
750 c = getopt_long(argc, argv, ":hf:r:T:qU",
751 long_options, &option_index);
752 if (c == -1) {
753 break;
755 switch(c) {
756 case ':':
757 missing_argument(argv[optind - 1]);
758 break;
759 case '?':
760 unrecognized_option(argv[optind - 1]);
761 break;
762 case 'h':
763 help();
764 break;
765 case 'f':
766 fmt = optarg;
767 break;
768 case 'r':
769 flags |= BDRV_O_RDWR;
771 if (!strcmp(optarg, "leaks")) {
772 fix = BDRV_FIX_LEAKS;
773 } else if (!strcmp(optarg, "all")) {
774 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
775 } else {
776 error_exit("Unknown option value for -r "
777 "(expecting 'leaks' or 'all'): %s", optarg);
779 break;
780 case OPTION_OUTPUT:
781 output = optarg;
782 break;
783 case 'T':
784 cache = optarg;
785 break;
786 case 'q':
787 quiet = true;
788 break;
789 case 'U':
790 force_share = true;
791 break;
792 case OPTION_OBJECT: {
793 QemuOpts *opts;
794 opts = qemu_opts_parse_noisily(&qemu_object_opts,
795 optarg, true);
796 if (!opts) {
797 return 1;
799 } break;
800 case OPTION_IMAGE_OPTS:
801 image_opts = true;
802 break;
805 if (optind != argc - 1) {
806 error_exit("Expecting one image file name");
808 filename = argv[optind++];
810 if (output && !strcmp(output, "json")) {
811 output_format = OFORMAT_JSON;
812 } else if (output && !strcmp(output, "human")) {
813 output_format = OFORMAT_HUMAN;
814 } else if (output) {
815 error_report("--output must be used with human or json as argument.");
816 return 1;
819 if (qemu_opts_foreach(&qemu_object_opts,
820 user_creatable_add_opts_foreach,
821 qemu_img_object_print_help, &error_fatal)) {
822 return 1;
825 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
826 if (ret < 0) {
827 error_report("Invalid source cache option: %s", cache);
828 return 1;
831 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
832 force_share);
833 if (!blk) {
834 return 1;
836 bs = blk_bs(blk);
838 check = g_new0(ImageCheck, 1);
839 ret = collect_image_check(bs, check, filename, fmt, fix);
841 if (ret == -ENOTSUP) {
842 error_report("This image format does not support checks");
843 ret = 63;
844 goto fail;
847 if (check->corruptions_fixed || check->leaks_fixed) {
848 int corruptions_fixed, leaks_fixed;
849 bool has_leaks_fixed, has_corruptions_fixed;
851 leaks_fixed = check->leaks_fixed;
852 has_leaks_fixed = check->has_leaks_fixed;
853 corruptions_fixed = check->corruptions_fixed;
854 has_corruptions_fixed = check->has_corruptions_fixed;
856 if (output_format == OFORMAT_HUMAN) {
857 qprintf(quiet,
858 "The following inconsistencies were found and repaired:\n\n"
859 " %" PRId64 " leaked clusters\n"
860 " %" PRId64 " corruptions\n\n"
861 "Double checking the fixed image now...\n",
862 check->leaks_fixed,
863 check->corruptions_fixed);
866 qapi_free_ImageCheck(check);
867 check = g_new0(ImageCheck, 1);
868 ret = collect_image_check(bs, check, filename, fmt, 0);
870 check->leaks_fixed = leaks_fixed;
871 check->has_leaks_fixed = has_leaks_fixed;
872 check->corruptions_fixed = corruptions_fixed;
873 check->has_corruptions_fixed = has_corruptions_fixed;
876 if (!ret) {
877 switch (output_format) {
878 case OFORMAT_HUMAN:
879 dump_human_image_check(check, quiet);
880 break;
881 case OFORMAT_JSON:
882 dump_json_image_check(check, quiet);
883 break;
887 if (ret || check->check_errors) {
888 if (ret) {
889 error_report("Check failed: %s", strerror(-ret));
890 } else {
891 error_report("Check failed");
893 ret = 1;
894 goto fail;
897 if (check->corruptions) {
898 ret = 2;
899 } else if (check->leaks) {
900 ret = 3;
901 } else {
902 ret = 0;
905 fail:
906 qapi_free_ImageCheck(check);
907 blk_unref(blk);
908 return ret;
911 typedef struct CommonBlockJobCBInfo {
912 BlockDriverState *bs;
913 Error **errp;
914 } CommonBlockJobCBInfo;
916 static void common_block_job_cb(void *opaque, int ret)
918 CommonBlockJobCBInfo *cbi = opaque;
920 if (ret < 0) {
921 error_setg_errno(cbi->errp, -ret, "Block job failed");
925 static void run_block_job(BlockJob *job, Error **errp)
927 AioContext *aio_context = blk_get_aio_context(job->blk);
928 int ret = 0;
930 aio_context_acquire(aio_context);
931 job_ref(&job->job);
932 do {
933 float progress = 0.0f;
934 aio_poll(aio_context, true);
935 if (job->job.progress.total) {
936 progress = (float)job->job.progress.current /
937 job->job.progress.total * 100.f;
939 qemu_progress_print(progress, 0);
940 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
942 if (!job_is_completed(&job->job)) {
943 ret = job_complete_sync(&job->job, errp);
944 } else {
945 ret = job->job.ret;
947 job_unref(&job->job);
948 aio_context_release(aio_context);
950 /* publish completion progress only when success */
951 if (!ret) {
952 qemu_progress_print(100.f, 0);
956 static int img_commit(int argc, char **argv)
958 int c, ret, flags;
959 const char *filename, *fmt, *cache, *base;
960 BlockBackend *blk;
961 BlockDriverState *bs, *base_bs;
962 BlockJob *job;
963 bool progress = false, quiet = false, drop = false;
964 bool writethrough;
965 Error *local_err = NULL;
966 CommonBlockJobCBInfo cbi;
967 bool image_opts = false;
968 AioContext *aio_context;
970 fmt = NULL;
971 cache = BDRV_DEFAULT_CACHE;
972 base = NULL;
973 for(;;) {
974 static const struct option long_options[] = {
975 {"help", no_argument, 0, 'h'},
976 {"object", required_argument, 0, OPTION_OBJECT},
977 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
978 {0, 0, 0, 0}
980 c = getopt_long(argc, argv, ":f:ht:b:dpq",
981 long_options, NULL);
982 if (c == -1) {
983 break;
985 switch(c) {
986 case ':':
987 missing_argument(argv[optind - 1]);
988 break;
989 case '?':
990 unrecognized_option(argv[optind - 1]);
991 break;
992 case 'h':
993 help();
994 break;
995 case 'f':
996 fmt = optarg;
997 break;
998 case 't':
999 cache = optarg;
1000 break;
1001 case 'b':
1002 base = optarg;
1003 /* -b implies -d */
1004 drop = true;
1005 break;
1006 case 'd':
1007 drop = true;
1008 break;
1009 case 'p':
1010 progress = true;
1011 break;
1012 case 'q':
1013 quiet = true;
1014 break;
1015 case OPTION_OBJECT: {
1016 QemuOpts *opts;
1017 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1018 optarg, true);
1019 if (!opts) {
1020 return 1;
1022 } break;
1023 case OPTION_IMAGE_OPTS:
1024 image_opts = true;
1025 break;
1029 /* Progress is not shown in Quiet mode */
1030 if (quiet) {
1031 progress = false;
1034 if (optind != argc - 1) {
1035 error_exit("Expecting one image file name");
1037 filename = argv[optind++];
1039 if (qemu_opts_foreach(&qemu_object_opts,
1040 user_creatable_add_opts_foreach,
1041 qemu_img_object_print_help, &error_fatal)) {
1042 return 1;
1045 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
1046 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1047 if (ret < 0) {
1048 error_report("Invalid cache option: %s", cache);
1049 return 1;
1052 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1053 false);
1054 if (!blk) {
1055 return 1;
1057 bs = blk_bs(blk);
1059 qemu_progress_init(progress, 1.f);
1060 qemu_progress_print(0.f, 100);
1062 if (base) {
1063 base_bs = bdrv_find_backing_image(bs, base);
1064 if (!base_bs) {
1065 error_setg(&local_err,
1066 "Did not find '%s' in the backing chain of '%s'",
1067 base, filename);
1068 goto done;
1070 } else {
1071 /* This is different from QMP, which by default uses the deepest file in
1072 * the backing chain (i.e., the very base); however, the traditional
1073 * behavior of qemu-img commit is using the immediate backing file. */
1074 base_bs = backing_bs(bs);
1075 if (!base_bs) {
1076 error_setg(&local_err, "Image does not have a backing file");
1077 goto done;
1081 cbi = (CommonBlockJobCBInfo){
1082 .errp = &local_err,
1083 .bs = bs,
1086 aio_context = bdrv_get_aio_context(bs);
1087 aio_context_acquire(aio_context);
1088 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
1089 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1090 &cbi, false, &local_err);
1091 aio_context_release(aio_context);
1092 if (local_err) {
1093 goto done;
1096 /* When the block job completes, the BlockBackend reference will point to
1097 * the old backing file. In order to avoid that the top image is already
1098 * deleted, so we can still empty it afterwards, increment the reference
1099 * counter here preemptively. */
1100 if (!drop) {
1101 bdrv_ref(bs);
1104 job = block_job_get("commit");
1105 assert(job);
1106 run_block_job(job, &local_err);
1107 if (local_err) {
1108 goto unref_backing;
1111 if (!drop && bs->drv->bdrv_make_empty) {
1112 ret = bs->drv->bdrv_make_empty(bs);
1113 if (ret) {
1114 error_setg_errno(&local_err, -ret, "Could not empty %s",
1115 filename);
1116 goto unref_backing;
1120 unref_backing:
1121 if (!drop) {
1122 bdrv_unref(bs);
1125 done:
1126 qemu_progress_end();
1128 blk_unref(blk);
1130 if (local_err) {
1131 error_report_err(local_err);
1132 return 1;
1135 qprintf(quiet, "Image committed.\n");
1136 return 0;
1140 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1141 * of the first sector boundary within buf where the sector contains a
1142 * non-zero byte. This function is robust to a buffer that is not
1143 * sector-aligned.
1145 static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1147 int64_t i;
1148 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1150 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1151 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1152 return i;
1155 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1156 return i;
1158 return -1;
1162 * Returns true iff the first sector pointed to by 'buf' contains at least
1163 * a non-NUL byte.
1165 * 'pnum' is set to the number of sectors (including and immediately following
1166 * the first one) that are known to be in the same allocated/unallocated state.
1167 * The function will try to align the end offset to alignment boundaries so
1168 * that the request will at least end aligned and consequtive requests will
1169 * also start at an aligned offset.
1171 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1172 int64_t sector_num, int alignment)
1174 bool is_zero;
1175 int i, tail;
1177 if (n <= 0) {
1178 *pnum = 0;
1179 return 0;
1181 is_zero = buffer_is_zero(buf, 512);
1182 for(i = 1; i < n; i++) {
1183 buf += 512;
1184 if (is_zero != buffer_is_zero(buf, 512)) {
1185 break;
1189 tail = (sector_num + i) & (alignment - 1);
1190 if (tail) {
1191 if (is_zero && i <= tail) {
1192 /* treat unallocated areas which only consist
1193 * of a small tail as allocated. */
1194 is_zero = false;
1196 if (!is_zero) {
1197 /* align up end offset of allocated areas. */
1198 i += alignment - tail;
1199 i = MIN(i, n);
1200 } else {
1201 /* align down end offset of zero areas. */
1202 i -= tail;
1205 *pnum = i;
1206 return !is_zero;
1210 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1211 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1212 * breaking up write requests for only small sparse areas.
1214 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1215 int min, int64_t sector_num, int alignment)
1217 int ret;
1218 int num_checked, num_used;
1220 if (n < min) {
1221 min = n;
1224 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1225 if (!ret) {
1226 return ret;
1229 num_used = *pnum;
1230 buf += BDRV_SECTOR_SIZE * *pnum;
1231 n -= *pnum;
1232 sector_num += *pnum;
1233 num_checked = num_used;
1235 while (n > 0) {
1236 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1238 buf += BDRV_SECTOR_SIZE * *pnum;
1239 n -= *pnum;
1240 sector_num += *pnum;
1241 num_checked += *pnum;
1242 if (ret) {
1243 num_used = num_checked;
1244 } else if (*pnum >= min) {
1245 break;
1249 *pnum = num_used;
1250 return 1;
1254 * Compares two buffers sector by sector. Returns 0 if the first
1255 * sector of each buffer matches, non-zero otherwise.
1257 * pnum is set to the sector-aligned size of the buffer prefix that
1258 * has the same matching status as the first sector.
1260 static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1261 int64_t bytes, int64_t *pnum)
1263 bool res;
1264 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
1266 assert(bytes > 0);
1268 res = !!memcmp(buf1, buf2, i);
1269 while (i < bytes) {
1270 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
1272 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
1273 break;
1275 i += len;
1278 *pnum = i;
1279 return res;
1282 #define IO_BUF_SIZE (2 * MiB)
1285 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1287 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1288 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1289 * failure), and 4 on error (the exit status for read errors), after emitting
1290 * an error message.
1292 * @param blk: BlockBackend for the image
1293 * @param offset: Starting offset to check
1294 * @param bytes: Number of bytes to check
1295 * @param filename: Name of disk file we are checking (logging purpose)
1296 * @param buffer: Allocated buffer for storing read data
1297 * @param quiet: Flag for quiet mode
1299 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1300 int64_t bytes, const char *filename,
1301 uint8_t *buffer, bool quiet)
1303 int ret = 0;
1304 int64_t idx;
1306 ret = blk_pread(blk, offset, buffer, bytes);
1307 if (ret < 0) {
1308 error_report("Error while reading offset %" PRId64 " of %s: %s",
1309 offset, filename, strerror(-ret));
1310 return 4;
1312 idx = find_nonzero(buffer, bytes);
1313 if (idx >= 0) {
1314 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1315 offset + idx);
1316 return 1;
1319 return 0;
1323 * Compares two images. Exit codes:
1325 * 0 - Images are identical
1326 * 1 - Images differ
1327 * >1 - Error occurred
1329 static int img_compare(int argc, char **argv)
1331 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1332 BlockBackend *blk1, *blk2;
1333 BlockDriverState *bs1, *bs2;
1334 int64_t total_size1, total_size2;
1335 uint8_t *buf1 = NULL, *buf2 = NULL;
1336 int64_t pnum1, pnum2;
1337 int allocated1, allocated2;
1338 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1339 bool progress = false, quiet = false, strict = false;
1340 int flags;
1341 bool writethrough;
1342 int64_t total_size;
1343 int64_t offset = 0;
1344 int64_t chunk;
1345 int c;
1346 uint64_t progress_base;
1347 bool image_opts = false;
1348 bool force_share = false;
1350 cache = BDRV_DEFAULT_CACHE;
1351 for (;;) {
1352 static const struct option long_options[] = {
1353 {"help", no_argument, 0, 'h'},
1354 {"object", required_argument, 0, OPTION_OBJECT},
1355 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1356 {"force-share", no_argument, 0, 'U'},
1357 {0, 0, 0, 0}
1359 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1360 long_options, NULL);
1361 if (c == -1) {
1362 break;
1364 switch (c) {
1365 case ':':
1366 missing_argument(argv[optind - 1]);
1367 break;
1368 case '?':
1369 unrecognized_option(argv[optind - 1]);
1370 break;
1371 case 'h':
1372 help();
1373 break;
1374 case 'f':
1375 fmt1 = optarg;
1376 break;
1377 case 'F':
1378 fmt2 = optarg;
1379 break;
1380 case 'T':
1381 cache = optarg;
1382 break;
1383 case 'p':
1384 progress = true;
1385 break;
1386 case 'q':
1387 quiet = true;
1388 break;
1389 case 's':
1390 strict = true;
1391 break;
1392 case 'U':
1393 force_share = true;
1394 break;
1395 case OPTION_OBJECT: {
1396 QemuOpts *opts;
1397 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1398 optarg, true);
1399 if (!opts) {
1400 ret = 2;
1401 goto out4;
1403 } break;
1404 case OPTION_IMAGE_OPTS:
1405 image_opts = true;
1406 break;
1410 /* Progress is not shown in Quiet mode */
1411 if (quiet) {
1412 progress = false;
1416 if (optind != argc - 2) {
1417 error_exit("Expecting two image file names");
1419 filename1 = argv[optind++];
1420 filename2 = argv[optind++];
1422 if (qemu_opts_foreach(&qemu_object_opts,
1423 user_creatable_add_opts_foreach,
1424 qemu_img_object_print_help, &error_fatal)) {
1425 ret = 2;
1426 goto out4;
1429 /* Initialize before goto out */
1430 qemu_progress_init(progress, 2.0);
1432 flags = 0;
1433 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1434 if (ret < 0) {
1435 error_report("Invalid source cache option: %s", cache);
1436 ret = 2;
1437 goto out3;
1440 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1441 force_share);
1442 if (!blk1) {
1443 ret = 2;
1444 goto out3;
1447 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1448 force_share);
1449 if (!blk2) {
1450 ret = 2;
1451 goto out2;
1453 bs1 = blk_bs(blk1);
1454 bs2 = blk_bs(blk2);
1456 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1457 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1458 total_size1 = blk_getlength(blk1);
1459 if (total_size1 < 0) {
1460 error_report("Can't get size of %s: %s",
1461 filename1, strerror(-total_size1));
1462 ret = 4;
1463 goto out;
1465 total_size2 = blk_getlength(blk2);
1466 if (total_size2 < 0) {
1467 error_report("Can't get size of %s: %s",
1468 filename2, strerror(-total_size2));
1469 ret = 4;
1470 goto out;
1472 total_size = MIN(total_size1, total_size2);
1473 progress_base = MAX(total_size1, total_size2);
1475 qemu_progress_print(0, 100);
1477 if (strict && total_size1 != total_size2) {
1478 ret = 1;
1479 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1480 goto out;
1483 while (offset < total_size) {
1484 int status1, status2;
1486 status1 = bdrv_block_status_above(bs1, NULL, offset,
1487 total_size1 - offset, &pnum1, NULL,
1488 NULL);
1489 if (status1 < 0) {
1490 ret = 3;
1491 error_report("Sector allocation test failed for %s", filename1);
1492 goto out;
1494 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1496 status2 = bdrv_block_status_above(bs2, NULL, offset,
1497 total_size2 - offset, &pnum2, NULL,
1498 NULL);
1499 if (status2 < 0) {
1500 ret = 3;
1501 error_report("Sector allocation test failed for %s", filename2);
1502 goto out;
1504 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1506 assert(pnum1 && pnum2);
1507 chunk = MIN(pnum1, pnum2);
1509 if (strict) {
1510 if (status1 != status2) {
1511 ret = 1;
1512 qprintf(quiet, "Strict mode: Offset %" PRId64
1513 " block status mismatch!\n", offset);
1514 goto out;
1517 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1518 /* nothing to do */
1519 } else if (allocated1 == allocated2) {
1520 if (allocated1) {
1521 int64_t pnum;
1523 chunk = MIN(chunk, IO_BUF_SIZE);
1524 ret = blk_pread(blk1, offset, buf1, chunk);
1525 if (ret < 0) {
1526 error_report("Error while reading offset %" PRId64
1527 " of %s: %s",
1528 offset, filename1, strerror(-ret));
1529 ret = 4;
1530 goto out;
1532 ret = blk_pread(blk2, offset, buf2, chunk);
1533 if (ret < 0) {
1534 error_report("Error while reading offset %" PRId64
1535 " of %s: %s",
1536 offset, filename2, strerror(-ret));
1537 ret = 4;
1538 goto out;
1540 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1541 if (ret || pnum != chunk) {
1542 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1543 offset + (ret ? 0 : pnum));
1544 ret = 1;
1545 goto out;
1548 } else {
1549 chunk = MIN(chunk, IO_BUF_SIZE);
1550 if (allocated1) {
1551 ret = check_empty_sectors(blk1, offset, chunk,
1552 filename1, buf1, quiet);
1553 } else {
1554 ret = check_empty_sectors(blk2, offset, chunk,
1555 filename2, buf1, quiet);
1557 if (ret) {
1558 goto out;
1561 offset += chunk;
1562 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1565 if (total_size1 != total_size2) {
1566 BlockBackend *blk_over;
1567 const char *filename_over;
1569 qprintf(quiet, "Warning: Image size mismatch!\n");
1570 if (total_size1 > total_size2) {
1571 blk_over = blk1;
1572 filename_over = filename1;
1573 } else {
1574 blk_over = blk2;
1575 filename_over = filename2;
1578 while (offset < progress_base) {
1579 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1580 progress_base - offset, &chunk,
1581 NULL, NULL);
1582 if (ret < 0) {
1583 ret = 3;
1584 error_report("Sector allocation test failed for %s",
1585 filename_over);
1586 goto out;
1589 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1590 chunk = MIN(chunk, IO_BUF_SIZE);
1591 ret = check_empty_sectors(blk_over, offset, chunk,
1592 filename_over, buf1, quiet);
1593 if (ret) {
1594 goto out;
1597 offset += chunk;
1598 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1602 qprintf(quiet, "Images are identical.\n");
1603 ret = 0;
1605 out:
1606 qemu_vfree(buf1);
1607 qemu_vfree(buf2);
1608 blk_unref(blk2);
1609 out2:
1610 blk_unref(blk1);
1611 out3:
1612 qemu_progress_end();
1613 out4:
1614 return ret;
1617 enum ImgConvertBlockStatus {
1618 BLK_DATA,
1619 BLK_ZERO,
1620 BLK_BACKING_FILE,
1623 #define MAX_COROUTINES 16
1625 typedef struct ImgConvertState {
1626 BlockBackend **src;
1627 int64_t *src_sectors;
1628 int src_num;
1629 int64_t total_sectors;
1630 int64_t allocated_sectors;
1631 int64_t allocated_done;
1632 int64_t sector_num;
1633 int64_t wr_offs;
1634 enum ImgConvertBlockStatus status;
1635 int64_t sector_next_status;
1636 BlockBackend *target;
1637 bool has_zero_init;
1638 bool compressed;
1639 bool unallocated_blocks_are_zero;
1640 bool target_is_new;
1641 bool target_has_backing;
1642 int64_t target_backing_sectors; /* negative if unknown */
1643 bool wr_in_order;
1644 bool copy_range;
1645 bool salvage;
1646 bool quiet;
1647 int min_sparse;
1648 int alignment;
1649 size_t cluster_sectors;
1650 size_t buf_sectors;
1651 long num_coroutines;
1652 int running_coroutines;
1653 Coroutine *co[MAX_COROUTINES];
1654 int64_t wait_sector_num[MAX_COROUTINES];
1655 CoMutex lock;
1656 int ret;
1657 } ImgConvertState;
1659 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1660 int *src_cur, int64_t *src_cur_offset)
1662 *src_cur = 0;
1663 *src_cur_offset = 0;
1664 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1665 *src_cur_offset += s->src_sectors[*src_cur];
1666 (*src_cur)++;
1667 assert(*src_cur < s->src_num);
1671 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1673 int64_t src_cur_offset;
1674 int ret, n, src_cur;
1675 bool post_backing_zero = false;
1677 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1679 assert(s->total_sectors > sector_num);
1680 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1682 if (s->target_backing_sectors >= 0) {
1683 if (sector_num >= s->target_backing_sectors) {
1684 post_backing_zero = s->unallocated_blocks_are_zero;
1685 } else if (sector_num + n > s->target_backing_sectors) {
1686 /* Split requests around target_backing_sectors (because
1687 * starting from there, zeros are handled differently) */
1688 n = s->target_backing_sectors - sector_num;
1692 if (s->sector_next_status <= sector_num) {
1693 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1694 int64_t count;
1696 do {
1697 count = n * BDRV_SECTOR_SIZE;
1699 if (s->target_has_backing) {
1700 ret = bdrv_block_status(blk_bs(s->src[src_cur]), offset,
1701 count, &count, NULL, NULL);
1702 } else {
1703 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1704 offset, count, &count, NULL,
1705 NULL);
1708 if (ret < 0) {
1709 if (s->salvage) {
1710 if (n == 1) {
1711 if (!s->quiet) {
1712 warn_report("error while reading block status at "
1713 "offset %" PRIu64 ": %s", offset,
1714 strerror(-ret));
1716 /* Just try to read the data, then */
1717 ret = BDRV_BLOCK_DATA;
1718 count = BDRV_SECTOR_SIZE;
1719 } else {
1720 /* Retry on a shorter range */
1721 n = DIV_ROUND_UP(n, 4);
1723 } else {
1724 error_report("error while reading block status at offset "
1725 "%" PRIu64 ": %s", offset, strerror(-ret));
1726 return ret;
1729 } while (ret < 0);
1731 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1733 if (ret & BDRV_BLOCK_ZERO) {
1734 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
1735 } else if (ret & BDRV_BLOCK_DATA) {
1736 s->status = BLK_DATA;
1737 } else {
1738 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1741 s->sector_next_status = sector_num + n;
1744 n = MIN(n, s->sector_next_status - sector_num);
1745 if (s->status == BLK_DATA) {
1746 n = MIN(n, s->buf_sectors);
1749 /* We need to write complete clusters for compressed images, so if an
1750 * unallocated area is shorter than that, we must consider the whole
1751 * cluster allocated. */
1752 if (s->compressed) {
1753 if (n < s->cluster_sectors) {
1754 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1755 s->status = BLK_DATA;
1756 } else {
1757 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1761 return n;
1764 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1765 int nb_sectors, uint8_t *buf)
1767 uint64_t single_read_until = 0;
1768 int n, ret;
1770 assert(nb_sectors <= s->buf_sectors);
1771 while (nb_sectors > 0) {
1772 BlockBackend *blk;
1773 int src_cur;
1774 int64_t bs_sectors, src_cur_offset;
1775 uint64_t offset;
1777 /* In the case of compression with multiple source files, we can get a
1778 * nb_sectors that spreads into the next part. So we must be able to
1779 * read across multiple BDSes for one convert_read() call. */
1780 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1781 blk = s->src[src_cur];
1782 bs_sectors = s->src_sectors[src_cur];
1784 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1786 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1787 if (single_read_until > offset) {
1788 n = 1;
1791 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
1792 if (ret < 0) {
1793 if (s->salvage) {
1794 if (n > 1) {
1795 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1796 continue;
1797 } else {
1798 if (!s->quiet) {
1799 warn_report("error while reading offset %" PRIu64
1800 ": %s", offset, strerror(-ret));
1802 memset(buf, 0, BDRV_SECTOR_SIZE);
1804 } else {
1805 return ret;
1809 sector_num += n;
1810 nb_sectors -= n;
1811 buf += n * BDRV_SECTOR_SIZE;
1814 return 0;
1818 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1819 int nb_sectors, uint8_t *buf,
1820 enum ImgConvertBlockStatus status)
1822 int ret;
1824 while (nb_sectors > 0) {
1825 int n = nb_sectors;
1826 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1828 switch (status) {
1829 case BLK_BACKING_FILE:
1830 /* If we have a backing file, leave clusters unallocated that are
1831 * unallocated in the source image, so that the backing file is
1832 * visible at the respective offset. */
1833 assert(s->target_has_backing);
1834 break;
1836 case BLK_DATA:
1837 /* If we're told to keep the target fully allocated (-S 0) or there
1838 * is real non-zero data, we must write it. Otherwise we can treat
1839 * it as zero sectors.
1840 * Compressed clusters need to be written as a whole, so in that
1841 * case we can only save the write if the buffer is completely
1842 * zeroed. */
1843 if (!s->min_sparse ||
1844 (!s->compressed &&
1845 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1846 sector_num, s->alignment)) ||
1847 (s->compressed &&
1848 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1850 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1851 n << BDRV_SECTOR_BITS, buf, flags);
1852 if (ret < 0) {
1853 return ret;
1855 break;
1857 /* fall-through */
1859 case BLK_ZERO:
1860 if (s->has_zero_init) {
1861 assert(!s->target_has_backing);
1862 break;
1864 ret = blk_co_pwrite_zeroes(s->target,
1865 sector_num << BDRV_SECTOR_BITS,
1866 n << BDRV_SECTOR_BITS,
1867 BDRV_REQ_MAY_UNMAP);
1868 if (ret < 0) {
1869 return ret;
1871 break;
1874 sector_num += n;
1875 nb_sectors -= n;
1876 buf += n * BDRV_SECTOR_SIZE;
1879 return 0;
1882 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1883 int nb_sectors)
1885 int n, ret;
1887 while (nb_sectors > 0) {
1888 BlockBackend *blk;
1889 int src_cur;
1890 int64_t bs_sectors, src_cur_offset;
1891 int64_t offset;
1893 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1894 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1895 blk = s->src[src_cur];
1896 bs_sectors = s->src_sectors[src_cur];
1898 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1900 ret = blk_co_copy_range(blk, offset, s->target,
1901 sector_num << BDRV_SECTOR_BITS,
1902 n << BDRV_SECTOR_BITS, 0, 0);
1903 if (ret < 0) {
1904 return ret;
1907 sector_num += n;
1908 nb_sectors -= n;
1910 return 0;
1913 static void coroutine_fn convert_co_do_copy(void *opaque)
1915 ImgConvertState *s = opaque;
1916 uint8_t *buf = NULL;
1917 int ret, i;
1918 int index = -1;
1920 for (i = 0; i < s->num_coroutines; i++) {
1921 if (s->co[i] == qemu_coroutine_self()) {
1922 index = i;
1923 break;
1926 assert(index >= 0);
1928 s->running_coroutines++;
1929 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1931 while (1) {
1932 int n;
1933 int64_t sector_num;
1934 enum ImgConvertBlockStatus status;
1935 bool copy_range;
1937 qemu_co_mutex_lock(&s->lock);
1938 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1939 qemu_co_mutex_unlock(&s->lock);
1940 break;
1942 n = convert_iteration_sectors(s, s->sector_num);
1943 if (n < 0) {
1944 qemu_co_mutex_unlock(&s->lock);
1945 s->ret = n;
1946 break;
1948 /* save current sector and allocation status to local variables */
1949 sector_num = s->sector_num;
1950 status = s->status;
1951 if (!s->min_sparse && s->status == BLK_ZERO) {
1952 n = MIN(n, s->buf_sectors);
1954 /* increment global sector counter so that other coroutines can
1955 * already continue reading beyond this request */
1956 s->sector_num += n;
1957 qemu_co_mutex_unlock(&s->lock);
1959 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1960 s->allocated_done += n;
1961 qemu_progress_print(100.0 * s->allocated_done /
1962 s->allocated_sectors, 0);
1965 retry:
1966 copy_range = s->copy_range && s->status == BLK_DATA;
1967 if (status == BLK_DATA && !copy_range) {
1968 ret = convert_co_read(s, sector_num, n, buf);
1969 if (ret < 0) {
1970 error_report("error while reading at byte %lld: %s",
1971 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
1972 s->ret = ret;
1974 } else if (!s->min_sparse && status == BLK_ZERO) {
1975 status = BLK_DATA;
1976 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1979 if (s->wr_in_order) {
1980 /* keep writes in order */
1981 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
1982 s->wait_sector_num[index] = sector_num;
1983 qemu_coroutine_yield();
1985 s->wait_sector_num[index] = -1;
1988 if (s->ret == -EINPROGRESS) {
1989 if (copy_range) {
1990 ret = convert_co_copy_range(s, sector_num, n);
1991 if (ret) {
1992 s->copy_range = false;
1993 goto retry;
1995 } else {
1996 ret = convert_co_write(s, sector_num, n, buf, status);
1998 if (ret < 0) {
1999 error_report("error while writing at byte %lld: %s",
2000 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2001 s->ret = ret;
2005 if (s->wr_in_order) {
2006 /* reenter the coroutine that might have waited
2007 * for this write to complete */
2008 s->wr_offs = sector_num + n;
2009 for (i = 0; i < s->num_coroutines; i++) {
2010 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2012 * A -> B -> A cannot occur because A has
2013 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2014 * B will never enter A during this time window.
2016 qemu_coroutine_enter(s->co[i]);
2017 break;
2023 qemu_vfree(buf);
2024 s->co[index] = NULL;
2025 s->running_coroutines--;
2026 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2027 /* the convert job finished successfully */
2028 s->ret = 0;
2032 static int convert_do_copy(ImgConvertState *s)
2034 int ret, i, n;
2035 int64_t sector_num = 0;
2037 /* Check whether we have zero initialisation or can get it efficiently */
2038 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2039 !s->target_has_backing) {
2040 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
2043 if (!s->has_zero_init && !s->target_has_backing &&
2044 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
2046 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
2047 if (ret == 0) {
2048 s->has_zero_init = true;
2052 /* Allocate buffer for copied data. For compressed images, only one cluster
2053 * can be copied at a time. */
2054 if (s->compressed) {
2055 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2056 error_report("invalid cluster size");
2057 return -EINVAL;
2059 s->buf_sectors = s->cluster_sectors;
2062 while (sector_num < s->total_sectors) {
2063 n = convert_iteration_sectors(s, sector_num);
2064 if (n < 0) {
2065 return n;
2067 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2069 s->allocated_sectors += n;
2071 sector_num += n;
2074 /* Do the copy */
2075 s->sector_next_status = 0;
2076 s->ret = -EINPROGRESS;
2078 qemu_co_mutex_init(&s->lock);
2079 for (i = 0; i < s->num_coroutines; i++) {
2080 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2081 s->wait_sector_num[i] = -1;
2082 qemu_coroutine_enter(s->co[i]);
2085 while (s->running_coroutines) {
2086 main_loop_wait(false);
2089 if (s->compressed && !s->ret) {
2090 /* signal EOF to align */
2091 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
2092 if (ret < 0) {
2093 return ret;
2097 return s->ret;
2100 #define MAX_BUF_SECTORS 32768
2102 static int img_convert(int argc, char **argv)
2104 int c, bs_i, flags, src_flags = 0;
2105 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
2106 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2107 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
2108 BlockDriver *drv = NULL, *proto_drv = NULL;
2109 BlockDriverInfo bdi;
2110 BlockDriverState *out_bs;
2111 QemuOpts *opts = NULL, *sn_opts = NULL;
2112 QemuOptsList *create_opts = NULL;
2113 QDict *open_opts = NULL;
2114 char *options = NULL;
2115 Error *local_err = NULL;
2116 bool writethrough, src_writethrough, image_opts = false,
2117 skip_create = false, progress = false, tgt_image_opts = false;
2118 int64_t ret = -EINVAL;
2119 bool force_share = false;
2120 bool explict_min_sparse = false;
2122 ImgConvertState s = (ImgConvertState) {
2123 /* Need at least 4k of zeros for sparse detection */
2124 .min_sparse = 8,
2125 .copy_range = false,
2126 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2127 .wr_in_order = true,
2128 .num_coroutines = 8,
2131 for(;;) {
2132 static const struct option long_options[] = {
2133 {"help", no_argument, 0, 'h'},
2134 {"object", required_argument, 0, OPTION_OBJECT},
2135 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2136 {"force-share", no_argument, 0, 'U'},
2137 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
2138 {"salvage", no_argument, 0, OPTION_SALVAGE},
2139 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
2140 {0, 0, 0, 0}
2142 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2143 long_options, NULL);
2144 if (c == -1) {
2145 break;
2147 switch(c) {
2148 case ':':
2149 missing_argument(argv[optind - 1]);
2150 break;
2151 case '?':
2152 unrecognized_option(argv[optind - 1]);
2153 break;
2154 case 'h':
2155 help();
2156 break;
2157 case 'f':
2158 fmt = optarg;
2159 break;
2160 case 'O':
2161 out_fmt = optarg;
2162 break;
2163 case 'B':
2164 out_baseimg = optarg;
2165 break;
2166 case 'C':
2167 s.copy_range = true;
2168 break;
2169 case 'c':
2170 s.compressed = true;
2171 break;
2172 case 'o':
2173 if (accumulate_options(&options, optarg) < 0) {
2174 goto fail_getopt;
2176 break;
2177 case 'l':
2178 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2179 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2180 optarg, false);
2181 if (!sn_opts) {
2182 error_report("Failed in parsing snapshot param '%s'",
2183 optarg);
2184 goto fail_getopt;
2186 } else {
2187 snapshot_name = optarg;
2189 break;
2190 case 'S':
2192 int64_t sval;
2194 sval = cvtnum("buffer size for sparse output", optarg);
2195 if (sval < 0) {
2196 goto fail_getopt;
2197 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
2198 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2199 error_report("Invalid buffer size for sparse output specified. "
2200 "Valid sizes are multiples of %llu up to %llu. Select "
2201 "0 to disable sparse detection (fully allocates output).",
2202 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
2203 goto fail_getopt;
2206 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2207 explict_min_sparse = true;
2208 break;
2210 case 'p':
2211 progress = true;
2212 break;
2213 case 't':
2214 cache = optarg;
2215 break;
2216 case 'T':
2217 src_cache = optarg;
2218 break;
2219 case 'q':
2220 s.quiet = true;
2221 break;
2222 case 'n':
2223 skip_create = true;
2224 break;
2225 case 'm':
2226 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2227 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2228 error_report("Invalid number of coroutines. Allowed number of"
2229 " coroutines is between 1 and %d", MAX_COROUTINES);
2230 goto fail_getopt;
2232 break;
2233 case 'W':
2234 s.wr_in_order = false;
2235 break;
2236 case 'U':
2237 force_share = true;
2238 break;
2239 case OPTION_OBJECT: {
2240 QemuOpts *object_opts;
2241 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2242 optarg, true);
2243 if (!object_opts) {
2244 goto fail_getopt;
2246 break;
2248 case OPTION_IMAGE_OPTS:
2249 image_opts = true;
2250 break;
2251 case OPTION_SALVAGE:
2252 s.salvage = true;
2253 break;
2254 case OPTION_TARGET_IMAGE_OPTS:
2255 tgt_image_opts = true;
2256 break;
2257 case OPTION_TARGET_IS_ZERO:
2259 * The user asserting that the target is blank has the
2260 * same effect as the target driver supporting zero
2261 * initialisation.
2263 s.has_zero_init = true;
2264 break;
2268 if (!out_fmt && !tgt_image_opts) {
2269 out_fmt = "raw";
2272 if (qemu_opts_foreach(&qemu_object_opts,
2273 user_creatable_add_opts_foreach,
2274 qemu_img_object_print_help, &error_fatal)) {
2275 goto fail_getopt;
2278 if (s.compressed && s.copy_range) {
2279 error_report("Cannot enable copy offloading when -c is used");
2280 goto fail_getopt;
2283 if (explict_min_sparse && s.copy_range) {
2284 error_report("Cannot enable copy offloading when -S is used");
2285 goto fail_getopt;
2288 if (s.copy_range && s.salvage) {
2289 error_report("Cannot use copy offloading in salvaging mode");
2290 goto fail_getopt;
2293 if (tgt_image_opts && !skip_create) {
2294 error_report("--target-image-opts requires use of -n flag");
2295 goto fail_getopt;
2298 if (skip_create && options) {
2299 warn_report("-o has no effect when skipping image creation");
2300 warn_report("This will become an error in future QEMU versions.");
2303 if (s.has_zero_init && !skip_create) {
2304 error_report("--target-is-zero requires use of -n flag");
2305 goto fail_getopt;
2308 s.src_num = argc - optind - 1;
2309 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2311 if (options && has_help_option(options)) {
2312 if (out_fmt) {
2313 ret = print_block_option_help(out_filename, out_fmt);
2314 goto fail_getopt;
2315 } else {
2316 error_report("Option help requires a format be specified");
2317 goto fail_getopt;
2321 if (s.src_num < 1) {
2322 error_report("Must specify image file name");
2323 goto fail_getopt;
2327 /* ret is still -EINVAL until here */
2328 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2329 if (ret < 0) {
2330 error_report("Invalid source cache option: %s", src_cache);
2331 goto fail_getopt;
2334 /* Initialize before goto out */
2335 if (s.quiet) {
2336 progress = false;
2338 qemu_progress_init(progress, 1.0);
2339 qemu_progress_print(0, 100);
2341 s.src = g_new0(BlockBackend *, s.src_num);
2342 s.src_sectors = g_new(int64_t, s.src_num);
2344 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2345 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2346 fmt, src_flags, src_writethrough, s.quiet,
2347 force_share);
2348 if (!s.src[bs_i]) {
2349 ret = -1;
2350 goto out;
2352 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2353 if (s.src_sectors[bs_i] < 0) {
2354 error_report("Could not get size of %s: %s",
2355 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2356 ret = -1;
2357 goto out;
2359 s.total_sectors += s.src_sectors[bs_i];
2362 if (sn_opts) {
2363 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2364 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2365 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2366 &local_err);
2367 } else if (snapshot_name != NULL) {
2368 if (s.src_num > 1) {
2369 error_report("No support for concatenating multiple snapshot");
2370 ret = -1;
2371 goto out;
2374 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2375 &local_err);
2377 if (local_err) {
2378 error_reportf_err(local_err, "Failed to load snapshot: ");
2379 ret = -1;
2380 goto out;
2383 if (!skip_create) {
2384 /* Find driver and parse its options */
2385 drv = bdrv_find_format(out_fmt);
2386 if (!drv) {
2387 error_report("Unknown file format '%s'", out_fmt);
2388 ret = -1;
2389 goto out;
2392 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2393 if (!proto_drv) {
2394 error_report_err(local_err);
2395 ret = -1;
2396 goto out;
2399 if (!drv->create_opts) {
2400 error_report("Format driver '%s' does not support image creation",
2401 drv->format_name);
2402 ret = -1;
2403 goto out;
2406 if (!proto_drv->create_opts) {
2407 error_report("Protocol driver '%s' does not support image creation",
2408 proto_drv->format_name);
2409 ret = -1;
2410 goto out;
2413 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2414 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2416 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2417 if (options) {
2418 qemu_opts_do_parse(opts, options, NULL, &local_err);
2419 if (local_err) {
2420 error_report_err(local_err);
2421 ret = -1;
2422 goto out;
2426 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2427 &error_abort);
2428 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2429 if (ret < 0) {
2430 goto out;
2434 /* Get backing file name if -o backing_file was used */
2435 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2436 if (out_baseimg_param) {
2437 out_baseimg = out_baseimg_param;
2439 s.target_has_backing = (bool) out_baseimg;
2441 if (s.has_zero_init && s.target_has_backing) {
2442 error_report("Cannot use --target-is-zero when the destination "
2443 "image has a backing file");
2444 goto out;
2447 if (s.src_num > 1 && out_baseimg) {
2448 error_report("Having a backing file for the target makes no sense when "
2449 "concatenating multiple input images");
2450 ret = -1;
2451 goto out;
2454 /* Check if compression is supported */
2455 if (s.compressed) {
2456 bool encryption =
2457 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2458 const char *encryptfmt =
2459 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2460 const char *preallocation =
2461 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2463 if (drv && !block_driver_can_compress(drv)) {
2464 error_report("Compression not supported for this file format");
2465 ret = -1;
2466 goto out;
2469 if (encryption || encryptfmt) {
2470 error_report("Compression and encryption not supported at "
2471 "the same time");
2472 ret = -1;
2473 goto out;
2476 if (preallocation
2477 && strcmp(preallocation, "off"))
2479 error_report("Compression and preallocation not supported at "
2480 "the same time");
2481 ret = -1;
2482 goto out;
2487 * The later open call will need any decryption secrets, and
2488 * bdrv_create() will purge "opts", so extract them now before
2489 * they are lost.
2491 if (!skip_create) {
2492 open_opts = qdict_new();
2493 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2496 if (!skip_create) {
2497 /* Create the new image */
2498 ret = bdrv_create(drv, out_filename, opts, &local_err);
2499 if (ret < 0) {
2500 error_reportf_err(local_err, "%s: error while converting %s: ",
2501 out_filename, out_fmt);
2502 goto out;
2506 s.target_is_new = !skip_create;
2508 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2509 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2510 if (ret < 0) {
2511 error_report("Invalid cache option: %s", cache);
2512 goto out;
2515 if (skip_create) {
2516 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2517 flags, writethrough, s.quiet, false);
2518 } else {
2519 /* TODO ultimately we should allow --target-image-opts
2520 * to be used even when -n is not given.
2521 * That has to wait for bdrv_create to be improved
2522 * to allow filenames in option syntax
2524 s.target = img_open_file(out_filename, open_opts, out_fmt,
2525 flags, writethrough, s.quiet, false);
2526 open_opts = NULL; /* blk_new_open will have freed it */
2528 if (!s.target) {
2529 ret = -1;
2530 goto out;
2532 out_bs = blk_bs(s.target);
2534 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
2535 error_report("Compression not supported for this file format");
2536 ret = -1;
2537 goto out;
2540 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2541 * or discard_alignment of the out_bs is greater. Limit to
2542 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2543 s.buf_sectors = MIN(MAX_BUF_SECTORS,
2544 MAX(s.buf_sectors,
2545 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2546 out_bs->bl.pdiscard_alignment >>
2547 BDRV_SECTOR_BITS)));
2549 /* try to align the write requests to the destination to avoid unnecessary
2550 * RMW cycles. */
2551 s.alignment = MAX(pow2floor(s.min_sparse),
2552 DIV_ROUND_UP(out_bs->bl.request_alignment,
2553 BDRV_SECTOR_SIZE));
2554 assert(is_power_of_2(s.alignment));
2556 if (skip_create) {
2557 int64_t output_sectors = blk_nb_sectors(s.target);
2558 if (output_sectors < 0) {
2559 error_report("unable to get output image length: %s",
2560 strerror(-output_sectors));
2561 ret = -1;
2562 goto out;
2563 } else if (output_sectors < s.total_sectors) {
2564 error_report("output file is smaller than input file");
2565 ret = -1;
2566 goto out;
2570 if (s.target_has_backing && s.target_is_new) {
2571 /* Errors are treated as "backing length unknown" (which means
2572 * s.target_backing_sectors has to be negative, which it will
2573 * be automatically). The backing file length is used only
2574 * for optimizations, so such a case is not fatal. */
2575 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2576 } else {
2577 s.target_backing_sectors = -1;
2580 ret = bdrv_get_info(out_bs, &bdi);
2581 if (ret < 0) {
2582 if (s.compressed) {
2583 error_report("could not get block driver info");
2584 goto out;
2586 } else {
2587 s.compressed = s.compressed || bdi.needs_compressed_writes;
2588 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2589 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
2592 ret = convert_do_copy(&s);
2593 out:
2594 if (!ret) {
2595 qemu_progress_print(100, 0);
2597 qemu_progress_end();
2598 qemu_opts_del(opts);
2599 qemu_opts_free(create_opts);
2600 qemu_opts_del(sn_opts);
2601 qobject_unref(open_opts);
2602 blk_unref(s.target);
2603 if (s.src) {
2604 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2605 blk_unref(s.src[bs_i]);
2607 g_free(s.src);
2609 g_free(s.src_sectors);
2610 fail_getopt:
2611 g_free(options);
2613 return !!ret;
2617 static void dump_snapshots(BlockDriverState *bs)
2619 QEMUSnapshotInfo *sn_tab, *sn;
2620 int nb_sns, i;
2622 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2623 if (nb_sns <= 0)
2624 return;
2625 printf("Snapshot list:\n");
2626 bdrv_snapshot_dump(NULL);
2627 printf("\n");
2628 for(i = 0; i < nb_sns; i++) {
2629 sn = &sn_tab[i];
2630 bdrv_snapshot_dump(sn);
2631 printf("\n");
2633 g_free(sn_tab);
2636 static void dump_json_image_info_list(ImageInfoList *list)
2638 QString *str;
2639 QObject *obj;
2640 Visitor *v = qobject_output_visitor_new(&obj);
2642 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2643 visit_complete(v, &obj);
2644 str = qobject_to_json_pretty(obj);
2645 assert(str != NULL);
2646 printf("%s\n", qstring_get_str(str));
2647 qobject_unref(obj);
2648 visit_free(v);
2649 qobject_unref(str);
2652 static void dump_json_image_info(ImageInfo *info)
2654 QString *str;
2655 QObject *obj;
2656 Visitor *v = qobject_output_visitor_new(&obj);
2658 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2659 visit_complete(v, &obj);
2660 str = qobject_to_json_pretty(obj);
2661 assert(str != NULL);
2662 printf("%s\n", qstring_get_str(str));
2663 qobject_unref(obj);
2664 visit_free(v);
2665 qobject_unref(str);
2668 static void dump_human_image_info_list(ImageInfoList *list)
2670 ImageInfoList *elem;
2671 bool delim = false;
2673 for (elem = list; elem; elem = elem->next) {
2674 if (delim) {
2675 printf("\n");
2677 delim = true;
2679 bdrv_image_info_dump(elem->value);
2683 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2685 return strcmp(a, b) == 0;
2689 * Open an image file chain and return an ImageInfoList
2691 * @filename: topmost image filename
2692 * @fmt: topmost image format (may be NULL to autodetect)
2693 * @chain: true - enumerate entire backing file chain
2694 * false - only topmost image file
2696 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2697 * image file. If there was an error a message will have been printed to
2698 * stderr.
2700 static ImageInfoList *collect_image_info_list(bool image_opts,
2701 const char *filename,
2702 const char *fmt,
2703 bool chain, bool force_share)
2705 ImageInfoList *head = NULL;
2706 ImageInfoList **last = &head;
2707 GHashTable *filenames;
2708 Error *err = NULL;
2710 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2712 while (filename) {
2713 BlockBackend *blk;
2714 BlockDriverState *bs;
2715 ImageInfo *info;
2716 ImageInfoList *elem;
2718 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2719 error_report("Backing file '%s' creates an infinite loop.",
2720 filename);
2721 goto err;
2723 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2725 blk = img_open(image_opts, filename, fmt,
2726 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2727 force_share);
2728 if (!blk) {
2729 goto err;
2731 bs = blk_bs(blk);
2733 bdrv_query_image_info(bs, &info, &err);
2734 if (err) {
2735 error_report_err(err);
2736 blk_unref(blk);
2737 goto err;
2740 elem = g_new0(ImageInfoList, 1);
2741 elem->value = info;
2742 *last = elem;
2743 last = &elem->next;
2745 blk_unref(blk);
2747 /* Clear parameters that only apply to the topmost image */
2748 filename = fmt = NULL;
2749 image_opts = false;
2751 if (chain) {
2752 if (info->has_full_backing_filename) {
2753 filename = info->full_backing_filename;
2754 } else if (info->has_backing_filename) {
2755 error_report("Could not determine absolute backing filename,"
2756 " but backing filename '%s' present",
2757 info->backing_filename);
2758 goto err;
2760 if (info->has_backing_filename_format) {
2761 fmt = info->backing_filename_format;
2765 g_hash_table_destroy(filenames);
2766 return head;
2768 err:
2769 qapi_free_ImageInfoList(head);
2770 g_hash_table_destroy(filenames);
2771 return NULL;
2774 static int img_info(int argc, char **argv)
2776 int c;
2777 OutputFormat output_format = OFORMAT_HUMAN;
2778 bool chain = false;
2779 const char *filename, *fmt, *output;
2780 ImageInfoList *list;
2781 bool image_opts = false;
2782 bool force_share = false;
2784 fmt = NULL;
2785 output = NULL;
2786 for(;;) {
2787 int option_index = 0;
2788 static const struct option long_options[] = {
2789 {"help", no_argument, 0, 'h'},
2790 {"format", required_argument, 0, 'f'},
2791 {"output", required_argument, 0, OPTION_OUTPUT},
2792 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2793 {"object", required_argument, 0, OPTION_OBJECT},
2794 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2795 {"force-share", no_argument, 0, 'U'},
2796 {0, 0, 0, 0}
2798 c = getopt_long(argc, argv, ":f:hU",
2799 long_options, &option_index);
2800 if (c == -1) {
2801 break;
2803 switch(c) {
2804 case ':':
2805 missing_argument(argv[optind - 1]);
2806 break;
2807 case '?':
2808 unrecognized_option(argv[optind - 1]);
2809 break;
2810 case 'h':
2811 help();
2812 break;
2813 case 'f':
2814 fmt = optarg;
2815 break;
2816 case 'U':
2817 force_share = true;
2818 break;
2819 case OPTION_OUTPUT:
2820 output = optarg;
2821 break;
2822 case OPTION_BACKING_CHAIN:
2823 chain = true;
2824 break;
2825 case OPTION_OBJECT: {
2826 QemuOpts *opts;
2827 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2828 optarg, true);
2829 if (!opts) {
2830 return 1;
2832 } break;
2833 case OPTION_IMAGE_OPTS:
2834 image_opts = true;
2835 break;
2838 if (optind != argc - 1) {
2839 error_exit("Expecting one image file name");
2841 filename = argv[optind++];
2843 if (output && !strcmp(output, "json")) {
2844 output_format = OFORMAT_JSON;
2845 } else if (output && !strcmp(output, "human")) {
2846 output_format = OFORMAT_HUMAN;
2847 } else if (output) {
2848 error_report("--output must be used with human or json as argument.");
2849 return 1;
2852 if (qemu_opts_foreach(&qemu_object_opts,
2853 user_creatable_add_opts_foreach,
2854 qemu_img_object_print_help, &error_fatal)) {
2855 return 1;
2858 list = collect_image_info_list(image_opts, filename, fmt, chain,
2859 force_share);
2860 if (!list) {
2861 return 1;
2864 switch (output_format) {
2865 case OFORMAT_HUMAN:
2866 dump_human_image_info_list(list);
2867 break;
2868 case OFORMAT_JSON:
2869 if (chain) {
2870 dump_json_image_info_list(list);
2871 } else {
2872 dump_json_image_info(list->value);
2874 break;
2877 qapi_free_ImageInfoList(list);
2878 return 0;
2881 static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2882 MapEntry *next)
2884 switch (output_format) {
2885 case OFORMAT_HUMAN:
2886 if (e->data && !e->has_offset) {
2887 error_report("File contains external, encrypted or compressed clusters.");
2888 return -1;
2890 if (e->data && !e->zero) {
2891 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2892 e->start, e->length,
2893 e->has_offset ? e->offset : 0,
2894 e->has_filename ? e->filename : "");
2896 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2897 * Modify the flags here to allow more coalescing.
2899 if (next && (!next->data || next->zero)) {
2900 next->data = false;
2901 next->zero = true;
2903 break;
2904 case OFORMAT_JSON:
2905 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
2906 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2907 e->start, e->length, e->depth,
2908 e->zero ? "true" : "false",
2909 e->data ? "true" : "false");
2910 if (e->has_offset) {
2911 printf(", \"offset\": %"PRId64"", e->offset);
2913 putchar('}');
2915 if (next) {
2916 puts(",");
2918 break;
2920 return 0;
2923 static int get_block_status(BlockDriverState *bs, int64_t offset,
2924 int64_t bytes, MapEntry *e)
2926 int ret;
2927 int depth;
2928 BlockDriverState *file;
2929 bool has_offset;
2930 int64_t map;
2931 char *filename = NULL;
2933 /* As an optimization, we could cache the current range of unallocated
2934 * clusters in each file of the chain, and avoid querying the same
2935 * range repeatedly.
2938 depth = 0;
2939 for (;;) {
2940 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
2941 if (ret < 0) {
2942 return ret;
2944 assert(bytes);
2945 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2946 break;
2948 bs = backing_bs(bs);
2949 if (bs == NULL) {
2950 ret = 0;
2951 break;
2954 depth++;
2957 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2959 if (file && has_offset) {
2960 bdrv_refresh_filename(file);
2961 filename = file->filename;
2964 *e = (MapEntry) {
2965 .start = offset,
2966 .length = bytes,
2967 .data = !!(ret & BDRV_BLOCK_DATA),
2968 .zero = !!(ret & BDRV_BLOCK_ZERO),
2969 .offset = map,
2970 .has_offset = has_offset,
2971 .depth = depth,
2972 .has_filename = filename,
2973 .filename = filename,
2976 return 0;
2979 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2981 if (curr->length == 0) {
2982 return false;
2984 if (curr->zero != next->zero ||
2985 curr->data != next->data ||
2986 curr->depth != next->depth ||
2987 curr->has_filename != next->has_filename ||
2988 curr->has_offset != next->has_offset) {
2989 return false;
2991 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2992 return false;
2994 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2995 return false;
2997 return true;
3000 static int img_map(int argc, char **argv)
3002 int c;
3003 OutputFormat output_format = OFORMAT_HUMAN;
3004 BlockBackend *blk;
3005 BlockDriverState *bs;
3006 const char *filename, *fmt, *output;
3007 int64_t length;
3008 MapEntry curr = { .length = 0 }, next;
3009 int ret = 0;
3010 bool image_opts = false;
3011 bool force_share = false;
3012 int64_t start_offset = 0;
3013 int64_t max_length = -1;
3015 fmt = NULL;
3016 output = NULL;
3017 for (;;) {
3018 int option_index = 0;
3019 static const struct option long_options[] = {
3020 {"help", no_argument, 0, 'h'},
3021 {"format", required_argument, 0, 'f'},
3022 {"output", required_argument, 0, OPTION_OUTPUT},
3023 {"object", required_argument, 0, OPTION_OBJECT},
3024 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3025 {"force-share", no_argument, 0, 'U'},
3026 {"start-offset", required_argument, 0, 's'},
3027 {"max-length", required_argument, 0, 'l'},
3028 {0, 0, 0, 0}
3030 c = getopt_long(argc, argv, ":f:s:l:hU",
3031 long_options, &option_index);
3032 if (c == -1) {
3033 break;
3035 switch (c) {
3036 case ':':
3037 missing_argument(argv[optind - 1]);
3038 break;
3039 case '?':
3040 unrecognized_option(argv[optind - 1]);
3041 break;
3042 case 'h':
3043 help();
3044 break;
3045 case 'f':
3046 fmt = optarg;
3047 break;
3048 case 'U':
3049 force_share = true;
3050 break;
3051 case OPTION_OUTPUT:
3052 output = optarg;
3053 break;
3054 case 's':
3055 start_offset = cvtnum("start offset", optarg);
3056 if (start_offset < 0) {
3057 return 1;
3059 break;
3060 case 'l':
3061 max_length = cvtnum("max length", optarg);
3062 if (max_length < 0) {
3063 return 1;
3065 break;
3066 case OPTION_OBJECT: {
3067 QemuOpts *opts;
3068 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3069 optarg, true);
3070 if (!opts) {
3071 return 1;
3073 } break;
3074 case OPTION_IMAGE_OPTS:
3075 image_opts = true;
3076 break;
3079 if (optind != argc - 1) {
3080 error_exit("Expecting one image file name");
3082 filename = argv[optind];
3084 if (output && !strcmp(output, "json")) {
3085 output_format = OFORMAT_JSON;
3086 } else if (output && !strcmp(output, "human")) {
3087 output_format = OFORMAT_HUMAN;
3088 } else if (output) {
3089 error_report("--output must be used with human or json as argument.");
3090 return 1;
3093 if (qemu_opts_foreach(&qemu_object_opts,
3094 user_creatable_add_opts_foreach,
3095 qemu_img_object_print_help, &error_fatal)) {
3096 return 1;
3099 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
3100 if (!blk) {
3101 return 1;
3103 bs = blk_bs(blk);
3105 if (output_format == OFORMAT_HUMAN) {
3106 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3107 } else if (output_format == OFORMAT_JSON) {
3108 putchar('[');
3111 length = blk_getlength(blk);
3112 if (length < 0) {
3113 error_report("Failed to get size for '%s'", filename);
3114 return 1;
3116 if (max_length != -1) {
3117 length = MIN(start_offset + max_length, length);
3120 curr.start = start_offset;
3121 while (curr.start + curr.length < length) {
3122 int64_t offset = curr.start + curr.length;
3123 int64_t n;
3125 /* Probe up to 1 GiB at a time. */
3126 n = MIN(1 * GiB, length - offset);
3127 ret = get_block_status(bs, offset, n, &next);
3129 if (ret < 0) {
3130 error_report("Could not read file metadata: %s", strerror(-ret));
3131 goto out;
3134 if (entry_mergeable(&curr, &next)) {
3135 curr.length += next.length;
3136 continue;
3139 if (curr.length > 0) {
3140 ret = dump_map_entry(output_format, &curr, &next);
3141 if (ret < 0) {
3142 goto out;
3145 curr = next;
3148 ret = dump_map_entry(output_format, &curr, NULL);
3149 if (output_format == OFORMAT_JSON) {
3150 puts("]");
3153 out:
3154 blk_unref(blk);
3155 return ret < 0;
3158 #define SNAPSHOT_LIST 1
3159 #define SNAPSHOT_CREATE 2
3160 #define SNAPSHOT_APPLY 3
3161 #define SNAPSHOT_DELETE 4
3163 static int img_snapshot(int argc, char **argv)
3165 BlockBackend *blk;
3166 BlockDriverState *bs;
3167 QEMUSnapshotInfo sn;
3168 char *filename, *snapshot_name = NULL;
3169 int c, ret = 0, bdrv_oflags;
3170 int action = 0;
3171 qemu_timeval tv;
3172 bool quiet = false;
3173 Error *err = NULL;
3174 bool image_opts = false;
3175 bool force_share = false;
3177 bdrv_oflags = BDRV_O_RDWR;
3178 /* Parse commandline parameters */
3179 for(;;) {
3180 static const struct option long_options[] = {
3181 {"help", no_argument, 0, 'h'},
3182 {"object", required_argument, 0, OPTION_OBJECT},
3183 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3184 {"force-share", no_argument, 0, 'U'},
3185 {0, 0, 0, 0}
3187 c = getopt_long(argc, argv, ":la:c:d:hqU",
3188 long_options, NULL);
3189 if (c == -1) {
3190 break;
3192 switch(c) {
3193 case ':':
3194 missing_argument(argv[optind - 1]);
3195 break;
3196 case '?':
3197 unrecognized_option(argv[optind - 1]);
3198 break;
3199 case 'h':
3200 help();
3201 return 0;
3202 case 'l':
3203 if (action) {
3204 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3205 return 0;
3207 action = SNAPSHOT_LIST;
3208 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
3209 break;
3210 case 'a':
3211 if (action) {
3212 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3213 return 0;
3215 action = SNAPSHOT_APPLY;
3216 snapshot_name = optarg;
3217 break;
3218 case 'c':
3219 if (action) {
3220 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3221 return 0;
3223 action = SNAPSHOT_CREATE;
3224 snapshot_name = optarg;
3225 break;
3226 case 'd':
3227 if (action) {
3228 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3229 return 0;
3231 action = SNAPSHOT_DELETE;
3232 snapshot_name = optarg;
3233 break;
3234 case 'q':
3235 quiet = true;
3236 break;
3237 case 'U':
3238 force_share = true;
3239 break;
3240 case OPTION_OBJECT: {
3241 QemuOpts *opts;
3242 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3243 optarg, true);
3244 if (!opts) {
3245 return 1;
3247 } break;
3248 case OPTION_IMAGE_OPTS:
3249 image_opts = true;
3250 break;
3254 if (optind != argc - 1) {
3255 error_exit("Expecting one image file name");
3257 filename = argv[optind++];
3259 if (qemu_opts_foreach(&qemu_object_opts,
3260 user_creatable_add_opts_foreach,
3261 qemu_img_object_print_help, &error_fatal)) {
3262 return 1;
3265 /* Open the image */
3266 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3267 force_share);
3268 if (!blk) {
3269 return 1;
3271 bs = blk_bs(blk);
3273 /* Perform the requested action */
3274 switch(action) {
3275 case SNAPSHOT_LIST:
3276 dump_snapshots(bs);
3277 break;
3279 case SNAPSHOT_CREATE:
3280 memset(&sn, 0, sizeof(sn));
3281 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3283 qemu_gettimeofday(&tv);
3284 sn.date_sec = tv.tv_sec;
3285 sn.date_nsec = tv.tv_usec * 1000;
3287 ret = bdrv_snapshot_create(bs, &sn);
3288 if (ret) {
3289 error_report("Could not create snapshot '%s': %d (%s)",
3290 snapshot_name, ret, strerror(-ret));
3292 break;
3294 case SNAPSHOT_APPLY:
3295 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3296 if (ret) {
3297 error_reportf_err(err, "Could not apply snapshot '%s': ",
3298 snapshot_name);
3300 break;
3302 case SNAPSHOT_DELETE:
3303 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3304 if (ret < 0) {
3305 error_report("Could not delete snapshot '%s': snapshot not "
3306 "found", snapshot_name);
3307 ret = 1;
3308 } else {
3309 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3310 if (ret < 0) {
3311 error_reportf_err(err, "Could not delete snapshot '%s': ",
3312 snapshot_name);
3313 ret = 1;
3316 break;
3319 /* Cleanup */
3320 blk_unref(blk);
3321 if (ret) {
3322 return 1;
3324 return 0;
3327 static int img_rebase(int argc, char **argv)
3329 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3330 uint8_t *buf_old = NULL;
3331 uint8_t *buf_new = NULL;
3332 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
3333 char *filename;
3334 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3335 int c, flags, src_flags, ret;
3336 bool writethrough, src_writethrough;
3337 int unsafe = 0;
3338 bool force_share = false;
3339 int progress = 0;
3340 bool quiet = false;
3341 Error *local_err = NULL;
3342 bool image_opts = false;
3344 /* Parse commandline parameters */
3345 fmt = NULL;
3346 cache = BDRV_DEFAULT_CACHE;
3347 src_cache = BDRV_DEFAULT_CACHE;
3348 out_baseimg = NULL;
3349 out_basefmt = NULL;
3350 for(;;) {
3351 static const struct option long_options[] = {
3352 {"help", no_argument, 0, 'h'},
3353 {"object", required_argument, 0, OPTION_OBJECT},
3354 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3355 {"force-share", no_argument, 0, 'U'},
3356 {0, 0, 0, 0}
3358 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3359 long_options, NULL);
3360 if (c == -1) {
3361 break;
3363 switch(c) {
3364 case ':':
3365 missing_argument(argv[optind - 1]);
3366 break;
3367 case '?':
3368 unrecognized_option(argv[optind - 1]);
3369 break;
3370 case 'h':
3371 help();
3372 return 0;
3373 case 'f':
3374 fmt = optarg;
3375 break;
3376 case 'F':
3377 out_basefmt = optarg;
3378 break;
3379 case 'b':
3380 out_baseimg = optarg;
3381 break;
3382 case 'u':
3383 unsafe = 1;
3384 break;
3385 case 'p':
3386 progress = 1;
3387 break;
3388 case 't':
3389 cache = optarg;
3390 break;
3391 case 'T':
3392 src_cache = optarg;
3393 break;
3394 case 'q':
3395 quiet = true;
3396 break;
3397 case OPTION_OBJECT: {
3398 QemuOpts *opts;
3399 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3400 optarg, true);
3401 if (!opts) {
3402 return 1;
3404 } break;
3405 case OPTION_IMAGE_OPTS:
3406 image_opts = true;
3407 break;
3408 case 'U':
3409 force_share = true;
3410 break;
3414 if (quiet) {
3415 progress = 0;
3418 if (optind != argc - 1) {
3419 error_exit("Expecting one image file name");
3421 if (!unsafe && !out_baseimg) {
3422 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3424 filename = argv[optind++];
3426 if (qemu_opts_foreach(&qemu_object_opts,
3427 user_creatable_add_opts_foreach,
3428 qemu_img_object_print_help, &error_fatal)) {
3429 return 1;
3432 qemu_progress_init(progress, 2.0);
3433 qemu_progress_print(0, 100);
3435 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3436 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3437 if (ret < 0) {
3438 error_report("Invalid cache option: %s", cache);
3439 goto out;
3442 src_flags = 0;
3443 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3444 if (ret < 0) {
3445 error_report("Invalid source cache option: %s", src_cache);
3446 goto out;
3449 /* The source files are opened read-only, don't care about WCE */
3450 assert((src_flags & BDRV_O_RDWR) == 0);
3451 (void) src_writethrough;
3454 * Open the images.
3456 * Ignore the old backing file for unsafe rebase in case we want to correct
3457 * the reference to a renamed or moved backing file.
3459 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3460 false);
3461 if (!blk) {
3462 ret = -1;
3463 goto out;
3465 bs = blk_bs(blk);
3467 if (out_basefmt != NULL) {
3468 if (bdrv_find_format(out_basefmt) == NULL) {
3469 error_report("Invalid format name: '%s'", out_basefmt);
3470 ret = -1;
3471 goto out;
3475 /* For safe rebasing we need to compare old and new backing file */
3476 if (!unsafe) {
3477 QDict *options = NULL;
3478 BlockDriverState *base_bs = backing_bs(bs);
3480 if (base_bs) {
3481 blk_old_backing = blk_new(qemu_get_aio_context(),
3482 BLK_PERM_CONSISTENT_READ,
3483 BLK_PERM_ALL);
3484 ret = blk_insert_bs(blk_old_backing, base_bs,
3485 &local_err);
3486 if (ret < 0) {
3487 error_reportf_err(local_err,
3488 "Could not reuse old backing file '%s': ",
3489 base_bs->filename);
3490 goto out;
3492 } else {
3493 blk_old_backing = NULL;
3496 if (out_baseimg[0]) {
3497 const char *overlay_filename;
3498 char *out_real_path;
3500 options = qdict_new();
3501 if (out_basefmt) {
3502 qdict_put_str(options, "driver", out_basefmt);
3504 if (force_share) {
3505 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3508 bdrv_refresh_filename(bs);
3509 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3510 : bs->filename;
3511 out_real_path =
3512 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3513 out_baseimg,
3514 &local_err);
3515 if (local_err) {
3516 qobject_unref(options);
3517 error_reportf_err(local_err,
3518 "Could not resolve backing filename: ");
3519 ret = -1;
3520 goto out;
3524 * Find out whether we rebase an image on top of a previous image
3525 * in its chain.
3527 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
3528 if (prefix_chain_bs) {
3529 qobject_unref(options);
3530 g_free(out_real_path);
3532 blk_new_backing = blk_new(qemu_get_aio_context(),
3533 BLK_PERM_CONSISTENT_READ,
3534 BLK_PERM_ALL);
3535 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3536 &local_err);
3537 if (ret < 0) {
3538 error_reportf_err(local_err,
3539 "Could not reuse backing file '%s': ",
3540 out_baseimg);
3541 goto out;
3543 } else {
3544 blk_new_backing = blk_new_open(out_real_path, NULL,
3545 options, src_flags, &local_err);
3546 g_free(out_real_path);
3547 if (!blk_new_backing) {
3548 error_reportf_err(local_err,
3549 "Could not open new backing file '%s': ",
3550 out_baseimg);
3551 ret = -1;
3552 goto out;
3559 * Check each unallocated cluster in the COW file. If it is unallocated,
3560 * accesses go to the backing file. We must therefore compare this cluster
3561 * in the old and new backing file, and if they differ we need to copy it
3562 * from the old backing file into the COW file.
3564 * If qemu-img crashes during this step, no harm is done. The content of
3565 * the image is the same as the original one at any time.
3567 if (!unsafe) {
3568 int64_t size;
3569 int64_t old_backing_size = 0;
3570 int64_t new_backing_size = 0;
3571 uint64_t offset;
3572 int64_t n;
3573 float local_progress = 0;
3575 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3576 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3578 size = blk_getlength(blk);
3579 if (size < 0) {
3580 error_report("Could not get size of '%s': %s",
3581 filename, strerror(-size));
3582 ret = -1;
3583 goto out;
3585 if (blk_old_backing) {
3586 old_backing_size = blk_getlength(blk_old_backing);
3587 if (old_backing_size < 0) {
3588 char backing_name[PATH_MAX];
3590 bdrv_get_backing_filename(bs, backing_name,
3591 sizeof(backing_name));
3592 error_report("Could not get size of '%s': %s",
3593 backing_name, strerror(-old_backing_size));
3594 ret = -1;
3595 goto out;
3598 if (blk_new_backing) {
3599 new_backing_size = blk_getlength(blk_new_backing);
3600 if (new_backing_size < 0) {
3601 error_report("Could not get size of '%s': %s",
3602 out_baseimg, strerror(-new_backing_size));
3603 ret = -1;
3604 goto out;
3608 if (size != 0) {
3609 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3612 for (offset = 0; offset < size; offset += n) {
3613 bool buf_old_is_zero = false;
3615 /* How many bytes can we handle with the next read? */
3616 n = MIN(IO_BUF_SIZE, size - offset);
3618 /* If the cluster is allocated, we don't need to take action */
3619 ret = bdrv_is_allocated(bs, offset, n, &n);
3620 if (ret < 0) {
3621 error_report("error while reading image metadata: %s",
3622 strerror(-ret));
3623 goto out;
3625 if (ret) {
3626 continue;
3629 if (prefix_chain_bs) {
3631 * If cluster wasn't changed since prefix_chain, we don't need
3632 * to take action
3634 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
3635 false, offset, n, &n);
3636 if (ret < 0) {
3637 error_report("error while reading image metadata: %s",
3638 strerror(-ret));
3639 goto out;
3641 if (!ret) {
3642 continue;
3647 * Read old and new backing file and take into consideration that
3648 * backing files may be smaller than the COW image.
3650 if (offset >= old_backing_size) {
3651 memset(buf_old, 0, n);
3652 buf_old_is_zero = true;
3653 } else {
3654 if (offset + n > old_backing_size) {
3655 n = old_backing_size - offset;
3658 ret = blk_pread(blk_old_backing, offset, buf_old, n);
3659 if (ret < 0) {
3660 error_report("error while reading from old backing file");
3661 goto out;
3665 if (offset >= new_backing_size || !blk_new_backing) {
3666 memset(buf_new, 0, n);
3667 } else {
3668 if (offset + n > new_backing_size) {
3669 n = new_backing_size - offset;
3672 ret = blk_pread(blk_new_backing, offset, buf_new, n);
3673 if (ret < 0) {
3674 error_report("error while reading from new backing file");
3675 goto out;
3679 /* If they differ, we need to write to the COW file */
3680 uint64_t written = 0;
3682 while (written < n) {
3683 int64_t pnum;
3685 if (compare_buffers(buf_old + written, buf_new + written,
3686 n - written, &pnum))
3688 if (buf_old_is_zero) {
3689 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3690 } else {
3691 ret = blk_pwrite(blk, offset + written,
3692 buf_old + written, pnum, 0);
3694 if (ret < 0) {
3695 error_report("Error while writing to COW image: %s",
3696 strerror(-ret));
3697 goto out;
3701 written += pnum;
3703 qemu_progress_print(local_progress, 100);
3708 * Change the backing file. All clusters that are different from the old
3709 * backing file are overwritten in the COW file now, so the visible content
3710 * doesn't change when we switch the backing file.
3712 if (out_baseimg && *out_baseimg) {
3713 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3714 } else {
3715 ret = bdrv_change_backing_file(bs, NULL, NULL);
3718 if (ret == -ENOSPC) {
3719 error_report("Could not change the backing file to '%s': No "
3720 "space left in the file header", out_baseimg);
3721 } else if (ret < 0) {
3722 error_report("Could not change the backing file to '%s': %s",
3723 out_baseimg, strerror(-ret));
3726 qemu_progress_print(100, 0);
3728 * TODO At this point it is possible to check if any clusters that are
3729 * allocated in the COW file are the same in the backing file. If so, they
3730 * could be dropped from the COW file. Don't do this before switching the
3731 * backing file, in case of a crash this would lead to corruption.
3733 out:
3734 qemu_progress_end();
3735 /* Cleanup */
3736 if (!unsafe) {
3737 blk_unref(blk_old_backing);
3738 blk_unref(blk_new_backing);
3740 qemu_vfree(buf_old);
3741 qemu_vfree(buf_new);
3743 blk_unref(blk);
3744 if (ret) {
3745 return 1;
3747 return 0;
3750 static int img_resize(int argc, char **argv)
3752 Error *err = NULL;
3753 int c, ret, relative;
3754 const char *filename, *fmt, *size;
3755 int64_t n, total_size, current_size;
3756 bool quiet = false;
3757 BlockBackend *blk = NULL;
3758 PreallocMode prealloc = PREALLOC_MODE_OFF;
3759 QemuOpts *param;
3761 static QemuOptsList resize_options = {
3762 .name = "resize_options",
3763 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3764 .desc = {
3766 .name = BLOCK_OPT_SIZE,
3767 .type = QEMU_OPT_SIZE,
3768 .help = "Virtual disk size"
3769 }, {
3770 /* end of list */
3774 bool image_opts = false;
3775 bool shrink = false;
3777 /* Remove size from argv manually so that negative numbers are not treated
3778 * as options by getopt. */
3779 if (argc < 3) {
3780 error_exit("Not enough arguments");
3781 return 1;
3784 size = argv[--argc];
3786 /* Parse getopt arguments */
3787 fmt = NULL;
3788 for(;;) {
3789 static const struct option long_options[] = {
3790 {"help", no_argument, 0, 'h'},
3791 {"object", required_argument, 0, OPTION_OBJECT},
3792 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3793 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3794 {"shrink", no_argument, 0, OPTION_SHRINK},
3795 {0, 0, 0, 0}
3797 c = getopt_long(argc, argv, ":f:hq",
3798 long_options, NULL);
3799 if (c == -1) {
3800 break;
3802 switch(c) {
3803 case ':':
3804 missing_argument(argv[optind - 1]);
3805 break;
3806 case '?':
3807 unrecognized_option(argv[optind - 1]);
3808 break;
3809 case 'h':
3810 help();
3811 break;
3812 case 'f':
3813 fmt = optarg;
3814 break;
3815 case 'q':
3816 quiet = true;
3817 break;
3818 case OPTION_OBJECT: {
3819 QemuOpts *opts;
3820 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3821 optarg, true);
3822 if (!opts) {
3823 return 1;
3825 } break;
3826 case OPTION_IMAGE_OPTS:
3827 image_opts = true;
3828 break;
3829 case OPTION_PREALLOCATION:
3830 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3831 PREALLOC_MODE__MAX, NULL);
3832 if (prealloc == PREALLOC_MODE__MAX) {
3833 error_report("Invalid preallocation mode '%s'", optarg);
3834 return 1;
3836 break;
3837 case OPTION_SHRINK:
3838 shrink = true;
3839 break;
3842 if (optind != argc - 1) {
3843 error_exit("Expecting image file name and size");
3845 filename = argv[optind++];
3847 if (qemu_opts_foreach(&qemu_object_opts,
3848 user_creatable_add_opts_foreach,
3849 qemu_img_object_print_help, &error_fatal)) {
3850 return 1;
3853 /* Choose grow, shrink, or absolute resize mode */
3854 switch (size[0]) {
3855 case '+':
3856 relative = 1;
3857 size++;
3858 break;
3859 case '-':
3860 relative = -1;
3861 size++;
3862 break;
3863 default:
3864 relative = 0;
3865 break;
3868 /* Parse size */
3869 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3870 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3871 if (err) {
3872 error_report_err(err);
3873 ret = -1;
3874 qemu_opts_del(param);
3875 goto out;
3877 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3878 qemu_opts_del(param);
3880 blk = img_open(image_opts, filename, fmt,
3881 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3882 false);
3883 if (!blk) {
3884 ret = -1;
3885 goto out;
3888 current_size = blk_getlength(blk);
3889 if (current_size < 0) {
3890 error_report("Failed to inquire current image length: %s",
3891 strerror(-current_size));
3892 ret = -1;
3893 goto out;
3896 if (relative) {
3897 total_size = current_size + n * relative;
3898 } else {
3899 total_size = n;
3901 if (total_size <= 0) {
3902 error_report("New image size must be positive");
3903 ret = -1;
3904 goto out;
3907 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3908 error_report("Preallocation can only be used for growing images");
3909 ret = -1;
3910 goto out;
3913 if (total_size < current_size && !shrink) {
3914 warn_report("Shrinking an image will delete all data beyond the "
3915 "shrunken image's end. Before performing such an "
3916 "operation, make sure there is no important data there.");
3918 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3919 error_report(
3920 "Use the --shrink option to perform a shrink operation.");
3921 ret = -1;
3922 goto out;
3923 } else {
3924 warn_report("Using the --shrink option will suppress this message. "
3925 "Note that future versions of qemu-img may refuse to "
3926 "shrink images without this option.");
3931 * The user expects the image to have the desired size after
3932 * resizing, so pass @exact=true. It is of no use to report
3933 * success when the image has not actually been resized.
3935 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
3936 if (!ret) {
3937 qprintf(quiet, "Image resized.\n");
3938 } else {
3939 error_report_err(err);
3941 out:
3942 blk_unref(blk);
3943 if (ret) {
3944 return 1;
3946 return 0;
3949 static void amend_status_cb(BlockDriverState *bs,
3950 int64_t offset, int64_t total_work_size,
3951 void *opaque)
3953 qemu_progress_print(100.f * offset / total_work_size, 0);
3956 static int print_amend_option_help(const char *format)
3958 BlockDriver *drv;
3960 /* Find driver and parse its options */
3961 drv = bdrv_find_format(format);
3962 if (!drv) {
3963 error_report("Unknown file format '%s'", format);
3964 return 1;
3967 if (!drv->bdrv_amend_options) {
3968 error_report("Format driver '%s' does not support option amendment",
3969 format);
3970 return 1;
3973 /* Every driver supporting amendment must have create_opts */
3974 assert(drv->create_opts);
3976 printf("Creation options for '%s':\n", format);
3977 qemu_opts_print_help(drv->create_opts, false);
3978 printf("\nNote that not all of these options may be amendable.\n");
3979 return 0;
3982 static int img_amend(int argc, char **argv)
3984 Error *err = NULL;
3985 int c, ret = 0;
3986 char *options = NULL;
3987 QemuOptsList *create_opts = NULL;
3988 QemuOpts *opts = NULL;
3989 const char *fmt = NULL, *filename, *cache;
3990 int flags;
3991 bool writethrough;
3992 bool quiet = false, progress = false;
3993 BlockBackend *blk = NULL;
3994 BlockDriverState *bs = NULL;
3995 bool image_opts = false;
3997 cache = BDRV_DEFAULT_CACHE;
3998 for (;;) {
3999 static const struct option long_options[] = {
4000 {"help", no_argument, 0, 'h'},
4001 {"object", required_argument, 0, OPTION_OBJECT},
4002 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4003 {0, 0, 0, 0}
4005 c = getopt_long(argc, argv, ":ho:f:t:pq",
4006 long_options, NULL);
4007 if (c == -1) {
4008 break;
4011 switch (c) {
4012 case ':':
4013 missing_argument(argv[optind - 1]);
4014 break;
4015 case '?':
4016 unrecognized_option(argv[optind - 1]);
4017 break;
4018 case 'h':
4019 help();
4020 break;
4021 case 'o':
4022 if (accumulate_options(&options, optarg) < 0) {
4023 ret = -1;
4024 goto out_no_progress;
4026 break;
4027 case 'f':
4028 fmt = optarg;
4029 break;
4030 case 't':
4031 cache = optarg;
4032 break;
4033 case 'p':
4034 progress = true;
4035 break;
4036 case 'q':
4037 quiet = true;
4038 break;
4039 case OPTION_OBJECT:
4040 opts = qemu_opts_parse_noisily(&qemu_object_opts,
4041 optarg, true);
4042 if (!opts) {
4043 ret = -1;
4044 goto out_no_progress;
4046 break;
4047 case OPTION_IMAGE_OPTS:
4048 image_opts = true;
4049 break;
4053 if (!options) {
4054 error_exit("Must specify options (-o)");
4057 if (qemu_opts_foreach(&qemu_object_opts,
4058 user_creatable_add_opts_foreach,
4059 qemu_img_object_print_help, &error_fatal)) {
4060 ret = -1;
4061 goto out_no_progress;
4064 if (quiet) {
4065 progress = false;
4067 qemu_progress_init(progress, 1.0);
4069 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4070 if (fmt && has_help_option(options)) {
4071 /* If a format is explicitly specified (and possibly no filename is
4072 * given), print option help here */
4073 ret = print_amend_option_help(fmt);
4074 goto out;
4077 if (optind != argc - 1) {
4078 error_report("Expecting one image file name");
4079 ret = -1;
4080 goto out;
4083 flags = BDRV_O_RDWR;
4084 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
4085 if (ret < 0) {
4086 error_report("Invalid cache option: %s", cache);
4087 goto out;
4090 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4091 false);
4092 if (!blk) {
4093 ret = -1;
4094 goto out;
4096 bs = blk_bs(blk);
4098 fmt = bs->drv->format_name;
4100 if (has_help_option(options)) {
4101 /* If the format was auto-detected, print option help here */
4102 ret = print_amend_option_help(fmt);
4103 goto out;
4106 if (!bs->drv->bdrv_amend_options) {
4107 error_report("Format driver '%s' does not support option amendment",
4108 fmt);
4109 ret = -1;
4110 goto out;
4113 /* Every driver supporting amendment must have create_opts */
4114 assert(bs->drv->create_opts);
4116 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
4117 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4118 qemu_opts_do_parse(opts, options, NULL, &err);
4119 if (err) {
4120 error_report_err(err);
4121 ret = -1;
4122 goto out;
4125 /* In case the driver does not call amend_status_cb() */
4126 qemu_progress_print(0.f, 0);
4127 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
4128 qemu_progress_print(100.f, 0);
4129 if (ret < 0) {
4130 error_report_err(err);
4131 goto out;
4134 out:
4135 qemu_progress_end();
4137 out_no_progress:
4138 blk_unref(blk);
4139 qemu_opts_del(opts);
4140 qemu_opts_free(create_opts);
4141 g_free(options);
4143 if (ret) {
4144 return 1;
4146 return 0;
4149 typedef struct BenchData {
4150 BlockBackend *blk;
4151 uint64_t image_size;
4152 bool write;
4153 int bufsize;
4154 int step;
4155 int nrreq;
4156 int n;
4157 int flush_interval;
4158 bool drain_on_flush;
4159 uint8_t *buf;
4160 QEMUIOVector *qiov;
4162 int in_flight;
4163 bool in_flush;
4164 uint64_t offset;
4165 } BenchData;
4167 static void bench_undrained_flush_cb(void *opaque, int ret)
4169 if (ret < 0) {
4170 error_report("Failed flush request: %s", strerror(-ret));
4171 exit(EXIT_FAILURE);
4175 static void bench_cb(void *opaque, int ret)
4177 BenchData *b = opaque;
4178 BlockAIOCB *acb;
4180 if (ret < 0) {
4181 error_report("Failed request: %s", strerror(-ret));
4182 exit(EXIT_FAILURE);
4185 if (b->in_flush) {
4186 /* Just finished a flush with drained queue: Start next requests */
4187 assert(b->in_flight == 0);
4188 b->in_flush = false;
4189 } else if (b->in_flight > 0) {
4190 int remaining = b->n - b->in_flight;
4192 b->n--;
4193 b->in_flight--;
4195 /* Time for flush? Drain queue if requested, then flush */
4196 if (b->flush_interval && remaining % b->flush_interval == 0) {
4197 if (!b->in_flight || !b->drain_on_flush) {
4198 BlockCompletionFunc *cb;
4200 if (b->drain_on_flush) {
4201 b->in_flush = true;
4202 cb = bench_cb;
4203 } else {
4204 cb = bench_undrained_flush_cb;
4207 acb = blk_aio_flush(b->blk, cb, b);
4208 if (!acb) {
4209 error_report("Failed to issue flush request");
4210 exit(EXIT_FAILURE);
4213 if (b->drain_on_flush) {
4214 return;
4219 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4220 int64_t offset = b->offset;
4221 /* blk_aio_* might look for completed I/Os and kick bench_cb
4222 * again, so make sure this operation is counted by in_flight
4223 * and b->offset is ready for the next submission.
4225 b->in_flight++;
4226 b->offset += b->step;
4227 b->offset %= b->image_size;
4228 if (b->write) {
4229 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
4230 } else {
4231 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
4233 if (!acb) {
4234 error_report("Failed to issue request");
4235 exit(EXIT_FAILURE);
4240 static int img_bench(int argc, char **argv)
4242 int c, ret = 0;
4243 const char *fmt = NULL, *filename;
4244 bool quiet = false;
4245 bool image_opts = false;
4246 bool is_write = false;
4247 int count = 75000;
4248 int depth = 64;
4249 int64_t offset = 0;
4250 size_t bufsize = 4096;
4251 int pattern = 0;
4252 size_t step = 0;
4253 int flush_interval = 0;
4254 bool drain_on_flush = true;
4255 int64_t image_size;
4256 BlockBackend *blk = NULL;
4257 BenchData data = {};
4258 int flags = 0;
4259 bool writethrough = false;
4260 struct timeval t1, t2;
4261 int i;
4262 bool force_share = false;
4263 size_t buf_size;
4265 for (;;) {
4266 static const struct option long_options[] = {
4267 {"help", no_argument, 0, 'h'},
4268 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
4269 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4270 {"pattern", required_argument, 0, OPTION_PATTERN},
4271 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
4272 {"force-share", no_argument, 0, 'U'},
4273 {0, 0, 0, 0}
4275 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4276 NULL);
4277 if (c == -1) {
4278 break;
4281 switch (c) {
4282 case ':':
4283 missing_argument(argv[optind - 1]);
4284 break;
4285 case '?':
4286 unrecognized_option(argv[optind - 1]);
4287 break;
4288 case 'h':
4289 help();
4290 break;
4291 case 'c':
4293 unsigned long res;
4295 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4296 error_report("Invalid request count specified");
4297 return 1;
4299 count = res;
4300 break;
4302 case 'd':
4304 unsigned long res;
4306 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4307 error_report("Invalid queue depth specified");
4308 return 1;
4310 depth = res;
4311 break;
4313 case 'f':
4314 fmt = optarg;
4315 break;
4316 case 'n':
4317 flags |= BDRV_O_NATIVE_AIO;
4318 break;
4319 case 'i':
4320 ret = bdrv_parse_aio(optarg, &flags);
4321 if (ret < 0) {
4322 error_report("Invalid aio option: %s", optarg);
4323 ret = -1;
4324 goto out;
4326 break;
4327 case 'o':
4329 offset = cvtnum("offset", optarg);
4330 if (offset < 0) {
4331 return 1;
4333 break;
4335 break;
4336 case 'q':
4337 quiet = true;
4338 break;
4339 case 's':
4341 int64_t sval;
4343 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4344 if (sval < 0) {
4345 return 1;
4348 bufsize = sval;
4349 break;
4351 case 'S':
4353 int64_t sval;
4355 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4356 if (sval < 0) {
4357 return 1;
4360 step = sval;
4361 break;
4363 case 't':
4364 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4365 if (ret < 0) {
4366 error_report("Invalid cache mode");
4367 ret = -1;
4368 goto out;
4370 break;
4371 case 'w':
4372 flags |= BDRV_O_RDWR;
4373 is_write = true;
4374 break;
4375 case 'U':
4376 force_share = true;
4377 break;
4378 case OPTION_PATTERN:
4380 unsigned long res;
4382 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4383 error_report("Invalid pattern byte specified");
4384 return 1;
4386 pattern = res;
4387 break;
4389 case OPTION_FLUSH_INTERVAL:
4391 unsigned long res;
4393 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4394 error_report("Invalid flush interval specified");
4395 return 1;
4397 flush_interval = res;
4398 break;
4400 case OPTION_NO_DRAIN:
4401 drain_on_flush = false;
4402 break;
4403 case OPTION_IMAGE_OPTS:
4404 image_opts = true;
4405 break;
4409 if (optind != argc - 1) {
4410 error_exit("Expecting one image file name");
4412 filename = argv[argc - 1];
4414 if (!is_write && flush_interval) {
4415 error_report("--flush-interval is only available in write tests");
4416 ret = -1;
4417 goto out;
4419 if (flush_interval && flush_interval < depth) {
4420 error_report("Flush interval can't be smaller than depth");
4421 ret = -1;
4422 goto out;
4425 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4426 force_share);
4427 if (!blk) {
4428 ret = -1;
4429 goto out;
4432 image_size = blk_getlength(blk);
4433 if (image_size < 0) {
4434 ret = image_size;
4435 goto out;
4438 data = (BenchData) {
4439 .blk = blk,
4440 .image_size = image_size,
4441 .bufsize = bufsize,
4442 .step = step ?: bufsize,
4443 .nrreq = depth,
4444 .n = count,
4445 .offset = offset,
4446 .write = is_write,
4447 .flush_interval = flush_interval,
4448 .drain_on_flush = drain_on_flush,
4450 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4451 "(starting at offset %" PRId64 ", step size %d)\n",
4452 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4453 data.offset, data.step);
4454 if (flush_interval) {
4455 printf("Sending flush every %d requests\n", flush_interval);
4458 buf_size = data.nrreq * data.bufsize;
4459 data.buf = blk_blockalign(blk, buf_size);
4460 memset(data.buf, pattern, data.nrreq * data.bufsize);
4462 blk_register_buf(blk, data.buf, buf_size);
4464 data.qiov = g_new(QEMUIOVector, data.nrreq);
4465 for (i = 0; i < data.nrreq; i++) {
4466 qemu_iovec_init(&data.qiov[i], 1);
4467 qemu_iovec_add(&data.qiov[i],
4468 data.buf + i * data.bufsize, data.bufsize);
4471 gettimeofday(&t1, NULL);
4472 bench_cb(&data, 0);
4474 while (data.n > 0) {
4475 main_loop_wait(false);
4477 gettimeofday(&t2, NULL);
4479 printf("Run completed in %3.3f seconds.\n",
4480 (t2.tv_sec - t1.tv_sec)
4481 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4483 out:
4484 if (data.buf) {
4485 blk_unregister_buf(blk, data.buf);
4487 qemu_vfree(data.buf);
4488 blk_unref(blk);
4490 if (ret) {
4491 return 1;
4493 return 0;
4496 #define C_BS 01
4497 #define C_COUNT 02
4498 #define C_IF 04
4499 #define C_OF 010
4500 #define C_SKIP 020
4502 struct DdInfo {
4503 unsigned int flags;
4504 int64_t count;
4507 struct DdIo {
4508 int bsz; /* Block size */
4509 char *filename;
4510 uint8_t *buf;
4511 int64_t offset;
4514 struct DdOpts {
4515 const char *name;
4516 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4517 unsigned int flag;
4520 static int img_dd_bs(const char *arg,
4521 struct DdIo *in, struct DdIo *out,
4522 struct DdInfo *dd)
4524 int64_t res;
4526 res = cvtnum_full("bs", arg, 1, INT_MAX);
4528 if (res < 0) {
4529 return 1;
4531 in->bsz = out->bsz = res;
4533 return 0;
4536 static int img_dd_count(const char *arg,
4537 struct DdIo *in, struct DdIo *out,
4538 struct DdInfo *dd)
4540 dd->count = cvtnum("count", arg);
4542 if (dd->count < 0) {
4543 return 1;
4546 return 0;
4549 static int img_dd_if(const char *arg,
4550 struct DdIo *in, struct DdIo *out,
4551 struct DdInfo *dd)
4553 in->filename = g_strdup(arg);
4555 return 0;
4558 static int img_dd_of(const char *arg,
4559 struct DdIo *in, struct DdIo *out,
4560 struct DdInfo *dd)
4562 out->filename = g_strdup(arg);
4564 return 0;
4567 static int img_dd_skip(const char *arg,
4568 struct DdIo *in, struct DdIo *out,
4569 struct DdInfo *dd)
4571 in->offset = cvtnum("skip", arg);
4573 if (in->offset < 0) {
4574 return 1;
4577 return 0;
4580 static int img_dd(int argc, char **argv)
4582 int ret = 0;
4583 char *arg = NULL;
4584 char *tmp;
4585 BlockDriver *drv = NULL, *proto_drv = NULL;
4586 BlockBackend *blk1 = NULL, *blk2 = NULL;
4587 QemuOpts *opts = NULL;
4588 QemuOptsList *create_opts = NULL;
4589 Error *local_err = NULL;
4590 bool image_opts = false;
4591 int c, i;
4592 const char *out_fmt = "raw";
4593 const char *fmt = NULL;
4594 int64_t size = 0;
4595 int64_t block_count = 0, out_pos, in_pos;
4596 bool force_share = false;
4597 struct DdInfo dd = {
4598 .flags = 0,
4599 .count = 0,
4601 struct DdIo in = {
4602 .bsz = 512, /* Block size is by default 512 bytes */
4603 .filename = NULL,
4604 .buf = NULL,
4605 .offset = 0
4607 struct DdIo out = {
4608 .bsz = 512,
4609 .filename = NULL,
4610 .buf = NULL,
4611 .offset = 0
4614 const struct DdOpts options[] = {
4615 { "bs", img_dd_bs, C_BS },
4616 { "count", img_dd_count, C_COUNT },
4617 { "if", img_dd_if, C_IF },
4618 { "of", img_dd_of, C_OF },
4619 { "skip", img_dd_skip, C_SKIP },
4620 { NULL, NULL, 0 }
4622 const struct option long_options[] = {
4623 { "help", no_argument, 0, 'h'},
4624 { "object", required_argument, 0, OPTION_OBJECT},
4625 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4626 { "force-share", no_argument, 0, 'U'},
4627 { 0, 0, 0, 0 }
4630 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4631 if (c == EOF) {
4632 break;
4634 switch (c) {
4635 case 'O':
4636 out_fmt = optarg;
4637 break;
4638 case 'f':
4639 fmt = optarg;
4640 break;
4641 case ':':
4642 missing_argument(argv[optind - 1]);
4643 break;
4644 case '?':
4645 unrecognized_option(argv[optind - 1]);
4646 break;
4647 case 'h':
4648 help();
4649 break;
4650 case 'U':
4651 force_share = true;
4652 break;
4653 case OPTION_OBJECT:
4654 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4655 ret = -1;
4656 goto out;
4658 break;
4659 case OPTION_IMAGE_OPTS:
4660 image_opts = true;
4661 break;
4665 for (i = optind; i < argc; i++) {
4666 int j;
4667 arg = g_strdup(argv[i]);
4669 tmp = strchr(arg, '=');
4670 if (tmp == NULL) {
4671 error_report("unrecognized operand %s", arg);
4672 ret = -1;
4673 goto out;
4676 *tmp++ = '\0';
4678 for (j = 0; options[j].name != NULL; j++) {
4679 if (!strcmp(arg, options[j].name)) {
4680 break;
4683 if (options[j].name == NULL) {
4684 error_report("unrecognized operand %s", arg);
4685 ret = -1;
4686 goto out;
4689 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4690 ret = -1;
4691 goto out;
4693 dd.flags |= options[j].flag;
4694 g_free(arg);
4695 arg = NULL;
4698 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4699 error_report("Must specify both input and output files");
4700 ret = -1;
4701 goto out;
4704 if (qemu_opts_foreach(&qemu_object_opts,
4705 user_creatable_add_opts_foreach,
4706 qemu_img_object_print_help, &error_fatal)) {
4707 ret = -1;
4708 goto out;
4711 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4712 force_share);
4714 if (!blk1) {
4715 ret = -1;
4716 goto out;
4719 drv = bdrv_find_format(out_fmt);
4720 if (!drv) {
4721 error_report("Unknown file format");
4722 ret = -1;
4723 goto out;
4725 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4727 if (!proto_drv) {
4728 error_report_err(local_err);
4729 ret = -1;
4730 goto out;
4732 if (!drv->create_opts) {
4733 error_report("Format driver '%s' does not support image creation",
4734 drv->format_name);
4735 ret = -1;
4736 goto out;
4738 if (!proto_drv->create_opts) {
4739 error_report("Protocol driver '%s' does not support image creation",
4740 proto_drv->format_name);
4741 ret = -1;
4742 goto out;
4744 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4745 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4747 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4749 size = blk_getlength(blk1);
4750 if (size < 0) {
4751 error_report("Failed to get size for '%s'", in.filename);
4752 ret = -1;
4753 goto out;
4756 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4757 dd.count * in.bsz < size) {
4758 size = dd.count * in.bsz;
4761 /* Overflow means the specified offset is beyond input image's size */
4762 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4763 size < in.bsz * in.offset)) {
4764 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4765 } else {
4766 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4767 size - in.bsz * in.offset, &error_abort);
4770 ret = bdrv_create(drv, out.filename, opts, &local_err);
4771 if (ret < 0) {
4772 error_reportf_err(local_err,
4773 "%s: error while creating output image: ",
4774 out.filename);
4775 ret = -1;
4776 goto out;
4779 /* TODO, we can't honour --image-opts for the target,
4780 * since it needs to be given in a format compatible
4781 * with the bdrv_create() call above which does not
4782 * support image-opts style.
4784 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
4785 false, false, false);
4787 if (!blk2) {
4788 ret = -1;
4789 goto out;
4792 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4793 size < in.offset * in.bsz)) {
4794 /* We give a warning if the skip option is bigger than the input
4795 * size and create an empty output disk image (i.e. like dd(1)).
4797 error_report("%s: cannot skip to specified offset", in.filename);
4798 in_pos = size;
4799 } else {
4800 in_pos = in.offset * in.bsz;
4803 in.buf = g_new(uint8_t, in.bsz);
4805 for (out_pos = 0; in_pos < size; block_count++) {
4806 int in_ret, out_ret;
4808 if (in_pos + in.bsz > size) {
4809 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4810 } else {
4811 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4813 if (in_ret < 0) {
4814 error_report("error while reading from input image file: %s",
4815 strerror(-in_ret));
4816 ret = -1;
4817 goto out;
4819 in_pos += in_ret;
4821 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4823 if (out_ret < 0) {
4824 error_report("error while writing to output image file: %s",
4825 strerror(-out_ret));
4826 ret = -1;
4827 goto out;
4829 out_pos += out_ret;
4832 out:
4833 g_free(arg);
4834 qemu_opts_del(opts);
4835 qemu_opts_free(create_opts);
4836 blk_unref(blk1);
4837 blk_unref(blk2);
4838 g_free(in.filename);
4839 g_free(out.filename);
4840 g_free(in.buf);
4841 g_free(out.buf);
4843 if (ret) {
4844 return 1;
4846 return 0;
4849 static void dump_json_block_measure_info(BlockMeasureInfo *info)
4851 QString *str;
4852 QObject *obj;
4853 Visitor *v = qobject_output_visitor_new(&obj);
4855 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4856 visit_complete(v, &obj);
4857 str = qobject_to_json_pretty(obj);
4858 assert(str != NULL);
4859 printf("%s\n", qstring_get_str(str));
4860 qobject_unref(obj);
4861 visit_free(v);
4862 qobject_unref(str);
4865 static int img_measure(int argc, char **argv)
4867 static const struct option long_options[] = {
4868 {"help", no_argument, 0, 'h'},
4869 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4870 {"object", required_argument, 0, OPTION_OBJECT},
4871 {"output", required_argument, 0, OPTION_OUTPUT},
4872 {"size", required_argument, 0, OPTION_SIZE},
4873 {"force-share", no_argument, 0, 'U'},
4874 {0, 0, 0, 0}
4876 OutputFormat output_format = OFORMAT_HUMAN;
4877 BlockBackend *in_blk = NULL;
4878 BlockDriver *drv;
4879 const char *filename = NULL;
4880 const char *fmt = NULL;
4881 const char *out_fmt = "raw";
4882 char *options = NULL;
4883 char *snapshot_name = NULL;
4884 bool force_share = false;
4885 QemuOpts *opts = NULL;
4886 QemuOpts *object_opts = NULL;
4887 QemuOpts *sn_opts = NULL;
4888 QemuOptsList *create_opts = NULL;
4889 bool image_opts = false;
4890 uint64_t img_size = UINT64_MAX;
4891 BlockMeasureInfo *info = NULL;
4892 Error *local_err = NULL;
4893 int ret = 1;
4894 int c;
4896 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4897 long_options, NULL)) != -1) {
4898 switch (c) {
4899 case '?':
4900 case 'h':
4901 help();
4902 break;
4903 case 'f':
4904 fmt = optarg;
4905 break;
4906 case 'O':
4907 out_fmt = optarg;
4908 break;
4909 case 'o':
4910 if (accumulate_options(&options, optarg) < 0) {
4911 goto out;
4913 break;
4914 case 'l':
4915 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4916 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4917 optarg, false);
4918 if (!sn_opts) {
4919 error_report("Failed in parsing snapshot param '%s'",
4920 optarg);
4921 goto out;
4923 } else {
4924 snapshot_name = optarg;
4926 break;
4927 case 'U':
4928 force_share = true;
4929 break;
4930 case OPTION_OBJECT:
4931 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4932 optarg, true);
4933 if (!object_opts) {
4934 goto out;
4936 break;
4937 case OPTION_IMAGE_OPTS:
4938 image_opts = true;
4939 break;
4940 case OPTION_OUTPUT:
4941 if (!strcmp(optarg, "json")) {
4942 output_format = OFORMAT_JSON;
4943 } else if (!strcmp(optarg, "human")) {
4944 output_format = OFORMAT_HUMAN;
4945 } else {
4946 error_report("--output must be used with human or json "
4947 "as argument.");
4948 goto out;
4950 break;
4951 case OPTION_SIZE:
4953 int64_t sval;
4955 sval = cvtnum("image size", optarg);
4956 if (sval < 0) {
4957 goto out;
4959 img_size = (uint64_t)sval;
4961 break;
4965 if (qemu_opts_foreach(&qemu_object_opts,
4966 user_creatable_add_opts_foreach,
4967 qemu_img_object_print_help, &error_fatal)) {
4968 goto out;
4971 if (argc - optind > 1) {
4972 error_report("At most one filename argument is allowed.");
4973 goto out;
4974 } else if (argc - optind == 1) {
4975 filename = argv[optind];
4978 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
4979 error_report("--image-opts, -f, and -l require a filename argument.");
4980 goto out;
4982 if (filename && img_size != UINT64_MAX) {
4983 error_report("--size N cannot be used together with a filename.");
4984 goto out;
4986 if (!filename && img_size == UINT64_MAX) {
4987 error_report("Either --size N or one filename must be specified.");
4988 goto out;
4991 if (filename) {
4992 in_blk = img_open(image_opts, filename, fmt, 0,
4993 false, false, force_share);
4994 if (!in_blk) {
4995 goto out;
4998 if (sn_opts) {
4999 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5000 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5001 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5002 &local_err);
5003 } else if (snapshot_name != NULL) {
5004 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5005 snapshot_name, &local_err);
5007 if (local_err) {
5008 error_reportf_err(local_err, "Failed to load snapshot: ");
5009 goto out;
5013 drv = bdrv_find_format(out_fmt);
5014 if (!drv) {
5015 error_report("Unknown file format '%s'", out_fmt);
5016 goto out;
5018 if (!drv->create_opts) {
5019 error_report("Format driver '%s' does not support image creation",
5020 drv->format_name);
5021 goto out;
5024 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5025 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5026 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5027 if (options) {
5028 qemu_opts_do_parse(opts, options, NULL, &local_err);
5029 if (local_err) {
5030 error_report_err(local_err);
5031 error_report("Invalid options for file format '%s'", out_fmt);
5032 goto out;
5035 if (img_size != UINT64_MAX) {
5036 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5039 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5040 if (local_err) {
5041 error_report_err(local_err);
5042 goto out;
5045 if (output_format == OFORMAT_HUMAN) {
5046 printf("required size: %" PRIu64 "\n", info->required);
5047 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
5048 } else {
5049 dump_json_block_measure_info(info);
5052 ret = 0;
5054 out:
5055 qapi_free_BlockMeasureInfo(info);
5056 qemu_opts_del(object_opts);
5057 qemu_opts_del(opts);
5058 qemu_opts_del(sn_opts);
5059 qemu_opts_free(create_opts);
5060 g_free(options);
5061 blk_unref(in_blk);
5062 return ret;
5065 static const img_cmd_t img_cmds[] = {
5066 #define DEF(option, callback, arg_string) \
5067 { option, callback },
5068 #include "qemu-img-cmds.h"
5069 #undef DEF
5070 { NULL, NULL, },
5073 int main(int argc, char **argv)
5075 const img_cmd_t *cmd;
5076 const char *cmdname;
5077 Error *local_error = NULL;
5078 char *trace_file = NULL;
5079 int c;
5080 static const struct option long_options[] = {
5081 {"help", no_argument, 0, 'h'},
5082 {"version", no_argument, 0, 'V'},
5083 {"trace", required_argument, NULL, 'T'},
5084 {0, 0, 0, 0}
5087 #ifdef CONFIG_POSIX
5088 signal(SIGPIPE, SIG_IGN);
5089 #endif
5091 error_init(argv[0]);
5092 module_call_init(MODULE_INIT_TRACE);
5093 qemu_init_exec_dir(argv[0]);
5095 if (qemu_init_main_loop(&local_error)) {
5096 error_report_err(local_error);
5097 exit(EXIT_FAILURE);
5100 qcrypto_init(&error_fatal);
5102 module_call_init(MODULE_INIT_QOM);
5103 bdrv_init();
5104 if (argc < 2) {
5105 error_exit("Not enough arguments");
5108 qemu_add_opts(&qemu_object_opts);
5109 qemu_add_opts(&qemu_source_opts);
5110 qemu_add_opts(&qemu_trace_opts);
5112 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
5113 switch (c) {
5114 case ':':
5115 missing_argument(argv[optind - 1]);
5116 return 0;
5117 case '?':
5118 unrecognized_option(argv[optind - 1]);
5119 return 0;
5120 case 'h':
5121 help();
5122 return 0;
5123 case 'V':
5124 printf(QEMU_IMG_VERSION);
5125 return 0;
5126 case 'T':
5127 g_free(trace_file);
5128 trace_file = trace_opt_parse(optarg);
5129 break;
5133 cmdname = argv[optind];
5135 /* reset getopt_long scanning */
5136 argc -= optind;
5137 if (argc < 1) {
5138 return 0;
5140 argv += optind;
5141 qemu_reset_optind();
5143 if (!trace_init_backends()) {
5144 exit(1);
5146 trace_init_file(trace_file);
5147 qemu_set_log(LOG_TRACE);
5149 /* find the command */
5150 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5151 if (!strcmp(cmdname, cmd->name)) {
5152 return cmd->handler(argc, argv);
5156 /* not found */
5157 error_exit("Command not found: %s", cmdname);