qemu-img: Report bdrv_block_status failures
[qemu.git] / qemu-img.c
blob03a9a10dec145cf65b0f00b2cd5bd2209eb3c061
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-version.h"
29 #include "qapi/error.h"
30 #include "qapi/qapi-visit-block-core.h"
31 #include "qapi/qobject-output-visitor.h"
32 #include "qapi/qmp/qjson.h"
33 #include "qapi/qmp/qdict.h"
34 #include "qapi/qmp/qstring.h"
35 #include "qemu/cutils.h"
36 #include "qemu/config-file.h"
37 #include "qemu/option.h"
38 #include "qemu/error-report.h"
39 #include "qemu/log.h"
40 #include "qom/object_interfaces.h"
41 #include "sysemu/sysemu.h"
42 #include "sysemu/block-backend.h"
43 #include "block/block_int.h"
44 #include "block/blockjob.h"
45 #include "block/qapi.h"
46 #include "crypto/init.h"
47 #include "trace/control.h"
49 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
50 "\n" QEMU_COPYRIGHT "\n"
52 typedef struct img_cmd_t {
53 const char *name;
54 int (*handler)(int argc, char **argv);
55 } img_cmd_t;
57 enum {
58 OPTION_OUTPUT = 256,
59 OPTION_BACKING_CHAIN = 257,
60 OPTION_OBJECT = 258,
61 OPTION_IMAGE_OPTS = 259,
62 OPTION_PATTERN = 260,
63 OPTION_FLUSH_INTERVAL = 261,
64 OPTION_NO_DRAIN = 262,
65 OPTION_TARGET_IMAGE_OPTS = 263,
66 OPTION_SIZE = 264,
67 OPTION_PREALLOCATION = 265,
68 OPTION_SHRINK = 266,
71 typedef enum OutputFormat {
72 OFORMAT_JSON,
73 OFORMAT_HUMAN,
74 } OutputFormat;
76 /* Default to cache=writeback as data integrity is not important for qemu-img */
77 #define BDRV_DEFAULT_CACHE "writeback"
79 static void format_print(void *opaque, const char *name)
81 printf(" %s", name);
84 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
86 va_list ap;
88 error_printf("qemu-img: ");
90 va_start(ap, fmt);
91 error_vprintf(fmt, ap);
92 va_end(ap);
94 error_printf("\nTry 'qemu-img --help' for more information\n");
95 exit(EXIT_FAILURE);
98 static void QEMU_NORETURN missing_argument(const char *option)
100 error_exit("missing argument for option '%s'", option);
103 static void QEMU_NORETURN unrecognized_option(const char *option)
105 error_exit("unrecognized option '%s'", option);
108 /* Please keep in synch with qemu-img.texi */
109 static void QEMU_NORETURN help(void)
111 const char *help_msg =
112 QEMU_IMG_VERSION
113 "usage: qemu-img [standard options] command [command options]\n"
114 "QEMU disk image utility\n"
115 "\n"
116 " '-h', '--help' display this help and exit\n"
117 " '-V', '--version' output version information and exit\n"
118 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
119 " specify tracing options\n"
120 "\n"
121 "Command syntax:\n"
122 #define DEF(option, callback, arg_string) \
123 " " arg_string "\n"
124 #include "qemu-img-cmds.h"
125 #undef DEF
126 "\n"
127 "Command parameters:\n"
128 " 'filename' is a disk image filename\n"
129 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
130 " manual page for a description of the object properties. The most common\n"
131 " object type is a 'secret', which is used to supply passwords and/or\n"
132 " encryption keys.\n"
133 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
134 " 'cache' is the cache mode used to write the output disk image, the valid\n"
135 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
136 " 'directsync' and 'unsafe' (default for convert)\n"
137 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
138 " options are the same as for the 'cache' option\n"
139 " 'size' is the disk image size in bytes. Optional suffixes\n"
140 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
141 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
142 " supported. 'b' is ignored.\n"
143 " 'output_filename' is the destination disk image filename\n"
144 " 'output_fmt' is the destination format\n"
145 " 'options' is a comma separated list of format specific options in a\n"
146 " name=value format. Use -o ? for an overview of the options supported by the\n"
147 " used format\n"
148 " 'snapshot_param' is param used for internal snapshot, format\n"
149 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
150 " '[ID_OR_NAME]'\n"
151 " '-c' indicates that target image must be compressed (qcow format only)\n"
152 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
153 " new backing file match exactly. The image doesn't need a working\n"
154 " backing file before rebasing in this case (useful for renaming the\n"
155 " backing file). For image creation, allow creating without attempting\n"
156 " to open the backing file.\n"
157 " '-h' with or without a command shows this help and lists the supported formats\n"
158 " '-p' show progress of command (only certain commands)\n"
159 " '-q' use Quiet mode - do not print any output (except errors)\n"
160 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
161 " contain only zeros for qemu-img to create a sparse image during\n"
162 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
163 " unallocated or zero sectors, and the destination image will always be\n"
164 " fully allocated\n"
165 " '--output' takes the format in which the output must be done (human or json)\n"
166 " '-n' skips the target volume creation (useful if the volume is created\n"
167 " prior to running qemu-img)\n"
168 "\n"
169 "Parameters to check subcommand:\n"
170 " '-r' tries to repair any inconsistencies that are found during the check.\n"
171 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
172 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
173 " hiding corruption that has already occurred.\n"
174 "\n"
175 "Parameters to convert subcommand:\n"
176 " '-m' specifies how many coroutines work in parallel during the convert\n"
177 " process (defaults to 8)\n"
178 " '-W' allow to write to the target out of order rather than sequential\n"
179 "\n"
180 "Parameters to snapshot subcommand:\n"
181 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
182 " '-a' applies a snapshot (revert disk to saved state)\n"
183 " '-c' creates a snapshot\n"
184 " '-d' deletes a snapshot\n"
185 " '-l' lists all snapshots in the given image\n"
186 "\n"
187 "Parameters to compare subcommand:\n"
188 " '-f' first image format\n"
189 " '-F' second image format\n"
190 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
191 "\n"
192 "Parameters to dd subcommand:\n"
193 " 'bs=BYTES' read and write up to BYTES bytes at a time "
194 "(default: 512)\n"
195 " 'count=N' copy only N input blocks\n"
196 " 'if=FILE' read from FILE\n"
197 " 'of=FILE' write to FILE\n"
198 " 'skip=N' skip N bs-sized blocks at the start of input\n";
200 printf("%s\nSupported formats:", help_msg);
201 bdrv_iterate_format(format_print, NULL, false);
202 printf("\n\n" QEMU_HELP_BOTTOM "\n");
203 exit(EXIT_SUCCESS);
206 static QemuOptsList qemu_object_opts = {
207 .name = "object",
208 .implied_opt_name = "qom-type",
209 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
210 .desc = {
215 static QemuOptsList qemu_source_opts = {
216 .name = "source",
217 .implied_opt_name = "file",
218 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
219 .desc = {
224 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
226 int ret = 0;
227 if (!quiet) {
228 va_list args;
229 va_start(args, fmt);
230 ret = vprintf(fmt, args);
231 va_end(args);
233 return ret;
237 static int print_block_option_help(const char *filename, const char *fmt)
239 BlockDriver *drv, *proto_drv;
240 QemuOptsList *create_opts = NULL;
241 Error *local_err = NULL;
243 /* Find driver and parse its options */
244 drv = bdrv_find_format(fmt);
245 if (!drv) {
246 error_report("Unknown file format '%s'", fmt);
247 return 1;
250 if (!drv->create_opts) {
251 error_report("Format driver '%s' does not support image creation", fmt);
252 return 1;
255 create_opts = qemu_opts_append(create_opts, drv->create_opts);
256 if (filename) {
257 proto_drv = bdrv_find_protocol(filename, true, &local_err);
258 if (!proto_drv) {
259 error_report_err(local_err);
260 qemu_opts_free(create_opts);
261 return 1;
263 if (!proto_drv->create_opts) {
264 error_report("Protocol driver '%s' does not support image creation",
265 proto_drv->format_name);
266 qemu_opts_free(create_opts);
267 return 1;
269 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
272 printf("Supported options:\n");
273 qemu_opts_print_help(create_opts, false);
274 qemu_opts_free(create_opts);
275 return 0;
279 static BlockBackend *img_open_opts(const char *optstr,
280 QemuOpts *opts, int flags, bool writethrough,
281 bool quiet, bool force_share)
283 QDict *options;
284 Error *local_err = NULL;
285 BlockBackend *blk;
286 options = qemu_opts_to_qdict(opts, NULL);
287 if (force_share) {
288 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
289 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
290 error_report("--force-share/-U conflicts with image options");
291 qobject_unref(options);
292 return NULL;
294 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
296 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
297 if (!blk) {
298 error_reportf_err(local_err, "Could not open '%s': ", optstr);
299 return NULL;
301 blk_set_enable_write_cache(blk, !writethrough);
303 return blk;
306 static BlockBackend *img_open_file(const char *filename,
307 QDict *options,
308 const char *fmt, int flags,
309 bool writethrough, bool quiet,
310 bool force_share)
312 BlockBackend *blk;
313 Error *local_err = NULL;
315 if (!options) {
316 options = qdict_new();
318 if (fmt) {
319 qdict_put_str(options, "driver", fmt);
322 if (force_share) {
323 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
325 blk = blk_new_open(filename, NULL, options, flags, &local_err);
326 if (!blk) {
327 error_reportf_err(local_err, "Could not open '%s': ", filename);
328 return NULL;
330 blk_set_enable_write_cache(blk, !writethrough);
332 return blk;
336 static int img_add_key_secrets(void *opaque,
337 const char *name, const char *value,
338 Error **errp)
340 QDict *options = opaque;
342 if (g_str_has_suffix(name, "key-secret")) {
343 qdict_put_str(options, name, value);
346 return 0;
350 static BlockBackend *img_open(bool image_opts,
351 const char *filename,
352 const char *fmt, int flags, bool writethrough,
353 bool quiet, bool force_share)
355 BlockBackend *blk;
356 if (image_opts) {
357 QemuOpts *opts;
358 if (fmt) {
359 error_report("--image-opts and --format are mutually exclusive");
360 return NULL;
362 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
363 filename, true);
364 if (!opts) {
365 return NULL;
367 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
368 force_share);
369 } else {
370 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
371 force_share);
373 return blk;
377 static int add_old_style_options(const char *fmt, QemuOpts *opts,
378 const char *base_filename,
379 const char *base_fmt)
381 Error *err = NULL;
383 if (base_filename) {
384 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
385 if (err) {
386 error_report("Backing file not supported for file format '%s'",
387 fmt);
388 error_free(err);
389 return -1;
392 if (base_fmt) {
393 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
394 if (err) {
395 error_report("Backing file format not supported for file "
396 "format '%s'", fmt);
397 error_free(err);
398 return -1;
401 return 0;
404 static int64_t cvtnum(const char *s)
406 int err;
407 uint64_t value;
409 err = qemu_strtosz(s, NULL, &value);
410 if (err < 0) {
411 return err;
413 if (value > INT64_MAX) {
414 return -ERANGE;
416 return value;
419 static int img_create(int argc, char **argv)
421 int c;
422 uint64_t img_size = -1;
423 const char *fmt = "raw";
424 const char *base_fmt = NULL;
425 const char *filename;
426 const char *base_filename = NULL;
427 char *options = NULL;
428 Error *local_err = NULL;
429 bool quiet = false;
430 int flags = 0;
432 for(;;) {
433 static const struct option long_options[] = {
434 {"help", no_argument, 0, 'h'},
435 {"object", required_argument, 0, OPTION_OBJECT},
436 {0, 0, 0, 0}
438 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
439 long_options, NULL);
440 if (c == -1) {
441 break;
443 switch(c) {
444 case ':':
445 missing_argument(argv[optind - 1]);
446 break;
447 case '?':
448 unrecognized_option(argv[optind - 1]);
449 break;
450 case 'h':
451 help();
452 break;
453 case 'F':
454 base_fmt = optarg;
455 break;
456 case 'b':
457 base_filename = optarg;
458 break;
459 case 'f':
460 fmt = optarg;
461 break;
462 case 'o':
463 if (!is_valid_option_list(optarg)) {
464 error_report("Invalid option list: %s", optarg);
465 goto fail;
467 if (!options) {
468 options = g_strdup(optarg);
469 } else {
470 char *old_options = options;
471 options = g_strdup_printf("%s,%s", options, optarg);
472 g_free(old_options);
474 break;
475 case 'q':
476 quiet = true;
477 break;
478 case 'u':
479 flags |= BDRV_O_NO_BACKING;
480 break;
481 case OPTION_OBJECT: {
482 QemuOpts *opts;
483 opts = qemu_opts_parse_noisily(&qemu_object_opts,
484 optarg, true);
485 if (!opts) {
486 goto fail;
488 } break;
492 /* Get the filename */
493 filename = (optind < argc) ? argv[optind] : NULL;
494 if (options && has_help_option(options)) {
495 g_free(options);
496 return print_block_option_help(filename, fmt);
499 if (optind >= argc) {
500 error_exit("Expecting image file name");
502 optind++;
504 if (qemu_opts_foreach(&qemu_object_opts,
505 user_creatable_add_opts_foreach,
506 NULL, &error_fatal)) {
507 goto fail;
510 /* Get image size, if specified */
511 if (optind < argc) {
512 int64_t sval;
514 sval = cvtnum(argv[optind++]);
515 if (sval < 0) {
516 if (sval == -ERANGE) {
517 error_report("Image size must be less than 8 EiB!");
518 } else {
519 error_report("Invalid image size specified! You may use k, M, "
520 "G, T, P or E suffixes for ");
521 error_report("kilobytes, megabytes, gigabytes, terabytes, "
522 "petabytes and exabytes.");
524 goto fail;
526 img_size = (uint64_t)sval;
528 if (optind != argc) {
529 error_exit("Unexpected argument: %s", argv[optind]);
532 bdrv_img_create(filename, fmt, base_filename, base_fmt,
533 options, img_size, flags, quiet, &local_err);
534 if (local_err) {
535 error_reportf_err(local_err, "%s: ", filename);
536 goto fail;
539 g_free(options);
540 return 0;
542 fail:
543 g_free(options);
544 return 1;
547 static void dump_json_image_check(ImageCheck *check, bool quiet)
549 QString *str;
550 QObject *obj;
551 Visitor *v = qobject_output_visitor_new(&obj);
553 visit_type_ImageCheck(v, NULL, &check, &error_abort);
554 visit_complete(v, &obj);
555 str = qobject_to_json_pretty(obj);
556 assert(str != NULL);
557 qprintf(quiet, "%s\n", qstring_get_str(str));
558 qobject_unref(obj);
559 visit_free(v);
560 qobject_unref(str);
563 static void dump_human_image_check(ImageCheck *check, bool quiet)
565 if (!(check->corruptions || check->leaks || check->check_errors)) {
566 qprintf(quiet, "No errors were found on the image.\n");
567 } else {
568 if (check->corruptions) {
569 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
570 "Data may be corrupted, or further writes to the image "
571 "may corrupt it.\n",
572 check->corruptions);
575 if (check->leaks) {
576 qprintf(quiet,
577 "\n%" PRId64 " leaked clusters were found on the image.\n"
578 "This means waste of disk space, but no harm to data.\n",
579 check->leaks);
582 if (check->check_errors) {
583 qprintf(quiet,
584 "\n%" PRId64
585 " internal errors have occurred during the check.\n",
586 check->check_errors);
590 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
591 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
592 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
593 check->allocated_clusters, check->total_clusters,
594 check->allocated_clusters * 100.0 / check->total_clusters,
595 check->fragmented_clusters * 100.0 / check->allocated_clusters,
596 check->compressed_clusters * 100.0 /
597 check->allocated_clusters);
600 if (check->image_end_offset) {
601 qprintf(quiet,
602 "Image end offset: %" PRId64 "\n", check->image_end_offset);
606 static int collect_image_check(BlockDriverState *bs,
607 ImageCheck *check,
608 const char *filename,
609 const char *fmt,
610 int fix)
612 int ret;
613 BdrvCheckResult result;
615 ret = bdrv_check(bs, &result, fix);
616 if (ret < 0) {
617 return ret;
620 check->filename = g_strdup(filename);
621 check->format = g_strdup(bdrv_get_format_name(bs));
622 check->check_errors = result.check_errors;
623 check->corruptions = result.corruptions;
624 check->has_corruptions = result.corruptions != 0;
625 check->leaks = result.leaks;
626 check->has_leaks = result.leaks != 0;
627 check->corruptions_fixed = result.corruptions_fixed;
628 check->has_corruptions_fixed = result.corruptions != 0;
629 check->leaks_fixed = result.leaks_fixed;
630 check->has_leaks_fixed = result.leaks != 0;
631 check->image_end_offset = result.image_end_offset;
632 check->has_image_end_offset = result.image_end_offset != 0;
633 check->total_clusters = result.bfi.total_clusters;
634 check->has_total_clusters = result.bfi.total_clusters != 0;
635 check->allocated_clusters = result.bfi.allocated_clusters;
636 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
637 check->fragmented_clusters = result.bfi.fragmented_clusters;
638 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
639 check->compressed_clusters = result.bfi.compressed_clusters;
640 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
642 return 0;
646 * Checks an image for consistency. Exit codes:
648 * 0 - Check completed, image is good
649 * 1 - Check not completed because of internal errors
650 * 2 - Check completed, image is corrupted
651 * 3 - Check completed, image has leaked clusters, but is good otherwise
652 * 63 - Checks are not supported by the image format
654 static int img_check(int argc, char **argv)
656 int c, ret;
657 OutputFormat output_format = OFORMAT_HUMAN;
658 const char *filename, *fmt, *output, *cache;
659 BlockBackend *blk;
660 BlockDriverState *bs;
661 int fix = 0;
662 int flags = BDRV_O_CHECK;
663 bool writethrough;
664 ImageCheck *check;
665 bool quiet = false;
666 bool image_opts = false;
667 bool force_share = false;
669 fmt = NULL;
670 output = NULL;
671 cache = BDRV_DEFAULT_CACHE;
673 for(;;) {
674 int option_index = 0;
675 static const struct option long_options[] = {
676 {"help", no_argument, 0, 'h'},
677 {"format", required_argument, 0, 'f'},
678 {"repair", required_argument, 0, 'r'},
679 {"output", required_argument, 0, OPTION_OUTPUT},
680 {"object", required_argument, 0, OPTION_OBJECT},
681 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
682 {"force-share", no_argument, 0, 'U'},
683 {0, 0, 0, 0}
685 c = getopt_long(argc, argv, ":hf:r:T:qU",
686 long_options, &option_index);
687 if (c == -1) {
688 break;
690 switch(c) {
691 case ':':
692 missing_argument(argv[optind - 1]);
693 break;
694 case '?':
695 unrecognized_option(argv[optind - 1]);
696 break;
697 case 'h':
698 help();
699 break;
700 case 'f':
701 fmt = optarg;
702 break;
703 case 'r':
704 flags |= BDRV_O_RDWR;
706 if (!strcmp(optarg, "leaks")) {
707 fix = BDRV_FIX_LEAKS;
708 } else if (!strcmp(optarg, "all")) {
709 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
710 } else {
711 error_exit("Unknown option value for -r "
712 "(expecting 'leaks' or 'all'): %s", optarg);
714 break;
715 case OPTION_OUTPUT:
716 output = optarg;
717 break;
718 case 'T':
719 cache = optarg;
720 break;
721 case 'q':
722 quiet = true;
723 break;
724 case 'U':
725 force_share = true;
726 break;
727 case OPTION_OBJECT: {
728 QemuOpts *opts;
729 opts = qemu_opts_parse_noisily(&qemu_object_opts,
730 optarg, true);
731 if (!opts) {
732 return 1;
734 } break;
735 case OPTION_IMAGE_OPTS:
736 image_opts = true;
737 break;
740 if (optind != argc - 1) {
741 error_exit("Expecting one image file name");
743 filename = argv[optind++];
745 if (output && !strcmp(output, "json")) {
746 output_format = OFORMAT_JSON;
747 } else if (output && !strcmp(output, "human")) {
748 output_format = OFORMAT_HUMAN;
749 } else if (output) {
750 error_report("--output must be used with human or json as argument.");
751 return 1;
754 if (qemu_opts_foreach(&qemu_object_opts,
755 user_creatable_add_opts_foreach,
756 NULL, &error_fatal)) {
757 return 1;
760 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
761 if (ret < 0) {
762 error_report("Invalid source cache option: %s", cache);
763 return 1;
766 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
767 force_share);
768 if (!blk) {
769 return 1;
771 bs = blk_bs(blk);
773 check = g_new0(ImageCheck, 1);
774 ret = collect_image_check(bs, check, filename, fmt, fix);
776 if (ret == -ENOTSUP) {
777 error_report("This image format does not support checks");
778 ret = 63;
779 goto fail;
782 if (check->corruptions_fixed || check->leaks_fixed) {
783 int corruptions_fixed, leaks_fixed;
785 leaks_fixed = check->leaks_fixed;
786 corruptions_fixed = check->corruptions_fixed;
788 if (output_format == OFORMAT_HUMAN) {
789 qprintf(quiet,
790 "The following inconsistencies were found and repaired:\n\n"
791 " %" PRId64 " leaked clusters\n"
792 " %" PRId64 " corruptions\n\n"
793 "Double checking the fixed image now...\n",
794 check->leaks_fixed,
795 check->corruptions_fixed);
798 ret = collect_image_check(bs, check, filename, fmt, 0);
800 check->leaks_fixed = leaks_fixed;
801 check->corruptions_fixed = corruptions_fixed;
804 if (!ret) {
805 switch (output_format) {
806 case OFORMAT_HUMAN:
807 dump_human_image_check(check, quiet);
808 break;
809 case OFORMAT_JSON:
810 dump_json_image_check(check, quiet);
811 break;
815 if (ret || check->check_errors) {
816 if (ret) {
817 error_report("Check failed: %s", strerror(-ret));
818 } else {
819 error_report("Check failed");
821 ret = 1;
822 goto fail;
825 if (check->corruptions) {
826 ret = 2;
827 } else if (check->leaks) {
828 ret = 3;
829 } else {
830 ret = 0;
833 fail:
834 qapi_free_ImageCheck(check);
835 blk_unref(blk);
836 return ret;
839 typedef struct CommonBlockJobCBInfo {
840 BlockDriverState *bs;
841 Error **errp;
842 } CommonBlockJobCBInfo;
844 static void common_block_job_cb(void *opaque, int ret)
846 CommonBlockJobCBInfo *cbi = opaque;
848 if (ret < 0) {
849 error_setg_errno(cbi->errp, -ret, "Block job failed");
853 static void run_block_job(BlockJob *job, Error **errp)
855 AioContext *aio_context = blk_get_aio_context(job->blk);
856 int ret = 0;
858 aio_context_acquire(aio_context);
859 job_ref(&job->job);
860 do {
861 float progress = 0.0f;
862 aio_poll(aio_context, true);
863 if (job->job.progress_total) {
864 progress = (float)job->job.progress_current /
865 job->job.progress_total * 100.f;
867 qemu_progress_print(progress, 0);
868 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
870 if (!job_is_completed(&job->job)) {
871 ret = job_complete_sync(&job->job, errp);
872 } else {
873 ret = job->job.ret;
875 job_unref(&job->job);
876 aio_context_release(aio_context);
878 /* publish completion progress only when success */
879 if (!ret) {
880 qemu_progress_print(100.f, 0);
884 static int img_commit(int argc, char **argv)
886 int c, ret, flags;
887 const char *filename, *fmt, *cache, *base;
888 BlockBackend *blk;
889 BlockDriverState *bs, *base_bs;
890 BlockJob *job;
891 bool progress = false, quiet = false, drop = false;
892 bool writethrough;
893 Error *local_err = NULL;
894 CommonBlockJobCBInfo cbi;
895 bool image_opts = false;
896 AioContext *aio_context;
898 fmt = NULL;
899 cache = BDRV_DEFAULT_CACHE;
900 base = NULL;
901 for(;;) {
902 static const struct option long_options[] = {
903 {"help", no_argument, 0, 'h'},
904 {"object", required_argument, 0, OPTION_OBJECT},
905 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
906 {0, 0, 0, 0}
908 c = getopt_long(argc, argv, ":f:ht:b:dpq",
909 long_options, NULL);
910 if (c == -1) {
911 break;
913 switch(c) {
914 case ':':
915 missing_argument(argv[optind - 1]);
916 break;
917 case '?':
918 unrecognized_option(argv[optind - 1]);
919 break;
920 case 'h':
921 help();
922 break;
923 case 'f':
924 fmt = optarg;
925 break;
926 case 't':
927 cache = optarg;
928 break;
929 case 'b':
930 base = optarg;
931 /* -b implies -d */
932 drop = true;
933 break;
934 case 'd':
935 drop = true;
936 break;
937 case 'p':
938 progress = true;
939 break;
940 case 'q':
941 quiet = true;
942 break;
943 case OPTION_OBJECT: {
944 QemuOpts *opts;
945 opts = qemu_opts_parse_noisily(&qemu_object_opts,
946 optarg, true);
947 if (!opts) {
948 return 1;
950 } break;
951 case OPTION_IMAGE_OPTS:
952 image_opts = true;
953 break;
957 /* Progress is not shown in Quiet mode */
958 if (quiet) {
959 progress = false;
962 if (optind != argc - 1) {
963 error_exit("Expecting one image file name");
965 filename = argv[optind++];
967 if (qemu_opts_foreach(&qemu_object_opts,
968 user_creatable_add_opts_foreach,
969 NULL, &error_fatal)) {
970 return 1;
973 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
974 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
975 if (ret < 0) {
976 error_report("Invalid cache option: %s", cache);
977 return 1;
980 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
981 false);
982 if (!blk) {
983 return 1;
985 bs = blk_bs(blk);
987 qemu_progress_init(progress, 1.f);
988 qemu_progress_print(0.f, 100);
990 if (base) {
991 base_bs = bdrv_find_backing_image(bs, base);
992 if (!base_bs) {
993 error_setg(&local_err,
994 "Did not find '%s' in the backing chain of '%s'",
995 base, filename);
996 goto done;
998 } else {
999 /* This is different from QMP, which by default uses the deepest file in
1000 * the backing chain (i.e., the very base); however, the traditional
1001 * behavior of qemu-img commit is using the immediate backing file. */
1002 base_bs = backing_bs(bs);
1003 if (!base_bs) {
1004 error_setg(&local_err, "Image does not have a backing file");
1005 goto done;
1009 cbi = (CommonBlockJobCBInfo){
1010 .errp = &local_err,
1011 .bs = bs,
1014 aio_context = bdrv_get_aio_context(bs);
1015 aio_context_acquire(aio_context);
1016 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
1017 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1018 &cbi, false, &local_err);
1019 aio_context_release(aio_context);
1020 if (local_err) {
1021 goto done;
1024 /* When the block job completes, the BlockBackend reference will point to
1025 * the old backing file. In order to avoid that the top image is already
1026 * deleted, so we can still empty it afterwards, increment the reference
1027 * counter here preemptively. */
1028 if (!drop) {
1029 bdrv_ref(bs);
1032 job = block_job_get("commit");
1033 assert(job);
1034 run_block_job(job, &local_err);
1035 if (local_err) {
1036 goto unref_backing;
1039 if (!drop && bs->drv->bdrv_make_empty) {
1040 ret = bs->drv->bdrv_make_empty(bs);
1041 if (ret) {
1042 error_setg_errno(&local_err, -ret, "Could not empty %s",
1043 filename);
1044 goto unref_backing;
1048 unref_backing:
1049 if (!drop) {
1050 bdrv_unref(bs);
1053 done:
1054 qemu_progress_end();
1056 blk_unref(blk);
1058 if (local_err) {
1059 error_report_err(local_err);
1060 return 1;
1063 qprintf(quiet, "Image committed.\n");
1064 return 0;
1068 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1069 * of the first sector boundary within buf where the sector contains a
1070 * non-zero byte. This function is robust to a buffer that is not
1071 * sector-aligned.
1073 static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1075 int64_t i;
1076 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1078 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1079 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1080 return i;
1083 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1084 return i;
1086 return -1;
1090 * Returns true iff the first sector pointed to by 'buf' contains at least
1091 * a non-NUL byte.
1093 * 'pnum' is set to the number of sectors (including and immediately following
1094 * the first one) that are known to be in the same allocated/unallocated state.
1095 * The function will try to align the end offset to alignment boundaries so
1096 * that the request will at least end aligned and consequtive requests will
1097 * also start at an aligned offset.
1099 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1100 int64_t sector_num, int alignment)
1102 bool is_zero;
1103 int i, tail;
1105 if (n <= 0) {
1106 *pnum = 0;
1107 return 0;
1109 is_zero = buffer_is_zero(buf, 512);
1110 for(i = 1; i < n; i++) {
1111 buf += 512;
1112 if (is_zero != buffer_is_zero(buf, 512)) {
1113 break;
1117 tail = (sector_num + i) & (alignment - 1);
1118 if (tail) {
1119 if (is_zero && i <= tail) {
1120 /* treat unallocated areas which only consist
1121 * of a small tail as allocated. */
1122 is_zero = false;
1124 if (!is_zero) {
1125 /* align up end offset of allocated areas. */
1126 i += alignment - tail;
1127 i = MIN(i, n);
1128 } else {
1129 /* align down end offset of zero areas. */
1130 i -= tail;
1133 *pnum = i;
1134 return !is_zero;
1138 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1139 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1140 * breaking up write requests for only small sparse areas.
1142 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1143 int min, int64_t sector_num, int alignment)
1145 int ret;
1146 int num_checked, num_used;
1148 if (n < min) {
1149 min = n;
1152 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1153 if (!ret) {
1154 return ret;
1157 num_used = *pnum;
1158 buf += BDRV_SECTOR_SIZE * *pnum;
1159 n -= *pnum;
1160 sector_num += *pnum;
1161 num_checked = num_used;
1163 while (n > 0) {
1164 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1166 buf += BDRV_SECTOR_SIZE * *pnum;
1167 n -= *pnum;
1168 sector_num += *pnum;
1169 num_checked += *pnum;
1170 if (ret) {
1171 num_used = num_checked;
1172 } else if (*pnum >= min) {
1173 break;
1177 *pnum = num_used;
1178 return 1;
1182 * Compares two buffers sector by sector. Returns 0 if the first
1183 * sector of each buffer matches, non-zero otherwise.
1185 * pnum is set to the sector-aligned size of the buffer prefix that
1186 * has the same matching status as the first sector.
1188 static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1189 int64_t bytes, int64_t *pnum)
1191 bool res;
1192 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
1194 assert(bytes > 0);
1196 res = !!memcmp(buf1, buf2, i);
1197 while (i < bytes) {
1198 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
1200 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
1201 break;
1203 i += len;
1206 *pnum = i;
1207 return res;
1210 #define IO_BUF_SIZE (2 * 1024 * 1024)
1213 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1215 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1216 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1217 * failure), and 4 on error (the exit status for read errors), after emitting
1218 * an error message.
1220 * @param blk: BlockBackend for the image
1221 * @param offset: Starting offset to check
1222 * @param bytes: Number of bytes to check
1223 * @param filename: Name of disk file we are checking (logging purpose)
1224 * @param buffer: Allocated buffer for storing read data
1225 * @param quiet: Flag for quiet mode
1227 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1228 int64_t bytes, const char *filename,
1229 uint8_t *buffer, bool quiet)
1231 int ret = 0;
1232 int64_t idx;
1234 ret = blk_pread(blk, offset, buffer, bytes);
1235 if (ret < 0) {
1236 error_report("Error while reading offset %" PRId64 " of %s: %s",
1237 offset, filename, strerror(-ret));
1238 return 4;
1240 idx = find_nonzero(buffer, bytes);
1241 if (idx >= 0) {
1242 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1243 offset + idx);
1244 return 1;
1247 return 0;
1251 * Compares two images. Exit codes:
1253 * 0 - Images are identical
1254 * 1 - Images differ
1255 * >1 - Error occurred
1257 static int img_compare(int argc, char **argv)
1259 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1260 BlockBackend *blk1, *blk2;
1261 BlockDriverState *bs1, *bs2;
1262 int64_t total_size1, total_size2;
1263 uint8_t *buf1 = NULL, *buf2 = NULL;
1264 int64_t pnum1, pnum2;
1265 int allocated1, allocated2;
1266 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1267 bool progress = false, quiet = false, strict = false;
1268 int flags;
1269 bool writethrough;
1270 int64_t total_size;
1271 int64_t offset = 0;
1272 int64_t chunk;
1273 int c;
1274 uint64_t progress_base;
1275 bool image_opts = false;
1276 bool force_share = false;
1278 cache = BDRV_DEFAULT_CACHE;
1279 for (;;) {
1280 static const struct option long_options[] = {
1281 {"help", no_argument, 0, 'h'},
1282 {"object", required_argument, 0, OPTION_OBJECT},
1283 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1284 {"force-share", no_argument, 0, 'U'},
1285 {0, 0, 0, 0}
1287 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1288 long_options, NULL);
1289 if (c == -1) {
1290 break;
1292 switch (c) {
1293 case ':':
1294 missing_argument(argv[optind - 1]);
1295 break;
1296 case '?':
1297 unrecognized_option(argv[optind - 1]);
1298 break;
1299 case 'h':
1300 help();
1301 break;
1302 case 'f':
1303 fmt1 = optarg;
1304 break;
1305 case 'F':
1306 fmt2 = optarg;
1307 break;
1308 case 'T':
1309 cache = optarg;
1310 break;
1311 case 'p':
1312 progress = true;
1313 break;
1314 case 'q':
1315 quiet = true;
1316 break;
1317 case 's':
1318 strict = true;
1319 break;
1320 case 'U':
1321 force_share = true;
1322 break;
1323 case OPTION_OBJECT: {
1324 QemuOpts *opts;
1325 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1326 optarg, true);
1327 if (!opts) {
1328 ret = 2;
1329 goto out4;
1331 } break;
1332 case OPTION_IMAGE_OPTS:
1333 image_opts = true;
1334 break;
1338 /* Progress is not shown in Quiet mode */
1339 if (quiet) {
1340 progress = false;
1344 if (optind != argc - 2) {
1345 error_exit("Expecting two image file names");
1347 filename1 = argv[optind++];
1348 filename2 = argv[optind++];
1350 if (qemu_opts_foreach(&qemu_object_opts,
1351 user_creatable_add_opts_foreach,
1352 NULL, &error_fatal)) {
1353 ret = 2;
1354 goto out4;
1357 /* Initialize before goto out */
1358 qemu_progress_init(progress, 2.0);
1360 flags = 0;
1361 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1362 if (ret < 0) {
1363 error_report("Invalid source cache option: %s", cache);
1364 ret = 2;
1365 goto out3;
1368 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1369 force_share);
1370 if (!blk1) {
1371 ret = 2;
1372 goto out3;
1375 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1376 force_share);
1377 if (!blk2) {
1378 ret = 2;
1379 goto out2;
1381 bs1 = blk_bs(blk1);
1382 bs2 = blk_bs(blk2);
1384 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1385 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1386 total_size1 = blk_getlength(blk1);
1387 if (total_size1 < 0) {
1388 error_report("Can't get size of %s: %s",
1389 filename1, strerror(-total_size1));
1390 ret = 4;
1391 goto out;
1393 total_size2 = blk_getlength(blk2);
1394 if (total_size2 < 0) {
1395 error_report("Can't get size of %s: %s",
1396 filename2, strerror(-total_size2));
1397 ret = 4;
1398 goto out;
1400 total_size = MIN(total_size1, total_size2);
1401 progress_base = MAX(total_size1, total_size2);
1403 qemu_progress_print(0, 100);
1405 if (strict && total_size1 != total_size2) {
1406 ret = 1;
1407 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1408 goto out;
1411 while (offset < total_size) {
1412 int status1, status2;
1414 status1 = bdrv_block_status_above(bs1, NULL, offset,
1415 total_size1 - offset, &pnum1, NULL,
1416 NULL);
1417 if (status1 < 0) {
1418 ret = 3;
1419 error_report("Sector allocation test failed for %s", filename1);
1420 goto out;
1422 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1424 status2 = bdrv_block_status_above(bs2, NULL, offset,
1425 total_size2 - offset, &pnum2, NULL,
1426 NULL);
1427 if (status2 < 0) {
1428 ret = 3;
1429 error_report("Sector allocation test failed for %s", filename2);
1430 goto out;
1432 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1434 assert(pnum1 && pnum2);
1435 chunk = MIN(pnum1, pnum2);
1437 if (strict) {
1438 if (status1 != status2) {
1439 ret = 1;
1440 qprintf(quiet, "Strict mode: Offset %" PRId64
1441 " block status mismatch!\n", offset);
1442 goto out;
1445 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1446 /* nothing to do */
1447 } else if (allocated1 == allocated2) {
1448 if (allocated1) {
1449 int64_t pnum;
1451 chunk = MIN(chunk, IO_BUF_SIZE);
1452 ret = blk_pread(blk1, offset, buf1, chunk);
1453 if (ret < 0) {
1454 error_report("Error while reading offset %" PRId64
1455 " of %s: %s",
1456 offset, filename1, strerror(-ret));
1457 ret = 4;
1458 goto out;
1460 ret = blk_pread(blk2, offset, buf2, chunk);
1461 if (ret < 0) {
1462 error_report("Error while reading offset %" PRId64
1463 " of %s: %s",
1464 offset, filename2, strerror(-ret));
1465 ret = 4;
1466 goto out;
1468 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1469 if (ret || pnum != chunk) {
1470 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1471 offset + (ret ? 0 : pnum));
1472 ret = 1;
1473 goto out;
1476 } else {
1477 chunk = MIN(chunk, IO_BUF_SIZE);
1478 if (allocated1) {
1479 ret = check_empty_sectors(blk1, offset, chunk,
1480 filename1, buf1, quiet);
1481 } else {
1482 ret = check_empty_sectors(blk2, offset, chunk,
1483 filename2, buf1, quiet);
1485 if (ret) {
1486 goto out;
1489 offset += chunk;
1490 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1493 if (total_size1 != total_size2) {
1494 BlockBackend *blk_over;
1495 const char *filename_over;
1497 qprintf(quiet, "Warning: Image size mismatch!\n");
1498 if (total_size1 > total_size2) {
1499 blk_over = blk1;
1500 filename_over = filename1;
1501 } else {
1502 blk_over = blk2;
1503 filename_over = filename2;
1506 while (offset < progress_base) {
1507 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1508 progress_base - offset, &chunk,
1509 NULL, NULL);
1510 if (ret < 0) {
1511 ret = 3;
1512 error_report("Sector allocation test failed for %s",
1513 filename_over);
1514 goto out;
1517 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1518 chunk = MIN(chunk, IO_BUF_SIZE);
1519 ret = check_empty_sectors(blk_over, offset, chunk,
1520 filename_over, buf1, quiet);
1521 if (ret) {
1522 goto out;
1525 offset += chunk;
1526 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1530 qprintf(quiet, "Images are identical.\n");
1531 ret = 0;
1533 out:
1534 qemu_vfree(buf1);
1535 qemu_vfree(buf2);
1536 blk_unref(blk2);
1537 out2:
1538 blk_unref(blk1);
1539 out3:
1540 qemu_progress_end();
1541 out4:
1542 return ret;
1545 enum ImgConvertBlockStatus {
1546 BLK_DATA,
1547 BLK_ZERO,
1548 BLK_BACKING_FILE,
1551 #define MAX_COROUTINES 16
1553 typedef struct ImgConvertState {
1554 BlockBackend **src;
1555 int64_t *src_sectors;
1556 int src_num;
1557 int64_t total_sectors;
1558 int64_t allocated_sectors;
1559 int64_t allocated_done;
1560 int64_t sector_num;
1561 int64_t wr_offs;
1562 enum ImgConvertBlockStatus status;
1563 int64_t sector_next_status;
1564 BlockBackend *target;
1565 bool has_zero_init;
1566 bool compressed;
1567 bool unallocated_blocks_are_zero;
1568 bool target_has_backing;
1569 int64_t target_backing_sectors; /* negative if unknown */
1570 bool wr_in_order;
1571 bool copy_range;
1572 int min_sparse;
1573 int alignment;
1574 size_t cluster_sectors;
1575 size_t buf_sectors;
1576 long num_coroutines;
1577 int running_coroutines;
1578 Coroutine *co[MAX_COROUTINES];
1579 int64_t wait_sector_num[MAX_COROUTINES];
1580 CoMutex lock;
1581 int ret;
1582 } ImgConvertState;
1584 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1585 int *src_cur, int64_t *src_cur_offset)
1587 *src_cur = 0;
1588 *src_cur_offset = 0;
1589 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1590 *src_cur_offset += s->src_sectors[*src_cur];
1591 (*src_cur)++;
1592 assert(*src_cur < s->src_num);
1596 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1598 int64_t src_cur_offset;
1599 int ret, n, src_cur;
1600 bool post_backing_zero = false;
1602 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1604 assert(s->total_sectors > sector_num);
1605 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1607 if (s->target_backing_sectors >= 0) {
1608 if (sector_num >= s->target_backing_sectors) {
1609 post_backing_zero = s->unallocated_blocks_are_zero;
1610 } else if (sector_num + n > s->target_backing_sectors) {
1611 /* Split requests around target_backing_sectors (because
1612 * starting from there, zeros are handled differently) */
1613 n = s->target_backing_sectors - sector_num;
1617 if (s->sector_next_status <= sector_num) {
1618 int64_t count = n * BDRV_SECTOR_SIZE;
1620 if (s->target_has_backing) {
1622 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1623 (sector_num - src_cur_offset) *
1624 BDRV_SECTOR_SIZE,
1625 count, &count, NULL, NULL);
1626 } else {
1627 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1628 (sector_num - src_cur_offset) *
1629 BDRV_SECTOR_SIZE,
1630 count, &count, NULL, NULL);
1632 if (ret < 0) {
1633 error_report("error while reading block status of sector %" PRId64
1634 ": %s", sector_num, strerror(-ret));
1635 return ret;
1637 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1639 if (ret & BDRV_BLOCK_ZERO) {
1640 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
1641 } else if (ret & BDRV_BLOCK_DATA) {
1642 s->status = BLK_DATA;
1643 } else {
1644 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1647 s->sector_next_status = sector_num + n;
1650 n = MIN(n, s->sector_next_status - sector_num);
1651 if (s->status == BLK_DATA) {
1652 n = MIN(n, s->buf_sectors);
1655 /* We need to write complete clusters for compressed images, so if an
1656 * unallocated area is shorter than that, we must consider the whole
1657 * cluster allocated. */
1658 if (s->compressed) {
1659 if (n < s->cluster_sectors) {
1660 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1661 s->status = BLK_DATA;
1662 } else {
1663 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1667 return n;
1670 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1671 int nb_sectors, uint8_t *buf)
1673 int n, ret;
1674 QEMUIOVector qiov;
1676 assert(nb_sectors <= s->buf_sectors);
1677 while (nb_sectors > 0) {
1678 BlockBackend *blk;
1679 int src_cur;
1680 int64_t bs_sectors, src_cur_offset;
1682 /* In the case of compression with multiple source files, we can get a
1683 * nb_sectors that spreads into the next part. So we must be able to
1684 * read across multiple BDSes for one convert_read() call. */
1685 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1686 blk = s->src[src_cur];
1687 bs_sectors = s->src_sectors[src_cur];
1689 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1690 qemu_iovec_init_buf(&qiov, buf, n << BDRV_SECTOR_BITS);
1692 ret = blk_co_preadv(
1693 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1694 n << BDRV_SECTOR_BITS, &qiov, 0);
1695 if (ret < 0) {
1696 return ret;
1699 sector_num += n;
1700 nb_sectors -= n;
1701 buf += n * BDRV_SECTOR_SIZE;
1704 return 0;
1708 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1709 int nb_sectors, uint8_t *buf,
1710 enum ImgConvertBlockStatus status)
1712 int ret;
1713 QEMUIOVector qiov;
1715 while (nb_sectors > 0) {
1716 int n = nb_sectors;
1717 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1719 switch (status) {
1720 case BLK_BACKING_FILE:
1721 /* If we have a backing file, leave clusters unallocated that are
1722 * unallocated in the source image, so that the backing file is
1723 * visible at the respective offset. */
1724 assert(s->target_has_backing);
1725 break;
1727 case BLK_DATA:
1728 /* If we're told to keep the target fully allocated (-S 0) or there
1729 * is real non-zero data, we must write it. Otherwise we can treat
1730 * it as zero sectors.
1731 * Compressed clusters need to be written as a whole, so in that
1732 * case we can only save the write if the buffer is completely
1733 * zeroed. */
1734 if (!s->min_sparse ||
1735 (!s->compressed &&
1736 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1737 sector_num, s->alignment)) ||
1738 (s->compressed &&
1739 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1741 qemu_iovec_init_buf(&qiov, buf, n << BDRV_SECTOR_BITS);
1743 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
1744 n << BDRV_SECTOR_BITS, &qiov, flags);
1745 if (ret < 0) {
1746 return ret;
1748 break;
1750 /* fall-through */
1752 case BLK_ZERO:
1753 if (s->has_zero_init) {
1754 assert(!s->target_has_backing);
1755 break;
1757 ret = blk_co_pwrite_zeroes(s->target,
1758 sector_num << BDRV_SECTOR_BITS,
1759 n << BDRV_SECTOR_BITS, 0);
1760 if (ret < 0) {
1761 return ret;
1763 break;
1766 sector_num += n;
1767 nb_sectors -= n;
1768 buf += n * BDRV_SECTOR_SIZE;
1771 return 0;
1774 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1775 int nb_sectors)
1777 int n, ret;
1779 while (nb_sectors > 0) {
1780 BlockBackend *blk;
1781 int src_cur;
1782 int64_t bs_sectors, src_cur_offset;
1783 int64_t offset;
1785 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1786 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1787 blk = s->src[src_cur];
1788 bs_sectors = s->src_sectors[src_cur];
1790 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1792 ret = blk_co_copy_range(blk, offset, s->target,
1793 sector_num << BDRV_SECTOR_BITS,
1794 n << BDRV_SECTOR_BITS, 0, 0);
1795 if (ret < 0) {
1796 return ret;
1799 sector_num += n;
1800 nb_sectors -= n;
1802 return 0;
1805 static void coroutine_fn convert_co_do_copy(void *opaque)
1807 ImgConvertState *s = opaque;
1808 uint8_t *buf = NULL;
1809 int ret, i;
1810 int index = -1;
1812 for (i = 0; i < s->num_coroutines; i++) {
1813 if (s->co[i] == qemu_coroutine_self()) {
1814 index = i;
1815 break;
1818 assert(index >= 0);
1820 s->running_coroutines++;
1821 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1823 while (1) {
1824 int n;
1825 int64_t sector_num;
1826 enum ImgConvertBlockStatus status;
1827 bool copy_range;
1829 qemu_co_mutex_lock(&s->lock);
1830 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1831 qemu_co_mutex_unlock(&s->lock);
1832 break;
1834 n = convert_iteration_sectors(s, s->sector_num);
1835 if (n < 0) {
1836 qemu_co_mutex_unlock(&s->lock);
1837 s->ret = n;
1838 break;
1840 /* save current sector and allocation status to local variables */
1841 sector_num = s->sector_num;
1842 status = s->status;
1843 if (!s->min_sparse && s->status == BLK_ZERO) {
1844 n = MIN(n, s->buf_sectors);
1846 /* increment global sector counter so that other coroutines can
1847 * already continue reading beyond this request */
1848 s->sector_num += n;
1849 qemu_co_mutex_unlock(&s->lock);
1851 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1852 s->allocated_done += n;
1853 qemu_progress_print(100.0 * s->allocated_done /
1854 s->allocated_sectors, 0);
1857 retry:
1858 copy_range = s->copy_range && s->status == BLK_DATA;
1859 if (status == BLK_DATA && !copy_range) {
1860 ret = convert_co_read(s, sector_num, n, buf);
1861 if (ret < 0) {
1862 error_report("error while reading sector %" PRId64
1863 ": %s", sector_num, strerror(-ret));
1864 s->ret = ret;
1866 } else if (!s->min_sparse && status == BLK_ZERO) {
1867 status = BLK_DATA;
1868 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1871 if (s->wr_in_order) {
1872 /* keep writes in order */
1873 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
1874 s->wait_sector_num[index] = sector_num;
1875 qemu_coroutine_yield();
1877 s->wait_sector_num[index] = -1;
1880 if (s->ret == -EINPROGRESS) {
1881 if (copy_range) {
1882 ret = convert_co_copy_range(s, sector_num, n);
1883 if (ret) {
1884 s->copy_range = false;
1885 goto retry;
1887 } else {
1888 ret = convert_co_write(s, sector_num, n, buf, status);
1890 if (ret < 0) {
1891 error_report("error while writing sector %" PRId64
1892 ": %s", sector_num, strerror(-ret));
1893 s->ret = ret;
1897 if (s->wr_in_order) {
1898 /* reenter the coroutine that might have waited
1899 * for this write to complete */
1900 s->wr_offs = sector_num + n;
1901 for (i = 0; i < s->num_coroutines; i++) {
1902 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1904 * A -> B -> A cannot occur because A has
1905 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1906 * B will never enter A during this time window.
1908 qemu_coroutine_enter(s->co[i]);
1909 break;
1915 qemu_vfree(buf);
1916 s->co[index] = NULL;
1917 s->running_coroutines--;
1918 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1919 /* the convert job finished successfully */
1920 s->ret = 0;
1924 static int convert_do_copy(ImgConvertState *s)
1926 int ret, i, n;
1927 int64_t sector_num = 0;
1929 /* Check whether we have zero initialisation or can get it efficiently */
1930 s->has_zero_init = s->min_sparse && !s->target_has_backing
1931 ? bdrv_has_zero_init(blk_bs(s->target))
1932 : false;
1934 if (!s->has_zero_init && !s->target_has_backing &&
1935 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1937 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
1938 if (ret == 0) {
1939 s->has_zero_init = true;
1943 /* Allocate buffer for copied data. For compressed images, only one cluster
1944 * can be copied at a time. */
1945 if (s->compressed) {
1946 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1947 error_report("invalid cluster size");
1948 return -EINVAL;
1950 s->buf_sectors = s->cluster_sectors;
1953 while (sector_num < s->total_sectors) {
1954 n = convert_iteration_sectors(s, sector_num);
1955 if (n < 0) {
1956 return n;
1958 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1960 s->allocated_sectors += n;
1962 sector_num += n;
1965 /* Do the copy */
1966 s->sector_next_status = 0;
1967 s->ret = -EINPROGRESS;
1969 qemu_co_mutex_init(&s->lock);
1970 for (i = 0; i < s->num_coroutines; i++) {
1971 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1972 s->wait_sector_num[i] = -1;
1973 qemu_coroutine_enter(s->co[i]);
1976 while (s->running_coroutines) {
1977 main_loop_wait(false);
1980 if (s->compressed && !s->ret) {
1981 /* signal EOF to align */
1982 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
1983 if (ret < 0) {
1984 return ret;
1988 return s->ret;
1991 #define MAX_BUF_SECTORS 32768
1993 static int img_convert(int argc, char **argv)
1995 int c, bs_i, flags, src_flags = 0;
1996 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
1997 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
1998 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
1999 BlockDriver *drv = NULL, *proto_drv = NULL;
2000 BlockDriverInfo bdi;
2001 BlockDriverState *out_bs;
2002 QemuOpts *opts = NULL, *sn_opts = NULL;
2003 QemuOptsList *create_opts = NULL;
2004 QDict *open_opts = NULL;
2005 char *options = NULL;
2006 Error *local_err = NULL;
2007 bool writethrough, src_writethrough, quiet = false, image_opts = false,
2008 skip_create = false, progress = false, tgt_image_opts = false;
2009 int64_t ret = -EINVAL;
2010 bool force_share = false;
2011 bool explict_min_sparse = false;
2013 ImgConvertState s = (ImgConvertState) {
2014 /* Need at least 4k of zeros for sparse detection */
2015 .min_sparse = 8,
2016 .copy_range = false,
2017 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2018 .wr_in_order = true,
2019 .num_coroutines = 8,
2022 for(;;) {
2023 static const struct option long_options[] = {
2024 {"help", no_argument, 0, 'h'},
2025 {"object", required_argument, 0, OPTION_OBJECT},
2026 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2027 {"force-share", no_argument, 0, 'U'},
2028 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
2029 {0, 0, 0, 0}
2031 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2032 long_options, NULL);
2033 if (c == -1) {
2034 break;
2036 switch(c) {
2037 case ':':
2038 missing_argument(argv[optind - 1]);
2039 break;
2040 case '?':
2041 unrecognized_option(argv[optind - 1]);
2042 break;
2043 case 'h':
2044 help();
2045 break;
2046 case 'f':
2047 fmt = optarg;
2048 break;
2049 case 'O':
2050 out_fmt = optarg;
2051 break;
2052 case 'B':
2053 out_baseimg = optarg;
2054 break;
2055 case 'C':
2056 s.copy_range = true;
2057 break;
2058 case 'c':
2059 s.compressed = true;
2060 break;
2061 case 'o':
2062 if (!is_valid_option_list(optarg)) {
2063 error_report("Invalid option list: %s", optarg);
2064 goto fail_getopt;
2066 if (!options) {
2067 options = g_strdup(optarg);
2068 } else {
2069 char *old_options = options;
2070 options = g_strdup_printf("%s,%s", options, optarg);
2071 g_free(old_options);
2073 break;
2074 case 'l':
2075 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2076 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2077 optarg, false);
2078 if (!sn_opts) {
2079 error_report("Failed in parsing snapshot param '%s'",
2080 optarg);
2081 goto fail_getopt;
2083 } else {
2084 snapshot_name = optarg;
2086 break;
2087 case 'S':
2089 int64_t sval;
2091 sval = cvtnum(optarg);
2092 if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
2093 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2094 error_report("Invalid buffer size for sparse output specified. "
2095 "Valid sizes are multiples of %llu up to %llu. Select "
2096 "0 to disable sparse detection (fully allocates output).",
2097 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
2098 goto fail_getopt;
2101 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2102 explict_min_sparse = true;
2103 break;
2105 case 'p':
2106 progress = true;
2107 break;
2108 case 't':
2109 cache = optarg;
2110 break;
2111 case 'T':
2112 src_cache = optarg;
2113 break;
2114 case 'q':
2115 quiet = true;
2116 break;
2117 case 'n':
2118 skip_create = true;
2119 break;
2120 case 'm':
2121 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2122 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2123 error_report("Invalid number of coroutines. Allowed number of"
2124 " coroutines is between 1 and %d", MAX_COROUTINES);
2125 goto fail_getopt;
2127 break;
2128 case 'W':
2129 s.wr_in_order = false;
2130 break;
2131 case 'U':
2132 force_share = true;
2133 break;
2134 case OPTION_OBJECT: {
2135 QemuOpts *object_opts;
2136 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2137 optarg, true);
2138 if (!object_opts) {
2139 goto fail_getopt;
2141 break;
2143 case OPTION_IMAGE_OPTS:
2144 image_opts = true;
2145 break;
2146 case OPTION_TARGET_IMAGE_OPTS:
2147 tgt_image_opts = true;
2148 break;
2152 if (!out_fmt && !tgt_image_opts) {
2153 out_fmt = "raw";
2156 if (qemu_opts_foreach(&qemu_object_opts,
2157 user_creatable_add_opts_foreach,
2158 NULL, &error_fatal)) {
2159 goto fail_getopt;
2162 if (s.compressed && s.copy_range) {
2163 error_report("Cannot enable copy offloading when -c is used");
2164 goto fail_getopt;
2167 if (explict_min_sparse && s.copy_range) {
2168 error_report("Cannot enable copy offloading when -S is used");
2169 goto fail_getopt;
2172 if (tgt_image_opts && !skip_create) {
2173 error_report("--target-image-opts requires use of -n flag");
2174 goto fail_getopt;
2177 s.src_num = argc - optind - 1;
2178 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2180 if (options && has_help_option(options)) {
2181 if (out_fmt) {
2182 ret = print_block_option_help(out_filename, out_fmt);
2183 goto fail_getopt;
2184 } else {
2185 error_report("Option help requires a format be specified");
2186 goto fail_getopt;
2190 if (s.src_num < 1) {
2191 error_report("Must specify image file name");
2192 goto fail_getopt;
2196 /* ret is still -EINVAL until here */
2197 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2198 if (ret < 0) {
2199 error_report("Invalid source cache option: %s", src_cache);
2200 goto fail_getopt;
2203 /* Initialize before goto out */
2204 if (quiet) {
2205 progress = false;
2207 qemu_progress_init(progress, 1.0);
2208 qemu_progress_print(0, 100);
2210 s.src = g_new0(BlockBackend *, s.src_num);
2211 s.src_sectors = g_new(int64_t, s.src_num);
2213 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2214 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2215 fmt, src_flags, src_writethrough, quiet,
2216 force_share);
2217 if (!s.src[bs_i]) {
2218 ret = -1;
2219 goto out;
2221 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2222 if (s.src_sectors[bs_i] < 0) {
2223 error_report("Could not get size of %s: %s",
2224 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2225 ret = -1;
2226 goto out;
2228 s.total_sectors += s.src_sectors[bs_i];
2231 if (sn_opts) {
2232 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2233 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2234 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2235 &local_err);
2236 } else if (snapshot_name != NULL) {
2237 if (s.src_num > 1) {
2238 error_report("No support for concatenating multiple snapshot");
2239 ret = -1;
2240 goto out;
2243 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2244 &local_err);
2246 if (local_err) {
2247 error_reportf_err(local_err, "Failed to load snapshot: ");
2248 ret = -1;
2249 goto out;
2252 if (!skip_create) {
2253 /* Find driver and parse its options */
2254 drv = bdrv_find_format(out_fmt);
2255 if (!drv) {
2256 error_report("Unknown file format '%s'", out_fmt);
2257 ret = -1;
2258 goto out;
2261 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2262 if (!proto_drv) {
2263 error_report_err(local_err);
2264 ret = -1;
2265 goto out;
2268 if (!drv->create_opts) {
2269 error_report("Format driver '%s' does not support image creation",
2270 drv->format_name);
2271 ret = -1;
2272 goto out;
2275 if (!proto_drv->create_opts) {
2276 error_report("Protocol driver '%s' does not support image creation",
2277 proto_drv->format_name);
2278 ret = -1;
2279 goto out;
2282 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2283 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2285 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2286 if (options) {
2287 qemu_opts_do_parse(opts, options, NULL, &local_err);
2288 if (local_err) {
2289 error_report_err(local_err);
2290 ret = -1;
2291 goto out;
2295 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2296 &error_abort);
2297 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2298 if (ret < 0) {
2299 goto out;
2303 /* Get backing file name if -o backing_file was used */
2304 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2305 if (out_baseimg_param) {
2306 out_baseimg = out_baseimg_param;
2308 s.target_has_backing = (bool) out_baseimg;
2310 if (s.src_num > 1 && out_baseimg) {
2311 error_report("Having a backing file for the target makes no sense when "
2312 "concatenating multiple input images");
2313 ret = -1;
2314 goto out;
2317 /* Check if compression is supported */
2318 if (s.compressed) {
2319 bool encryption =
2320 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2321 const char *encryptfmt =
2322 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2323 const char *preallocation =
2324 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2326 if (drv && !drv->bdrv_co_pwritev_compressed) {
2327 error_report("Compression not supported for this file format");
2328 ret = -1;
2329 goto out;
2332 if (encryption || encryptfmt) {
2333 error_report("Compression and encryption not supported at "
2334 "the same time");
2335 ret = -1;
2336 goto out;
2339 if (preallocation
2340 && strcmp(preallocation, "off"))
2342 error_report("Compression and preallocation not supported at "
2343 "the same time");
2344 ret = -1;
2345 goto out;
2350 * The later open call will need any decryption secrets, and
2351 * bdrv_create() will purge "opts", so extract them now before
2352 * they are lost.
2354 if (!skip_create) {
2355 open_opts = qdict_new();
2356 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2359 if (!skip_create) {
2360 /* Create the new image */
2361 ret = bdrv_create(drv, out_filename, opts, &local_err);
2362 if (ret < 0) {
2363 error_reportf_err(local_err, "%s: error while converting %s: ",
2364 out_filename, out_fmt);
2365 goto out;
2369 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2370 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2371 if (ret < 0) {
2372 error_report("Invalid cache option: %s", cache);
2373 goto out;
2376 if (skip_create) {
2377 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2378 flags, writethrough, quiet, false);
2379 } else {
2380 /* TODO ultimately we should allow --target-image-opts
2381 * to be used even when -n is not given.
2382 * That has to wait for bdrv_create to be improved
2383 * to allow filenames in option syntax
2385 s.target = img_open_file(out_filename, open_opts, out_fmt,
2386 flags, writethrough, quiet, false);
2387 open_opts = NULL; /* blk_new_open will have freed it */
2389 if (!s.target) {
2390 ret = -1;
2391 goto out;
2393 out_bs = blk_bs(s.target);
2395 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2396 error_report("Compression not supported for this file format");
2397 ret = -1;
2398 goto out;
2401 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2402 * or discard_alignment of the out_bs is greater. Limit to
2403 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2404 s.buf_sectors = MIN(MAX_BUF_SECTORS,
2405 MAX(s.buf_sectors,
2406 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2407 out_bs->bl.pdiscard_alignment >>
2408 BDRV_SECTOR_BITS)));
2410 /* try to align the write requests to the destination to avoid unnecessary
2411 * RMW cycles. */
2412 s.alignment = MAX(pow2floor(s.min_sparse),
2413 DIV_ROUND_UP(out_bs->bl.request_alignment,
2414 BDRV_SECTOR_SIZE));
2415 assert(is_power_of_2(s.alignment));
2417 if (skip_create) {
2418 int64_t output_sectors = blk_nb_sectors(s.target);
2419 if (output_sectors < 0) {
2420 error_report("unable to get output image length: %s",
2421 strerror(-output_sectors));
2422 ret = -1;
2423 goto out;
2424 } else if (output_sectors < s.total_sectors) {
2425 error_report("output file is smaller than input file");
2426 ret = -1;
2427 goto out;
2431 if (s.target_has_backing) {
2432 /* Errors are treated as "backing length unknown" (which means
2433 * s.target_backing_sectors has to be negative, which it will
2434 * be automatically). The backing file length is used only
2435 * for optimizations, so such a case is not fatal. */
2436 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2437 } else {
2438 s.target_backing_sectors = -1;
2441 ret = bdrv_get_info(out_bs, &bdi);
2442 if (ret < 0) {
2443 if (s.compressed) {
2444 error_report("could not get block driver info");
2445 goto out;
2447 } else {
2448 s.compressed = s.compressed || bdi.needs_compressed_writes;
2449 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2450 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
2453 ret = convert_do_copy(&s);
2454 out:
2455 if (!ret) {
2456 qemu_progress_print(100, 0);
2458 qemu_progress_end();
2459 qemu_opts_del(opts);
2460 qemu_opts_free(create_opts);
2461 qemu_opts_del(sn_opts);
2462 qobject_unref(open_opts);
2463 blk_unref(s.target);
2464 if (s.src) {
2465 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2466 blk_unref(s.src[bs_i]);
2468 g_free(s.src);
2470 g_free(s.src_sectors);
2471 fail_getopt:
2472 g_free(options);
2474 return !!ret;
2478 static void dump_snapshots(BlockDriverState *bs)
2480 QEMUSnapshotInfo *sn_tab, *sn;
2481 int nb_sns, i;
2483 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2484 if (nb_sns <= 0)
2485 return;
2486 printf("Snapshot list:\n");
2487 bdrv_snapshot_dump(fprintf, stdout, NULL);
2488 printf("\n");
2489 for(i = 0; i < nb_sns; i++) {
2490 sn = &sn_tab[i];
2491 bdrv_snapshot_dump(fprintf, stdout, sn);
2492 printf("\n");
2494 g_free(sn_tab);
2497 static void dump_json_image_info_list(ImageInfoList *list)
2499 QString *str;
2500 QObject *obj;
2501 Visitor *v = qobject_output_visitor_new(&obj);
2503 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2504 visit_complete(v, &obj);
2505 str = qobject_to_json_pretty(obj);
2506 assert(str != NULL);
2507 printf("%s\n", qstring_get_str(str));
2508 qobject_unref(obj);
2509 visit_free(v);
2510 qobject_unref(str);
2513 static void dump_json_image_info(ImageInfo *info)
2515 QString *str;
2516 QObject *obj;
2517 Visitor *v = qobject_output_visitor_new(&obj);
2519 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2520 visit_complete(v, &obj);
2521 str = qobject_to_json_pretty(obj);
2522 assert(str != NULL);
2523 printf("%s\n", qstring_get_str(str));
2524 qobject_unref(obj);
2525 visit_free(v);
2526 qobject_unref(str);
2529 static void dump_human_image_info_list(ImageInfoList *list)
2531 ImageInfoList *elem;
2532 bool delim = false;
2534 for (elem = list; elem; elem = elem->next) {
2535 if (delim) {
2536 printf("\n");
2538 delim = true;
2540 bdrv_image_info_dump(fprintf, stdout, elem->value);
2544 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2546 return strcmp(a, b) == 0;
2550 * Open an image file chain and return an ImageInfoList
2552 * @filename: topmost image filename
2553 * @fmt: topmost image format (may be NULL to autodetect)
2554 * @chain: true - enumerate entire backing file chain
2555 * false - only topmost image file
2557 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2558 * image file. If there was an error a message will have been printed to
2559 * stderr.
2561 static ImageInfoList *collect_image_info_list(bool image_opts,
2562 const char *filename,
2563 const char *fmt,
2564 bool chain, bool force_share)
2566 ImageInfoList *head = NULL;
2567 ImageInfoList **last = &head;
2568 GHashTable *filenames;
2569 Error *err = NULL;
2571 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2573 while (filename) {
2574 BlockBackend *blk;
2575 BlockDriverState *bs;
2576 ImageInfo *info;
2577 ImageInfoList *elem;
2579 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2580 error_report("Backing file '%s' creates an infinite loop.",
2581 filename);
2582 goto err;
2584 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2586 blk = img_open(image_opts, filename, fmt,
2587 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2588 force_share);
2589 if (!blk) {
2590 goto err;
2592 bs = blk_bs(blk);
2594 bdrv_query_image_info(bs, &info, &err);
2595 if (err) {
2596 error_report_err(err);
2597 blk_unref(blk);
2598 goto err;
2601 elem = g_new0(ImageInfoList, 1);
2602 elem->value = info;
2603 *last = elem;
2604 last = &elem->next;
2606 blk_unref(blk);
2608 filename = fmt = NULL;
2609 if (chain) {
2610 if (info->has_full_backing_filename) {
2611 filename = info->full_backing_filename;
2612 } else if (info->has_backing_filename) {
2613 error_report("Could not determine absolute backing filename,"
2614 " but backing filename '%s' present",
2615 info->backing_filename);
2616 goto err;
2618 if (info->has_backing_filename_format) {
2619 fmt = info->backing_filename_format;
2623 g_hash_table_destroy(filenames);
2624 return head;
2626 err:
2627 qapi_free_ImageInfoList(head);
2628 g_hash_table_destroy(filenames);
2629 return NULL;
2632 static int img_info(int argc, char **argv)
2634 int c;
2635 OutputFormat output_format = OFORMAT_HUMAN;
2636 bool chain = false;
2637 const char *filename, *fmt, *output;
2638 ImageInfoList *list;
2639 bool image_opts = false;
2640 bool force_share = false;
2642 fmt = NULL;
2643 output = NULL;
2644 for(;;) {
2645 int option_index = 0;
2646 static const struct option long_options[] = {
2647 {"help", no_argument, 0, 'h'},
2648 {"format", required_argument, 0, 'f'},
2649 {"output", required_argument, 0, OPTION_OUTPUT},
2650 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2651 {"object", required_argument, 0, OPTION_OBJECT},
2652 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2653 {"force-share", no_argument, 0, 'U'},
2654 {0, 0, 0, 0}
2656 c = getopt_long(argc, argv, ":f:hU",
2657 long_options, &option_index);
2658 if (c == -1) {
2659 break;
2661 switch(c) {
2662 case ':':
2663 missing_argument(argv[optind - 1]);
2664 break;
2665 case '?':
2666 unrecognized_option(argv[optind - 1]);
2667 break;
2668 case 'h':
2669 help();
2670 break;
2671 case 'f':
2672 fmt = optarg;
2673 break;
2674 case 'U':
2675 force_share = true;
2676 break;
2677 case OPTION_OUTPUT:
2678 output = optarg;
2679 break;
2680 case OPTION_BACKING_CHAIN:
2681 chain = true;
2682 break;
2683 case OPTION_OBJECT: {
2684 QemuOpts *opts;
2685 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2686 optarg, true);
2687 if (!opts) {
2688 return 1;
2690 } break;
2691 case OPTION_IMAGE_OPTS:
2692 image_opts = true;
2693 break;
2696 if (optind != argc - 1) {
2697 error_exit("Expecting one image file name");
2699 filename = argv[optind++];
2701 if (output && !strcmp(output, "json")) {
2702 output_format = OFORMAT_JSON;
2703 } else if (output && !strcmp(output, "human")) {
2704 output_format = OFORMAT_HUMAN;
2705 } else if (output) {
2706 error_report("--output must be used with human or json as argument.");
2707 return 1;
2710 if (qemu_opts_foreach(&qemu_object_opts,
2711 user_creatable_add_opts_foreach,
2712 NULL, &error_fatal)) {
2713 return 1;
2716 list = collect_image_info_list(image_opts, filename, fmt, chain,
2717 force_share);
2718 if (!list) {
2719 return 1;
2722 switch (output_format) {
2723 case OFORMAT_HUMAN:
2724 dump_human_image_info_list(list);
2725 break;
2726 case OFORMAT_JSON:
2727 if (chain) {
2728 dump_json_image_info_list(list);
2729 } else {
2730 dump_json_image_info(list->value);
2732 break;
2735 qapi_free_ImageInfoList(list);
2736 return 0;
2739 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2740 MapEntry *next)
2742 switch (output_format) {
2743 case OFORMAT_HUMAN:
2744 if (e->data && !e->has_offset) {
2745 error_report("File contains external, encrypted or compressed clusters.");
2746 exit(1);
2748 if (e->data && !e->zero) {
2749 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2750 e->start, e->length,
2751 e->has_offset ? e->offset : 0,
2752 e->has_filename ? e->filename : "");
2754 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2755 * Modify the flags here to allow more coalescing.
2757 if (next && (!next->data || next->zero)) {
2758 next->data = false;
2759 next->zero = true;
2761 break;
2762 case OFORMAT_JSON:
2763 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2764 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2765 (e->start == 0 ? "[" : ",\n"),
2766 e->start, e->length, e->depth,
2767 e->zero ? "true" : "false",
2768 e->data ? "true" : "false");
2769 if (e->has_offset) {
2770 printf(", \"offset\": %"PRId64"", e->offset);
2772 putchar('}');
2774 if (!next) {
2775 printf("]\n");
2777 break;
2781 static int get_block_status(BlockDriverState *bs, int64_t offset,
2782 int64_t bytes, MapEntry *e)
2784 int ret;
2785 int depth;
2786 BlockDriverState *file;
2787 bool has_offset;
2788 int64_t map;
2789 char *filename = NULL;
2791 /* As an optimization, we could cache the current range of unallocated
2792 * clusters in each file of the chain, and avoid querying the same
2793 * range repeatedly.
2796 depth = 0;
2797 for (;;) {
2798 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
2799 if (ret < 0) {
2800 return ret;
2802 assert(bytes);
2803 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2804 break;
2806 bs = backing_bs(bs);
2807 if (bs == NULL) {
2808 ret = 0;
2809 break;
2812 depth++;
2815 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2817 if (file && has_offset) {
2818 bdrv_refresh_filename(file);
2819 filename = file->filename;
2822 *e = (MapEntry) {
2823 .start = offset,
2824 .length = bytes,
2825 .data = !!(ret & BDRV_BLOCK_DATA),
2826 .zero = !!(ret & BDRV_BLOCK_ZERO),
2827 .offset = map,
2828 .has_offset = has_offset,
2829 .depth = depth,
2830 .has_filename = filename,
2831 .filename = filename,
2834 return 0;
2837 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2839 if (curr->length == 0) {
2840 return false;
2842 if (curr->zero != next->zero ||
2843 curr->data != next->data ||
2844 curr->depth != next->depth ||
2845 curr->has_filename != next->has_filename ||
2846 curr->has_offset != next->has_offset) {
2847 return false;
2849 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2850 return false;
2852 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2853 return false;
2855 return true;
2858 static int img_map(int argc, char **argv)
2860 int c;
2861 OutputFormat output_format = OFORMAT_HUMAN;
2862 BlockBackend *blk;
2863 BlockDriverState *bs;
2864 const char *filename, *fmt, *output;
2865 int64_t length;
2866 MapEntry curr = { .length = 0 }, next;
2867 int ret = 0;
2868 bool image_opts = false;
2869 bool force_share = false;
2871 fmt = NULL;
2872 output = NULL;
2873 for (;;) {
2874 int option_index = 0;
2875 static const struct option long_options[] = {
2876 {"help", no_argument, 0, 'h'},
2877 {"format", required_argument, 0, 'f'},
2878 {"output", required_argument, 0, OPTION_OUTPUT},
2879 {"object", required_argument, 0, OPTION_OBJECT},
2880 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2881 {"force-share", no_argument, 0, 'U'},
2882 {0, 0, 0, 0}
2884 c = getopt_long(argc, argv, ":f:hU",
2885 long_options, &option_index);
2886 if (c == -1) {
2887 break;
2889 switch (c) {
2890 case ':':
2891 missing_argument(argv[optind - 1]);
2892 break;
2893 case '?':
2894 unrecognized_option(argv[optind - 1]);
2895 break;
2896 case 'h':
2897 help();
2898 break;
2899 case 'f':
2900 fmt = optarg;
2901 break;
2902 case 'U':
2903 force_share = true;
2904 break;
2905 case OPTION_OUTPUT:
2906 output = optarg;
2907 break;
2908 case OPTION_OBJECT: {
2909 QemuOpts *opts;
2910 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2911 optarg, true);
2912 if (!opts) {
2913 return 1;
2915 } break;
2916 case OPTION_IMAGE_OPTS:
2917 image_opts = true;
2918 break;
2921 if (optind != argc - 1) {
2922 error_exit("Expecting one image file name");
2924 filename = argv[optind];
2926 if (output && !strcmp(output, "json")) {
2927 output_format = OFORMAT_JSON;
2928 } else if (output && !strcmp(output, "human")) {
2929 output_format = OFORMAT_HUMAN;
2930 } else if (output) {
2931 error_report("--output must be used with human or json as argument.");
2932 return 1;
2935 if (qemu_opts_foreach(&qemu_object_opts,
2936 user_creatable_add_opts_foreach,
2937 NULL, &error_fatal)) {
2938 return 1;
2941 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
2942 if (!blk) {
2943 return 1;
2945 bs = blk_bs(blk);
2947 if (output_format == OFORMAT_HUMAN) {
2948 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2951 length = blk_getlength(blk);
2952 while (curr.start + curr.length < length) {
2953 int64_t offset = curr.start + curr.length;
2954 int64_t n;
2956 /* Probe up to 1 GiB at a time. */
2957 n = MIN(1 << 30, length - offset);
2958 ret = get_block_status(bs, offset, n, &next);
2960 if (ret < 0) {
2961 error_report("Could not read file metadata: %s", strerror(-ret));
2962 goto out;
2965 if (entry_mergeable(&curr, &next)) {
2966 curr.length += next.length;
2967 continue;
2970 if (curr.length > 0) {
2971 dump_map_entry(output_format, &curr, &next);
2973 curr = next;
2976 dump_map_entry(output_format, &curr, NULL);
2978 out:
2979 blk_unref(blk);
2980 return ret < 0;
2983 #define SNAPSHOT_LIST 1
2984 #define SNAPSHOT_CREATE 2
2985 #define SNAPSHOT_APPLY 3
2986 #define SNAPSHOT_DELETE 4
2988 static int img_snapshot(int argc, char **argv)
2990 BlockBackend *blk;
2991 BlockDriverState *bs;
2992 QEMUSnapshotInfo sn;
2993 char *filename, *snapshot_name = NULL;
2994 int c, ret = 0, bdrv_oflags;
2995 int action = 0;
2996 qemu_timeval tv;
2997 bool quiet = false;
2998 Error *err = NULL;
2999 bool image_opts = false;
3000 bool force_share = false;
3002 bdrv_oflags = BDRV_O_RDWR;
3003 /* Parse commandline parameters */
3004 for(;;) {
3005 static const struct option long_options[] = {
3006 {"help", no_argument, 0, 'h'},
3007 {"object", required_argument, 0, OPTION_OBJECT},
3008 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3009 {"force-share", no_argument, 0, 'U'},
3010 {0, 0, 0, 0}
3012 c = getopt_long(argc, argv, ":la:c:d:hqU",
3013 long_options, NULL);
3014 if (c == -1) {
3015 break;
3017 switch(c) {
3018 case ':':
3019 missing_argument(argv[optind - 1]);
3020 break;
3021 case '?':
3022 unrecognized_option(argv[optind - 1]);
3023 break;
3024 case 'h':
3025 help();
3026 return 0;
3027 case 'l':
3028 if (action) {
3029 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3030 return 0;
3032 action = SNAPSHOT_LIST;
3033 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
3034 break;
3035 case 'a':
3036 if (action) {
3037 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3038 return 0;
3040 action = SNAPSHOT_APPLY;
3041 snapshot_name = optarg;
3042 break;
3043 case 'c':
3044 if (action) {
3045 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3046 return 0;
3048 action = SNAPSHOT_CREATE;
3049 snapshot_name = optarg;
3050 break;
3051 case 'd':
3052 if (action) {
3053 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3054 return 0;
3056 action = SNAPSHOT_DELETE;
3057 snapshot_name = optarg;
3058 break;
3059 case 'q':
3060 quiet = true;
3061 break;
3062 case 'U':
3063 force_share = true;
3064 break;
3065 case OPTION_OBJECT: {
3066 QemuOpts *opts;
3067 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3068 optarg, true);
3069 if (!opts) {
3070 return 1;
3072 } break;
3073 case OPTION_IMAGE_OPTS:
3074 image_opts = true;
3075 break;
3079 if (optind != argc - 1) {
3080 error_exit("Expecting one image file name");
3082 filename = argv[optind++];
3084 if (qemu_opts_foreach(&qemu_object_opts,
3085 user_creatable_add_opts_foreach,
3086 NULL, &error_fatal)) {
3087 return 1;
3090 /* Open the image */
3091 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3092 force_share);
3093 if (!blk) {
3094 return 1;
3096 bs = blk_bs(blk);
3098 /* Perform the requested action */
3099 switch(action) {
3100 case SNAPSHOT_LIST:
3101 dump_snapshots(bs);
3102 break;
3104 case SNAPSHOT_CREATE:
3105 memset(&sn, 0, sizeof(sn));
3106 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3108 qemu_gettimeofday(&tv);
3109 sn.date_sec = tv.tv_sec;
3110 sn.date_nsec = tv.tv_usec * 1000;
3112 ret = bdrv_snapshot_create(bs, &sn);
3113 if (ret) {
3114 error_report("Could not create snapshot '%s': %d (%s)",
3115 snapshot_name, ret, strerror(-ret));
3117 break;
3119 case SNAPSHOT_APPLY:
3120 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3121 if (ret) {
3122 error_reportf_err(err, "Could not apply snapshot '%s': ",
3123 snapshot_name);
3125 break;
3127 case SNAPSHOT_DELETE:
3128 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3129 if (ret < 0) {
3130 error_report("Could not delete snapshot '%s': snapshot not "
3131 "found", snapshot_name);
3132 ret = 1;
3133 } else {
3134 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3135 if (ret < 0) {
3136 error_reportf_err(err, "Could not delete snapshot '%s': ",
3137 snapshot_name);
3138 ret = 1;
3141 break;
3144 /* Cleanup */
3145 blk_unref(blk);
3146 if (ret) {
3147 return 1;
3149 return 0;
3152 static int img_rebase(int argc, char **argv)
3154 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3155 uint8_t *buf_old = NULL;
3156 uint8_t *buf_new = NULL;
3157 BlockDriverState *bs = NULL;
3158 char *filename;
3159 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3160 int c, flags, src_flags, ret;
3161 bool writethrough, src_writethrough;
3162 int unsafe = 0;
3163 bool force_share = false;
3164 int progress = 0;
3165 bool quiet = false;
3166 Error *local_err = NULL;
3167 bool image_opts = false;
3169 /* Parse commandline parameters */
3170 fmt = NULL;
3171 cache = BDRV_DEFAULT_CACHE;
3172 src_cache = BDRV_DEFAULT_CACHE;
3173 out_baseimg = NULL;
3174 out_basefmt = NULL;
3175 for(;;) {
3176 static const struct option long_options[] = {
3177 {"help", no_argument, 0, 'h'},
3178 {"object", required_argument, 0, OPTION_OBJECT},
3179 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3180 {"force-share", no_argument, 0, 'U'},
3181 {0, 0, 0, 0}
3183 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3184 long_options, NULL);
3185 if (c == -1) {
3186 break;
3188 switch(c) {
3189 case ':':
3190 missing_argument(argv[optind - 1]);
3191 break;
3192 case '?':
3193 unrecognized_option(argv[optind - 1]);
3194 break;
3195 case 'h':
3196 help();
3197 return 0;
3198 case 'f':
3199 fmt = optarg;
3200 break;
3201 case 'F':
3202 out_basefmt = optarg;
3203 break;
3204 case 'b':
3205 out_baseimg = optarg;
3206 break;
3207 case 'u':
3208 unsafe = 1;
3209 break;
3210 case 'p':
3211 progress = 1;
3212 break;
3213 case 't':
3214 cache = optarg;
3215 break;
3216 case 'T':
3217 src_cache = optarg;
3218 break;
3219 case 'q':
3220 quiet = true;
3221 break;
3222 case OPTION_OBJECT: {
3223 QemuOpts *opts;
3224 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3225 optarg, true);
3226 if (!opts) {
3227 return 1;
3229 } break;
3230 case OPTION_IMAGE_OPTS:
3231 image_opts = true;
3232 break;
3233 case 'U':
3234 force_share = true;
3235 break;
3239 if (quiet) {
3240 progress = 0;
3243 if (optind != argc - 1) {
3244 error_exit("Expecting one image file name");
3246 if (!unsafe && !out_baseimg) {
3247 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3249 filename = argv[optind++];
3251 if (qemu_opts_foreach(&qemu_object_opts,
3252 user_creatable_add_opts_foreach,
3253 NULL, &error_fatal)) {
3254 return 1;
3257 qemu_progress_init(progress, 2.0);
3258 qemu_progress_print(0, 100);
3260 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3261 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3262 if (ret < 0) {
3263 error_report("Invalid cache option: %s", cache);
3264 goto out;
3267 src_flags = 0;
3268 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3269 if (ret < 0) {
3270 error_report("Invalid source cache option: %s", src_cache);
3271 goto out;
3274 /* The source files are opened read-only, don't care about WCE */
3275 assert((src_flags & BDRV_O_RDWR) == 0);
3276 (void) src_writethrough;
3279 * Open the images.
3281 * Ignore the old backing file for unsafe rebase in case we want to correct
3282 * the reference to a renamed or moved backing file.
3284 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3285 false);
3286 if (!blk) {
3287 ret = -1;
3288 goto out;
3290 bs = blk_bs(blk);
3292 if (out_basefmt != NULL) {
3293 if (bdrv_find_format(out_basefmt) == NULL) {
3294 error_report("Invalid format name: '%s'", out_basefmt);
3295 ret = -1;
3296 goto out;
3300 /* For safe rebasing we need to compare old and new backing file */
3301 if (!unsafe) {
3302 char backing_name[PATH_MAX];
3303 QDict *options = NULL;
3305 if (bs->backing_format[0] != '\0') {
3306 options = qdict_new();
3307 qdict_put_str(options, "driver", bs->backing_format);
3310 if (force_share) {
3311 if (!options) {
3312 options = qdict_new();
3314 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3316 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3317 blk_old_backing = blk_new_open(backing_name, NULL,
3318 options, src_flags, &local_err);
3319 if (!blk_old_backing) {
3320 error_reportf_err(local_err,
3321 "Could not open old backing file '%s': ",
3322 backing_name);
3323 ret = -1;
3324 goto out;
3327 if (out_baseimg[0]) {
3328 const char *overlay_filename;
3329 char *out_real_path;
3331 options = qdict_new();
3332 if (out_basefmt) {
3333 qdict_put_str(options, "driver", out_basefmt);
3335 if (force_share) {
3336 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3339 bdrv_refresh_filename(bs);
3340 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3341 : bs->filename;
3342 out_real_path =
3343 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3344 out_baseimg,
3345 &local_err);
3346 if (local_err) {
3347 error_reportf_err(local_err,
3348 "Could not resolve backing filename: ");
3349 ret = -1;
3350 goto out;
3353 blk_new_backing = blk_new_open(out_real_path, NULL,
3354 options, src_flags, &local_err);
3355 g_free(out_real_path);
3356 if (!blk_new_backing) {
3357 error_reportf_err(local_err,
3358 "Could not open new backing file '%s': ",
3359 out_baseimg);
3360 ret = -1;
3361 goto out;
3367 * Check each unallocated cluster in the COW file. If it is unallocated,
3368 * accesses go to the backing file. We must therefore compare this cluster
3369 * in the old and new backing file, and if they differ we need to copy it
3370 * from the old backing file into the COW file.
3372 * If qemu-img crashes during this step, no harm is done. The content of
3373 * the image is the same as the original one at any time.
3375 if (!unsafe) {
3376 int64_t size;
3377 int64_t old_backing_size;
3378 int64_t new_backing_size = 0;
3379 uint64_t offset;
3380 int64_t n;
3381 float local_progress = 0;
3383 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3384 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3386 size = blk_getlength(blk);
3387 if (size < 0) {
3388 error_report("Could not get size of '%s': %s",
3389 filename, strerror(-size));
3390 ret = -1;
3391 goto out;
3393 old_backing_size = blk_getlength(blk_old_backing);
3394 if (old_backing_size < 0) {
3395 char backing_name[PATH_MAX];
3397 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3398 error_report("Could not get size of '%s': %s",
3399 backing_name, strerror(-old_backing_size));
3400 ret = -1;
3401 goto out;
3403 if (blk_new_backing) {
3404 new_backing_size = blk_getlength(blk_new_backing);
3405 if (new_backing_size < 0) {
3406 error_report("Could not get size of '%s': %s",
3407 out_baseimg, strerror(-new_backing_size));
3408 ret = -1;
3409 goto out;
3413 if (size != 0) {
3414 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3417 for (offset = 0; offset < size; offset += n) {
3418 /* How many bytes can we handle with the next read? */
3419 n = MIN(IO_BUF_SIZE, size - offset);
3421 /* If the cluster is allocated, we don't need to take action */
3422 ret = bdrv_is_allocated(bs, offset, n, &n);
3423 if (ret < 0) {
3424 error_report("error while reading image metadata: %s",
3425 strerror(-ret));
3426 goto out;
3428 if (ret) {
3429 continue;
3433 * Read old and new backing file and take into consideration that
3434 * backing files may be smaller than the COW image.
3436 if (offset >= old_backing_size) {
3437 memset(buf_old, 0, n);
3438 } else {
3439 if (offset + n > old_backing_size) {
3440 n = old_backing_size - offset;
3443 ret = blk_pread(blk_old_backing, offset, buf_old, n);
3444 if (ret < 0) {
3445 error_report("error while reading from old backing file");
3446 goto out;
3450 if (offset >= new_backing_size || !blk_new_backing) {
3451 memset(buf_new, 0, n);
3452 } else {
3453 if (offset + n > new_backing_size) {
3454 n = new_backing_size - offset;
3457 ret = blk_pread(blk_new_backing, offset, buf_new, n);
3458 if (ret < 0) {
3459 error_report("error while reading from new backing file");
3460 goto out;
3464 /* If they differ, we need to write to the COW file */
3465 uint64_t written = 0;
3467 while (written < n) {
3468 int64_t pnum;
3470 if (compare_buffers(buf_old + written, buf_new + written,
3471 n - written, &pnum))
3473 ret = blk_pwrite(blk, offset + written,
3474 buf_old + written, pnum, 0);
3475 if (ret < 0) {
3476 error_report("Error while writing to COW image: %s",
3477 strerror(-ret));
3478 goto out;
3482 written += pnum;
3484 qemu_progress_print(local_progress, 100);
3489 * Change the backing file. All clusters that are different from the old
3490 * backing file are overwritten in the COW file now, so the visible content
3491 * doesn't change when we switch the backing file.
3493 if (out_baseimg && *out_baseimg) {
3494 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3495 } else {
3496 ret = bdrv_change_backing_file(bs, NULL, NULL);
3499 if (ret == -ENOSPC) {
3500 error_report("Could not change the backing file to '%s': No "
3501 "space left in the file header", out_baseimg);
3502 } else if (ret < 0) {
3503 error_report("Could not change the backing file to '%s': %s",
3504 out_baseimg, strerror(-ret));
3507 qemu_progress_print(100, 0);
3509 * TODO At this point it is possible to check if any clusters that are
3510 * allocated in the COW file are the same in the backing file. If so, they
3511 * could be dropped from the COW file. Don't do this before switching the
3512 * backing file, in case of a crash this would lead to corruption.
3514 out:
3515 qemu_progress_end();
3516 /* Cleanup */
3517 if (!unsafe) {
3518 blk_unref(blk_old_backing);
3519 blk_unref(blk_new_backing);
3521 qemu_vfree(buf_old);
3522 qemu_vfree(buf_new);
3524 blk_unref(blk);
3525 if (ret) {
3526 return 1;
3528 return 0;
3531 static int img_resize(int argc, char **argv)
3533 Error *err = NULL;
3534 int c, ret, relative;
3535 const char *filename, *fmt, *size;
3536 int64_t n, total_size, current_size, new_size;
3537 bool quiet = false;
3538 BlockBackend *blk = NULL;
3539 PreallocMode prealloc = PREALLOC_MODE_OFF;
3540 QemuOpts *param;
3542 static QemuOptsList resize_options = {
3543 .name = "resize_options",
3544 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3545 .desc = {
3547 .name = BLOCK_OPT_SIZE,
3548 .type = QEMU_OPT_SIZE,
3549 .help = "Virtual disk size"
3550 }, {
3551 /* end of list */
3555 bool image_opts = false;
3556 bool shrink = false;
3558 /* Remove size from argv manually so that negative numbers are not treated
3559 * as options by getopt. */
3560 if (argc < 3) {
3561 error_exit("Not enough arguments");
3562 return 1;
3565 size = argv[--argc];
3567 /* Parse getopt arguments */
3568 fmt = NULL;
3569 for(;;) {
3570 static const struct option long_options[] = {
3571 {"help", no_argument, 0, 'h'},
3572 {"object", required_argument, 0, OPTION_OBJECT},
3573 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3574 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3575 {"shrink", no_argument, 0, OPTION_SHRINK},
3576 {0, 0, 0, 0}
3578 c = getopt_long(argc, argv, ":f:hq",
3579 long_options, NULL);
3580 if (c == -1) {
3581 break;
3583 switch(c) {
3584 case ':':
3585 missing_argument(argv[optind - 1]);
3586 break;
3587 case '?':
3588 unrecognized_option(argv[optind - 1]);
3589 break;
3590 case 'h':
3591 help();
3592 break;
3593 case 'f':
3594 fmt = optarg;
3595 break;
3596 case 'q':
3597 quiet = true;
3598 break;
3599 case OPTION_OBJECT: {
3600 QemuOpts *opts;
3601 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3602 optarg, true);
3603 if (!opts) {
3604 return 1;
3606 } break;
3607 case OPTION_IMAGE_OPTS:
3608 image_opts = true;
3609 break;
3610 case OPTION_PREALLOCATION:
3611 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3612 PREALLOC_MODE__MAX, NULL);
3613 if (prealloc == PREALLOC_MODE__MAX) {
3614 error_report("Invalid preallocation mode '%s'", optarg);
3615 return 1;
3617 break;
3618 case OPTION_SHRINK:
3619 shrink = true;
3620 break;
3623 if (optind != argc - 1) {
3624 error_exit("Expecting image file name and size");
3626 filename = argv[optind++];
3628 if (qemu_opts_foreach(&qemu_object_opts,
3629 user_creatable_add_opts_foreach,
3630 NULL, &error_fatal)) {
3631 return 1;
3634 /* Choose grow, shrink, or absolute resize mode */
3635 switch (size[0]) {
3636 case '+':
3637 relative = 1;
3638 size++;
3639 break;
3640 case '-':
3641 relative = -1;
3642 size++;
3643 break;
3644 default:
3645 relative = 0;
3646 break;
3649 /* Parse size */
3650 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3651 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3652 if (err) {
3653 error_report_err(err);
3654 ret = -1;
3655 qemu_opts_del(param);
3656 goto out;
3658 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3659 qemu_opts_del(param);
3661 blk = img_open(image_opts, filename, fmt,
3662 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3663 false);
3664 if (!blk) {
3665 ret = -1;
3666 goto out;
3669 current_size = blk_getlength(blk);
3670 if (current_size < 0) {
3671 error_report("Failed to inquire current image length: %s",
3672 strerror(-current_size));
3673 ret = -1;
3674 goto out;
3677 if (relative) {
3678 total_size = current_size + n * relative;
3679 } else {
3680 total_size = n;
3682 if (total_size <= 0) {
3683 error_report("New image size must be positive");
3684 ret = -1;
3685 goto out;
3688 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3689 error_report("Preallocation can only be used for growing images");
3690 ret = -1;
3691 goto out;
3694 if (total_size < current_size && !shrink) {
3695 warn_report("Shrinking an image will delete all data beyond the "
3696 "shrunken image's end. Before performing such an "
3697 "operation, make sure there is no important data there.");
3699 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3700 error_report(
3701 "Use the --shrink option to perform a shrink operation.");
3702 ret = -1;
3703 goto out;
3704 } else {
3705 warn_report("Using the --shrink option will suppress this message. "
3706 "Note that future versions of qemu-img may refuse to "
3707 "shrink images without this option.");
3711 ret = blk_truncate(blk, total_size, prealloc, &err);
3712 if (ret < 0) {
3713 error_report_err(err);
3714 goto out;
3717 new_size = blk_getlength(blk);
3718 if (new_size < 0) {
3719 error_report("Failed to verify truncated image length: %s",
3720 strerror(-new_size));
3721 ret = -1;
3722 goto out;
3725 /* Some block drivers implement a truncation method, but only so
3726 * the user can cause qemu to refresh the image's size from disk.
3727 * The idea is that the user resizes the image outside of qemu and
3728 * then invokes block_resize to inform qemu about it.
3729 * (This includes iscsi and file-posix for device files.)
3730 * Of course, that is not the behavior someone invoking
3731 * qemu-img resize would find useful, so we catch that behavior
3732 * here and tell the user. */
3733 if (new_size != total_size && new_size == current_size) {
3734 error_report("Image was not resized; resizing may not be supported "
3735 "for this image");
3736 ret = -1;
3737 goto out;
3740 if (new_size != total_size) {
3741 warn_report("Image should have been resized to %" PRIi64
3742 " bytes, but was resized to %" PRIi64 " bytes",
3743 total_size, new_size);
3746 qprintf(quiet, "Image resized.\n");
3748 out:
3749 blk_unref(blk);
3750 if (ret) {
3751 return 1;
3753 return 0;
3756 static void amend_status_cb(BlockDriverState *bs,
3757 int64_t offset, int64_t total_work_size,
3758 void *opaque)
3760 qemu_progress_print(100.f * offset / total_work_size, 0);
3763 static int print_amend_option_help(const char *format)
3765 BlockDriver *drv;
3767 /* Find driver and parse its options */
3768 drv = bdrv_find_format(format);
3769 if (!drv) {
3770 error_report("Unknown file format '%s'", format);
3771 return 1;
3774 if (!drv->bdrv_amend_options) {
3775 error_report("Format driver '%s' does not support option amendment",
3776 format);
3777 return 1;
3780 /* Every driver supporting amendment must have create_opts */
3781 assert(drv->create_opts);
3783 printf("Creation options for '%s':\n", format);
3784 qemu_opts_print_help(drv->create_opts, false);
3785 printf("\nNote that not all of these options may be amendable.\n");
3786 return 0;
3789 static int img_amend(int argc, char **argv)
3791 Error *err = NULL;
3792 int c, ret = 0;
3793 char *options = NULL;
3794 QemuOptsList *create_opts = NULL;
3795 QemuOpts *opts = NULL;
3796 const char *fmt = NULL, *filename, *cache;
3797 int flags;
3798 bool writethrough;
3799 bool quiet = false, progress = false;
3800 BlockBackend *blk = NULL;
3801 BlockDriverState *bs = NULL;
3802 bool image_opts = false;
3804 cache = BDRV_DEFAULT_CACHE;
3805 for (;;) {
3806 static const struct option long_options[] = {
3807 {"help", no_argument, 0, 'h'},
3808 {"object", required_argument, 0, OPTION_OBJECT},
3809 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3810 {0, 0, 0, 0}
3812 c = getopt_long(argc, argv, ":ho:f:t:pq",
3813 long_options, NULL);
3814 if (c == -1) {
3815 break;
3818 switch (c) {
3819 case ':':
3820 missing_argument(argv[optind - 1]);
3821 break;
3822 case '?':
3823 unrecognized_option(argv[optind - 1]);
3824 break;
3825 case 'h':
3826 help();
3827 break;
3828 case 'o':
3829 if (!is_valid_option_list(optarg)) {
3830 error_report("Invalid option list: %s", optarg);
3831 ret = -1;
3832 goto out_no_progress;
3834 if (!options) {
3835 options = g_strdup(optarg);
3836 } else {
3837 char *old_options = options;
3838 options = g_strdup_printf("%s,%s", options, optarg);
3839 g_free(old_options);
3841 break;
3842 case 'f':
3843 fmt = optarg;
3844 break;
3845 case 't':
3846 cache = optarg;
3847 break;
3848 case 'p':
3849 progress = true;
3850 break;
3851 case 'q':
3852 quiet = true;
3853 break;
3854 case OPTION_OBJECT:
3855 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3856 optarg, true);
3857 if (!opts) {
3858 ret = -1;
3859 goto out_no_progress;
3861 break;
3862 case OPTION_IMAGE_OPTS:
3863 image_opts = true;
3864 break;
3868 if (!options) {
3869 error_exit("Must specify options (-o)");
3872 if (qemu_opts_foreach(&qemu_object_opts,
3873 user_creatable_add_opts_foreach,
3874 NULL, &error_fatal)) {
3875 ret = -1;
3876 goto out_no_progress;
3879 if (quiet) {
3880 progress = false;
3882 qemu_progress_init(progress, 1.0);
3884 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3885 if (fmt && has_help_option(options)) {
3886 /* If a format is explicitly specified (and possibly no filename is
3887 * given), print option help here */
3888 ret = print_amend_option_help(fmt);
3889 goto out;
3892 if (optind != argc - 1) {
3893 error_report("Expecting one image file name");
3894 ret = -1;
3895 goto out;
3898 flags = BDRV_O_RDWR;
3899 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3900 if (ret < 0) {
3901 error_report("Invalid cache option: %s", cache);
3902 goto out;
3905 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3906 false);
3907 if (!blk) {
3908 ret = -1;
3909 goto out;
3911 bs = blk_bs(blk);
3913 fmt = bs->drv->format_name;
3915 if (has_help_option(options)) {
3916 /* If the format was auto-detected, print option help here */
3917 ret = print_amend_option_help(fmt);
3918 goto out;
3921 if (!bs->drv->bdrv_amend_options) {
3922 error_report("Format driver '%s' does not support option amendment",
3923 fmt);
3924 ret = -1;
3925 goto out;
3928 /* Every driver supporting amendment must have create_opts */
3929 assert(bs->drv->create_opts);
3931 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
3932 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3933 qemu_opts_do_parse(opts, options, NULL, &err);
3934 if (err) {
3935 error_report_err(err);
3936 ret = -1;
3937 goto out;
3940 /* In case the driver does not call amend_status_cb() */
3941 qemu_progress_print(0.f, 0);
3942 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
3943 qemu_progress_print(100.f, 0);
3944 if (ret < 0) {
3945 error_report_err(err);
3946 goto out;
3949 out:
3950 qemu_progress_end();
3952 out_no_progress:
3953 blk_unref(blk);
3954 qemu_opts_del(opts);
3955 qemu_opts_free(create_opts);
3956 g_free(options);
3958 if (ret) {
3959 return 1;
3961 return 0;
3964 typedef struct BenchData {
3965 BlockBackend *blk;
3966 uint64_t image_size;
3967 bool write;
3968 int bufsize;
3969 int step;
3970 int nrreq;
3971 int n;
3972 int flush_interval;
3973 bool drain_on_flush;
3974 uint8_t *buf;
3975 QEMUIOVector *qiov;
3977 int in_flight;
3978 bool in_flush;
3979 uint64_t offset;
3980 } BenchData;
3982 static void bench_undrained_flush_cb(void *opaque, int ret)
3984 if (ret < 0) {
3985 error_report("Failed flush request: %s", strerror(-ret));
3986 exit(EXIT_FAILURE);
3990 static void bench_cb(void *opaque, int ret)
3992 BenchData *b = opaque;
3993 BlockAIOCB *acb;
3995 if (ret < 0) {
3996 error_report("Failed request: %s", strerror(-ret));
3997 exit(EXIT_FAILURE);
4000 if (b->in_flush) {
4001 /* Just finished a flush with drained queue: Start next requests */
4002 assert(b->in_flight == 0);
4003 b->in_flush = false;
4004 } else if (b->in_flight > 0) {
4005 int remaining = b->n - b->in_flight;
4007 b->n--;
4008 b->in_flight--;
4010 /* Time for flush? Drain queue if requested, then flush */
4011 if (b->flush_interval && remaining % b->flush_interval == 0) {
4012 if (!b->in_flight || !b->drain_on_flush) {
4013 BlockCompletionFunc *cb;
4015 if (b->drain_on_flush) {
4016 b->in_flush = true;
4017 cb = bench_cb;
4018 } else {
4019 cb = bench_undrained_flush_cb;
4022 acb = blk_aio_flush(b->blk, cb, b);
4023 if (!acb) {
4024 error_report("Failed to issue flush request");
4025 exit(EXIT_FAILURE);
4028 if (b->drain_on_flush) {
4029 return;
4034 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4035 int64_t offset = b->offset;
4036 /* blk_aio_* might look for completed I/Os and kick bench_cb
4037 * again, so make sure this operation is counted by in_flight
4038 * and b->offset is ready for the next submission.
4040 b->in_flight++;
4041 b->offset += b->step;
4042 b->offset %= b->image_size;
4043 if (b->write) {
4044 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
4045 } else {
4046 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
4048 if (!acb) {
4049 error_report("Failed to issue request");
4050 exit(EXIT_FAILURE);
4055 static int img_bench(int argc, char **argv)
4057 int c, ret = 0;
4058 const char *fmt = NULL, *filename;
4059 bool quiet = false;
4060 bool image_opts = false;
4061 bool is_write = false;
4062 int count = 75000;
4063 int depth = 64;
4064 int64_t offset = 0;
4065 size_t bufsize = 4096;
4066 int pattern = 0;
4067 size_t step = 0;
4068 int flush_interval = 0;
4069 bool drain_on_flush = true;
4070 int64_t image_size;
4071 BlockBackend *blk = NULL;
4072 BenchData data = {};
4073 int flags = 0;
4074 bool writethrough = false;
4075 struct timeval t1, t2;
4076 int i;
4077 bool force_share = false;
4078 size_t buf_size;
4080 for (;;) {
4081 static const struct option long_options[] = {
4082 {"help", no_argument, 0, 'h'},
4083 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
4084 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4085 {"pattern", required_argument, 0, OPTION_PATTERN},
4086 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
4087 {"force-share", no_argument, 0, 'U'},
4088 {0, 0, 0, 0}
4090 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
4091 if (c == -1) {
4092 break;
4095 switch (c) {
4096 case ':':
4097 missing_argument(argv[optind - 1]);
4098 break;
4099 case '?':
4100 unrecognized_option(argv[optind - 1]);
4101 break;
4102 case 'h':
4103 help();
4104 break;
4105 case 'c':
4107 unsigned long res;
4109 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4110 error_report("Invalid request count specified");
4111 return 1;
4113 count = res;
4114 break;
4116 case 'd':
4118 unsigned long res;
4120 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4121 error_report("Invalid queue depth specified");
4122 return 1;
4124 depth = res;
4125 break;
4127 case 'f':
4128 fmt = optarg;
4129 break;
4130 case 'n':
4131 flags |= BDRV_O_NATIVE_AIO;
4132 break;
4133 case 'o':
4135 offset = cvtnum(optarg);
4136 if (offset < 0) {
4137 error_report("Invalid offset specified");
4138 return 1;
4140 break;
4142 break;
4143 case 'q':
4144 quiet = true;
4145 break;
4146 case 's':
4148 int64_t sval;
4150 sval = cvtnum(optarg);
4151 if (sval < 0 || sval > INT_MAX) {
4152 error_report("Invalid buffer size specified");
4153 return 1;
4156 bufsize = sval;
4157 break;
4159 case 'S':
4161 int64_t sval;
4163 sval = cvtnum(optarg);
4164 if (sval < 0 || sval > INT_MAX) {
4165 error_report("Invalid step size specified");
4166 return 1;
4169 step = sval;
4170 break;
4172 case 't':
4173 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4174 if (ret < 0) {
4175 error_report("Invalid cache mode");
4176 ret = -1;
4177 goto out;
4179 break;
4180 case 'w':
4181 flags |= BDRV_O_RDWR;
4182 is_write = true;
4183 break;
4184 case 'U':
4185 force_share = true;
4186 break;
4187 case OPTION_PATTERN:
4189 unsigned long res;
4191 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4192 error_report("Invalid pattern byte specified");
4193 return 1;
4195 pattern = res;
4196 break;
4198 case OPTION_FLUSH_INTERVAL:
4200 unsigned long res;
4202 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4203 error_report("Invalid flush interval specified");
4204 return 1;
4206 flush_interval = res;
4207 break;
4209 case OPTION_NO_DRAIN:
4210 drain_on_flush = false;
4211 break;
4212 case OPTION_IMAGE_OPTS:
4213 image_opts = true;
4214 break;
4218 if (optind != argc - 1) {
4219 error_exit("Expecting one image file name");
4221 filename = argv[argc - 1];
4223 if (!is_write && flush_interval) {
4224 error_report("--flush-interval is only available in write tests");
4225 ret = -1;
4226 goto out;
4228 if (flush_interval && flush_interval < depth) {
4229 error_report("Flush interval can't be smaller than depth");
4230 ret = -1;
4231 goto out;
4234 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4235 force_share);
4236 if (!blk) {
4237 ret = -1;
4238 goto out;
4241 image_size = blk_getlength(blk);
4242 if (image_size < 0) {
4243 ret = image_size;
4244 goto out;
4247 data = (BenchData) {
4248 .blk = blk,
4249 .image_size = image_size,
4250 .bufsize = bufsize,
4251 .step = step ?: bufsize,
4252 .nrreq = depth,
4253 .n = count,
4254 .offset = offset,
4255 .write = is_write,
4256 .flush_interval = flush_interval,
4257 .drain_on_flush = drain_on_flush,
4259 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4260 "(starting at offset %" PRId64 ", step size %d)\n",
4261 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4262 data.offset, data.step);
4263 if (flush_interval) {
4264 printf("Sending flush every %d requests\n", flush_interval);
4267 buf_size = data.nrreq * data.bufsize;
4268 data.buf = blk_blockalign(blk, buf_size);
4269 memset(data.buf, pattern, data.nrreq * data.bufsize);
4271 blk_register_buf(blk, data.buf, buf_size);
4273 data.qiov = g_new(QEMUIOVector, data.nrreq);
4274 for (i = 0; i < data.nrreq; i++) {
4275 qemu_iovec_init(&data.qiov[i], 1);
4276 qemu_iovec_add(&data.qiov[i],
4277 data.buf + i * data.bufsize, data.bufsize);
4280 gettimeofday(&t1, NULL);
4281 bench_cb(&data, 0);
4283 while (data.n > 0) {
4284 main_loop_wait(false);
4286 gettimeofday(&t2, NULL);
4288 printf("Run completed in %3.3f seconds.\n",
4289 (t2.tv_sec - t1.tv_sec)
4290 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4292 out:
4293 if (data.buf) {
4294 blk_unregister_buf(blk, data.buf);
4296 qemu_vfree(data.buf);
4297 blk_unref(blk);
4299 if (ret) {
4300 return 1;
4302 return 0;
4305 #define C_BS 01
4306 #define C_COUNT 02
4307 #define C_IF 04
4308 #define C_OF 010
4309 #define C_SKIP 020
4311 struct DdInfo {
4312 unsigned int flags;
4313 int64_t count;
4316 struct DdIo {
4317 int bsz; /* Block size */
4318 char *filename;
4319 uint8_t *buf;
4320 int64_t offset;
4323 struct DdOpts {
4324 const char *name;
4325 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4326 unsigned int flag;
4329 static int img_dd_bs(const char *arg,
4330 struct DdIo *in, struct DdIo *out,
4331 struct DdInfo *dd)
4333 int64_t res;
4335 res = cvtnum(arg);
4337 if (res <= 0 || res > INT_MAX) {
4338 error_report("invalid number: '%s'", arg);
4339 return 1;
4341 in->bsz = out->bsz = res;
4343 return 0;
4346 static int img_dd_count(const char *arg,
4347 struct DdIo *in, struct DdIo *out,
4348 struct DdInfo *dd)
4350 dd->count = cvtnum(arg);
4352 if (dd->count < 0) {
4353 error_report("invalid number: '%s'", arg);
4354 return 1;
4357 return 0;
4360 static int img_dd_if(const char *arg,
4361 struct DdIo *in, struct DdIo *out,
4362 struct DdInfo *dd)
4364 in->filename = g_strdup(arg);
4366 return 0;
4369 static int img_dd_of(const char *arg,
4370 struct DdIo *in, struct DdIo *out,
4371 struct DdInfo *dd)
4373 out->filename = g_strdup(arg);
4375 return 0;
4378 static int img_dd_skip(const char *arg,
4379 struct DdIo *in, struct DdIo *out,
4380 struct DdInfo *dd)
4382 in->offset = cvtnum(arg);
4384 if (in->offset < 0) {
4385 error_report("invalid number: '%s'", arg);
4386 return 1;
4389 return 0;
4392 static int img_dd(int argc, char **argv)
4394 int ret = 0;
4395 char *arg = NULL;
4396 char *tmp;
4397 BlockDriver *drv = NULL, *proto_drv = NULL;
4398 BlockBackend *blk1 = NULL, *blk2 = NULL;
4399 QemuOpts *opts = NULL;
4400 QemuOptsList *create_opts = NULL;
4401 Error *local_err = NULL;
4402 bool image_opts = false;
4403 int c, i;
4404 const char *out_fmt = "raw";
4405 const char *fmt = NULL;
4406 int64_t size = 0;
4407 int64_t block_count = 0, out_pos, in_pos;
4408 bool force_share = false;
4409 struct DdInfo dd = {
4410 .flags = 0,
4411 .count = 0,
4413 struct DdIo in = {
4414 .bsz = 512, /* Block size is by default 512 bytes */
4415 .filename = NULL,
4416 .buf = NULL,
4417 .offset = 0
4419 struct DdIo out = {
4420 .bsz = 512,
4421 .filename = NULL,
4422 .buf = NULL,
4423 .offset = 0
4426 const struct DdOpts options[] = {
4427 { "bs", img_dd_bs, C_BS },
4428 { "count", img_dd_count, C_COUNT },
4429 { "if", img_dd_if, C_IF },
4430 { "of", img_dd_of, C_OF },
4431 { "skip", img_dd_skip, C_SKIP },
4432 { NULL, NULL, 0 }
4434 const struct option long_options[] = {
4435 { "help", no_argument, 0, 'h'},
4436 { "object", required_argument, 0, OPTION_OBJECT},
4437 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4438 { "force-share", no_argument, 0, 'U'},
4439 { 0, 0, 0, 0 }
4442 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4443 if (c == EOF) {
4444 break;
4446 switch (c) {
4447 case 'O':
4448 out_fmt = optarg;
4449 break;
4450 case 'f':
4451 fmt = optarg;
4452 break;
4453 case ':':
4454 missing_argument(argv[optind - 1]);
4455 break;
4456 case '?':
4457 unrecognized_option(argv[optind - 1]);
4458 break;
4459 case 'h':
4460 help();
4461 break;
4462 case 'U':
4463 force_share = true;
4464 break;
4465 case OPTION_OBJECT:
4466 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4467 ret = -1;
4468 goto out;
4470 break;
4471 case OPTION_IMAGE_OPTS:
4472 image_opts = true;
4473 break;
4477 for (i = optind; i < argc; i++) {
4478 int j;
4479 arg = g_strdup(argv[i]);
4481 tmp = strchr(arg, '=');
4482 if (tmp == NULL) {
4483 error_report("unrecognized operand %s", arg);
4484 ret = -1;
4485 goto out;
4488 *tmp++ = '\0';
4490 for (j = 0; options[j].name != NULL; j++) {
4491 if (!strcmp(arg, options[j].name)) {
4492 break;
4495 if (options[j].name == NULL) {
4496 error_report("unrecognized operand %s", arg);
4497 ret = -1;
4498 goto out;
4501 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4502 ret = -1;
4503 goto out;
4505 dd.flags |= options[j].flag;
4506 g_free(arg);
4507 arg = NULL;
4510 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4511 error_report("Must specify both input and output files");
4512 ret = -1;
4513 goto out;
4516 if (qemu_opts_foreach(&qemu_object_opts,
4517 user_creatable_add_opts_foreach,
4518 NULL, &error_fatal)) {
4519 ret = -1;
4520 goto out;
4523 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4524 force_share);
4526 if (!blk1) {
4527 ret = -1;
4528 goto out;
4531 drv = bdrv_find_format(out_fmt);
4532 if (!drv) {
4533 error_report("Unknown file format");
4534 ret = -1;
4535 goto out;
4537 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4539 if (!proto_drv) {
4540 error_report_err(local_err);
4541 ret = -1;
4542 goto out;
4544 if (!drv->create_opts) {
4545 error_report("Format driver '%s' does not support image creation",
4546 drv->format_name);
4547 ret = -1;
4548 goto out;
4550 if (!proto_drv->create_opts) {
4551 error_report("Protocol driver '%s' does not support image creation",
4552 proto_drv->format_name);
4553 ret = -1;
4554 goto out;
4556 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4557 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4559 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4561 size = blk_getlength(blk1);
4562 if (size < 0) {
4563 error_report("Failed to get size for '%s'", in.filename);
4564 ret = -1;
4565 goto out;
4568 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4569 dd.count * in.bsz < size) {
4570 size = dd.count * in.bsz;
4573 /* Overflow means the specified offset is beyond input image's size */
4574 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4575 size < in.bsz * in.offset)) {
4576 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4577 } else {
4578 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4579 size - in.bsz * in.offset, &error_abort);
4582 ret = bdrv_create(drv, out.filename, opts, &local_err);
4583 if (ret < 0) {
4584 error_reportf_err(local_err,
4585 "%s: error while creating output image: ",
4586 out.filename);
4587 ret = -1;
4588 goto out;
4591 /* TODO, we can't honour --image-opts for the target,
4592 * since it needs to be given in a format compatible
4593 * with the bdrv_create() call above which does not
4594 * support image-opts style.
4596 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
4597 false, false, false);
4599 if (!blk2) {
4600 ret = -1;
4601 goto out;
4604 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4605 size < in.offset * in.bsz)) {
4606 /* We give a warning if the skip option is bigger than the input
4607 * size and create an empty output disk image (i.e. like dd(1)).
4609 error_report("%s: cannot skip to specified offset", in.filename);
4610 in_pos = size;
4611 } else {
4612 in_pos = in.offset * in.bsz;
4615 in.buf = g_new(uint8_t, in.bsz);
4617 for (out_pos = 0; in_pos < size; block_count++) {
4618 int in_ret, out_ret;
4620 if (in_pos + in.bsz > size) {
4621 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4622 } else {
4623 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4625 if (in_ret < 0) {
4626 error_report("error while reading from input image file: %s",
4627 strerror(-in_ret));
4628 ret = -1;
4629 goto out;
4631 in_pos += in_ret;
4633 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4635 if (out_ret < 0) {
4636 error_report("error while writing to output image file: %s",
4637 strerror(-out_ret));
4638 ret = -1;
4639 goto out;
4641 out_pos += out_ret;
4644 out:
4645 g_free(arg);
4646 qemu_opts_del(opts);
4647 qemu_opts_free(create_opts);
4648 blk_unref(blk1);
4649 blk_unref(blk2);
4650 g_free(in.filename);
4651 g_free(out.filename);
4652 g_free(in.buf);
4653 g_free(out.buf);
4655 if (ret) {
4656 return 1;
4658 return 0;
4661 static void dump_json_block_measure_info(BlockMeasureInfo *info)
4663 QString *str;
4664 QObject *obj;
4665 Visitor *v = qobject_output_visitor_new(&obj);
4667 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4668 visit_complete(v, &obj);
4669 str = qobject_to_json_pretty(obj);
4670 assert(str != NULL);
4671 printf("%s\n", qstring_get_str(str));
4672 qobject_unref(obj);
4673 visit_free(v);
4674 qobject_unref(str);
4677 static int img_measure(int argc, char **argv)
4679 static const struct option long_options[] = {
4680 {"help", no_argument, 0, 'h'},
4681 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4682 {"object", required_argument, 0, OPTION_OBJECT},
4683 {"output", required_argument, 0, OPTION_OUTPUT},
4684 {"size", required_argument, 0, OPTION_SIZE},
4685 {"force-share", no_argument, 0, 'U'},
4686 {0, 0, 0, 0}
4688 OutputFormat output_format = OFORMAT_HUMAN;
4689 BlockBackend *in_blk = NULL;
4690 BlockDriver *drv;
4691 const char *filename = NULL;
4692 const char *fmt = NULL;
4693 const char *out_fmt = "raw";
4694 char *options = NULL;
4695 char *snapshot_name = NULL;
4696 bool force_share = false;
4697 QemuOpts *opts = NULL;
4698 QemuOpts *object_opts = NULL;
4699 QemuOpts *sn_opts = NULL;
4700 QemuOptsList *create_opts = NULL;
4701 bool image_opts = false;
4702 uint64_t img_size = UINT64_MAX;
4703 BlockMeasureInfo *info = NULL;
4704 Error *local_err = NULL;
4705 int ret = 1;
4706 int c;
4708 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4709 long_options, NULL)) != -1) {
4710 switch (c) {
4711 case '?':
4712 case 'h':
4713 help();
4714 break;
4715 case 'f':
4716 fmt = optarg;
4717 break;
4718 case 'O':
4719 out_fmt = optarg;
4720 break;
4721 case 'o':
4722 if (!is_valid_option_list(optarg)) {
4723 error_report("Invalid option list: %s", optarg);
4724 goto out;
4726 if (!options) {
4727 options = g_strdup(optarg);
4728 } else {
4729 char *old_options = options;
4730 options = g_strdup_printf("%s,%s", options, optarg);
4731 g_free(old_options);
4733 break;
4734 case 'l':
4735 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4736 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4737 optarg, false);
4738 if (!sn_opts) {
4739 error_report("Failed in parsing snapshot param '%s'",
4740 optarg);
4741 goto out;
4743 } else {
4744 snapshot_name = optarg;
4746 break;
4747 case 'U':
4748 force_share = true;
4749 break;
4750 case OPTION_OBJECT:
4751 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4752 optarg, true);
4753 if (!object_opts) {
4754 goto out;
4756 break;
4757 case OPTION_IMAGE_OPTS:
4758 image_opts = true;
4759 break;
4760 case OPTION_OUTPUT:
4761 if (!strcmp(optarg, "json")) {
4762 output_format = OFORMAT_JSON;
4763 } else if (!strcmp(optarg, "human")) {
4764 output_format = OFORMAT_HUMAN;
4765 } else {
4766 error_report("--output must be used with human or json "
4767 "as argument.");
4768 goto out;
4770 break;
4771 case OPTION_SIZE:
4773 int64_t sval;
4775 sval = cvtnum(optarg);
4776 if (sval < 0) {
4777 if (sval == -ERANGE) {
4778 error_report("Image size must be less than 8 EiB!");
4779 } else {
4780 error_report("Invalid image size specified! You may use "
4781 "k, M, G, T, P or E suffixes for ");
4782 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4783 "petabytes and exabytes.");
4785 goto out;
4787 img_size = (uint64_t)sval;
4789 break;
4793 if (qemu_opts_foreach(&qemu_object_opts,
4794 user_creatable_add_opts_foreach,
4795 NULL, &error_fatal)) {
4796 goto out;
4799 if (argc - optind > 1) {
4800 error_report("At most one filename argument is allowed.");
4801 goto out;
4802 } else if (argc - optind == 1) {
4803 filename = argv[optind];
4806 if (!filename &&
4807 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4808 error_report("--object, --image-opts, -f, and -l "
4809 "require a filename argument.");
4810 goto out;
4812 if (filename && img_size != UINT64_MAX) {
4813 error_report("--size N cannot be used together with a filename.");
4814 goto out;
4816 if (!filename && img_size == UINT64_MAX) {
4817 error_report("Either --size N or one filename must be specified.");
4818 goto out;
4821 if (filename) {
4822 in_blk = img_open(image_opts, filename, fmt, 0,
4823 false, false, force_share);
4824 if (!in_blk) {
4825 goto out;
4828 if (sn_opts) {
4829 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4830 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4831 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4832 &local_err);
4833 } else if (snapshot_name != NULL) {
4834 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4835 snapshot_name, &local_err);
4837 if (local_err) {
4838 error_reportf_err(local_err, "Failed to load snapshot: ");
4839 goto out;
4843 drv = bdrv_find_format(out_fmt);
4844 if (!drv) {
4845 error_report("Unknown file format '%s'", out_fmt);
4846 goto out;
4848 if (!drv->create_opts) {
4849 error_report("Format driver '%s' does not support image creation",
4850 drv->format_name);
4851 goto out;
4854 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4855 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4856 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4857 if (options) {
4858 qemu_opts_do_parse(opts, options, NULL, &local_err);
4859 if (local_err) {
4860 error_report_err(local_err);
4861 error_report("Invalid options for file format '%s'", out_fmt);
4862 goto out;
4865 if (img_size != UINT64_MAX) {
4866 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4869 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4870 if (local_err) {
4871 error_report_err(local_err);
4872 goto out;
4875 if (output_format == OFORMAT_HUMAN) {
4876 printf("required size: %" PRIu64 "\n", info->required);
4877 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4878 } else {
4879 dump_json_block_measure_info(info);
4882 ret = 0;
4884 out:
4885 qapi_free_BlockMeasureInfo(info);
4886 qemu_opts_del(object_opts);
4887 qemu_opts_del(opts);
4888 qemu_opts_del(sn_opts);
4889 qemu_opts_free(create_opts);
4890 g_free(options);
4891 blk_unref(in_blk);
4892 return ret;
4895 static const img_cmd_t img_cmds[] = {
4896 #define DEF(option, callback, arg_string) \
4897 { option, callback },
4898 #include "qemu-img-cmds.h"
4899 #undef DEF
4900 { NULL, NULL, },
4903 int main(int argc, char **argv)
4905 const img_cmd_t *cmd;
4906 const char *cmdname;
4907 Error *local_error = NULL;
4908 char *trace_file = NULL;
4909 int c;
4910 static const struct option long_options[] = {
4911 {"help", no_argument, 0, 'h'},
4912 {"version", no_argument, 0, 'V'},
4913 {"trace", required_argument, NULL, 'T'},
4914 {0, 0, 0, 0}
4917 #ifdef CONFIG_POSIX
4918 signal(SIGPIPE, SIG_IGN);
4919 #endif
4921 module_call_init(MODULE_INIT_TRACE);
4922 error_set_progname(argv[0]);
4923 qemu_init_exec_dir(argv[0]);
4925 if (qemu_init_main_loop(&local_error)) {
4926 error_report_err(local_error);
4927 exit(EXIT_FAILURE);
4930 qcrypto_init(&error_fatal);
4932 module_call_init(MODULE_INIT_QOM);
4933 bdrv_init();
4934 if (argc < 2) {
4935 error_exit("Not enough arguments");
4938 qemu_add_opts(&qemu_object_opts);
4939 qemu_add_opts(&qemu_source_opts);
4940 qemu_add_opts(&qemu_trace_opts);
4942 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
4943 switch (c) {
4944 case ':':
4945 missing_argument(argv[optind - 1]);
4946 return 0;
4947 case '?':
4948 unrecognized_option(argv[optind - 1]);
4949 return 0;
4950 case 'h':
4951 help();
4952 return 0;
4953 case 'V':
4954 printf(QEMU_IMG_VERSION);
4955 return 0;
4956 case 'T':
4957 g_free(trace_file);
4958 trace_file = trace_opt_parse(optarg);
4959 break;
4963 cmdname = argv[optind];
4965 /* reset getopt_long scanning */
4966 argc -= optind;
4967 if (argc < 1) {
4968 return 0;
4970 argv += optind;
4971 qemu_reset_optind();
4973 if (!trace_init_backends()) {
4974 exit(1);
4976 trace_init_file(trace_file);
4977 qemu_set_log(LOG_TRACE);
4979 /* find the command */
4980 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4981 if (!strcmp(cmdname, cmd->name)) {
4982 return cmd->handler(argc, argv);
4986 /* not found */
4987 error_exit("Command not found: %s", cmdname);