qcow2: Fix qcow2_make_empty() with external data file
[qemu/ar7.git] / qemu-img.c
blobddd55ab29150440b06df491c97bfb3dd20fefa41
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 va_start(ap, fmt);
89 error_vreport(fmt, ap);
90 va_end(ap);
92 error_printf("Try 'qemu-img --help' for more information\n");
93 exit(EXIT_FAILURE);
96 static void QEMU_NORETURN missing_argument(const char *option)
98 error_exit("missing argument for option '%s'", option);
101 static void QEMU_NORETURN unrecognized_option(const char *option)
103 error_exit("unrecognized option '%s'", option);
106 /* Please keep in synch with qemu-img.texi */
107 static void QEMU_NORETURN help(void)
109 const char *help_msg =
110 QEMU_IMG_VERSION
111 "usage: qemu-img [standard options] command [command options]\n"
112 "QEMU disk image utility\n"
113 "\n"
114 " '-h', '--help' display this help and exit\n"
115 " '-V', '--version' output version information and exit\n"
116 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
117 " specify tracing options\n"
118 "\n"
119 "Command syntax:\n"
120 #define DEF(option, callback, arg_string) \
121 " " arg_string "\n"
122 #include "qemu-img-cmds.h"
123 #undef DEF
124 "\n"
125 "Command parameters:\n"
126 " 'filename' is a disk image filename\n"
127 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
128 " manual page for a description of the object properties. The most common\n"
129 " object type is a 'secret', which is used to supply passwords and/or\n"
130 " encryption keys.\n"
131 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
132 " 'cache' is the cache mode used to write the output disk image, the valid\n"
133 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
134 " 'directsync' and 'unsafe' (default for convert)\n"
135 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
136 " options are the same as for the 'cache' option\n"
137 " 'size' is the disk image size in bytes. Optional suffixes\n"
138 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
139 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
140 " supported. 'b' is ignored.\n"
141 " 'output_filename' is the destination disk image filename\n"
142 " 'output_fmt' is the destination format\n"
143 " 'options' is a comma separated list of format specific options in a\n"
144 " name=value format. Use -o ? for an overview of the options supported by the\n"
145 " used format\n"
146 " 'snapshot_param' is param used for internal snapshot, format\n"
147 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
148 " '[ID_OR_NAME]'\n"
149 " '-c' indicates that target image must be compressed (qcow format only)\n"
150 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
151 " new backing file match exactly. The image doesn't need a working\n"
152 " backing file before rebasing in this case (useful for renaming the\n"
153 " backing file). For image creation, allow creating without attempting\n"
154 " to open the backing file.\n"
155 " '-h' with or without a command shows this help and lists the supported formats\n"
156 " '-p' show progress of command (only certain commands)\n"
157 " '-q' use Quiet mode - do not print any output (except errors)\n"
158 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
159 " contain only zeros for qemu-img to create a sparse image during\n"
160 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
161 " unallocated or zero sectors, and the destination image will always be\n"
162 " fully allocated\n"
163 " '--output' takes the format in which the output must be done (human or json)\n"
164 " '-n' skips the target volume creation (useful if the volume is created\n"
165 " prior to running qemu-img)\n"
166 "\n"
167 "Parameters to check subcommand:\n"
168 " '-r' tries to repair any inconsistencies that are found during the check.\n"
169 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
170 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
171 " hiding corruption that has already occurred.\n"
172 "\n"
173 "Parameters to convert subcommand:\n"
174 " '-m' specifies how many coroutines work in parallel during the convert\n"
175 " process (defaults to 8)\n"
176 " '-W' allow to write to the target out of order rather than sequential\n"
177 "\n"
178 "Parameters to snapshot subcommand:\n"
179 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
180 " '-a' applies a snapshot (revert disk to saved state)\n"
181 " '-c' creates a snapshot\n"
182 " '-d' deletes a snapshot\n"
183 " '-l' lists all snapshots in the given image\n"
184 "\n"
185 "Parameters to compare subcommand:\n"
186 " '-f' first image format\n"
187 " '-F' second image format\n"
188 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
189 "\n"
190 "Parameters to dd subcommand:\n"
191 " 'bs=BYTES' read and write up to BYTES bytes at a time "
192 "(default: 512)\n"
193 " 'count=N' copy only N input blocks\n"
194 " 'if=FILE' read from FILE\n"
195 " 'of=FILE' write to FILE\n"
196 " 'skip=N' skip N bs-sized blocks at the start of input\n";
198 printf("%s\nSupported formats:", help_msg);
199 bdrv_iterate_format(format_print, NULL, false);
200 printf("\n\n" QEMU_HELP_BOTTOM "\n");
201 exit(EXIT_SUCCESS);
204 static QemuOptsList qemu_object_opts = {
205 .name = "object",
206 .implied_opt_name = "qom-type",
207 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
208 .desc = {
213 static QemuOptsList qemu_source_opts = {
214 .name = "source",
215 .implied_opt_name = "file",
216 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
217 .desc = {
222 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
224 int ret = 0;
225 if (!quiet) {
226 va_list args;
227 va_start(args, fmt);
228 ret = vprintf(fmt, args);
229 va_end(args);
231 return ret;
235 static int print_block_option_help(const char *filename, const char *fmt)
237 BlockDriver *drv, *proto_drv;
238 QemuOptsList *create_opts = NULL;
239 Error *local_err = NULL;
241 /* Find driver and parse its options */
242 drv = bdrv_find_format(fmt);
243 if (!drv) {
244 error_report("Unknown file format '%s'", fmt);
245 return 1;
248 if (!drv->create_opts) {
249 error_report("Format driver '%s' does not support image creation", fmt);
250 return 1;
253 create_opts = qemu_opts_append(create_opts, drv->create_opts);
254 if (filename) {
255 proto_drv = bdrv_find_protocol(filename, true, &local_err);
256 if (!proto_drv) {
257 error_report_err(local_err);
258 qemu_opts_free(create_opts);
259 return 1;
261 if (!proto_drv->create_opts) {
262 error_report("Protocol driver '%s' does not support image creation",
263 proto_drv->format_name);
264 qemu_opts_free(create_opts);
265 return 1;
267 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
270 if (filename) {
271 printf("Supported options:\n");
272 } else {
273 printf("Supported %s options:\n", fmt);
275 qemu_opts_print_help(create_opts, false);
276 qemu_opts_free(create_opts);
278 if (!filename) {
279 printf("\n"
280 "The protocol level may support further options.\n"
281 "Specify the target filename to include those options.\n");
284 return 0;
288 static BlockBackend *img_open_opts(const char *optstr,
289 QemuOpts *opts, int flags, bool writethrough,
290 bool quiet, bool force_share)
292 QDict *options;
293 Error *local_err = NULL;
294 BlockBackend *blk;
295 options = qemu_opts_to_qdict(opts, NULL);
296 if (force_share) {
297 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
298 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
299 error_report("--force-share/-U conflicts with image options");
300 qobject_unref(options);
301 return NULL;
303 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
305 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
306 if (!blk) {
307 error_reportf_err(local_err, "Could not open '%s': ", optstr);
308 return NULL;
310 blk_set_enable_write_cache(blk, !writethrough);
312 return blk;
315 static BlockBackend *img_open_file(const char *filename,
316 QDict *options,
317 const char *fmt, int flags,
318 bool writethrough, bool quiet,
319 bool force_share)
321 BlockBackend *blk;
322 Error *local_err = NULL;
324 if (!options) {
325 options = qdict_new();
327 if (fmt) {
328 qdict_put_str(options, "driver", fmt);
331 if (force_share) {
332 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
334 blk = blk_new_open(filename, NULL, options, flags, &local_err);
335 if (!blk) {
336 error_reportf_err(local_err, "Could not open '%s': ", filename);
337 return NULL;
339 blk_set_enable_write_cache(blk, !writethrough);
341 return blk;
345 static int img_add_key_secrets(void *opaque,
346 const char *name, const char *value,
347 Error **errp)
349 QDict *options = opaque;
351 if (g_str_has_suffix(name, "key-secret")) {
352 qdict_put_str(options, name, value);
355 return 0;
359 static BlockBackend *img_open(bool image_opts,
360 const char *filename,
361 const char *fmt, int flags, bool writethrough,
362 bool quiet, bool force_share)
364 BlockBackend *blk;
365 if (image_opts) {
366 QemuOpts *opts;
367 if (fmt) {
368 error_report("--image-opts and --format are mutually exclusive");
369 return NULL;
371 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
372 filename, true);
373 if (!opts) {
374 return NULL;
376 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
377 force_share);
378 } else {
379 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
380 force_share);
382 return blk;
386 static int add_old_style_options(const char *fmt, QemuOpts *opts,
387 const char *base_filename,
388 const char *base_fmt)
390 Error *err = NULL;
392 if (base_filename) {
393 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
394 if (err) {
395 error_report("Backing file not supported for file format '%s'",
396 fmt);
397 error_free(err);
398 return -1;
401 if (base_fmt) {
402 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
403 if (err) {
404 error_report("Backing file format not supported for file "
405 "format '%s'", fmt);
406 error_free(err);
407 return -1;
410 return 0;
413 static int64_t cvtnum(const char *s)
415 int err;
416 uint64_t value;
418 err = qemu_strtosz(s, NULL, &value);
419 if (err < 0) {
420 return err;
422 if (value > INT64_MAX) {
423 return -ERANGE;
425 return value;
428 static int img_create(int argc, char **argv)
430 int c;
431 uint64_t img_size = -1;
432 const char *fmt = "raw";
433 const char *base_fmt = NULL;
434 const char *filename;
435 const char *base_filename = NULL;
436 char *options = NULL;
437 Error *local_err = NULL;
438 bool quiet = false;
439 int flags = 0;
441 for(;;) {
442 static const struct option long_options[] = {
443 {"help", no_argument, 0, 'h'},
444 {"object", required_argument, 0, OPTION_OBJECT},
445 {0, 0, 0, 0}
447 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
448 long_options, NULL);
449 if (c == -1) {
450 break;
452 switch(c) {
453 case ':':
454 missing_argument(argv[optind - 1]);
455 break;
456 case '?':
457 unrecognized_option(argv[optind - 1]);
458 break;
459 case 'h':
460 help();
461 break;
462 case 'F':
463 base_fmt = optarg;
464 break;
465 case 'b':
466 base_filename = optarg;
467 break;
468 case 'f':
469 fmt = optarg;
470 break;
471 case 'o':
472 if (!is_valid_option_list(optarg)) {
473 error_report("Invalid option list: %s", optarg);
474 goto fail;
476 if (!options) {
477 options = g_strdup(optarg);
478 } else {
479 char *old_options = options;
480 options = g_strdup_printf("%s,%s", options, optarg);
481 g_free(old_options);
483 break;
484 case 'q':
485 quiet = true;
486 break;
487 case 'u':
488 flags |= BDRV_O_NO_BACKING;
489 break;
490 case OPTION_OBJECT: {
491 QemuOpts *opts;
492 opts = qemu_opts_parse_noisily(&qemu_object_opts,
493 optarg, true);
494 if (!opts) {
495 goto fail;
497 } break;
501 /* Get the filename */
502 filename = (optind < argc) ? argv[optind] : NULL;
503 if (options && has_help_option(options)) {
504 g_free(options);
505 return print_block_option_help(filename, fmt);
508 if (optind >= argc) {
509 error_exit("Expecting image file name");
511 optind++;
513 if (qemu_opts_foreach(&qemu_object_opts,
514 user_creatable_add_opts_foreach,
515 NULL, &error_fatal)) {
516 goto fail;
519 /* Get image size, if specified */
520 if (optind < argc) {
521 int64_t sval;
523 sval = cvtnum(argv[optind++]);
524 if (sval < 0) {
525 if (sval == -ERANGE) {
526 error_report("Image size must be less than 8 EiB!");
527 } else {
528 error_report("Invalid image size specified! You may use k, M, "
529 "G, T, P or E suffixes for ");
530 error_report("kilobytes, megabytes, gigabytes, terabytes, "
531 "petabytes and exabytes.");
533 goto fail;
535 img_size = (uint64_t)sval;
537 if (optind != argc) {
538 error_exit("Unexpected argument: %s", argv[optind]);
541 bdrv_img_create(filename, fmt, base_filename, base_fmt,
542 options, img_size, flags, quiet, &local_err);
543 if (local_err) {
544 error_reportf_err(local_err, "%s: ", filename);
545 goto fail;
548 g_free(options);
549 return 0;
551 fail:
552 g_free(options);
553 return 1;
556 static void dump_json_image_check(ImageCheck *check, bool quiet)
558 QString *str;
559 QObject *obj;
560 Visitor *v = qobject_output_visitor_new(&obj);
562 visit_type_ImageCheck(v, NULL, &check, &error_abort);
563 visit_complete(v, &obj);
564 str = qobject_to_json_pretty(obj);
565 assert(str != NULL);
566 qprintf(quiet, "%s\n", qstring_get_str(str));
567 qobject_unref(obj);
568 visit_free(v);
569 qobject_unref(str);
572 static void dump_human_image_check(ImageCheck *check, bool quiet)
574 if (!(check->corruptions || check->leaks || check->check_errors)) {
575 qprintf(quiet, "No errors were found on the image.\n");
576 } else {
577 if (check->corruptions) {
578 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
579 "Data may be corrupted, or further writes to the image "
580 "may corrupt it.\n",
581 check->corruptions);
584 if (check->leaks) {
585 qprintf(quiet,
586 "\n%" PRId64 " leaked clusters were found on the image.\n"
587 "This means waste of disk space, but no harm to data.\n",
588 check->leaks);
591 if (check->check_errors) {
592 qprintf(quiet,
593 "\n%" PRId64
594 " internal errors have occurred during the check.\n",
595 check->check_errors);
599 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
600 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
601 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
602 check->allocated_clusters, check->total_clusters,
603 check->allocated_clusters * 100.0 / check->total_clusters,
604 check->fragmented_clusters * 100.0 / check->allocated_clusters,
605 check->compressed_clusters * 100.0 /
606 check->allocated_clusters);
609 if (check->image_end_offset) {
610 qprintf(quiet,
611 "Image end offset: %" PRId64 "\n", check->image_end_offset);
615 static int collect_image_check(BlockDriverState *bs,
616 ImageCheck *check,
617 const char *filename,
618 const char *fmt,
619 int fix)
621 int ret;
622 BdrvCheckResult result;
624 ret = bdrv_check(bs, &result, fix);
625 if (ret < 0) {
626 return ret;
629 check->filename = g_strdup(filename);
630 check->format = g_strdup(bdrv_get_format_name(bs));
631 check->check_errors = result.check_errors;
632 check->corruptions = result.corruptions;
633 check->has_corruptions = result.corruptions != 0;
634 check->leaks = result.leaks;
635 check->has_leaks = result.leaks != 0;
636 check->corruptions_fixed = result.corruptions_fixed;
637 check->has_corruptions_fixed = result.corruptions != 0;
638 check->leaks_fixed = result.leaks_fixed;
639 check->has_leaks_fixed = result.leaks != 0;
640 check->image_end_offset = result.image_end_offset;
641 check->has_image_end_offset = result.image_end_offset != 0;
642 check->total_clusters = result.bfi.total_clusters;
643 check->has_total_clusters = result.bfi.total_clusters != 0;
644 check->allocated_clusters = result.bfi.allocated_clusters;
645 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
646 check->fragmented_clusters = result.bfi.fragmented_clusters;
647 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
648 check->compressed_clusters = result.bfi.compressed_clusters;
649 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
651 return 0;
655 * Checks an image for consistency. Exit codes:
657 * 0 - Check completed, image is good
658 * 1 - Check not completed because of internal errors
659 * 2 - Check completed, image is corrupted
660 * 3 - Check completed, image has leaked clusters, but is good otherwise
661 * 63 - Checks are not supported by the image format
663 static int img_check(int argc, char **argv)
665 int c, ret;
666 OutputFormat output_format = OFORMAT_HUMAN;
667 const char *filename, *fmt, *output, *cache;
668 BlockBackend *blk;
669 BlockDriverState *bs;
670 int fix = 0;
671 int flags = BDRV_O_CHECK;
672 bool writethrough;
673 ImageCheck *check;
674 bool quiet = false;
675 bool image_opts = false;
676 bool force_share = false;
678 fmt = NULL;
679 output = NULL;
680 cache = BDRV_DEFAULT_CACHE;
682 for(;;) {
683 int option_index = 0;
684 static const struct option long_options[] = {
685 {"help", no_argument, 0, 'h'},
686 {"format", required_argument, 0, 'f'},
687 {"repair", required_argument, 0, 'r'},
688 {"output", required_argument, 0, OPTION_OUTPUT},
689 {"object", required_argument, 0, OPTION_OBJECT},
690 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
691 {"force-share", no_argument, 0, 'U'},
692 {0, 0, 0, 0}
694 c = getopt_long(argc, argv, ":hf:r:T:qU",
695 long_options, &option_index);
696 if (c == -1) {
697 break;
699 switch(c) {
700 case ':':
701 missing_argument(argv[optind - 1]);
702 break;
703 case '?':
704 unrecognized_option(argv[optind - 1]);
705 break;
706 case 'h':
707 help();
708 break;
709 case 'f':
710 fmt = optarg;
711 break;
712 case 'r':
713 flags |= BDRV_O_RDWR;
715 if (!strcmp(optarg, "leaks")) {
716 fix = BDRV_FIX_LEAKS;
717 } else if (!strcmp(optarg, "all")) {
718 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
719 } else {
720 error_exit("Unknown option value for -r "
721 "(expecting 'leaks' or 'all'): %s", optarg);
723 break;
724 case OPTION_OUTPUT:
725 output = optarg;
726 break;
727 case 'T':
728 cache = optarg;
729 break;
730 case 'q':
731 quiet = true;
732 break;
733 case 'U':
734 force_share = true;
735 break;
736 case OPTION_OBJECT: {
737 QemuOpts *opts;
738 opts = qemu_opts_parse_noisily(&qemu_object_opts,
739 optarg, true);
740 if (!opts) {
741 return 1;
743 } break;
744 case OPTION_IMAGE_OPTS:
745 image_opts = true;
746 break;
749 if (optind != argc - 1) {
750 error_exit("Expecting one image file name");
752 filename = argv[optind++];
754 if (output && !strcmp(output, "json")) {
755 output_format = OFORMAT_JSON;
756 } else if (output && !strcmp(output, "human")) {
757 output_format = OFORMAT_HUMAN;
758 } else if (output) {
759 error_report("--output must be used with human or json as argument.");
760 return 1;
763 if (qemu_opts_foreach(&qemu_object_opts,
764 user_creatable_add_opts_foreach,
765 NULL, &error_fatal)) {
766 return 1;
769 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
770 if (ret < 0) {
771 error_report("Invalid source cache option: %s", cache);
772 return 1;
775 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
776 force_share);
777 if (!blk) {
778 return 1;
780 bs = blk_bs(blk);
782 check = g_new0(ImageCheck, 1);
783 ret = collect_image_check(bs, check, filename, fmt, fix);
785 if (ret == -ENOTSUP) {
786 error_report("This image format does not support checks");
787 ret = 63;
788 goto fail;
791 if (check->corruptions_fixed || check->leaks_fixed) {
792 int corruptions_fixed, leaks_fixed;
794 leaks_fixed = check->leaks_fixed;
795 corruptions_fixed = check->corruptions_fixed;
797 if (output_format == OFORMAT_HUMAN) {
798 qprintf(quiet,
799 "The following inconsistencies were found and repaired:\n\n"
800 " %" PRId64 " leaked clusters\n"
801 " %" PRId64 " corruptions\n\n"
802 "Double checking the fixed image now...\n",
803 check->leaks_fixed,
804 check->corruptions_fixed);
807 ret = collect_image_check(bs, check, filename, fmt, 0);
809 check->leaks_fixed = leaks_fixed;
810 check->corruptions_fixed = corruptions_fixed;
813 if (!ret) {
814 switch (output_format) {
815 case OFORMAT_HUMAN:
816 dump_human_image_check(check, quiet);
817 break;
818 case OFORMAT_JSON:
819 dump_json_image_check(check, quiet);
820 break;
824 if (ret || check->check_errors) {
825 if (ret) {
826 error_report("Check failed: %s", strerror(-ret));
827 } else {
828 error_report("Check failed");
830 ret = 1;
831 goto fail;
834 if (check->corruptions) {
835 ret = 2;
836 } else if (check->leaks) {
837 ret = 3;
838 } else {
839 ret = 0;
842 fail:
843 qapi_free_ImageCheck(check);
844 blk_unref(blk);
845 return ret;
848 typedef struct CommonBlockJobCBInfo {
849 BlockDriverState *bs;
850 Error **errp;
851 } CommonBlockJobCBInfo;
853 static void common_block_job_cb(void *opaque, int ret)
855 CommonBlockJobCBInfo *cbi = opaque;
857 if (ret < 0) {
858 error_setg_errno(cbi->errp, -ret, "Block job failed");
862 static void run_block_job(BlockJob *job, Error **errp)
864 AioContext *aio_context = blk_get_aio_context(job->blk);
865 int ret = 0;
867 aio_context_acquire(aio_context);
868 job_ref(&job->job);
869 do {
870 float progress = 0.0f;
871 aio_poll(aio_context, true);
872 if (job->job.progress_total) {
873 progress = (float)job->job.progress_current /
874 job->job.progress_total * 100.f;
876 qemu_progress_print(progress, 0);
877 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
879 if (!job_is_completed(&job->job)) {
880 ret = job_complete_sync(&job->job, errp);
881 } else {
882 ret = job->job.ret;
884 job_unref(&job->job);
885 aio_context_release(aio_context);
887 /* publish completion progress only when success */
888 if (!ret) {
889 qemu_progress_print(100.f, 0);
893 static int img_commit(int argc, char **argv)
895 int c, ret, flags;
896 const char *filename, *fmt, *cache, *base;
897 BlockBackend *blk;
898 BlockDriverState *bs, *base_bs;
899 BlockJob *job;
900 bool progress = false, quiet = false, drop = false;
901 bool writethrough;
902 Error *local_err = NULL;
903 CommonBlockJobCBInfo cbi;
904 bool image_opts = false;
905 AioContext *aio_context;
907 fmt = NULL;
908 cache = BDRV_DEFAULT_CACHE;
909 base = NULL;
910 for(;;) {
911 static const struct option long_options[] = {
912 {"help", no_argument, 0, 'h'},
913 {"object", required_argument, 0, OPTION_OBJECT},
914 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
915 {0, 0, 0, 0}
917 c = getopt_long(argc, argv, ":f:ht:b:dpq",
918 long_options, NULL);
919 if (c == -1) {
920 break;
922 switch(c) {
923 case ':':
924 missing_argument(argv[optind - 1]);
925 break;
926 case '?':
927 unrecognized_option(argv[optind - 1]);
928 break;
929 case 'h':
930 help();
931 break;
932 case 'f':
933 fmt = optarg;
934 break;
935 case 't':
936 cache = optarg;
937 break;
938 case 'b':
939 base = optarg;
940 /* -b implies -d */
941 drop = true;
942 break;
943 case 'd':
944 drop = true;
945 break;
946 case 'p':
947 progress = true;
948 break;
949 case 'q':
950 quiet = true;
951 break;
952 case OPTION_OBJECT: {
953 QemuOpts *opts;
954 opts = qemu_opts_parse_noisily(&qemu_object_opts,
955 optarg, true);
956 if (!opts) {
957 return 1;
959 } break;
960 case OPTION_IMAGE_OPTS:
961 image_opts = true;
962 break;
966 /* Progress is not shown in Quiet mode */
967 if (quiet) {
968 progress = false;
971 if (optind != argc - 1) {
972 error_exit("Expecting one image file name");
974 filename = argv[optind++];
976 if (qemu_opts_foreach(&qemu_object_opts,
977 user_creatable_add_opts_foreach,
978 NULL, &error_fatal)) {
979 return 1;
982 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
983 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
984 if (ret < 0) {
985 error_report("Invalid cache option: %s", cache);
986 return 1;
989 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
990 false);
991 if (!blk) {
992 return 1;
994 bs = blk_bs(blk);
996 qemu_progress_init(progress, 1.f);
997 qemu_progress_print(0.f, 100);
999 if (base) {
1000 base_bs = bdrv_find_backing_image(bs, base);
1001 if (!base_bs) {
1002 error_setg(&local_err,
1003 "Did not find '%s' in the backing chain of '%s'",
1004 base, filename);
1005 goto done;
1007 } else {
1008 /* This is different from QMP, which by default uses the deepest file in
1009 * the backing chain (i.e., the very base); however, the traditional
1010 * behavior of qemu-img commit is using the immediate backing file. */
1011 base_bs = backing_bs(bs);
1012 if (!base_bs) {
1013 error_setg(&local_err, "Image does not have a backing file");
1014 goto done;
1018 cbi = (CommonBlockJobCBInfo){
1019 .errp = &local_err,
1020 .bs = bs,
1023 aio_context = bdrv_get_aio_context(bs);
1024 aio_context_acquire(aio_context);
1025 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
1026 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1027 &cbi, false, &local_err);
1028 aio_context_release(aio_context);
1029 if (local_err) {
1030 goto done;
1033 /* When the block job completes, the BlockBackend reference will point to
1034 * the old backing file. In order to avoid that the top image is already
1035 * deleted, so we can still empty it afterwards, increment the reference
1036 * counter here preemptively. */
1037 if (!drop) {
1038 bdrv_ref(bs);
1041 job = block_job_get("commit");
1042 assert(job);
1043 run_block_job(job, &local_err);
1044 if (local_err) {
1045 goto unref_backing;
1048 if (!drop && bs->drv->bdrv_make_empty) {
1049 ret = bs->drv->bdrv_make_empty(bs);
1050 if (ret) {
1051 error_setg_errno(&local_err, -ret, "Could not empty %s",
1052 filename);
1053 goto unref_backing;
1057 unref_backing:
1058 if (!drop) {
1059 bdrv_unref(bs);
1062 done:
1063 qemu_progress_end();
1065 blk_unref(blk);
1067 if (local_err) {
1068 error_report_err(local_err);
1069 return 1;
1072 qprintf(quiet, "Image committed.\n");
1073 return 0;
1077 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1078 * of the first sector boundary within buf where the sector contains a
1079 * non-zero byte. This function is robust to a buffer that is not
1080 * sector-aligned.
1082 static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1084 int64_t i;
1085 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1087 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1088 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1089 return i;
1092 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1093 return i;
1095 return -1;
1099 * Returns true iff the first sector pointed to by 'buf' contains at least
1100 * a non-NUL byte.
1102 * 'pnum' is set to the number of sectors (including and immediately following
1103 * the first one) that are known to be in the same allocated/unallocated state.
1104 * The function will try to align the end offset to alignment boundaries so
1105 * that the request will at least end aligned and consequtive requests will
1106 * also start at an aligned offset.
1108 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1109 int64_t sector_num, int alignment)
1111 bool is_zero;
1112 int i, tail;
1114 if (n <= 0) {
1115 *pnum = 0;
1116 return 0;
1118 is_zero = buffer_is_zero(buf, 512);
1119 for(i = 1; i < n; i++) {
1120 buf += 512;
1121 if (is_zero != buffer_is_zero(buf, 512)) {
1122 break;
1126 tail = (sector_num + i) & (alignment - 1);
1127 if (tail) {
1128 if (is_zero && i <= tail) {
1129 /* treat unallocated areas which only consist
1130 * of a small tail as allocated. */
1131 is_zero = false;
1133 if (!is_zero) {
1134 /* align up end offset of allocated areas. */
1135 i += alignment - tail;
1136 i = MIN(i, n);
1137 } else {
1138 /* align down end offset of zero areas. */
1139 i -= tail;
1142 *pnum = i;
1143 return !is_zero;
1147 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1148 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1149 * breaking up write requests for only small sparse areas.
1151 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1152 int min, int64_t sector_num, int alignment)
1154 int ret;
1155 int num_checked, num_used;
1157 if (n < min) {
1158 min = n;
1161 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1162 if (!ret) {
1163 return ret;
1166 num_used = *pnum;
1167 buf += BDRV_SECTOR_SIZE * *pnum;
1168 n -= *pnum;
1169 sector_num += *pnum;
1170 num_checked = num_used;
1172 while (n > 0) {
1173 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1175 buf += BDRV_SECTOR_SIZE * *pnum;
1176 n -= *pnum;
1177 sector_num += *pnum;
1178 num_checked += *pnum;
1179 if (ret) {
1180 num_used = num_checked;
1181 } else if (*pnum >= min) {
1182 break;
1186 *pnum = num_used;
1187 return 1;
1191 * Compares two buffers sector by sector. Returns 0 if the first
1192 * sector of each buffer matches, non-zero otherwise.
1194 * pnum is set to the sector-aligned size of the buffer prefix that
1195 * has the same matching status as the first sector.
1197 static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1198 int64_t bytes, int64_t *pnum)
1200 bool res;
1201 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
1203 assert(bytes > 0);
1205 res = !!memcmp(buf1, buf2, i);
1206 while (i < bytes) {
1207 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
1209 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
1210 break;
1212 i += len;
1215 *pnum = i;
1216 return res;
1219 #define IO_BUF_SIZE (2 * 1024 * 1024)
1222 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1224 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1225 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1226 * failure), and 4 on error (the exit status for read errors), after emitting
1227 * an error message.
1229 * @param blk: BlockBackend for the image
1230 * @param offset: Starting offset to check
1231 * @param bytes: Number of bytes to check
1232 * @param filename: Name of disk file we are checking (logging purpose)
1233 * @param buffer: Allocated buffer for storing read data
1234 * @param quiet: Flag for quiet mode
1236 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1237 int64_t bytes, const char *filename,
1238 uint8_t *buffer, bool quiet)
1240 int ret = 0;
1241 int64_t idx;
1243 ret = blk_pread(blk, offset, buffer, bytes);
1244 if (ret < 0) {
1245 error_report("Error while reading offset %" PRId64 " of %s: %s",
1246 offset, filename, strerror(-ret));
1247 return 4;
1249 idx = find_nonzero(buffer, bytes);
1250 if (idx >= 0) {
1251 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1252 offset + idx);
1253 return 1;
1256 return 0;
1260 * Compares two images. Exit codes:
1262 * 0 - Images are identical
1263 * 1 - Images differ
1264 * >1 - Error occurred
1266 static int img_compare(int argc, char **argv)
1268 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1269 BlockBackend *blk1, *blk2;
1270 BlockDriverState *bs1, *bs2;
1271 int64_t total_size1, total_size2;
1272 uint8_t *buf1 = NULL, *buf2 = NULL;
1273 int64_t pnum1, pnum2;
1274 int allocated1, allocated2;
1275 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1276 bool progress = false, quiet = false, strict = false;
1277 int flags;
1278 bool writethrough;
1279 int64_t total_size;
1280 int64_t offset = 0;
1281 int64_t chunk;
1282 int c;
1283 uint64_t progress_base;
1284 bool image_opts = false;
1285 bool force_share = false;
1287 cache = BDRV_DEFAULT_CACHE;
1288 for (;;) {
1289 static const struct option long_options[] = {
1290 {"help", no_argument, 0, 'h'},
1291 {"object", required_argument, 0, OPTION_OBJECT},
1292 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1293 {"force-share", no_argument, 0, 'U'},
1294 {0, 0, 0, 0}
1296 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1297 long_options, NULL);
1298 if (c == -1) {
1299 break;
1301 switch (c) {
1302 case ':':
1303 missing_argument(argv[optind - 1]);
1304 break;
1305 case '?':
1306 unrecognized_option(argv[optind - 1]);
1307 break;
1308 case 'h':
1309 help();
1310 break;
1311 case 'f':
1312 fmt1 = optarg;
1313 break;
1314 case 'F':
1315 fmt2 = optarg;
1316 break;
1317 case 'T':
1318 cache = optarg;
1319 break;
1320 case 'p':
1321 progress = true;
1322 break;
1323 case 'q':
1324 quiet = true;
1325 break;
1326 case 's':
1327 strict = true;
1328 break;
1329 case 'U':
1330 force_share = true;
1331 break;
1332 case OPTION_OBJECT: {
1333 QemuOpts *opts;
1334 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1335 optarg, true);
1336 if (!opts) {
1337 ret = 2;
1338 goto out4;
1340 } break;
1341 case OPTION_IMAGE_OPTS:
1342 image_opts = true;
1343 break;
1347 /* Progress is not shown in Quiet mode */
1348 if (quiet) {
1349 progress = false;
1353 if (optind != argc - 2) {
1354 error_exit("Expecting two image file names");
1356 filename1 = argv[optind++];
1357 filename2 = argv[optind++];
1359 if (qemu_opts_foreach(&qemu_object_opts,
1360 user_creatable_add_opts_foreach,
1361 NULL, &error_fatal)) {
1362 ret = 2;
1363 goto out4;
1366 /* Initialize before goto out */
1367 qemu_progress_init(progress, 2.0);
1369 flags = 0;
1370 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1371 if (ret < 0) {
1372 error_report("Invalid source cache option: %s", cache);
1373 ret = 2;
1374 goto out3;
1377 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1378 force_share);
1379 if (!blk1) {
1380 ret = 2;
1381 goto out3;
1384 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1385 force_share);
1386 if (!blk2) {
1387 ret = 2;
1388 goto out2;
1390 bs1 = blk_bs(blk1);
1391 bs2 = blk_bs(blk2);
1393 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1394 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1395 total_size1 = blk_getlength(blk1);
1396 if (total_size1 < 0) {
1397 error_report("Can't get size of %s: %s",
1398 filename1, strerror(-total_size1));
1399 ret = 4;
1400 goto out;
1402 total_size2 = blk_getlength(blk2);
1403 if (total_size2 < 0) {
1404 error_report("Can't get size of %s: %s",
1405 filename2, strerror(-total_size2));
1406 ret = 4;
1407 goto out;
1409 total_size = MIN(total_size1, total_size2);
1410 progress_base = MAX(total_size1, total_size2);
1412 qemu_progress_print(0, 100);
1414 if (strict && total_size1 != total_size2) {
1415 ret = 1;
1416 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1417 goto out;
1420 while (offset < total_size) {
1421 int status1, status2;
1423 status1 = bdrv_block_status_above(bs1, NULL, offset,
1424 total_size1 - offset, &pnum1, NULL,
1425 NULL);
1426 if (status1 < 0) {
1427 ret = 3;
1428 error_report("Sector allocation test failed for %s", filename1);
1429 goto out;
1431 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1433 status2 = bdrv_block_status_above(bs2, NULL, offset,
1434 total_size2 - offset, &pnum2, NULL,
1435 NULL);
1436 if (status2 < 0) {
1437 ret = 3;
1438 error_report("Sector allocation test failed for %s", filename2);
1439 goto out;
1441 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1443 assert(pnum1 && pnum2);
1444 chunk = MIN(pnum1, pnum2);
1446 if (strict) {
1447 if (status1 != status2) {
1448 ret = 1;
1449 qprintf(quiet, "Strict mode: Offset %" PRId64
1450 " block status mismatch!\n", offset);
1451 goto out;
1454 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1455 /* nothing to do */
1456 } else if (allocated1 == allocated2) {
1457 if (allocated1) {
1458 int64_t pnum;
1460 chunk = MIN(chunk, IO_BUF_SIZE);
1461 ret = blk_pread(blk1, offset, buf1, chunk);
1462 if (ret < 0) {
1463 error_report("Error while reading offset %" PRId64
1464 " of %s: %s",
1465 offset, filename1, strerror(-ret));
1466 ret = 4;
1467 goto out;
1469 ret = blk_pread(blk2, offset, buf2, chunk);
1470 if (ret < 0) {
1471 error_report("Error while reading offset %" PRId64
1472 " of %s: %s",
1473 offset, filename2, strerror(-ret));
1474 ret = 4;
1475 goto out;
1477 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1478 if (ret || pnum != chunk) {
1479 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1480 offset + (ret ? 0 : pnum));
1481 ret = 1;
1482 goto out;
1485 } else {
1486 chunk = MIN(chunk, IO_BUF_SIZE);
1487 if (allocated1) {
1488 ret = check_empty_sectors(blk1, offset, chunk,
1489 filename1, buf1, quiet);
1490 } else {
1491 ret = check_empty_sectors(blk2, offset, chunk,
1492 filename2, buf1, quiet);
1494 if (ret) {
1495 goto out;
1498 offset += chunk;
1499 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1502 if (total_size1 != total_size2) {
1503 BlockBackend *blk_over;
1504 const char *filename_over;
1506 qprintf(quiet, "Warning: Image size mismatch!\n");
1507 if (total_size1 > total_size2) {
1508 blk_over = blk1;
1509 filename_over = filename1;
1510 } else {
1511 blk_over = blk2;
1512 filename_over = filename2;
1515 while (offset < progress_base) {
1516 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1517 progress_base - offset, &chunk,
1518 NULL, NULL);
1519 if (ret < 0) {
1520 ret = 3;
1521 error_report("Sector allocation test failed for %s",
1522 filename_over);
1523 goto out;
1526 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1527 chunk = MIN(chunk, IO_BUF_SIZE);
1528 ret = check_empty_sectors(blk_over, offset, chunk,
1529 filename_over, buf1, quiet);
1530 if (ret) {
1531 goto out;
1534 offset += chunk;
1535 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1539 qprintf(quiet, "Images are identical.\n");
1540 ret = 0;
1542 out:
1543 qemu_vfree(buf1);
1544 qemu_vfree(buf2);
1545 blk_unref(blk2);
1546 out2:
1547 blk_unref(blk1);
1548 out3:
1549 qemu_progress_end();
1550 out4:
1551 return ret;
1554 enum ImgConvertBlockStatus {
1555 BLK_DATA,
1556 BLK_ZERO,
1557 BLK_BACKING_FILE,
1560 #define MAX_COROUTINES 16
1562 typedef struct ImgConvertState {
1563 BlockBackend **src;
1564 int64_t *src_sectors;
1565 int src_num;
1566 int64_t total_sectors;
1567 int64_t allocated_sectors;
1568 int64_t allocated_done;
1569 int64_t sector_num;
1570 int64_t wr_offs;
1571 enum ImgConvertBlockStatus status;
1572 int64_t sector_next_status;
1573 BlockBackend *target;
1574 bool has_zero_init;
1575 bool compressed;
1576 bool unallocated_blocks_are_zero;
1577 bool target_has_backing;
1578 int64_t target_backing_sectors; /* negative if unknown */
1579 bool wr_in_order;
1580 bool copy_range;
1581 int min_sparse;
1582 int alignment;
1583 size_t cluster_sectors;
1584 size_t buf_sectors;
1585 long num_coroutines;
1586 int running_coroutines;
1587 Coroutine *co[MAX_COROUTINES];
1588 int64_t wait_sector_num[MAX_COROUTINES];
1589 CoMutex lock;
1590 int ret;
1591 } ImgConvertState;
1593 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1594 int *src_cur, int64_t *src_cur_offset)
1596 *src_cur = 0;
1597 *src_cur_offset = 0;
1598 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1599 *src_cur_offset += s->src_sectors[*src_cur];
1600 (*src_cur)++;
1601 assert(*src_cur < s->src_num);
1605 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1607 int64_t src_cur_offset;
1608 int ret, n, src_cur;
1609 bool post_backing_zero = false;
1611 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1613 assert(s->total_sectors > sector_num);
1614 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1616 if (s->target_backing_sectors >= 0) {
1617 if (sector_num >= s->target_backing_sectors) {
1618 post_backing_zero = s->unallocated_blocks_are_zero;
1619 } else if (sector_num + n > s->target_backing_sectors) {
1620 /* Split requests around target_backing_sectors (because
1621 * starting from there, zeros are handled differently) */
1622 n = s->target_backing_sectors - sector_num;
1626 if (s->sector_next_status <= sector_num) {
1627 int64_t count = n * BDRV_SECTOR_SIZE;
1629 if (s->target_has_backing) {
1631 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1632 (sector_num - src_cur_offset) *
1633 BDRV_SECTOR_SIZE,
1634 count, &count, NULL, NULL);
1635 } else {
1636 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1637 (sector_num - src_cur_offset) *
1638 BDRV_SECTOR_SIZE,
1639 count, &count, NULL, NULL);
1641 if (ret < 0) {
1642 error_report("error while reading block status of sector %" PRId64
1643 ": %s", sector_num, strerror(-ret));
1644 return ret;
1646 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1648 if (ret & BDRV_BLOCK_ZERO) {
1649 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
1650 } else if (ret & BDRV_BLOCK_DATA) {
1651 s->status = BLK_DATA;
1652 } else {
1653 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1656 s->sector_next_status = sector_num + n;
1659 n = MIN(n, s->sector_next_status - sector_num);
1660 if (s->status == BLK_DATA) {
1661 n = MIN(n, s->buf_sectors);
1664 /* We need to write complete clusters for compressed images, so if an
1665 * unallocated area is shorter than that, we must consider the whole
1666 * cluster allocated. */
1667 if (s->compressed) {
1668 if (n < s->cluster_sectors) {
1669 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1670 s->status = BLK_DATA;
1671 } else {
1672 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1676 return n;
1679 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1680 int nb_sectors, uint8_t *buf)
1682 int n, ret;
1683 QEMUIOVector qiov;
1685 assert(nb_sectors <= s->buf_sectors);
1686 while (nb_sectors > 0) {
1687 BlockBackend *blk;
1688 int src_cur;
1689 int64_t bs_sectors, src_cur_offset;
1691 /* In the case of compression with multiple source files, we can get a
1692 * nb_sectors that spreads into the next part. So we must be able to
1693 * read across multiple BDSes for one convert_read() call. */
1694 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1695 blk = s->src[src_cur];
1696 bs_sectors = s->src_sectors[src_cur];
1698 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1699 qemu_iovec_init_buf(&qiov, buf, n << BDRV_SECTOR_BITS);
1701 ret = blk_co_preadv(
1702 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1703 n << BDRV_SECTOR_BITS, &qiov, 0);
1704 if (ret < 0) {
1705 return ret;
1708 sector_num += n;
1709 nb_sectors -= n;
1710 buf += n * BDRV_SECTOR_SIZE;
1713 return 0;
1717 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1718 int nb_sectors, uint8_t *buf,
1719 enum ImgConvertBlockStatus status)
1721 int ret;
1722 QEMUIOVector qiov;
1724 while (nb_sectors > 0) {
1725 int n = nb_sectors;
1726 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1728 switch (status) {
1729 case BLK_BACKING_FILE:
1730 /* If we have a backing file, leave clusters unallocated that are
1731 * unallocated in the source image, so that the backing file is
1732 * visible at the respective offset. */
1733 assert(s->target_has_backing);
1734 break;
1736 case BLK_DATA:
1737 /* If we're told to keep the target fully allocated (-S 0) or there
1738 * is real non-zero data, we must write it. Otherwise we can treat
1739 * it as zero sectors.
1740 * Compressed clusters need to be written as a whole, so in that
1741 * case we can only save the write if the buffer is completely
1742 * zeroed. */
1743 if (!s->min_sparse ||
1744 (!s->compressed &&
1745 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1746 sector_num, s->alignment)) ||
1747 (s->compressed &&
1748 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1750 qemu_iovec_init_buf(&qiov, buf, n << BDRV_SECTOR_BITS);
1752 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
1753 n << BDRV_SECTOR_BITS, &qiov, flags);
1754 if (ret < 0) {
1755 return ret;
1757 break;
1759 /* fall-through */
1761 case BLK_ZERO:
1762 if (s->has_zero_init) {
1763 assert(!s->target_has_backing);
1764 break;
1766 ret = blk_co_pwrite_zeroes(s->target,
1767 sector_num << BDRV_SECTOR_BITS,
1768 n << BDRV_SECTOR_BITS,
1769 BDRV_REQ_MAY_UNMAP);
1770 if (ret < 0) {
1771 return ret;
1773 break;
1776 sector_num += n;
1777 nb_sectors -= n;
1778 buf += n * BDRV_SECTOR_SIZE;
1781 return 0;
1784 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1785 int nb_sectors)
1787 int n, ret;
1789 while (nb_sectors > 0) {
1790 BlockBackend *blk;
1791 int src_cur;
1792 int64_t bs_sectors, src_cur_offset;
1793 int64_t offset;
1795 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1796 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1797 blk = s->src[src_cur];
1798 bs_sectors = s->src_sectors[src_cur];
1800 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1802 ret = blk_co_copy_range(blk, offset, s->target,
1803 sector_num << BDRV_SECTOR_BITS,
1804 n << BDRV_SECTOR_BITS, 0, 0);
1805 if (ret < 0) {
1806 return ret;
1809 sector_num += n;
1810 nb_sectors -= n;
1812 return 0;
1815 static void coroutine_fn convert_co_do_copy(void *opaque)
1817 ImgConvertState *s = opaque;
1818 uint8_t *buf = NULL;
1819 int ret, i;
1820 int index = -1;
1822 for (i = 0; i < s->num_coroutines; i++) {
1823 if (s->co[i] == qemu_coroutine_self()) {
1824 index = i;
1825 break;
1828 assert(index >= 0);
1830 s->running_coroutines++;
1831 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1833 while (1) {
1834 int n;
1835 int64_t sector_num;
1836 enum ImgConvertBlockStatus status;
1837 bool copy_range;
1839 qemu_co_mutex_lock(&s->lock);
1840 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1841 qemu_co_mutex_unlock(&s->lock);
1842 break;
1844 n = convert_iteration_sectors(s, s->sector_num);
1845 if (n < 0) {
1846 qemu_co_mutex_unlock(&s->lock);
1847 s->ret = n;
1848 break;
1850 /* save current sector and allocation status to local variables */
1851 sector_num = s->sector_num;
1852 status = s->status;
1853 if (!s->min_sparse && s->status == BLK_ZERO) {
1854 n = MIN(n, s->buf_sectors);
1856 /* increment global sector counter so that other coroutines can
1857 * already continue reading beyond this request */
1858 s->sector_num += n;
1859 qemu_co_mutex_unlock(&s->lock);
1861 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1862 s->allocated_done += n;
1863 qemu_progress_print(100.0 * s->allocated_done /
1864 s->allocated_sectors, 0);
1867 retry:
1868 copy_range = s->copy_range && s->status == BLK_DATA;
1869 if (status == BLK_DATA && !copy_range) {
1870 ret = convert_co_read(s, sector_num, n, buf);
1871 if (ret < 0) {
1872 error_report("error while reading sector %" PRId64
1873 ": %s", sector_num, strerror(-ret));
1874 s->ret = ret;
1876 } else if (!s->min_sparse && status == BLK_ZERO) {
1877 status = BLK_DATA;
1878 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1881 if (s->wr_in_order) {
1882 /* keep writes in order */
1883 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
1884 s->wait_sector_num[index] = sector_num;
1885 qemu_coroutine_yield();
1887 s->wait_sector_num[index] = -1;
1890 if (s->ret == -EINPROGRESS) {
1891 if (copy_range) {
1892 ret = convert_co_copy_range(s, sector_num, n);
1893 if (ret) {
1894 s->copy_range = false;
1895 goto retry;
1897 } else {
1898 ret = convert_co_write(s, sector_num, n, buf, status);
1900 if (ret < 0) {
1901 error_report("error while writing sector %" PRId64
1902 ": %s", sector_num, strerror(-ret));
1903 s->ret = ret;
1907 if (s->wr_in_order) {
1908 /* reenter the coroutine that might have waited
1909 * for this write to complete */
1910 s->wr_offs = sector_num + n;
1911 for (i = 0; i < s->num_coroutines; i++) {
1912 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1914 * A -> B -> A cannot occur because A has
1915 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1916 * B will never enter A during this time window.
1918 qemu_coroutine_enter(s->co[i]);
1919 break;
1925 qemu_vfree(buf);
1926 s->co[index] = NULL;
1927 s->running_coroutines--;
1928 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1929 /* the convert job finished successfully */
1930 s->ret = 0;
1934 static int convert_do_copy(ImgConvertState *s)
1936 int ret, i, n;
1937 int64_t sector_num = 0;
1939 /* Check whether we have zero initialisation or can get it efficiently */
1940 s->has_zero_init = s->min_sparse && !s->target_has_backing
1941 ? bdrv_has_zero_init(blk_bs(s->target))
1942 : false;
1944 if (!s->has_zero_init && !s->target_has_backing &&
1945 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1947 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
1948 if (ret == 0) {
1949 s->has_zero_init = true;
1953 /* Allocate buffer for copied data. For compressed images, only one cluster
1954 * can be copied at a time. */
1955 if (s->compressed) {
1956 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1957 error_report("invalid cluster size");
1958 return -EINVAL;
1960 s->buf_sectors = s->cluster_sectors;
1963 while (sector_num < s->total_sectors) {
1964 n = convert_iteration_sectors(s, sector_num);
1965 if (n < 0) {
1966 return n;
1968 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1970 s->allocated_sectors += n;
1972 sector_num += n;
1975 /* Do the copy */
1976 s->sector_next_status = 0;
1977 s->ret = -EINPROGRESS;
1979 qemu_co_mutex_init(&s->lock);
1980 for (i = 0; i < s->num_coroutines; i++) {
1981 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1982 s->wait_sector_num[i] = -1;
1983 qemu_coroutine_enter(s->co[i]);
1986 while (s->running_coroutines) {
1987 main_loop_wait(false);
1990 if (s->compressed && !s->ret) {
1991 /* signal EOF to align */
1992 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
1993 if (ret < 0) {
1994 return ret;
1998 return s->ret;
2001 #define MAX_BUF_SECTORS 32768
2003 static int img_convert(int argc, char **argv)
2005 int c, bs_i, flags, src_flags = 0;
2006 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
2007 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2008 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
2009 BlockDriver *drv = NULL, *proto_drv = NULL;
2010 BlockDriverInfo bdi;
2011 BlockDriverState *out_bs;
2012 QemuOpts *opts = NULL, *sn_opts = NULL;
2013 QemuOptsList *create_opts = NULL;
2014 QDict *open_opts = NULL;
2015 char *options = NULL;
2016 Error *local_err = NULL;
2017 bool writethrough, src_writethrough, quiet = false, image_opts = false,
2018 skip_create = false, progress = false, tgt_image_opts = false;
2019 int64_t ret = -EINVAL;
2020 bool force_share = false;
2021 bool explict_min_sparse = false;
2023 ImgConvertState s = (ImgConvertState) {
2024 /* Need at least 4k of zeros for sparse detection */
2025 .min_sparse = 8,
2026 .copy_range = false,
2027 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2028 .wr_in_order = true,
2029 .num_coroutines = 8,
2032 for(;;) {
2033 static const struct option long_options[] = {
2034 {"help", no_argument, 0, 'h'},
2035 {"object", required_argument, 0, OPTION_OBJECT},
2036 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2037 {"force-share", no_argument, 0, 'U'},
2038 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
2039 {0, 0, 0, 0}
2041 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2042 long_options, NULL);
2043 if (c == -1) {
2044 break;
2046 switch(c) {
2047 case ':':
2048 missing_argument(argv[optind - 1]);
2049 break;
2050 case '?':
2051 unrecognized_option(argv[optind - 1]);
2052 break;
2053 case 'h':
2054 help();
2055 break;
2056 case 'f':
2057 fmt = optarg;
2058 break;
2059 case 'O':
2060 out_fmt = optarg;
2061 break;
2062 case 'B':
2063 out_baseimg = optarg;
2064 break;
2065 case 'C':
2066 s.copy_range = true;
2067 break;
2068 case 'c':
2069 s.compressed = true;
2070 break;
2071 case 'o':
2072 if (!is_valid_option_list(optarg)) {
2073 error_report("Invalid option list: %s", optarg);
2074 goto fail_getopt;
2076 if (!options) {
2077 options = g_strdup(optarg);
2078 } else {
2079 char *old_options = options;
2080 options = g_strdup_printf("%s,%s", options, optarg);
2081 g_free(old_options);
2083 break;
2084 case 'l':
2085 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2086 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2087 optarg, false);
2088 if (!sn_opts) {
2089 error_report("Failed in parsing snapshot param '%s'",
2090 optarg);
2091 goto fail_getopt;
2093 } else {
2094 snapshot_name = optarg;
2096 break;
2097 case 'S':
2099 int64_t sval;
2101 sval = cvtnum(optarg);
2102 if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
2103 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2104 error_report("Invalid buffer size for sparse output specified. "
2105 "Valid sizes are multiples of %llu up to %llu. Select "
2106 "0 to disable sparse detection (fully allocates output).",
2107 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
2108 goto fail_getopt;
2111 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2112 explict_min_sparse = true;
2113 break;
2115 case 'p':
2116 progress = true;
2117 break;
2118 case 't':
2119 cache = optarg;
2120 break;
2121 case 'T':
2122 src_cache = optarg;
2123 break;
2124 case 'q':
2125 quiet = true;
2126 break;
2127 case 'n':
2128 skip_create = true;
2129 break;
2130 case 'm':
2131 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2132 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2133 error_report("Invalid number of coroutines. Allowed number of"
2134 " coroutines is between 1 and %d", MAX_COROUTINES);
2135 goto fail_getopt;
2137 break;
2138 case 'W':
2139 s.wr_in_order = false;
2140 break;
2141 case 'U':
2142 force_share = true;
2143 break;
2144 case OPTION_OBJECT: {
2145 QemuOpts *object_opts;
2146 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2147 optarg, true);
2148 if (!object_opts) {
2149 goto fail_getopt;
2151 break;
2153 case OPTION_IMAGE_OPTS:
2154 image_opts = true;
2155 break;
2156 case OPTION_TARGET_IMAGE_OPTS:
2157 tgt_image_opts = true;
2158 break;
2162 if (!out_fmt && !tgt_image_opts) {
2163 out_fmt = "raw";
2166 if (qemu_opts_foreach(&qemu_object_opts,
2167 user_creatable_add_opts_foreach,
2168 NULL, &error_fatal)) {
2169 goto fail_getopt;
2172 if (s.compressed && s.copy_range) {
2173 error_report("Cannot enable copy offloading when -c is used");
2174 goto fail_getopt;
2177 if (explict_min_sparse && s.copy_range) {
2178 error_report("Cannot enable copy offloading when -S is used");
2179 goto fail_getopt;
2182 if (tgt_image_opts && !skip_create) {
2183 error_report("--target-image-opts requires use of -n flag");
2184 goto fail_getopt;
2187 s.src_num = argc - optind - 1;
2188 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2190 if (options && has_help_option(options)) {
2191 if (out_fmt) {
2192 ret = print_block_option_help(out_filename, out_fmt);
2193 goto fail_getopt;
2194 } else {
2195 error_report("Option help requires a format be specified");
2196 goto fail_getopt;
2200 if (s.src_num < 1) {
2201 error_report("Must specify image file name");
2202 goto fail_getopt;
2206 /* ret is still -EINVAL until here */
2207 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2208 if (ret < 0) {
2209 error_report("Invalid source cache option: %s", src_cache);
2210 goto fail_getopt;
2213 /* Initialize before goto out */
2214 if (quiet) {
2215 progress = false;
2217 qemu_progress_init(progress, 1.0);
2218 qemu_progress_print(0, 100);
2220 s.src = g_new0(BlockBackend *, s.src_num);
2221 s.src_sectors = g_new(int64_t, s.src_num);
2223 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2224 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2225 fmt, src_flags, src_writethrough, quiet,
2226 force_share);
2227 if (!s.src[bs_i]) {
2228 ret = -1;
2229 goto out;
2231 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2232 if (s.src_sectors[bs_i] < 0) {
2233 error_report("Could not get size of %s: %s",
2234 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2235 ret = -1;
2236 goto out;
2238 s.total_sectors += s.src_sectors[bs_i];
2241 if (sn_opts) {
2242 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2243 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2244 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2245 &local_err);
2246 } else if (snapshot_name != NULL) {
2247 if (s.src_num > 1) {
2248 error_report("No support for concatenating multiple snapshot");
2249 ret = -1;
2250 goto out;
2253 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2254 &local_err);
2256 if (local_err) {
2257 error_reportf_err(local_err, "Failed to load snapshot: ");
2258 ret = -1;
2259 goto out;
2262 if (!skip_create) {
2263 /* Find driver and parse its options */
2264 drv = bdrv_find_format(out_fmt);
2265 if (!drv) {
2266 error_report("Unknown file format '%s'", out_fmt);
2267 ret = -1;
2268 goto out;
2271 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2272 if (!proto_drv) {
2273 error_report_err(local_err);
2274 ret = -1;
2275 goto out;
2278 if (!drv->create_opts) {
2279 error_report("Format driver '%s' does not support image creation",
2280 drv->format_name);
2281 ret = -1;
2282 goto out;
2285 if (!proto_drv->create_opts) {
2286 error_report("Protocol driver '%s' does not support image creation",
2287 proto_drv->format_name);
2288 ret = -1;
2289 goto out;
2292 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2293 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2295 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2296 if (options) {
2297 qemu_opts_do_parse(opts, options, NULL, &local_err);
2298 if (local_err) {
2299 error_report_err(local_err);
2300 ret = -1;
2301 goto out;
2305 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2306 &error_abort);
2307 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2308 if (ret < 0) {
2309 goto out;
2313 /* Get backing file name if -o backing_file was used */
2314 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2315 if (out_baseimg_param) {
2316 out_baseimg = out_baseimg_param;
2318 s.target_has_backing = (bool) out_baseimg;
2320 if (s.src_num > 1 && out_baseimg) {
2321 error_report("Having a backing file for the target makes no sense when "
2322 "concatenating multiple input images");
2323 ret = -1;
2324 goto out;
2327 /* Check if compression is supported */
2328 if (s.compressed) {
2329 bool encryption =
2330 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2331 const char *encryptfmt =
2332 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2333 const char *preallocation =
2334 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2336 if (drv && !drv->bdrv_co_pwritev_compressed) {
2337 error_report("Compression not supported for this file format");
2338 ret = -1;
2339 goto out;
2342 if (encryption || encryptfmt) {
2343 error_report("Compression and encryption not supported at "
2344 "the same time");
2345 ret = -1;
2346 goto out;
2349 if (preallocation
2350 && strcmp(preallocation, "off"))
2352 error_report("Compression and preallocation not supported at "
2353 "the same time");
2354 ret = -1;
2355 goto out;
2360 * The later open call will need any decryption secrets, and
2361 * bdrv_create() will purge "opts", so extract them now before
2362 * they are lost.
2364 if (!skip_create) {
2365 open_opts = qdict_new();
2366 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2369 if (!skip_create) {
2370 /* Create the new image */
2371 ret = bdrv_create(drv, out_filename, opts, &local_err);
2372 if (ret < 0) {
2373 error_reportf_err(local_err, "%s: error while converting %s: ",
2374 out_filename, out_fmt);
2375 goto out;
2379 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2380 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2381 if (ret < 0) {
2382 error_report("Invalid cache option: %s", cache);
2383 goto out;
2386 if (skip_create) {
2387 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2388 flags, writethrough, quiet, false);
2389 } else {
2390 /* TODO ultimately we should allow --target-image-opts
2391 * to be used even when -n is not given.
2392 * That has to wait for bdrv_create to be improved
2393 * to allow filenames in option syntax
2395 s.target = img_open_file(out_filename, open_opts, out_fmt,
2396 flags, writethrough, quiet, false);
2397 open_opts = NULL; /* blk_new_open will have freed it */
2399 if (!s.target) {
2400 ret = -1;
2401 goto out;
2403 out_bs = blk_bs(s.target);
2405 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2406 error_report("Compression not supported for this file format");
2407 ret = -1;
2408 goto out;
2411 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2412 * or discard_alignment of the out_bs is greater. Limit to
2413 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2414 s.buf_sectors = MIN(MAX_BUF_SECTORS,
2415 MAX(s.buf_sectors,
2416 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2417 out_bs->bl.pdiscard_alignment >>
2418 BDRV_SECTOR_BITS)));
2420 /* try to align the write requests to the destination to avoid unnecessary
2421 * RMW cycles. */
2422 s.alignment = MAX(pow2floor(s.min_sparse),
2423 DIV_ROUND_UP(out_bs->bl.request_alignment,
2424 BDRV_SECTOR_SIZE));
2425 assert(is_power_of_2(s.alignment));
2427 if (skip_create) {
2428 int64_t output_sectors = blk_nb_sectors(s.target);
2429 if (output_sectors < 0) {
2430 error_report("unable to get output image length: %s",
2431 strerror(-output_sectors));
2432 ret = -1;
2433 goto out;
2434 } else if (output_sectors < s.total_sectors) {
2435 error_report("output file is smaller than input file");
2436 ret = -1;
2437 goto out;
2441 if (s.target_has_backing) {
2442 /* Errors are treated as "backing length unknown" (which means
2443 * s.target_backing_sectors has to be negative, which it will
2444 * be automatically). The backing file length is used only
2445 * for optimizations, so such a case is not fatal. */
2446 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2447 } else {
2448 s.target_backing_sectors = -1;
2451 ret = bdrv_get_info(out_bs, &bdi);
2452 if (ret < 0) {
2453 if (s.compressed) {
2454 error_report("could not get block driver info");
2455 goto out;
2457 } else {
2458 s.compressed = s.compressed || bdi.needs_compressed_writes;
2459 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2460 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
2463 ret = convert_do_copy(&s);
2464 out:
2465 if (!ret) {
2466 qemu_progress_print(100, 0);
2468 qemu_progress_end();
2469 qemu_opts_del(opts);
2470 qemu_opts_free(create_opts);
2471 qemu_opts_del(sn_opts);
2472 qobject_unref(open_opts);
2473 blk_unref(s.target);
2474 if (s.src) {
2475 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2476 blk_unref(s.src[bs_i]);
2478 g_free(s.src);
2480 g_free(s.src_sectors);
2481 fail_getopt:
2482 g_free(options);
2484 return !!ret;
2488 static void dump_snapshots(BlockDriverState *bs)
2490 QEMUSnapshotInfo *sn_tab, *sn;
2491 int nb_sns, i;
2493 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2494 if (nb_sns <= 0)
2495 return;
2496 printf("Snapshot list:\n");
2497 bdrv_snapshot_dump(NULL);
2498 printf("\n");
2499 for(i = 0; i < nb_sns; i++) {
2500 sn = &sn_tab[i];
2501 bdrv_snapshot_dump(sn);
2502 printf("\n");
2504 g_free(sn_tab);
2507 static void dump_json_image_info_list(ImageInfoList *list)
2509 QString *str;
2510 QObject *obj;
2511 Visitor *v = qobject_output_visitor_new(&obj);
2513 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2514 visit_complete(v, &obj);
2515 str = qobject_to_json_pretty(obj);
2516 assert(str != NULL);
2517 printf("%s\n", qstring_get_str(str));
2518 qobject_unref(obj);
2519 visit_free(v);
2520 qobject_unref(str);
2523 static void dump_json_image_info(ImageInfo *info)
2525 QString *str;
2526 QObject *obj;
2527 Visitor *v = qobject_output_visitor_new(&obj);
2529 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2530 visit_complete(v, &obj);
2531 str = qobject_to_json_pretty(obj);
2532 assert(str != NULL);
2533 printf("%s\n", qstring_get_str(str));
2534 qobject_unref(obj);
2535 visit_free(v);
2536 qobject_unref(str);
2539 static void dump_human_image_info_list(ImageInfoList *list)
2541 ImageInfoList *elem;
2542 bool delim = false;
2544 for (elem = list; elem; elem = elem->next) {
2545 if (delim) {
2546 printf("\n");
2548 delim = true;
2550 bdrv_image_info_dump(elem->value);
2554 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2556 return strcmp(a, b) == 0;
2560 * Open an image file chain and return an ImageInfoList
2562 * @filename: topmost image filename
2563 * @fmt: topmost image format (may be NULL to autodetect)
2564 * @chain: true - enumerate entire backing file chain
2565 * false - only topmost image file
2567 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2568 * image file. If there was an error a message will have been printed to
2569 * stderr.
2571 static ImageInfoList *collect_image_info_list(bool image_opts,
2572 const char *filename,
2573 const char *fmt,
2574 bool chain, bool force_share)
2576 ImageInfoList *head = NULL;
2577 ImageInfoList **last = &head;
2578 GHashTable *filenames;
2579 Error *err = NULL;
2581 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2583 while (filename) {
2584 BlockBackend *blk;
2585 BlockDriverState *bs;
2586 ImageInfo *info;
2587 ImageInfoList *elem;
2589 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2590 error_report("Backing file '%s' creates an infinite loop.",
2591 filename);
2592 goto err;
2594 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2596 blk = img_open(image_opts, filename, fmt,
2597 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2598 force_share);
2599 if (!blk) {
2600 goto err;
2602 bs = blk_bs(blk);
2604 bdrv_query_image_info(bs, &info, &err);
2605 if (err) {
2606 error_report_err(err);
2607 blk_unref(blk);
2608 goto err;
2611 elem = g_new0(ImageInfoList, 1);
2612 elem->value = info;
2613 *last = elem;
2614 last = &elem->next;
2616 blk_unref(blk);
2618 filename = fmt = NULL;
2619 if (chain) {
2620 if (info->has_full_backing_filename) {
2621 filename = info->full_backing_filename;
2622 } else if (info->has_backing_filename) {
2623 error_report("Could not determine absolute backing filename,"
2624 " but backing filename '%s' present",
2625 info->backing_filename);
2626 goto err;
2628 if (info->has_backing_filename_format) {
2629 fmt = info->backing_filename_format;
2633 g_hash_table_destroy(filenames);
2634 return head;
2636 err:
2637 qapi_free_ImageInfoList(head);
2638 g_hash_table_destroy(filenames);
2639 return NULL;
2642 static int img_info(int argc, char **argv)
2644 int c;
2645 OutputFormat output_format = OFORMAT_HUMAN;
2646 bool chain = false;
2647 const char *filename, *fmt, *output;
2648 ImageInfoList *list;
2649 bool image_opts = false;
2650 bool force_share = false;
2652 fmt = NULL;
2653 output = NULL;
2654 for(;;) {
2655 int option_index = 0;
2656 static const struct option long_options[] = {
2657 {"help", no_argument, 0, 'h'},
2658 {"format", required_argument, 0, 'f'},
2659 {"output", required_argument, 0, OPTION_OUTPUT},
2660 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2661 {"object", required_argument, 0, OPTION_OBJECT},
2662 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2663 {"force-share", no_argument, 0, 'U'},
2664 {0, 0, 0, 0}
2666 c = getopt_long(argc, argv, ":f:hU",
2667 long_options, &option_index);
2668 if (c == -1) {
2669 break;
2671 switch(c) {
2672 case ':':
2673 missing_argument(argv[optind - 1]);
2674 break;
2675 case '?':
2676 unrecognized_option(argv[optind - 1]);
2677 break;
2678 case 'h':
2679 help();
2680 break;
2681 case 'f':
2682 fmt = optarg;
2683 break;
2684 case 'U':
2685 force_share = true;
2686 break;
2687 case OPTION_OUTPUT:
2688 output = optarg;
2689 break;
2690 case OPTION_BACKING_CHAIN:
2691 chain = true;
2692 break;
2693 case OPTION_OBJECT: {
2694 QemuOpts *opts;
2695 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2696 optarg, true);
2697 if (!opts) {
2698 return 1;
2700 } break;
2701 case OPTION_IMAGE_OPTS:
2702 image_opts = true;
2703 break;
2706 if (optind != argc - 1) {
2707 error_exit("Expecting one image file name");
2709 filename = argv[optind++];
2711 if (output && !strcmp(output, "json")) {
2712 output_format = OFORMAT_JSON;
2713 } else if (output && !strcmp(output, "human")) {
2714 output_format = OFORMAT_HUMAN;
2715 } else if (output) {
2716 error_report("--output must be used with human or json as argument.");
2717 return 1;
2720 if (qemu_opts_foreach(&qemu_object_opts,
2721 user_creatable_add_opts_foreach,
2722 NULL, &error_fatal)) {
2723 return 1;
2726 list = collect_image_info_list(image_opts, filename, fmt, chain,
2727 force_share);
2728 if (!list) {
2729 return 1;
2732 switch (output_format) {
2733 case OFORMAT_HUMAN:
2734 dump_human_image_info_list(list);
2735 break;
2736 case OFORMAT_JSON:
2737 if (chain) {
2738 dump_json_image_info_list(list);
2739 } else {
2740 dump_json_image_info(list->value);
2742 break;
2745 qapi_free_ImageInfoList(list);
2746 return 0;
2749 static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2750 MapEntry *next)
2752 switch (output_format) {
2753 case OFORMAT_HUMAN:
2754 if (e->data && !e->has_offset) {
2755 error_report("File contains external, encrypted or compressed clusters.");
2756 return -1;
2758 if (e->data && !e->zero) {
2759 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2760 e->start, e->length,
2761 e->has_offset ? e->offset : 0,
2762 e->has_filename ? e->filename : "");
2764 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2765 * Modify the flags here to allow more coalescing.
2767 if (next && (!next->data || next->zero)) {
2768 next->data = false;
2769 next->zero = true;
2771 break;
2772 case OFORMAT_JSON:
2773 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2774 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2775 (e->start == 0 ? "[" : ",\n"),
2776 e->start, e->length, e->depth,
2777 e->zero ? "true" : "false",
2778 e->data ? "true" : "false");
2779 if (e->has_offset) {
2780 printf(", \"offset\": %"PRId64"", e->offset);
2782 putchar('}');
2784 if (!next) {
2785 printf("]\n");
2787 break;
2789 return 0;
2792 static int get_block_status(BlockDriverState *bs, int64_t offset,
2793 int64_t bytes, MapEntry *e)
2795 int ret;
2796 int depth;
2797 BlockDriverState *file;
2798 bool has_offset;
2799 int64_t map;
2800 char *filename = NULL;
2802 /* As an optimization, we could cache the current range of unallocated
2803 * clusters in each file of the chain, and avoid querying the same
2804 * range repeatedly.
2807 depth = 0;
2808 for (;;) {
2809 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
2810 if (ret < 0) {
2811 return ret;
2813 assert(bytes);
2814 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2815 break;
2817 bs = backing_bs(bs);
2818 if (bs == NULL) {
2819 ret = 0;
2820 break;
2823 depth++;
2826 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2828 if (file && has_offset) {
2829 bdrv_refresh_filename(file);
2830 filename = file->filename;
2833 *e = (MapEntry) {
2834 .start = offset,
2835 .length = bytes,
2836 .data = !!(ret & BDRV_BLOCK_DATA),
2837 .zero = !!(ret & BDRV_BLOCK_ZERO),
2838 .offset = map,
2839 .has_offset = has_offset,
2840 .depth = depth,
2841 .has_filename = filename,
2842 .filename = filename,
2845 return 0;
2848 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2850 if (curr->length == 0) {
2851 return false;
2853 if (curr->zero != next->zero ||
2854 curr->data != next->data ||
2855 curr->depth != next->depth ||
2856 curr->has_filename != next->has_filename ||
2857 curr->has_offset != next->has_offset) {
2858 return false;
2860 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2861 return false;
2863 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2864 return false;
2866 return true;
2869 static int img_map(int argc, char **argv)
2871 int c;
2872 OutputFormat output_format = OFORMAT_HUMAN;
2873 BlockBackend *blk;
2874 BlockDriverState *bs;
2875 const char *filename, *fmt, *output;
2876 int64_t length;
2877 MapEntry curr = { .length = 0 }, next;
2878 int ret = 0;
2879 bool image_opts = false;
2880 bool force_share = false;
2882 fmt = NULL;
2883 output = NULL;
2884 for (;;) {
2885 int option_index = 0;
2886 static const struct option long_options[] = {
2887 {"help", no_argument, 0, 'h'},
2888 {"format", required_argument, 0, 'f'},
2889 {"output", required_argument, 0, OPTION_OUTPUT},
2890 {"object", required_argument, 0, OPTION_OBJECT},
2891 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2892 {"force-share", no_argument, 0, 'U'},
2893 {0, 0, 0, 0}
2895 c = getopt_long(argc, argv, ":f:hU",
2896 long_options, &option_index);
2897 if (c == -1) {
2898 break;
2900 switch (c) {
2901 case ':':
2902 missing_argument(argv[optind - 1]);
2903 break;
2904 case '?':
2905 unrecognized_option(argv[optind - 1]);
2906 break;
2907 case 'h':
2908 help();
2909 break;
2910 case 'f':
2911 fmt = optarg;
2912 break;
2913 case 'U':
2914 force_share = true;
2915 break;
2916 case OPTION_OUTPUT:
2917 output = optarg;
2918 break;
2919 case OPTION_OBJECT: {
2920 QemuOpts *opts;
2921 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2922 optarg, true);
2923 if (!opts) {
2924 return 1;
2926 } break;
2927 case OPTION_IMAGE_OPTS:
2928 image_opts = true;
2929 break;
2932 if (optind != argc - 1) {
2933 error_exit("Expecting one image file name");
2935 filename = argv[optind];
2937 if (output && !strcmp(output, "json")) {
2938 output_format = OFORMAT_JSON;
2939 } else if (output && !strcmp(output, "human")) {
2940 output_format = OFORMAT_HUMAN;
2941 } else if (output) {
2942 error_report("--output must be used with human or json as argument.");
2943 return 1;
2946 if (qemu_opts_foreach(&qemu_object_opts,
2947 user_creatable_add_opts_foreach,
2948 NULL, &error_fatal)) {
2949 return 1;
2952 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
2953 if (!blk) {
2954 return 1;
2956 bs = blk_bs(blk);
2958 if (output_format == OFORMAT_HUMAN) {
2959 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2962 length = blk_getlength(blk);
2963 while (curr.start + curr.length < length) {
2964 int64_t offset = curr.start + curr.length;
2965 int64_t n;
2967 /* Probe up to 1 GiB at a time. */
2968 n = MIN(1 << 30, length - offset);
2969 ret = get_block_status(bs, offset, n, &next);
2971 if (ret < 0) {
2972 error_report("Could not read file metadata: %s", strerror(-ret));
2973 goto out;
2976 if (entry_mergeable(&curr, &next)) {
2977 curr.length += next.length;
2978 continue;
2981 if (curr.length > 0) {
2982 ret = dump_map_entry(output_format, &curr, &next);
2983 if (ret < 0) {
2984 goto out;
2987 curr = next;
2990 ret = dump_map_entry(output_format, &curr, NULL);
2992 out:
2993 blk_unref(blk);
2994 return ret < 0;
2997 #define SNAPSHOT_LIST 1
2998 #define SNAPSHOT_CREATE 2
2999 #define SNAPSHOT_APPLY 3
3000 #define SNAPSHOT_DELETE 4
3002 static int img_snapshot(int argc, char **argv)
3004 BlockBackend *blk;
3005 BlockDriverState *bs;
3006 QEMUSnapshotInfo sn;
3007 char *filename, *snapshot_name = NULL;
3008 int c, ret = 0, bdrv_oflags;
3009 int action = 0;
3010 qemu_timeval tv;
3011 bool quiet = false;
3012 Error *err = NULL;
3013 bool image_opts = false;
3014 bool force_share = false;
3016 bdrv_oflags = BDRV_O_RDWR;
3017 /* Parse commandline parameters */
3018 for(;;) {
3019 static const struct option long_options[] = {
3020 {"help", no_argument, 0, 'h'},
3021 {"object", required_argument, 0, OPTION_OBJECT},
3022 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3023 {"force-share", no_argument, 0, 'U'},
3024 {0, 0, 0, 0}
3026 c = getopt_long(argc, argv, ":la:c:d:hqU",
3027 long_options, NULL);
3028 if (c == -1) {
3029 break;
3031 switch(c) {
3032 case ':':
3033 missing_argument(argv[optind - 1]);
3034 break;
3035 case '?':
3036 unrecognized_option(argv[optind - 1]);
3037 break;
3038 case 'h':
3039 help();
3040 return 0;
3041 case 'l':
3042 if (action) {
3043 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3044 return 0;
3046 action = SNAPSHOT_LIST;
3047 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
3048 break;
3049 case 'a':
3050 if (action) {
3051 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3052 return 0;
3054 action = SNAPSHOT_APPLY;
3055 snapshot_name = optarg;
3056 break;
3057 case 'c':
3058 if (action) {
3059 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3060 return 0;
3062 action = SNAPSHOT_CREATE;
3063 snapshot_name = optarg;
3064 break;
3065 case 'd':
3066 if (action) {
3067 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3068 return 0;
3070 action = SNAPSHOT_DELETE;
3071 snapshot_name = optarg;
3072 break;
3073 case 'q':
3074 quiet = true;
3075 break;
3076 case 'U':
3077 force_share = true;
3078 break;
3079 case OPTION_OBJECT: {
3080 QemuOpts *opts;
3081 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3082 optarg, true);
3083 if (!opts) {
3084 return 1;
3086 } break;
3087 case OPTION_IMAGE_OPTS:
3088 image_opts = true;
3089 break;
3093 if (optind != argc - 1) {
3094 error_exit("Expecting one image file name");
3096 filename = argv[optind++];
3098 if (qemu_opts_foreach(&qemu_object_opts,
3099 user_creatable_add_opts_foreach,
3100 NULL, &error_fatal)) {
3101 return 1;
3104 /* Open the image */
3105 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3106 force_share);
3107 if (!blk) {
3108 return 1;
3110 bs = blk_bs(blk);
3112 /* Perform the requested action */
3113 switch(action) {
3114 case SNAPSHOT_LIST:
3115 dump_snapshots(bs);
3116 break;
3118 case SNAPSHOT_CREATE:
3119 memset(&sn, 0, sizeof(sn));
3120 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3122 qemu_gettimeofday(&tv);
3123 sn.date_sec = tv.tv_sec;
3124 sn.date_nsec = tv.tv_usec * 1000;
3126 ret = bdrv_snapshot_create(bs, &sn);
3127 if (ret) {
3128 error_report("Could not create snapshot '%s': %d (%s)",
3129 snapshot_name, ret, strerror(-ret));
3131 break;
3133 case SNAPSHOT_APPLY:
3134 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3135 if (ret) {
3136 error_reportf_err(err, "Could not apply snapshot '%s': ",
3137 snapshot_name);
3139 break;
3141 case SNAPSHOT_DELETE:
3142 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3143 if (ret < 0) {
3144 error_report("Could not delete snapshot '%s': snapshot not "
3145 "found", snapshot_name);
3146 ret = 1;
3147 } else {
3148 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3149 if (ret < 0) {
3150 error_reportf_err(err, "Could not delete snapshot '%s': ",
3151 snapshot_name);
3152 ret = 1;
3155 break;
3158 /* Cleanup */
3159 blk_unref(blk);
3160 if (ret) {
3161 return 1;
3163 return 0;
3166 static int img_rebase(int argc, char **argv)
3168 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3169 uint8_t *buf_old = NULL;
3170 uint8_t *buf_new = NULL;
3171 BlockDriverState *bs = NULL;
3172 char *filename;
3173 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3174 int c, flags, src_flags, ret;
3175 bool writethrough, src_writethrough;
3176 int unsafe = 0;
3177 bool force_share = false;
3178 int progress = 0;
3179 bool quiet = false;
3180 Error *local_err = NULL;
3181 bool image_opts = false;
3183 /* Parse commandline parameters */
3184 fmt = NULL;
3185 cache = BDRV_DEFAULT_CACHE;
3186 src_cache = BDRV_DEFAULT_CACHE;
3187 out_baseimg = NULL;
3188 out_basefmt = NULL;
3189 for(;;) {
3190 static const struct option long_options[] = {
3191 {"help", no_argument, 0, 'h'},
3192 {"object", required_argument, 0, OPTION_OBJECT},
3193 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3194 {"force-share", no_argument, 0, 'U'},
3195 {0, 0, 0, 0}
3197 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3198 long_options, NULL);
3199 if (c == -1) {
3200 break;
3202 switch(c) {
3203 case ':':
3204 missing_argument(argv[optind - 1]);
3205 break;
3206 case '?':
3207 unrecognized_option(argv[optind - 1]);
3208 break;
3209 case 'h':
3210 help();
3211 return 0;
3212 case 'f':
3213 fmt = optarg;
3214 break;
3215 case 'F':
3216 out_basefmt = optarg;
3217 break;
3218 case 'b':
3219 out_baseimg = optarg;
3220 break;
3221 case 'u':
3222 unsafe = 1;
3223 break;
3224 case 'p':
3225 progress = 1;
3226 break;
3227 case 't':
3228 cache = optarg;
3229 break;
3230 case 'T':
3231 src_cache = optarg;
3232 break;
3233 case 'q':
3234 quiet = true;
3235 break;
3236 case OPTION_OBJECT: {
3237 QemuOpts *opts;
3238 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3239 optarg, true);
3240 if (!opts) {
3241 return 1;
3243 } break;
3244 case OPTION_IMAGE_OPTS:
3245 image_opts = true;
3246 break;
3247 case 'U':
3248 force_share = true;
3249 break;
3253 if (quiet) {
3254 progress = 0;
3257 if (optind != argc - 1) {
3258 error_exit("Expecting one image file name");
3260 if (!unsafe && !out_baseimg) {
3261 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3263 filename = argv[optind++];
3265 if (qemu_opts_foreach(&qemu_object_opts,
3266 user_creatable_add_opts_foreach,
3267 NULL, &error_fatal)) {
3268 return 1;
3271 qemu_progress_init(progress, 2.0);
3272 qemu_progress_print(0, 100);
3274 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3275 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3276 if (ret < 0) {
3277 error_report("Invalid cache option: %s", cache);
3278 goto out;
3281 src_flags = 0;
3282 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3283 if (ret < 0) {
3284 error_report("Invalid source cache option: %s", src_cache);
3285 goto out;
3288 /* The source files are opened read-only, don't care about WCE */
3289 assert((src_flags & BDRV_O_RDWR) == 0);
3290 (void) src_writethrough;
3293 * Open the images.
3295 * Ignore the old backing file for unsafe rebase in case we want to correct
3296 * the reference to a renamed or moved backing file.
3298 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3299 false);
3300 if (!blk) {
3301 ret = -1;
3302 goto out;
3304 bs = blk_bs(blk);
3306 if (out_basefmt != NULL) {
3307 if (bdrv_find_format(out_basefmt) == NULL) {
3308 error_report("Invalid format name: '%s'", out_basefmt);
3309 ret = -1;
3310 goto out;
3314 /* For safe rebasing we need to compare old and new backing file */
3315 if (!unsafe) {
3316 char backing_name[PATH_MAX];
3317 QDict *options = NULL;
3319 if (bs->backing_format[0] != '\0') {
3320 options = qdict_new();
3321 qdict_put_str(options, "driver", bs->backing_format);
3324 if (force_share) {
3325 if (!options) {
3326 options = qdict_new();
3328 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3330 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3331 blk_old_backing = blk_new_open(backing_name, NULL,
3332 options, src_flags, &local_err);
3333 if (!blk_old_backing) {
3334 error_reportf_err(local_err,
3335 "Could not open old backing file '%s': ",
3336 backing_name);
3337 ret = -1;
3338 goto out;
3341 if (out_baseimg[0]) {
3342 const char *overlay_filename;
3343 char *out_real_path;
3345 options = qdict_new();
3346 if (out_basefmt) {
3347 qdict_put_str(options, "driver", out_basefmt);
3349 if (force_share) {
3350 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3353 bdrv_refresh_filename(bs);
3354 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3355 : bs->filename;
3356 out_real_path =
3357 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3358 out_baseimg,
3359 &local_err);
3360 if (local_err) {
3361 error_reportf_err(local_err,
3362 "Could not resolve backing filename: ");
3363 ret = -1;
3364 goto out;
3367 blk_new_backing = blk_new_open(out_real_path, NULL,
3368 options, src_flags, &local_err);
3369 g_free(out_real_path);
3370 if (!blk_new_backing) {
3371 error_reportf_err(local_err,
3372 "Could not open new backing file '%s': ",
3373 out_baseimg);
3374 ret = -1;
3375 goto out;
3381 * Check each unallocated cluster in the COW file. If it is unallocated,
3382 * accesses go to the backing file. We must therefore compare this cluster
3383 * in the old and new backing file, and if they differ we need to copy it
3384 * from the old backing file into the COW file.
3386 * If qemu-img crashes during this step, no harm is done. The content of
3387 * the image is the same as the original one at any time.
3389 if (!unsafe) {
3390 int64_t size;
3391 int64_t old_backing_size;
3392 int64_t new_backing_size = 0;
3393 uint64_t offset;
3394 int64_t n;
3395 float local_progress = 0;
3397 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3398 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3400 size = blk_getlength(blk);
3401 if (size < 0) {
3402 error_report("Could not get size of '%s': %s",
3403 filename, strerror(-size));
3404 ret = -1;
3405 goto out;
3407 old_backing_size = blk_getlength(blk_old_backing);
3408 if (old_backing_size < 0) {
3409 char backing_name[PATH_MAX];
3411 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3412 error_report("Could not get size of '%s': %s",
3413 backing_name, strerror(-old_backing_size));
3414 ret = -1;
3415 goto out;
3417 if (blk_new_backing) {
3418 new_backing_size = blk_getlength(blk_new_backing);
3419 if (new_backing_size < 0) {
3420 error_report("Could not get size of '%s': %s",
3421 out_baseimg, strerror(-new_backing_size));
3422 ret = -1;
3423 goto out;
3427 if (size != 0) {
3428 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3431 for (offset = 0; offset < size; offset += n) {
3432 /* How many bytes can we handle with the next read? */
3433 n = MIN(IO_BUF_SIZE, size - offset);
3435 /* If the cluster is allocated, we don't need to take action */
3436 ret = bdrv_is_allocated(bs, offset, n, &n);
3437 if (ret < 0) {
3438 error_report("error while reading image metadata: %s",
3439 strerror(-ret));
3440 goto out;
3442 if (ret) {
3443 continue;
3447 * Read old and new backing file and take into consideration that
3448 * backing files may be smaller than the COW image.
3450 if (offset >= old_backing_size) {
3451 memset(buf_old, 0, n);
3452 } else {
3453 if (offset + n > old_backing_size) {
3454 n = old_backing_size - offset;
3457 ret = blk_pread(blk_old_backing, offset, buf_old, n);
3458 if (ret < 0) {
3459 error_report("error while reading from old backing file");
3460 goto out;
3464 if (offset >= new_backing_size || !blk_new_backing) {
3465 memset(buf_new, 0, n);
3466 } else {
3467 if (offset + n > new_backing_size) {
3468 n = new_backing_size - offset;
3471 ret = blk_pread(blk_new_backing, offset, buf_new, n);
3472 if (ret < 0) {
3473 error_report("error while reading from new backing file");
3474 goto out;
3478 /* If they differ, we need to write to the COW file */
3479 uint64_t written = 0;
3481 while (written < n) {
3482 int64_t pnum;
3484 if (compare_buffers(buf_old + written, buf_new + written,
3485 n - written, &pnum))
3487 ret = blk_pwrite(blk, offset + written,
3488 buf_old + written, pnum, 0);
3489 if (ret < 0) {
3490 error_report("Error while writing to COW image: %s",
3491 strerror(-ret));
3492 goto out;
3496 written += pnum;
3498 qemu_progress_print(local_progress, 100);
3503 * Change the backing file. All clusters that are different from the old
3504 * backing file are overwritten in the COW file now, so the visible content
3505 * doesn't change when we switch the backing file.
3507 if (out_baseimg && *out_baseimg) {
3508 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3509 } else {
3510 ret = bdrv_change_backing_file(bs, NULL, NULL);
3513 if (ret == -ENOSPC) {
3514 error_report("Could not change the backing file to '%s': No "
3515 "space left in the file header", out_baseimg);
3516 } else if (ret < 0) {
3517 error_report("Could not change the backing file to '%s': %s",
3518 out_baseimg, strerror(-ret));
3521 qemu_progress_print(100, 0);
3523 * TODO At this point it is possible to check if any clusters that are
3524 * allocated in the COW file are the same in the backing file. If so, they
3525 * could be dropped from the COW file. Don't do this before switching the
3526 * backing file, in case of a crash this would lead to corruption.
3528 out:
3529 qemu_progress_end();
3530 /* Cleanup */
3531 if (!unsafe) {
3532 blk_unref(blk_old_backing);
3533 blk_unref(blk_new_backing);
3535 qemu_vfree(buf_old);
3536 qemu_vfree(buf_new);
3538 blk_unref(blk);
3539 if (ret) {
3540 return 1;
3542 return 0;
3545 static int img_resize(int argc, char **argv)
3547 Error *err = NULL;
3548 int c, ret, relative;
3549 const char *filename, *fmt, *size;
3550 int64_t n, total_size, current_size, new_size;
3551 bool quiet = false;
3552 BlockBackend *blk = NULL;
3553 PreallocMode prealloc = PREALLOC_MODE_OFF;
3554 QemuOpts *param;
3556 static QemuOptsList resize_options = {
3557 .name = "resize_options",
3558 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3559 .desc = {
3561 .name = BLOCK_OPT_SIZE,
3562 .type = QEMU_OPT_SIZE,
3563 .help = "Virtual disk size"
3564 }, {
3565 /* end of list */
3569 bool image_opts = false;
3570 bool shrink = false;
3572 /* Remove size from argv manually so that negative numbers are not treated
3573 * as options by getopt. */
3574 if (argc < 3) {
3575 error_exit("Not enough arguments");
3576 return 1;
3579 size = argv[--argc];
3581 /* Parse getopt arguments */
3582 fmt = NULL;
3583 for(;;) {
3584 static const struct option long_options[] = {
3585 {"help", no_argument, 0, 'h'},
3586 {"object", required_argument, 0, OPTION_OBJECT},
3587 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3588 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3589 {"shrink", no_argument, 0, OPTION_SHRINK},
3590 {0, 0, 0, 0}
3592 c = getopt_long(argc, argv, ":f:hq",
3593 long_options, NULL);
3594 if (c == -1) {
3595 break;
3597 switch(c) {
3598 case ':':
3599 missing_argument(argv[optind - 1]);
3600 break;
3601 case '?':
3602 unrecognized_option(argv[optind - 1]);
3603 break;
3604 case 'h':
3605 help();
3606 break;
3607 case 'f':
3608 fmt = optarg;
3609 break;
3610 case 'q':
3611 quiet = true;
3612 break;
3613 case OPTION_OBJECT: {
3614 QemuOpts *opts;
3615 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3616 optarg, true);
3617 if (!opts) {
3618 return 1;
3620 } break;
3621 case OPTION_IMAGE_OPTS:
3622 image_opts = true;
3623 break;
3624 case OPTION_PREALLOCATION:
3625 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3626 PREALLOC_MODE__MAX, NULL);
3627 if (prealloc == PREALLOC_MODE__MAX) {
3628 error_report("Invalid preallocation mode '%s'", optarg);
3629 return 1;
3631 break;
3632 case OPTION_SHRINK:
3633 shrink = true;
3634 break;
3637 if (optind != argc - 1) {
3638 error_exit("Expecting image file name and size");
3640 filename = argv[optind++];
3642 if (qemu_opts_foreach(&qemu_object_opts,
3643 user_creatable_add_opts_foreach,
3644 NULL, &error_fatal)) {
3645 return 1;
3648 /* Choose grow, shrink, or absolute resize mode */
3649 switch (size[0]) {
3650 case '+':
3651 relative = 1;
3652 size++;
3653 break;
3654 case '-':
3655 relative = -1;
3656 size++;
3657 break;
3658 default:
3659 relative = 0;
3660 break;
3663 /* Parse size */
3664 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3665 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3666 if (err) {
3667 error_report_err(err);
3668 ret = -1;
3669 qemu_opts_del(param);
3670 goto out;
3672 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3673 qemu_opts_del(param);
3675 blk = img_open(image_opts, filename, fmt,
3676 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3677 false);
3678 if (!blk) {
3679 ret = -1;
3680 goto out;
3683 current_size = blk_getlength(blk);
3684 if (current_size < 0) {
3685 error_report("Failed to inquire current image length: %s",
3686 strerror(-current_size));
3687 ret = -1;
3688 goto out;
3691 if (relative) {
3692 total_size = current_size + n * relative;
3693 } else {
3694 total_size = n;
3696 if (total_size <= 0) {
3697 error_report("New image size must be positive");
3698 ret = -1;
3699 goto out;
3702 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3703 error_report("Preallocation can only be used for growing images");
3704 ret = -1;
3705 goto out;
3708 if (total_size < current_size && !shrink) {
3709 warn_report("Shrinking an image will delete all data beyond the "
3710 "shrunken image's end. Before performing such an "
3711 "operation, make sure there is no important data there.");
3713 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3714 error_report(
3715 "Use the --shrink option to perform a shrink operation.");
3716 ret = -1;
3717 goto out;
3718 } else {
3719 warn_report("Using the --shrink option will suppress this message. "
3720 "Note that future versions of qemu-img may refuse to "
3721 "shrink images without this option.");
3725 ret = blk_truncate(blk, total_size, prealloc, &err);
3726 if (ret < 0) {
3727 error_report_err(err);
3728 goto out;
3731 new_size = blk_getlength(blk);
3732 if (new_size < 0) {
3733 error_report("Failed to verify truncated image length: %s",
3734 strerror(-new_size));
3735 ret = -1;
3736 goto out;
3739 /* Some block drivers implement a truncation method, but only so
3740 * the user can cause qemu to refresh the image's size from disk.
3741 * The idea is that the user resizes the image outside of qemu and
3742 * then invokes block_resize to inform qemu about it.
3743 * (This includes iscsi and file-posix for device files.)
3744 * Of course, that is not the behavior someone invoking
3745 * qemu-img resize would find useful, so we catch that behavior
3746 * here and tell the user. */
3747 if (new_size != total_size && new_size == current_size) {
3748 error_report("Image was not resized; resizing may not be supported "
3749 "for this image");
3750 ret = -1;
3751 goto out;
3754 if (new_size != total_size) {
3755 warn_report("Image should have been resized to %" PRIi64
3756 " bytes, but was resized to %" PRIi64 " bytes",
3757 total_size, new_size);
3760 qprintf(quiet, "Image resized.\n");
3762 out:
3763 blk_unref(blk);
3764 if (ret) {
3765 return 1;
3767 return 0;
3770 static void amend_status_cb(BlockDriverState *bs,
3771 int64_t offset, int64_t total_work_size,
3772 void *opaque)
3774 qemu_progress_print(100.f * offset / total_work_size, 0);
3777 static int print_amend_option_help(const char *format)
3779 BlockDriver *drv;
3781 /* Find driver and parse its options */
3782 drv = bdrv_find_format(format);
3783 if (!drv) {
3784 error_report("Unknown file format '%s'", format);
3785 return 1;
3788 if (!drv->bdrv_amend_options) {
3789 error_report("Format driver '%s' does not support option amendment",
3790 format);
3791 return 1;
3794 /* Every driver supporting amendment must have create_opts */
3795 assert(drv->create_opts);
3797 printf("Creation options for '%s':\n", format);
3798 qemu_opts_print_help(drv->create_opts, false);
3799 printf("\nNote that not all of these options may be amendable.\n");
3800 return 0;
3803 static int img_amend(int argc, char **argv)
3805 Error *err = NULL;
3806 int c, ret = 0;
3807 char *options = NULL;
3808 QemuOptsList *create_opts = NULL;
3809 QemuOpts *opts = NULL;
3810 const char *fmt = NULL, *filename, *cache;
3811 int flags;
3812 bool writethrough;
3813 bool quiet = false, progress = false;
3814 BlockBackend *blk = NULL;
3815 BlockDriverState *bs = NULL;
3816 bool image_opts = false;
3818 cache = BDRV_DEFAULT_CACHE;
3819 for (;;) {
3820 static const struct option long_options[] = {
3821 {"help", no_argument, 0, 'h'},
3822 {"object", required_argument, 0, OPTION_OBJECT},
3823 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3824 {0, 0, 0, 0}
3826 c = getopt_long(argc, argv, ":ho:f:t:pq",
3827 long_options, NULL);
3828 if (c == -1) {
3829 break;
3832 switch (c) {
3833 case ':':
3834 missing_argument(argv[optind - 1]);
3835 break;
3836 case '?':
3837 unrecognized_option(argv[optind - 1]);
3838 break;
3839 case 'h':
3840 help();
3841 break;
3842 case 'o':
3843 if (!is_valid_option_list(optarg)) {
3844 error_report("Invalid option list: %s", optarg);
3845 ret = -1;
3846 goto out_no_progress;
3848 if (!options) {
3849 options = g_strdup(optarg);
3850 } else {
3851 char *old_options = options;
3852 options = g_strdup_printf("%s,%s", options, optarg);
3853 g_free(old_options);
3855 break;
3856 case 'f':
3857 fmt = optarg;
3858 break;
3859 case 't':
3860 cache = optarg;
3861 break;
3862 case 'p':
3863 progress = true;
3864 break;
3865 case 'q':
3866 quiet = true;
3867 break;
3868 case OPTION_OBJECT:
3869 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3870 optarg, true);
3871 if (!opts) {
3872 ret = -1;
3873 goto out_no_progress;
3875 break;
3876 case OPTION_IMAGE_OPTS:
3877 image_opts = true;
3878 break;
3882 if (!options) {
3883 error_exit("Must specify options (-o)");
3886 if (qemu_opts_foreach(&qemu_object_opts,
3887 user_creatable_add_opts_foreach,
3888 NULL, &error_fatal)) {
3889 ret = -1;
3890 goto out_no_progress;
3893 if (quiet) {
3894 progress = false;
3896 qemu_progress_init(progress, 1.0);
3898 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3899 if (fmt && has_help_option(options)) {
3900 /* If a format is explicitly specified (and possibly no filename is
3901 * given), print option help here */
3902 ret = print_amend_option_help(fmt);
3903 goto out;
3906 if (optind != argc - 1) {
3907 error_report("Expecting one image file name");
3908 ret = -1;
3909 goto out;
3912 flags = BDRV_O_RDWR;
3913 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3914 if (ret < 0) {
3915 error_report("Invalid cache option: %s", cache);
3916 goto out;
3919 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3920 false);
3921 if (!blk) {
3922 ret = -1;
3923 goto out;
3925 bs = blk_bs(blk);
3927 fmt = bs->drv->format_name;
3929 if (has_help_option(options)) {
3930 /* If the format was auto-detected, print option help here */
3931 ret = print_amend_option_help(fmt);
3932 goto out;
3935 if (!bs->drv->bdrv_amend_options) {
3936 error_report("Format driver '%s' does not support option amendment",
3937 fmt);
3938 ret = -1;
3939 goto out;
3942 /* Every driver supporting amendment must have create_opts */
3943 assert(bs->drv->create_opts);
3945 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
3946 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3947 qemu_opts_do_parse(opts, options, NULL, &err);
3948 if (err) {
3949 error_report_err(err);
3950 ret = -1;
3951 goto out;
3954 /* In case the driver does not call amend_status_cb() */
3955 qemu_progress_print(0.f, 0);
3956 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
3957 qemu_progress_print(100.f, 0);
3958 if (ret < 0) {
3959 error_report_err(err);
3960 goto out;
3963 out:
3964 qemu_progress_end();
3966 out_no_progress:
3967 blk_unref(blk);
3968 qemu_opts_del(opts);
3969 qemu_opts_free(create_opts);
3970 g_free(options);
3972 if (ret) {
3973 return 1;
3975 return 0;
3978 typedef struct BenchData {
3979 BlockBackend *blk;
3980 uint64_t image_size;
3981 bool write;
3982 int bufsize;
3983 int step;
3984 int nrreq;
3985 int n;
3986 int flush_interval;
3987 bool drain_on_flush;
3988 uint8_t *buf;
3989 QEMUIOVector *qiov;
3991 int in_flight;
3992 bool in_flush;
3993 uint64_t offset;
3994 } BenchData;
3996 static void bench_undrained_flush_cb(void *opaque, int ret)
3998 if (ret < 0) {
3999 error_report("Failed flush request: %s", strerror(-ret));
4000 exit(EXIT_FAILURE);
4004 static void bench_cb(void *opaque, int ret)
4006 BenchData *b = opaque;
4007 BlockAIOCB *acb;
4009 if (ret < 0) {
4010 error_report("Failed request: %s", strerror(-ret));
4011 exit(EXIT_FAILURE);
4014 if (b->in_flush) {
4015 /* Just finished a flush with drained queue: Start next requests */
4016 assert(b->in_flight == 0);
4017 b->in_flush = false;
4018 } else if (b->in_flight > 0) {
4019 int remaining = b->n - b->in_flight;
4021 b->n--;
4022 b->in_flight--;
4024 /* Time for flush? Drain queue if requested, then flush */
4025 if (b->flush_interval && remaining % b->flush_interval == 0) {
4026 if (!b->in_flight || !b->drain_on_flush) {
4027 BlockCompletionFunc *cb;
4029 if (b->drain_on_flush) {
4030 b->in_flush = true;
4031 cb = bench_cb;
4032 } else {
4033 cb = bench_undrained_flush_cb;
4036 acb = blk_aio_flush(b->blk, cb, b);
4037 if (!acb) {
4038 error_report("Failed to issue flush request");
4039 exit(EXIT_FAILURE);
4042 if (b->drain_on_flush) {
4043 return;
4048 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4049 int64_t offset = b->offset;
4050 /* blk_aio_* might look for completed I/Os and kick bench_cb
4051 * again, so make sure this operation is counted by in_flight
4052 * and b->offset is ready for the next submission.
4054 b->in_flight++;
4055 b->offset += b->step;
4056 b->offset %= b->image_size;
4057 if (b->write) {
4058 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
4059 } else {
4060 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
4062 if (!acb) {
4063 error_report("Failed to issue request");
4064 exit(EXIT_FAILURE);
4069 static int img_bench(int argc, char **argv)
4071 int c, ret = 0;
4072 const char *fmt = NULL, *filename;
4073 bool quiet = false;
4074 bool image_opts = false;
4075 bool is_write = false;
4076 int count = 75000;
4077 int depth = 64;
4078 int64_t offset = 0;
4079 size_t bufsize = 4096;
4080 int pattern = 0;
4081 size_t step = 0;
4082 int flush_interval = 0;
4083 bool drain_on_flush = true;
4084 int64_t image_size;
4085 BlockBackend *blk = NULL;
4086 BenchData data = {};
4087 int flags = 0;
4088 bool writethrough = false;
4089 struct timeval t1, t2;
4090 int i;
4091 bool force_share = false;
4092 size_t buf_size;
4094 for (;;) {
4095 static const struct option long_options[] = {
4096 {"help", no_argument, 0, 'h'},
4097 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
4098 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4099 {"pattern", required_argument, 0, OPTION_PATTERN},
4100 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
4101 {"force-share", no_argument, 0, 'U'},
4102 {0, 0, 0, 0}
4104 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
4105 if (c == -1) {
4106 break;
4109 switch (c) {
4110 case ':':
4111 missing_argument(argv[optind - 1]);
4112 break;
4113 case '?':
4114 unrecognized_option(argv[optind - 1]);
4115 break;
4116 case 'h':
4117 help();
4118 break;
4119 case 'c':
4121 unsigned long res;
4123 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4124 error_report("Invalid request count specified");
4125 return 1;
4127 count = res;
4128 break;
4130 case 'd':
4132 unsigned long res;
4134 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4135 error_report("Invalid queue depth specified");
4136 return 1;
4138 depth = res;
4139 break;
4141 case 'f':
4142 fmt = optarg;
4143 break;
4144 case 'n':
4145 flags |= BDRV_O_NATIVE_AIO;
4146 break;
4147 case 'o':
4149 offset = cvtnum(optarg);
4150 if (offset < 0) {
4151 error_report("Invalid offset specified");
4152 return 1;
4154 break;
4156 break;
4157 case 'q':
4158 quiet = true;
4159 break;
4160 case 's':
4162 int64_t sval;
4164 sval = cvtnum(optarg);
4165 if (sval < 0 || sval > INT_MAX) {
4166 error_report("Invalid buffer size specified");
4167 return 1;
4170 bufsize = sval;
4171 break;
4173 case 'S':
4175 int64_t sval;
4177 sval = cvtnum(optarg);
4178 if (sval < 0 || sval > INT_MAX) {
4179 error_report("Invalid step size specified");
4180 return 1;
4183 step = sval;
4184 break;
4186 case 't':
4187 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4188 if (ret < 0) {
4189 error_report("Invalid cache mode");
4190 ret = -1;
4191 goto out;
4193 break;
4194 case 'w':
4195 flags |= BDRV_O_RDWR;
4196 is_write = true;
4197 break;
4198 case 'U':
4199 force_share = true;
4200 break;
4201 case OPTION_PATTERN:
4203 unsigned long res;
4205 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4206 error_report("Invalid pattern byte specified");
4207 return 1;
4209 pattern = res;
4210 break;
4212 case OPTION_FLUSH_INTERVAL:
4214 unsigned long res;
4216 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4217 error_report("Invalid flush interval specified");
4218 return 1;
4220 flush_interval = res;
4221 break;
4223 case OPTION_NO_DRAIN:
4224 drain_on_flush = false;
4225 break;
4226 case OPTION_IMAGE_OPTS:
4227 image_opts = true;
4228 break;
4232 if (optind != argc - 1) {
4233 error_exit("Expecting one image file name");
4235 filename = argv[argc - 1];
4237 if (!is_write && flush_interval) {
4238 error_report("--flush-interval is only available in write tests");
4239 ret = -1;
4240 goto out;
4242 if (flush_interval && flush_interval < depth) {
4243 error_report("Flush interval can't be smaller than depth");
4244 ret = -1;
4245 goto out;
4248 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4249 force_share);
4250 if (!blk) {
4251 ret = -1;
4252 goto out;
4255 image_size = blk_getlength(blk);
4256 if (image_size < 0) {
4257 ret = image_size;
4258 goto out;
4261 data = (BenchData) {
4262 .blk = blk,
4263 .image_size = image_size,
4264 .bufsize = bufsize,
4265 .step = step ?: bufsize,
4266 .nrreq = depth,
4267 .n = count,
4268 .offset = offset,
4269 .write = is_write,
4270 .flush_interval = flush_interval,
4271 .drain_on_flush = drain_on_flush,
4273 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4274 "(starting at offset %" PRId64 ", step size %d)\n",
4275 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4276 data.offset, data.step);
4277 if (flush_interval) {
4278 printf("Sending flush every %d requests\n", flush_interval);
4281 buf_size = data.nrreq * data.bufsize;
4282 data.buf = blk_blockalign(blk, buf_size);
4283 memset(data.buf, pattern, data.nrreq * data.bufsize);
4285 blk_register_buf(blk, data.buf, buf_size);
4287 data.qiov = g_new(QEMUIOVector, data.nrreq);
4288 for (i = 0; i < data.nrreq; i++) {
4289 qemu_iovec_init(&data.qiov[i], 1);
4290 qemu_iovec_add(&data.qiov[i],
4291 data.buf + i * data.bufsize, data.bufsize);
4294 gettimeofday(&t1, NULL);
4295 bench_cb(&data, 0);
4297 while (data.n > 0) {
4298 main_loop_wait(false);
4300 gettimeofday(&t2, NULL);
4302 printf("Run completed in %3.3f seconds.\n",
4303 (t2.tv_sec - t1.tv_sec)
4304 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4306 out:
4307 if (data.buf) {
4308 blk_unregister_buf(blk, data.buf);
4310 qemu_vfree(data.buf);
4311 blk_unref(blk);
4313 if (ret) {
4314 return 1;
4316 return 0;
4319 #define C_BS 01
4320 #define C_COUNT 02
4321 #define C_IF 04
4322 #define C_OF 010
4323 #define C_SKIP 020
4325 struct DdInfo {
4326 unsigned int flags;
4327 int64_t count;
4330 struct DdIo {
4331 int bsz; /* Block size */
4332 char *filename;
4333 uint8_t *buf;
4334 int64_t offset;
4337 struct DdOpts {
4338 const char *name;
4339 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4340 unsigned int flag;
4343 static int img_dd_bs(const char *arg,
4344 struct DdIo *in, struct DdIo *out,
4345 struct DdInfo *dd)
4347 int64_t res;
4349 res = cvtnum(arg);
4351 if (res <= 0 || res > INT_MAX) {
4352 error_report("invalid number: '%s'", arg);
4353 return 1;
4355 in->bsz = out->bsz = res;
4357 return 0;
4360 static int img_dd_count(const char *arg,
4361 struct DdIo *in, struct DdIo *out,
4362 struct DdInfo *dd)
4364 dd->count = cvtnum(arg);
4366 if (dd->count < 0) {
4367 error_report("invalid number: '%s'", arg);
4368 return 1;
4371 return 0;
4374 static int img_dd_if(const char *arg,
4375 struct DdIo *in, struct DdIo *out,
4376 struct DdInfo *dd)
4378 in->filename = g_strdup(arg);
4380 return 0;
4383 static int img_dd_of(const char *arg,
4384 struct DdIo *in, struct DdIo *out,
4385 struct DdInfo *dd)
4387 out->filename = g_strdup(arg);
4389 return 0;
4392 static int img_dd_skip(const char *arg,
4393 struct DdIo *in, struct DdIo *out,
4394 struct DdInfo *dd)
4396 in->offset = cvtnum(arg);
4398 if (in->offset < 0) {
4399 error_report("invalid number: '%s'", arg);
4400 return 1;
4403 return 0;
4406 static int img_dd(int argc, char **argv)
4408 int ret = 0;
4409 char *arg = NULL;
4410 char *tmp;
4411 BlockDriver *drv = NULL, *proto_drv = NULL;
4412 BlockBackend *blk1 = NULL, *blk2 = NULL;
4413 QemuOpts *opts = NULL;
4414 QemuOptsList *create_opts = NULL;
4415 Error *local_err = NULL;
4416 bool image_opts = false;
4417 int c, i;
4418 const char *out_fmt = "raw";
4419 const char *fmt = NULL;
4420 int64_t size = 0;
4421 int64_t block_count = 0, out_pos, in_pos;
4422 bool force_share = false;
4423 struct DdInfo dd = {
4424 .flags = 0,
4425 .count = 0,
4427 struct DdIo in = {
4428 .bsz = 512, /* Block size is by default 512 bytes */
4429 .filename = NULL,
4430 .buf = NULL,
4431 .offset = 0
4433 struct DdIo out = {
4434 .bsz = 512,
4435 .filename = NULL,
4436 .buf = NULL,
4437 .offset = 0
4440 const struct DdOpts options[] = {
4441 { "bs", img_dd_bs, C_BS },
4442 { "count", img_dd_count, C_COUNT },
4443 { "if", img_dd_if, C_IF },
4444 { "of", img_dd_of, C_OF },
4445 { "skip", img_dd_skip, C_SKIP },
4446 { NULL, NULL, 0 }
4448 const struct option long_options[] = {
4449 { "help", no_argument, 0, 'h'},
4450 { "object", required_argument, 0, OPTION_OBJECT},
4451 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4452 { "force-share", no_argument, 0, 'U'},
4453 { 0, 0, 0, 0 }
4456 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4457 if (c == EOF) {
4458 break;
4460 switch (c) {
4461 case 'O':
4462 out_fmt = optarg;
4463 break;
4464 case 'f':
4465 fmt = optarg;
4466 break;
4467 case ':':
4468 missing_argument(argv[optind - 1]);
4469 break;
4470 case '?':
4471 unrecognized_option(argv[optind - 1]);
4472 break;
4473 case 'h':
4474 help();
4475 break;
4476 case 'U':
4477 force_share = true;
4478 break;
4479 case OPTION_OBJECT:
4480 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4481 ret = -1;
4482 goto out;
4484 break;
4485 case OPTION_IMAGE_OPTS:
4486 image_opts = true;
4487 break;
4491 for (i = optind; i < argc; i++) {
4492 int j;
4493 arg = g_strdup(argv[i]);
4495 tmp = strchr(arg, '=');
4496 if (tmp == NULL) {
4497 error_report("unrecognized operand %s", arg);
4498 ret = -1;
4499 goto out;
4502 *tmp++ = '\0';
4504 for (j = 0; options[j].name != NULL; j++) {
4505 if (!strcmp(arg, options[j].name)) {
4506 break;
4509 if (options[j].name == NULL) {
4510 error_report("unrecognized operand %s", arg);
4511 ret = -1;
4512 goto out;
4515 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4516 ret = -1;
4517 goto out;
4519 dd.flags |= options[j].flag;
4520 g_free(arg);
4521 arg = NULL;
4524 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4525 error_report("Must specify both input and output files");
4526 ret = -1;
4527 goto out;
4530 if (qemu_opts_foreach(&qemu_object_opts,
4531 user_creatable_add_opts_foreach,
4532 NULL, &error_fatal)) {
4533 ret = -1;
4534 goto out;
4537 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4538 force_share);
4540 if (!blk1) {
4541 ret = -1;
4542 goto out;
4545 drv = bdrv_find_format(out_fmt);
4546 if (!drv) {
4547 error_report("Unknown file format");
4548 ret = -1;
4549 goto out;
4551 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4553 if (!proto_drv) {
4554 error_report_err(local_err);
4555 ret = -1;
4556 goto out;
4558 if (!drv->create_opts) {
4559 error_report("Format driver '%s' does not support image creation",
4560 drv->format_name);
4561 ret = -1;
4562 goto out;
4564 if (!proto_drv->create_opts) {
4565 error_report("Protocol driver '%s' does not support image creation",
4566 proto_drv->format_name);
4567 ret = -1;
4568 goto out;
4570 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4571 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4573 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4575 size = blk_getlength(blk1);
4576 if (size < 0) {
4577 error_report("Failed to get size for '%s'", in.filename);
4578 ret = -1;
4579 goto out;
4582 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4583 dd.count * in.bsz < size) {
4584 size = dd.count * in.bsz;
4587 /* Overflow means the specified offset is beyond input image's size */
4588 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4589 size < in.bsz * in.offset)) {
4590 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4591 } else {
4592 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4593 size - in.bsz * in.offset, &error_abort);
4596 ret = bdrv_create(drv, out.filename, opts, &local_err);
4597 if (ret < 0) {
4598 error_reportf_err(local_err,
4599 "%s: error while creating output image: ",
4600 out.filename);
4601 ret = -1;
4602 goto out;
4605 /* TODO, we can't honour --image-opts for the target,
4606 * since it needs to be given in a format compatible
4607 * with the bdrv_create() call above which does not
4608 * support image-opts style.
4610 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
4611 false, false, false);
4613 if (!blk2) {
4614 ret = -1;
4615 goto out;
4618 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4619 size < in.offset * in.bsz)) {
4620 /* We give a warning if the skip option is bigger than the input
4621 * size and create an empty output disk image (i.e. like dd(1)).
4623 error_report("%s: cannot skip to specified offset", in.filename);
4624 in_pos = size;
4625 } else {
4626 in_pos = in.offset * in.bsz;
4629 in.buf = g_new(uint8_t, in.bsz);
4631 for (out_pos = 0; in_pos < size; block_count++) {
4632 int in_ret, out_ret;
4634 if (in_pos + in.bsz > size) {
4635 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4636 } else {
4637 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4639 if (in_ret < 0) {
4640 error_report("error while reading from input image file: %s",
4641 strerror(-in_ret));
4642 ret = -1;
4643 goto out;
4645 in_pos += in_ret;
4647 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4649 if (out_ret < 0) {
4650 error_report("error while writing to output image file: %s",
4651 strerror(-out_ret));
4652 ret = -1;
4653 goto out;
4655 out_pos += out_ret;
4658 out:
4659 g_free(arg);
4660 qemu_opts_del(opts);
4661 qemu_opts_free(create_opts);
4662 blk_unref(blk1);
4663 blk_unref(blk2);
4664 g_free(in.filename);
4665 g_free(out.filename);
4666 g_free(in.buf);
4667 g_free(out.buf);
4669 if (ret) {
4670 return 1;
4672 return 0;
4675 static void dump_json_block_measure_info(BlockMeasureInfo *info)
4677 QString *str;
4678 QObject *obj;
4679 Visitor *v = qobject_output_visitor_new(&obj);
4681 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4682 visit_complete(v, &obj);
4683 str = qobject_to_json_pretty(obj);
4684 assert(str != NULL);
4685 printf("%s\n", qstring_get_str(str));
4686 qobject_unref(obj);
4687 visit_free(v);
4688 qobject_unref(str);
4691 static int img_measure(int argc, char **argv)
4693 static const struct option long_options[] = {
4694 {"help", no_argument, 0, 'h'},
4695 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4696 {"object", required_argument, 0, OPTION_OBJECT},
4697 {"output", required_argument, 0, OPTION_OUTPUT},
4698 {"size", required_argument, 0, OPTION_SIZE},
4699 {"force-share", no_argument, 0, 'U'},
4700 {0, 0, 0, 0}
4702 OutputFormat output_format = OFORMAT_HUMAN;
4703 BlockBackend *in_blk = NULL;
4704 BlockDriver *drv;
4705 const char *filename = NULL;
4706 const char *fmt = NULL;
4707 const char *out_fmt = "raw";
4708 char *options = NULL;
4709 char *snapshot_name = NULL;
4710 bool force_share = false;
4711 QemuOpts *opts = NULL;
4712 QemuOpts *object_opts = NULL;
4713 QemuOpts *sn_opts = NULL;
4714 QemuOptsList *create_opts = NULL;
4715 bool image_opts = false;
4716 uint64_t img_size = UINT64_MAX;
4717 BlockMeasureInfo *info = NULL;
4718 Error *local_err = NULL;
4719 int ret = 1;
4720 int c;
4722 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4723 long_options, NULL)) != -1) {
4724 switch (c) {
4725 case '?':
4726 case 'h':
4727 help();
4728 break;
4729 case 'f':
4730 fmt = optarg;
4731 break;
4732 case 'O':
4733 out_fmt = optarg;
4734 break;
4735 case 'o':
4736 if (!is_valid_option_list(optarg)) {
4737 error_report("Invalid option list: %s", optarg);
4738 goto out;
4740 if (!options) {
4741 options = g_strdup(optarg);
4742 } else {
4743 char *old_options = options;
4744 options = g_strdup_printf("%s,%s", options, optarg);
4745 g_free(old_options);
4747 break;
4748 case 'l':
4749 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4750 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4751 optarg, false);
4752 if (!sn_opts) {
4753 error_report("Failed in parsing snapshot param '%s'",
4754 optarg);
4755 goto out;
4757 } else {
4758 snapshot_name = optarg;
4760 break;
4761 case 'U':
4762 force_share = true;
4763 break;
4764 case OPTION_OBJECT:
4765 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4766 optarg, true);
4767 if (!object_opts) {
4768 goto out;
4770 break;
4771 case OPTION_IMAGE_OPTS:
4772 image_opts = true;
4773 break;
4774 case OPTION_OUTPUT:
4775 if (!strcmp(optarg, "json")) {
4776 output_format = OFORMAT_JSON;
4777 } else if (!strcmp(optarg, "human")) {
4778 output_format = OFORMAT_HUMAN;
4779 } else {
4780 error_report("--output must be used with human or json "
4781 "as argument.");
4782 goto out;
4784 break;
4785 case OPTION_SIZE:
4787 int64_t sval;
4789 sval = cvtnum(optarg);
4790 if (sval < 0) {
4791 if (sval == -ERANGE) {
4792 error_report("Image size must be less than 8 EiB!");
4793 } else {
4794 error_report("Invalid image size specified! You may use "
4795 "k, M, G, T, P or E suffixes for ");
4796 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4797 "petabytes and exabytes.");
4799 goto out;
4801 img_size = (uint64_t)sval;
4803 break;
4807 if (qemu_opts_foreach(&qemu_object_opts,
4808 user_creatable_add_opts_foreach,
4809 NULL, &error_fatal)) {
4810 goto out;
4813 if (argc - optind > 1) {
4814 error_report("At most one filename argument is allowed.");
4815 goto out;
4816 } else if (argc - optind == 1) {
4817 filename = argv[optind];
4820 if (!filename &&
4821 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4822 error_report("--object, --image-opts, -f, and -l "
4823 "require a filename argument.");
4824 goto out;
4826 if (filename && img_size != UINT64_MAX) {
4827 error_report("--size N cannot be used together with a filename.");
4828 goto out;
4830 if (!filename && img_size == UINT64_MAX) {
4831 error_report("Either --size N or one filename must be specified.");
4832 goto out;
4835 if (filename) {
4836 in_blk = img_open(image_opts, filename, fmt, 0,
4837 false, false, force_share);
4838 if (!in_blk) {
4839 goto out;
4842 if (sn_opts) {
4843 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4844 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4845 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4846 &local_err);
4847 } else if (snapshot_name != NULL) {
4848 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4849 snapshot_name, &local_err);
4851 if (local_err) {
4852 error_reportf_err(local_err, "Failed to load snapshot: ");
4853 goto out;
4857 drv = bdrv_find_format(out_fmt);
4858 if (!drv) {
4859 error_report("Unknown file format '%s'", out_fmt);
4860 goto out;
4862 if (!drv->create_opts) {
4863 error_report("Format driver '%s' does not support image creation",
4864 drv->format_name);
4865 goto out;
4868 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4869 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4870 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4871 if (options) {
4872 qemu_opts_do_parse(opts, options, NULL, &local_err);
4873 if (local_err) {
4874 error_report_err(local_err);
4875 error_report("Invalid options for file format '%s'", out_fmt);
4876 goto out;
4879 if (img_size != UINT64_MAX) {
4880 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4883 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4884 if (local_err) {
4885 error_report_err(local_err);
4886 goto out;
4889 if (output_format == OFORMAT_HUMAN) {
4890 printf("required size: %" PRIu64 "\n", info->required);
4891 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4892 } else {
4893 dump_json_block_measure_info(info);
4896 ret = 0;
4898 out:
4899 qapi_free_BlockMeasureInfo(info);
4900 qemu_opts_del(object_opts);
4901 qemu_opts_del(opts);
4902 qemu_opts_del(sn_opts);
4903 qemu_opts_free(create_opts);
4904 g_free(options);
4905 blk_unref(in_blk);
4906 return ret;
4909 static const img_cmd_t img_cmds[] = {
4910 #define DEF(option, callback, arg_string) \
4911 { option, callback },
4912 #include "qemu-img-cmds.h"
4913 #undef DEF
4914 { NULL, NULL, },
4917 int main(int argc, char **argv)
4919 const img_cmd_t *cmd;
4920 const char *cmdname;
4921 Error *local_error = NULL;
4922 char *trace_file = NULL;
4923 int c;
4924 static const struct option long_options[] = {
4925 {"help", no_argument, 0, 'h'},
4926 {"version", no_argument, 0, 'V'},
4927 {"trace", required_argument, NULL, 'T'},
4928 {0, 0, 0, 0}
4931 #ifdef CONFIG_POSIX
4932 signal(SIGPIPE, SIG_IGN);
4933 #endif
4935 error_init(argv[0]);
4936 module_call_init(MODULE_INIT_TRACE);
4937 qemu_init_exec_dir(argv[0]);
4939 if (qemu_init_main_loop(&local_error)) {
4940 error_report_err(local_error);
4941 exit(EXIT_FAILURE);
4944 qcrypto_init(&error_fatal);
4946 module_call_init(MODULE_INIT_QOM);
4947 bdrv_init();
4948 if (argc < 2) {
4949 error_exit("Not enough arguments");
4952 qemu_add_opts(&qemu_object_opts);
4953 qemu_add_opts(&qemu_source_opts);
4954 qemu_add_opts(&qemu_trace_opts);
4956 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
4957 switch (c) {
4958 case ':':
4959 missing_argument(argv[optind - 1]);
4960 return 0;
4961 case '?':
4962 unrecognized_option(argv[optind - 1]);
4963 return 0;
4964 case 'h':
4965 help();
4966 return 0;
4967 case 'V':
4968 printf(QEMU_IMG_VERSION);
4969 return 0;
4970 case 'T':
4971 g_free(trace_file);
4972 trace_file = trace_opt_parse(optarg);
4973 break;
4977 cmdname = argv[optind];
4979 /* reset getopt_long scanning */
4980 argc -= optind;
4981 if (argc < 1) {
4982 return 0;
4984 argv += optind;
4985 qemu_reset_optind();
4987 if (!trace_init_backends()) {
4988 exit(1);
4990 trace_init_file(trace_file);
4991 qemu_set_log(LOG_TRACE);
4993 /* find the command */
4994 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4995 if (!strcmp(cmdname, cmd->name)) {
4996 return cmd->handler(argc, argv);
5000 /* not found */
5001 error_exit("Command not found: %s", cmdname);