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
25 #include "qemu/osdep.h"
28 #include "qemu/help-texts.h"
29 #include "qemu/qemu-progress.h"
30 #include "qemu-version.h"
31 #include "qapi/error.h"
32 #include "qapi/qapi-commands-block-core.h"
33 #include "qapi/qapi-visit-block-core.h"
34 #include "qapi/qobject-output-visitor.h"
35 #include "qapi/qmp/qjson.h"
36 #include "qapi/qmp/qdict.h"
37 #include "qemu/cutils.h"
38 #include "qemu/config-file.h"
39 #include "qemu/option.h"
40 #include "qemu/error-report.h"
42 #include "qemu/main-loop.h"
43 #include "qemu/module.h"
44 #include "qemu/sockets.h"
45 #include "qemu/units.h"
46 #include "qemu/memalign.h"
47 #include "qom/object_interfaces.h"
48 #include "sysemu/block-backend.h"
49 #include "block/block_int.h"
50 #include "block/blockjob.h"
51 #include "block/dirty-bitmap.h"
52 #include "block/qapi.h"
53 #include "crypto/init.h"
54 #include "trace/control.h"
55 #include "qemu/throttle.h"
56 #include "block/throttle-groups.h"
58 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
59 "\n" QEMU_COPYRIGHT "\n"
61 typedef struct img_cmd_t {
63 int (*handler)(int argc, char **argv);
68 OPTION_BACKING_CHAIN = 257,
70 OPTION_IMAGE_OPTS = 259,
72 OPTION_FLUSH_INTERVAL = 261,
73 OPTION_NO_DRAIN = 262,
74 OPTION_TARGET_IMAGE_OPTS = 263,
76 OPTION_PREALLOCATION = 265,
79 OPTION_TARGET_IS_ZERO = 268,
88 OPTION_SKIP_BROKEN = 277,
91 typedef enum OutputFormat {
96 /* Default to cache=writeback as data integrity is not important for qemu-img */
97 #define BDRV_DEFAULT_CACHE "writeback"
99 static void format_print(void *opaque, const char *name)
104 static G_NORETURN G_GNUC_PRINTF(1, 2)
105 void error_exit(const char *fmt, ...)
110 error_vreport(fmt, ap);
113 error_printf("Try 'qemu-img --help' for more information\n");
118 void missing_argument(const char *option)
120 error_exit("missing argument for option '%s'", option);
124 void unrecognized_option(const char *option)
126 error_exit("unrecognized option '%s'", option);
129 /* Please keep in synch with docs/tools/qemu-img.rst */
133 const char *help_msg =
135 "usage: qemu-img [standard options] command [command options]\n"
136 "QEMU disk image utility\n"
138 " '-h', '--help' display this help and exit\n"
139 " '-V', '--version' output version information and exit\n"
140 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
141 " specify tracing options\n"
144 #define DEF(option, callback, arg_string) \
146 #include "qemu-img-cmds.h"
149 "Command parameters:\n"
150 " 'filename' is a disk image filename\n"
151 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
152 " manual page for a description of the object properties. The most common\n"
153 " object type is a 'secret', which is used to supply passwords and/or\n"
154 " encryption keys.\n"
155 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
156 " 'cache' is the cache mode used to write the output disk image, the valid\n"
157 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
158 " 'directsync' and 'unsafe' (default for convert)\n"
159 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
160 " options are the same as for the 'cache' option\n"
161 " 'size' is the disk image size in bytes. Optional suffixes\n"
162 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
163 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
164 " supported. 'b' is ignored.\n"
165 " 'output_filename' is the destination disk image filename\n"
166 " 'output_fmt' is the destination format\n"
167 " 'options' is a comma separated list of format specific options in a\n"
168 " name=value format. Use -o help for an overview of the options supported by\n"
170 " 'snapshot_param' is param used for internal snapshot, format\n"
171 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
173 " '-c' indicates that target image must be compressed (qcow format only)\n"
174 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
175 " new backing file match exactly. The image doesn't need a working\n"
176 " backing file before rebasing in this case (useful for renaming the\n"
177 " backing file). For image creation, allow creating without attempting\n"
178 " to open the backing file.\n"
179 " '-h' with or without a command shows this help and lists the supported formats\n"
180 " '-p' show progress of command (only certain commands)\n"
181 " '-q' use Quiet mode - do not print any output (except errors)\n"
182 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
183 " contain only zeros for qemu-img to create a sparse image during\n"
184 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
185 " unallocated or zero sectors, and the destination image will always be\n"
187 " '--output' takes the format in which the output must be done (human or json)\n"
188 " '-n' skips the target volume creation (useful if the volume is created\n"
189 " prior to running qemu-img)\n"
191 "Parameters to bitmap subcommand:\n"
192 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
193 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
194 " or '--merge source'\n"
195 " '-g granularity' sets the granularity for '--add' actions\n"
196 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
197 " bitmaps from an alternative file\n"
199 "Parameters to check subcommand:\n"
200 " '-r' tries to repair any inconsistencies that are found during the check.\n"
201 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
202 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
203 " hiding corruption that has already occurred.\n"
205 "Parameters to convert subcommand:\n"
206 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
207 " '-m' specifies how many coroutines work in parallel during the convert\n"
208 " process (defaults to 8)\n"
209 " '-W' allow to write to the target out of order rather than sequential\n"
211 "Parameters to snapshot subcommand:\n"
212 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
213 " '-a' applies a snapshot (revert disk to saved state)\n"
214 " '-c' creates a snapshot\n"
215 " '-d' deletes a snapshot\n"
216 " '-l' lists all snapshots in the given image\n"
218 "Parameters to compare subcommand:\n"
219 " '-f' first image format\n"
220 " '-F' second image format\n"
221 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
223 "Parameters to dd subcommand:\n"
224 " 'bs=BYTES' read and write up to BYTES bytes at a time "
226 " 'count=N' copy only N input blocks\n"
227 " 'if=FILE' read from FILE\n"
228 " 'of=FILE' write to FILE\n"
229 " 'skip=N' skip N bs-sized blocks at the start of input\n";
231 printf("%s\nSupported formats:", help_msg);
232 bdrv_iterate_format(format_print, NULL, false);
233 printf("\n\n" QEMU_HELP_BOTTOM "\n");
238 * Is @optarg safe for accumulate_options()?
239 * It is when multiple of them can be joined together separated by ','.
240 * To make that work, @optarg must not start with ',' (or else a
241 * separating ',' preceding it gets escaped), and it must not end with
242 * an odd number of ',' (or else a separating ',' following it gets
243 * escaped), or be empty (or else a separating ',' preceding it can
244 * escape a separating ',' following it).
247 static bool is_valid_option_list(const char *optarg)
249 size_t len = strlen(optarg);
252 if (!optarg[0] || optarg[0] == ',') {
256 for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
265 static int accumulate_options(char **options, char *optarg)
269 if (!is_valid_option_list(optarg)) {
270 error_report("Invalid option list: %s", optarg);
275 *options = g_strdup(optarg);
277 new_options = g_strdup_printf("%s,%s", *options, optarg);
279 *options = new_options;
284 static QemuOptsList qemu_source_opts = {
286 .implied_opt_name = "file",
287 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
293 static int G_GNUC_PRINTF(2, 3) qprintf(bool quiet, const char *fmt, ...)
299 ret = vprintf(fmt, args);
306 static int print_block_option_help(const char *filename, const char *fmt)
308 BlockDriver *drv, *proto_drv;
309 QemuOptsList *create_opts = NULL;
310 Error *local_err = NULL;
312 /* Find driver and parse its options */
313 drv = bdrv_find_format(fmt);
315 error_report("Unknown file format '%s'", fmt);
319 if (!drv->create_opts) {
320 error_report("Format driver '%s' does not support image creation", fmt);
324 create_opts = qemu_opts_append(create_opts, drv->create_opts);
326 proto_drv = bdrv_find_protocol(filename, true, &local_err);
328 error_report_err(local_err);
329 qemu_opts_free(create_opts);
332 if (!proto_drv->create_opts) {
333 error_report("Protocol driver '%s' does not support image creation",
334 proto_drv->format_name);
335 qemu_opts_free(create_opts);
338 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
342 printf("Supported options:\n");
344 printf("Supported %s options:\n", fmt);
346 qemu_opts_print_help(create_opts, false);
347 qemu_opts_free(create_opts);
351 "The protocol level may support further options.\n"
352 "Specify the target filename to include those options.\n");
359 static BlockBackend *img_open_opts(const char *optstr,
360 QemuOpts *opts, int flags, bool writethrough,
361 bool quiet, bool force_share)
364 Error *local_err = NULL;
366 options = qemu_opts_to_qdict(opts, NULL);
368 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
369 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
370 error_report("--force-share/-U conflicts with image options");
371 qobject_unref(options);
374 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
376 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
378 error_reportf_err(local_err, "Could not open '%s': ", optstr);
381 blk_set_enable_write_cache(blk, !writethrough);
386 static BlockBackend *img_open_file(const char *filename,
388 const char *fmt, int flags,
389 bool writethrough, bool quiet,
393 Error *local_err = NULL;
396 options = qdict_new();
399 qdict_put_str(options, "driver", fmt);
403 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
405 blk = blk_new_open(filename, NULL, options, flags, &local_err);
407 error_reportf_err(local_err, "Could not open '%s': ", filename);
410 blk_set_enable_write_cache(blk, !writethrough);
416 static int img_add_key_secrets(void *opaque,
417 const char *name, const char *value,
420 QDict *options = opaque;
422 if (g_str_has_suffix(name, "key-secret")) {
423 qdict_put_str(options, name, value);
430 static BlockBackend *img_open(bool image_opts,
431 const char *filename,
432 const char *fmt, int flags, bool writethrough,
433 bool quiet, bool force_share)
439 error_report("--image-opts and --format are mutually exclusive");
442 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
447 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
450 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
457 static int add_old_style_options(const char *fmt, QemuOpts *opts,
458 const char *base_filename,
459 const char *base_fmt)
462 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
464 error_report("Backing file not supported for file format '%s'",
470 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
471 error_report("Backing file format not supported for file "
479 static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
485 err = qemu_strtosz(value, NULL, &res);
486 if (err < 0 && err != -ERANGE) {
487 error_report("Invalid %s specified. You may use "
488 "k, M, G, T, P or E suffixes for", name);
489 error_report("kilobytes, megabytes, gigabytes, terabytes, "
490 "petabytes and exabytes.");
493 if (err == -ERANGE || res > max || res < min) {
494 error_report("Invalid %s specified. Must be between %" PRId64
495 " and %" PRId64 ".", name, min, max);
501 static int64_t cvtnum(const char *name, const char *value)
503 return cvtnum_full(name, value, 0, INT64_MAX);
506 static int img_create(int argc, char **argv)
509 uint64_t img_size = -1;
510 const char *fmt = "raw";
511 const char *base_fmt = NULL;
512 const char *filename;
513 const char *base_filename = NULL;
514 char *options = NULL;
515 Error *local_err = NULL;
520 static const struct option long_options[] = {
521 {"help", no_argument, 0, 'h'},
522 {"object", required_argument, 0, OPTION_OBJECT},
525 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
532 missing_argument(argv[optind - 1]);
535 unrecognized_option(argv[optind - 1]);
544 base_filename = optarg;
550 if (accumulate_options(&options, optarg) < 0) {
558 flags |= BDRV_O_NO_BACKING;
561 user_creatable_process_cmdline(optarg);
566 /* Get the filename */
567 filename = (optind < argc) ? argv[optind] : NULL;
568 if (options && has_help_option(options)) {
570 return print_block_option_help(filename, fmt);
573 if (optind >= argc) {
574 error_exit("Expecting image file name");
578 /* Get image size, if specified */
582 sval = cvtnum("image size", argv[optind++]);
586 img_size = (uint64_t)sval;
588 if (optind != argc) {
589 error_exit("Unexpected argument: %s", argv[optind]);
592 bdrv_img_create(filename, fmt, base_filename, base_fmt,
593 options, img_size, flags, quiet, &local_err);
595 error_reportf_err(local_err, "%s: ", filename);
607 static void dump_json_image_check(ImageCheck *check, bool quiet)
611 Visitor *v = qobject_output_visitor_new(&obj);
613 visit_type_ImageCheck(v, NULL, &check, &error_abort);
614 visit_complete(v, &obj);
615 str = qobject_to_json_pretty(obj, true);
617 qprintf(quiet, "%s\n", str->str);
620 g_string_free(str, true);
623 static void dump_human_image_check(ImageCheck *check, bool quiet)
625 if (!(check->corruptions || check->leaks || check->check_errors)) {
626 qprintf(quiet, "No errors were found on the image.\n");
628 if (check->corruptions) {
629 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
630 "Data may be corrupted, or further writes to the image "
637 "\n%" PRId64 " leaked clusters were found on the image.\n"
638 "This means waste of disk space, but no harm to data.\n",
642 if (check->check_errors) {
645 " internal errors have occurred during the check.\n",
646 check->check_errors);
650 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
651 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
652 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
653 check->allocated_clusters, check->total_clusters,
654 check->allocated_clusters * 100.0 / check->total_clusters,
655 check->fragmented_clusters * 100.0 / check->allocated_clusters,
656 check->compressed_clusters * 100.0 /
657 check->allocated_clusters);
660 if (check->image_end_offset) {
662 "Image end offset: %" PRId64 "\n", check->image_end_offset);
666 static int collect_image_check(BlockDriverState *bs,
668 const char *filename,
673 BdrvCheckResult result;
675 ret = bdrv_check(bs, &result, fix);
680 check->filename = g_strdup(filename);
681 check->format = g_strdup(bdrv_get_format_name(bs));
682 check->check_errors = result.check_errors;
683 check->corruptions = result.corruptions;
684 check->has_corruptions = result.corruptions != 0;
685 check->leaks = result.leaks;
686 check->has_leaks = result.leaks != 0;
687 check->corruptions_fixed = result.corruptions_fixed;
688 check->has_corruptions_fixed = result.corruptions_fixed != 0;
689 check->leaks_fixed = result.leaks_fixed;
690 check->has_leaks_fixed = result.leaks_fixed != 0;
691 check->image_end_offset = result.image_end_offset;
692 check->has_image_end_offset = result.image_end_offset != 0;
693 check->total_clusters = result.bfi.total_clusters;
694 check->has_total_clusters = result.bfi.total_clusters != 0;
695 check->allocated_clusters = result.bfi.allocated_clusters;
696 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
697 check->fragmented_clusters = result.bfi.fragmented_clusters;
698 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
699 check->compressed_clusters = result.bfi.compressed_clusters;
700 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
706 * Checks an image for consistency. Exit codes:
708 * 0 - Check completed, image is good
709 * 1 - Check not completed because of internal errors
710 * 2 - Check completed, image is corrupted
711 * 3 - Check completed, image has leaked clusters, but is good otherwise
712 * 63 - Checks are not supported by the image format
714 static int img_check(int argc, char **argv)
717 OutputFormat output_format = OFORMAT_HUMAN;
718 const char *filename, *fmt, *output, *cache;
720 BlockDriverState *bs;
722 int flags = BDRV_O_CHECK;
726 bool image_opts = false;
727 bool force_share = false;
731 cache = BDRV_DEFAULT_CACHE;
734 int option_index = 0;
735 static const struct option long_options[] = {
736 {"help", no_argument, 0, 'h'},
737 {"format", required_argument, 0, 'f'},
738 {"repair", required_argument, 0, 'r'},
739 {"output", required_argument, 0, OPTION_OUTPUT},
740 {"object", required_argument, 0, OPTION_OBJECT},
741 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
742 {"force-share", no_argument, 0, 'U'},
745 c = getopt_long(argc, argv, ":hf:r:T:qU",
746 long_options, &option_index);
752 missing_argument(argv[optind - 1]);
755 unrecognized_option(argv[optind - 1]);
764 flags |= BDRV_O_RDWR;
766 if (!strcmp(optarg, "leaks")) {
767 fix = BDRV_FIX_LEAKS;
768 } else if (!strcmp(optarg, "all")) {
769 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
771 error_exit("Unknown option value for -r "
772 "(expecting 'leaks' or 'all'): %s", optarg);
788 user_creatable_process_cmdline(optarg);
790 case OPTION_IMAGE_OPTS:
795 if (optind != argc - 1) {
796 error_exit("Expecting one image file name");
798 filename = argv[optind++];
800 if (output && !strcmp(output, "json")) {
801 output_format = OFORMAT_JSON;
802 } else if (output && !strcmp(output, "human")) {
803 output_format = OFORMAT_HUMAN;
805 error_report("--output must be used with human or json as argument.");
809 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
811 error_report("Invalid source cache option: %s", cache);
815 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
822 check = g_new0(ImageCheck, 1);
823 ret = collect_image_check(bs, check, filename, fmt, fix);
825 if (ret == -ENOTSUP) {
826 error_report("This image format does not support checks");
831 if (check->corruptions_fixed || check->leaks_fixed) {
832 int corruptions_fixed, leaks_fixed;
833 bool has_leaks_fixed, has_corruptions_fixed;
835 leaks_fixed = check->leaks_fixed;
836 has_leaks_fixed = check->has_leaks_fixed;
837 corruptions_fixed = check->corruptions_fixed;
838 has_corruptions_fixed = check->has_corruptions_fixed;
840 if (output_format == OFORMAT_HUMAN) {
842 "The following inconsistencies were found and repaired:\n\n"
843 " %" PRId64 " leaked clusters\n"
844 " %" PRId64 " corruptions\n\n"
845 "Double checking the fixed image now...\n",
847 check->corruptions_fixed);
850 qapi_free_ImageCheck(check);
851 check = g_new0(ImageCheck, 1);
852 ret = collect_image_check(bs, check, filename, fmt, 0);
854 check->leaks_fixed = leaks_fixed;
855 check->has_leaks_fixed = has_leaks_fixed;
856 check->corruptions_fixed = corruptions_fixed;
857 check->has_corruptions_fixed = has_corruptions_fixed;
861 switch (output_format) {
863 dump_human_image_check(check, quiet);
866 dump_json_image_check(check, quiet);
871 if (ret || check->check_errors) {
873 error_report("Check failed: %s", strerror(-ret));
875 error_report("Check failed");
881 if (check->corruptions) {
883 } else if (check->leaks) {
890 qapi_free_ImageCheck(check);
895 typedef struct CommonBlockJobCBInfo {
896 BlockDriverState *bs;
898 } CommonBlockJobCBInfo;
900 static void common_block_job_cb(void *opaque, int ret)
902 CommonBlockJobCBInfo *cbi = opaque;
905 error_setg_errno(cbi->errp, -ret, "Block job failed");
909 static void run_block_job(BlockJob *job, Error **errp)
911 uint64_t progress_current, progress_total;
912 AioContext *aio_context = block_job_get_aio_context(job);
916 job_ref_locked(&job->job);
918 float progress = 0.0f;
920 aio_poll(aio_context, true);
922 progress_get_snapshot(&job->job.progress, &progress_current,
924 if (progress_total) {
925 progress = (float)progress_current / progress_total * 100.f;
927 qemu_progress_print(progress, 0);
929 } while (!job_is_ready_locked(&job->job) &&
930 !job_is_completed_locked(&job->job));
932 if (!job_is_completed_locked(&job->job)) {
933 ret = job_complete_sync_locked(&job->job, errp);
937 job_unref_locked(&job->job);
940 /* publish completion progress only when success */
942 qemu_progress_print(100.f, 0);
946 static int img_commit(int argc, char **argv)
949 const char *filename, *fmt, *cache, *base;
951 BlockDriverState *bs, *base_bs;
953 bool progress = false, quiet = false, drop = false;
955 Error *local_err = NULL;
956 CommonBlockJobCBInfo cbi;
957 bool image_opts = false;
958 AioContext *aio_context;
959 int64_t rate_limit = 0;
962 cache = BDRV_DEFAULT_CACHE;
965 static const struct option long_options[] = {
966 {"help", no_argument, 0, 'h'},
967 {"object", required_argument, 0, OPTION_OBJECT},
968 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
971 c = getopt_long(argc, argv, ":f:ht:b:dpqr:",
978 missing_argument(argv[optind - 1]);
981 unrecognized_option(argv[optind - 1]);
1007 rate_limit = cvtnum("rate limit", optarg);
1008 if (rate_limit < 0) {
1013 user_creatable_process_cmdline(optarg);
1015 case OPTION_IMAGE_OPTS:
1021 /* Progress is not shown in Quiet mode */
1026 if (optind != argc - 1) {
1027 error_exit("Expecting one image file name");
1029 filename = argv[optind++];
1031 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
1032 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1034 error_report("Invalid cache option: %s", cache);
1038 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1045 qemu_progress_init(progress, 1.f);
1046 qemu_progress_print(0.f, 100);
1049 base_bs = bdrv_find_backing_image(bs, base);
1051 error_setg(&local_err,
1052 "Did not find '%s' in the backing chain of '%s'",
1057 /* This is different from QMP, which by default uses the deepest file in
1058 * the backing chain (i.e., the very base); however, the traditional
1059 * behavior of qemu-img commit is using the immediate backing file. */
1060 base_bs = bdrv_backing_chain_next(bs);
1062 error_setg(&local_err, "Image does not have a backing file");
1067 cbi = (CommonBlockJobCBInfo){
1072 aio_context = bdrv_get_aio_context(bs);
1073 aio_context_acquire(aio_context);
1074 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, rate_limit,
1075 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1076 &cbi, false, &local_err);
1077 aio_context_release(aio_context);
1082 /* When the block job completes, the BlockBackend reference will point to
1083 * the old backing file. In order to avoid that the top image is already
1084 * deleted, so we can still empty it afterwards, increment the reference
1085 * counter here preemptively. */
1090 job = block_job_get("commit");
1092 run_block_job(job, &local_err);
1098 BlockBackend *old_backing_blk;
1100 old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1102 if (!old_backing_blk) {
1105 ret = blk_make_empty(old_backing_blk, &local_err);
1106 blk_unref(old_backing_blk);
1107 if (ret == -ENOTSUP) {
1108 error_free(local_err);
1110 } else if (ret < 0) {
1121 qemu_progress_end();
1126 error_report_err(local_err);
1130 qprintf(quiet, "Image committed.\n");
1135 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1136 * of the first sector boundary within buf where the sector contains a
1137 * non-zero byte. This function is robust to a buffer that is not
1140 static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1143 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1145 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1146 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1150 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1157 * Returns true iff the first sector pointed to by 'buf' contains at least
1160 * 'pnum' is set to the number of sectors (including and immediately following
1161 * the first one) that are known to be in the same allocated/unallocated state.
1162 * The function will try to align the end offset to alignment boundaries so
1163 * that the request will at least end aligned and consecutive requests will
1164 * also start at an aligned offset.
1166 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1167 int64_t sector_num, int alignment)
1176 is_zero = buffer_is_zero(buf, BDRV_SECTOR_SIZE);
1177 for(i = 1; i < n; i++) {
1178 buf += BDRV_SECTOR_SIZE;
1179 if (is_zero != buffer_is_zero(buf, BDRV_SECTOR_SIZE)) {
1186 * The whole buf is the same.
1187 * No reason to split it into chunks, so return now.
1193 tail = (sector_num + i) & (alignment - 1);
1195 if (is_zero && i <= tail) {
1197 * For sure next sector after i is data, and it will rewrite this
1198 * tail anyway due to RMW. So, let's just write data now.
1203 /* If possible, align up end offset of allocated areas. */
1204 i += alignment - tail;
1208 * For sure next sector after i is data, and it will rewrite this
1209 * tail anyway due to RMW. Better is avoid RMW and write zeroes up
1220 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1221 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1222 * breaking up write requests for only small sparse areas.
1224 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1225 int min, int64_t sector_num, int alignment)
1228 int num_checked, num_used;
1234 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1240 buf += BDRV_SECTOR_SIZE * *pnum;
1242 sector_num += *pnum;
1243 num_checked = num_used;
1246 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1248 buf += BDRV_SECTOR_SIZE * *pnum;
1250 sector_num += *pnum;
1251 num_checked += *pnum;
1253 num_used = num_checked;
1254 } else if (*pnum >= min) {
1264 * Compares two buffers sector by sector. Returns 0 if the first
1265 * sector of each buffer matches, non-zero otherwise.
1267 * pnum is set to the sector-aligned size of the buffer prefix that
1268 * has the same matching status as the first sector.
1270 static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1271 int64_t bytes, int64_t *pnum)
1274 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
1278 res = !!memcmp(buf1, buf2, i);
1280 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
1282 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
1292 #define IO_BUF_SIZE (2 * MiB)
1295 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1297 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1298 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1299 * failure), and 4 on error (the exit status for read errors), after emitting
1302 * @param blk: BlockBackend for the image
1303 * @param offset: Starting offset to check
1304 * @param bytes: Number of bytes to check
1305 * @param filename: Name of disk file we are checking (logging purpose)
1306 * @param buffer: Allocated buffer for storing read data
1307 * @param quiet: Flag for quiet mode
1309 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1310 int64_t bytes, const char *filename,
1311 uint8_t *buffer, bool quiet)
1316 ret = blk_pread(blk, offset, bytes, buffer, 0);
1318 error_report("Error while reading offset %" PRId64 " of %s: %s",
1319 offset, filename, strerror(-ret));
1322 idx = find_nonzero(buffer, bytes);
1324 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1333 * Compares two images. Exit codes:
1335 * 0 - Images are identical or the requested help was printed
1337 * >1 - Error occurred
1339 static int img_compare(int argc, char **argv)
1341 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1342 BlockBackend *blk1, *blk2;
1343 BlockDriverState *bs1, *bs2;
1344 int64_t total_size1, total_size2;
1345 uint8_t *buf1 = NULL, *buf2 = NULL;
1346 int64_t pnum1, pnum2;
1347 int allocated1, allocated2;
1348 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1349 bool progress = false, quiet = false, strict = false;
1356 uint64_t progress_base;
1357 bool image_opts = false;
1358 bool force_share = false;
1360 cache = BDRV_DEFAULT_CACHE;
1362 static const struct option long_options[] = {
1363 {"help", no_argument, 0, 'h'},
1364 {"object", required_argument, 0, OPTION_OBJECT},
1365 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1366 {"force-share", no_argument, 0, 'U'},
1369 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1370 long_options, NULL);
1376 missing_argument(argv[optind - 1]);
1379 unrecognized_option(argv[optind - 1]);
1407 Error *local_err = NULL;
1409 if (!user_creatable_add_from_str(optarg, &local_err)) {
1411 error_report_err(local_err);
1414 /* Help was printed */
1420 case OPTION_IMAGE_OPTS:
1426 /* Progress is not shown in Quiet mode */
1432 if (optind != argc - 2) {
1433 error_exit("Expecting two image file names");
1435 filename1 = argv[optind++];
1436 filename2 = argv[optind++];
1438 /* Initialize before goto out */
1439 qemu_progress_init(progress, 2.0);
1442 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1444 error_report("Invalid source cache option: %s", cache);
1449 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1456 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1465 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1466 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1467 total_size1 = blk_getlength(blk1);
1468 if (total_size1 < 0) {
1469 error_report("Can't get size of %s: %s",
1470 filename1, strerror(-total_size1));
1474 total_size2 = blk_getlength(blk2);
1475 if (total_size2 < 0) {
1476 error_report("Can't get size of %s: %s",
1477 filename2, strerror(-total_size2));
1481 total_size = MIN(total_size1, total_size2);
1482 progress_base = MAX(total_size1, total_size2);
1484 qemu_progress_print(0, 100);
1486 if (strict && total_size1 != total_size2) {
1488 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1492 while (offset < total_size) {
1493 int status1, status2;
1495 status1 = bdrv_block_status_above(bs1, NULL, offset,
1496 total_size1 - offset, &pnum1, NULL,
1500 error_report("Sector allocation test failed for %s", filename1);
1503 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1505 status2 = bdrv_block_status_above(bs2, NULL, offset,
1506 total_size2 - offset, &pnum2, NULL,
1510 error_report("Sector allocation test failed for %s", filename2);
1513 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1515 assert(pnum1 && pnum2);
1516 chunk = MIN(pnum1, pnum2);
1519 if (status1 != status2) {
1521 qprintf(quiet, "Strict mode: Offset %" PRId64
1522 " block status mismatch!\n", offset);
1526 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1528 } else if (allocated1 == allocated2) {
1532 chunk = MIN(chunk, IO_BUF_SIZE);
1533 ret = blk_pread(blk1, offset, chunk, buf1, 0);
1535 error_report("Error while reading offset %" PRId64
1537 offset, filename1, strerror(-ret));
1541 ret = blk_pread(blk2, offset, chunk, buf2, 0);
1543 error_report("Error while reading offset %" PRId64
1545 offset, filename2, strerror(-ret));
1549 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1550 if (ret || pnum != chunk) {
1551 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1552 offset + (ret ? 0 : pnum));
1558 chunk = MIN(chunk, IO_BUF_SIZE);
1560 ret = check_empty_sectors(blk1, offset, chunk,
1561 filename1, buf1, quiet);
1563 ret = check_empty_sectors(blk2, offset, chunk,
1564 filename2, buf1, quiet);
1571 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1574 if (total_size1 != total_size2) {
1575 BlockBackend *blk_over;
1576 const char *filename_over;
1578 qprintf(quiet, "Warning: Image size mismatch!\n");
1579 if (total_size1 > total_size2) {
1581 filename_over = filename1;
1584 filename_over = filename2;
1587 while (offset < progress_base) {
1588 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1589 progress_base - offset, &chunk,
1593 error_report("Sector allocation test failed for %s",
1598 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1599 chunk = MIN(chunk, IO_BUF_SIZE);
1600 ret = check_empty_sectors(blk_over, offset, chunk,
1601 filename_over, buf1, quiet);
1607 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1611 qprintf(quiet, "Images are identical.\n");
1621 qemu_progress_end();
1625 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1626 static void do_dirty_bitmap_merge(const char *dst_node, const char *dst_name,
1627 const char *src_node, const char *src_name,
1630 BlockDirtyBitmapOrStr *merge_src;
1631 BlockDirtyBitmapOrStrList *list = NULL;
1633 merge_src = g_new0(BlockDirtyBitmapOrStr, 1);
1634 merge_src->type = QTYPE_QDICT;
1635 merge_src->u.external.node = g_strdup(src_node);
1636 merge_src->u.external.name = g_strdup(src_name);
1637 QAPI_LIST_PREPEND(list, merge_src);
1638 qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
1639 qapi_free_BlockDirtyBitmapOrStrList(list);
1642 enum ImgConvertBlockStatus {
1648 #define MAX_COROUTINES 16
1649 #define CONVERT_THROTTLE_GROUP "img_convert"
1651 typedef struct ImgConvertState {
1653 int64_t *src_sectors;
1656 int64_t total_sectors;
1657 int64_t allocated_sectors;
1658 int64_t allocated_done;
1661 enum ImgConvertBlockStatus status;
1662 int64_t sector_next_status;
1663 BlockBackend *target;
1667 bool target_has_backing;
1668 int64_t target_backing_sectors; /* negative if unknown */
1675 size_t cluster_sectors;
1677 long num_coroutines;
1678 int running_coroutines;
1679 Coroutine *co[MAX_COROUTINES];
1680 int64_t wait_sector_num[MAX_COROUTINES];
1685 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1686 int *src_cur, int64_t *src_cur_offset)
1689 *src_cur_offset = 0;
1690 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1691 *src_cur_offset += s->src_sectors[*src_cur];
1693 assert(*src_cur < s->src_num);
1697 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1699 int64_t src_cur_offset;
1700 int ret, n, src_cur;
1701 bool post_backing_zero = false;
1703 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1705 assert(s->total_sectors > sector_num);
1706 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1708 if (s->target_backing_sectors >= 0) {
1709 if (sector_num >= s->target_backing_sectors) {
1710 post_backing_zero = true;
1711 } else if (sector_num + n > s->target_backing_sectors) {
1712 /* Split requests around target_backing_sectors (because
1713 * starting from there, zeros are handled differently) */
1714 n = s->target_backing_sectors - sector_num;
1718 if (s->sector_next_status <= sector_num) {
1719 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1722 BlockDriverState *src_bs = blk_bs(s->src[src_cur]);
1723 BlockDriverState *base;
1725 if (s->target_has_backing) {
1726 base = bdrv_cow_bs(bdrv_skip_filters(src_bs));
1732 count = n * BDRV_SECTOR_SIZE;
1734 ret = bdrv_block_status_above(src_bs, base, offset, count, &count,
1741 warn_report("error while reading block status at "
1742 "offset %" PRIu64 ": %s", offset,
1745 /* Just try to read the data, then */
1746 ret = BDRV_BLOCK_DATA;
1747 count = BDRV_SECTOR_SIZE;
1749 /* Retry on a shorter range */
1750 n = DIV_ROUND_UP(n, 4);
1753 error_report("error while reading block status at offset "
1754 "%" PRIu64 ": %s", offset, strerror(-ret));
1760 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1763 * Avoid that s->sector_next_status becomes unaligned to the source
1764 * request alignment and/or cluster size to avoid unnecessary read
1767 tail = (sector_num - src_cur_offset + n) % s->src_alignment[src_cur];
1772 if (ret & BDRV_BLOCK_ZERO) {
1773 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
1774 } else if (ret & BDRV_BLOCK_DATA) {
1775 s->status = BLK_DATA;
1777 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1780 s->sector_next_status = sector_num + n;
1783 n = MIN(n, s->sector_next_status - sector_num);
1784 if (s->status == BLK_DATA) {
1785 n = MIN(n, s->buf_sectors);
1788 /* We need to write complete clusters for compressed images, so if an
1789 * unallocated area is shorter than that, we must consider the whole
1790 * cluster allocated. */
1791 if (s->compressed) {
1792 if (n < s->cluster_sectors) {
1793 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1794 s->status = BLK_DATA;
1796 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1803 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1804 int nb_sectors, uint8_t *buf)
1806 uint64_t single_read_until = 0;
1809 assert(nb_sectors <= s->buf_sectors);
1810 while (nb_sectors > 0) {
1813 int64_t bs_sectors, src_cur_offset;
1816 /* In the case of compression with multiple source files, we can get a
1817 * nb_sectors that spreads into the next part. So we must be able to
1818 * read across multiple BDSes for one convert_read() call. */
1819 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1820 blk = s->src[src_cur];
1821 bs_sectors = s->src_sectors[src_cur];
1823 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1825 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1826 if (single_read_until > offset) {
1830 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
1834 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1838 warn_report("error while reading offset %" PRIu64
1839 ": %s", offset, strerror(-ret));
1841 memset(buf, 0, BDRV_SECTOR_SIZE);
1850 buf += n * BDRV_SECTOR_SIZE;
1857 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1858 int nb_sectors, uint8_t *buf,
1859 enum ImgConvertBlockStatus status)
1863 while (nb_sectors > 0) {
1865 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1868 case BLK_BACKING_FILE:
1869 /* If we have a backing file, leave clusters unallocated that are
1870 * unallocated in the source image, so that the backing file is
1871 * visible at the respective offset. */
1872 assert(s->target_has_backing);
1876 /* If we're told to keep the target fully allocated (-S 0) or there
1877 * is real non-zero data, we must write it. Otherwise we can treat
1878 * it as zero sectors.
1879 * Compressed clusters need to be written as a whole, so in that
1880 * case we can only save the write if the buffer is completely
1882 if (!s->min_sparse ||
1884 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1885 sector_num, s->alignment)) ||
1887 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1889 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1890 n << BDRV_SECTOR_BITS, buf, flags);
1899 if (s->has_zero_init) {
1900 assert(!s->target_has_backing);
1903 ret = blk_co_pwrite_zeroes(s->target,
1904 sector_num << BDRV_SECTOR_BITS,
1905 n << BDRV_SECTOR_BITS,
1906 BDRV_REQ_MAY_UNMAP);
1915 buf += n * BDRV_SECTOR_SIZE;
1921 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1926 while (nb_sectors > 0) {
1929 int64_t bs_sectors, src_cur_offset;
1932 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1933 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1934 blk = s->src[src_cur];
1935 bs_sectors = s->src_sectors[src_cur];
1937 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1939 ret = blk_co_copy_range(blk, offset, s->target,
1940 sector_num << BDRV_SECTOR_BITS,
1941 n << BDRV_SECTOR_BITS, 0, 0);
1952 static void coroutine_fn convert_co_do_copy(void *opaque)
1954 ImgConvertState *s = opaque;
1955 uint8_t *buf = NULL;
1959 for (i = 0; i < s->num_coroutines; i++) {
1960 if (s->co[i] == qemu_coroutine_self()) {
1967 s->running_coroutines++;
1968 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1973 enum ImgConvertBlockStatus status;
1976 qemu_co_mutex_lock(&s->lock);
1977 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1978 qemu_co_mutex_unlock(&s->lock);
1981 n = convert_iteration_sectors(s, s->sector_num);
1983 qemu_co_mutex_unlock(&s->lock);
1987 /* save current sector and allocation status to local variables */
1988 sector_num = s->sector_num;
1990 if (!s->min_sparse && s->status == BLK_ZERO) {
1991 n = MIN(n, s->buf_sectors);
1993 /* increment global sector counter so that other coroutines can
1994 * already continue reading beyond this request */
1996 qemu_co_mutex_unlock(&s->lock);
1998 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1999 s->allocated_done += n;
2000 qemu_progress_print(100.0 * s->allocated_done /
2001 s->allocated_sectors, 0);
2005 copy_range = s->copy_range && s->status == BLK_DATA;
2006 if (status == BLK_DATA && !copy_range) {
2007 ret = convert_co_read(s, sector_num, n, buf);
2009 error_report("error while reading at byte %lld: %s",
2010 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2013 } else if (!s->min_sparse && status == BLK_ZERO) {
2015 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
2018 if (s->wr_in_order) {
2019 /* keep writes in order */
2020 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
2021 s->wait_sector_num[index] = sector_num;
2022 qemu_coroutine_yield();
2024 s->wait_sector_num[index] = -1;
2027 if (s->ret == -EINPROGRESS) {
2029 ret = convert_co_copy_range(s, sector_num, n);
2031 s->copy_range = false;
2035 ret = convert_co_write(s, sector_num, n, buf, status);
2038 error_report("error while writing at byte %lld: %s",
2039 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2044 if (s->wr_in_order) {
2045 /* reenter the coroutine that might have waited
2046 * for this write to complete */
2047 s->wr_offs = sector_num + n;
2048 for (i = 0; i < s->num_coroutines; i++) {
2049 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2051 * A -> B -> A cannot occur because A has
2052 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2053 * B will never enter A during this time window.
2055 qemu_coroutine_enter(s->co[i]);
2063 s->co[index] = NULL;
2064 s->running_coroutines--;
2065 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2066 /* the convert job finished successfully */
2071 static int convert_do_copy(ImgConvertState *s)
2074 int64_t sector_num = 0;
2076 /* Check whether we have zero initialisation or can get it efficiently */
2077 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2078 !s->target_has_backing) {
2079 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
2082 /* Allocate buffer for copied data. For compressed images, only one cluster
2083 * can be copied at a time. */
2084 if (s->compressed) {
2085 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2086 error_report("invalid cluster size");
2089 s->buf_sectors = s->cluster_sectors;
2092 while (sector_num < s->total_sectors) {
2093 n = convert_iteration_sectors(s, sector_num);
2097 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2099 s->allocated_sectors += n;
2105 s->sector_next_status = 0;
2106 s->ret = -EINPROGRESS;
2108 qemu_co_mutex_init(&s->lock);
2109 for (i = 0; i < s->num_coroutines; i++) {
2110 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2111 s->wait_sector_num[i] = -1;
2112 qemu_coroutine_enter(s->co[i]);
2115 while (s->running_coroutines) {
2116 main_loop_wait(false);
2119 if (s->compressed && !s->ret) {
2120 /* signal EOF to align */
2121 ret = blk_pwrite_compressed(s->target, 0, 0, NULL);
2130 /* Check that bitmaps can be copied, or output an error */
2131 static int convert_check_bitmaps(BlockDriverState *src, bool skip_broken)
2133 BdrvDirtyBitmap *bm;
2135 if (!bdrv_supports_persistent_dirty_bitmap(src)) {
2136 error_report("Source lacks bitmap support");
2139 FOR_EACH_DIRTY_BITMAP(src, bm) {
2140 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2143 if (!skip_broken && bdrv_dirty_bitmap_inconsistent(bm)) {
2144 error_report("Cannot copy inconsistent bitmap '%s'",
2145 bdrv_dirty_bitmap_name(bm));
2146 error_printf("Try --skip-broken-bitmaps, or "
2147 "use 'qemu-img bitmap --remove' to delete it\n");
2154 static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst,
2157 BdrvDirtyBitmap *bm;
2160 FOR_EACH_DIRTY_BITMAP(src, bm) {
2163 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2166 name = bdrv_dirty_bitmap_name(bm);
2167 if (skip_broken && bdrv_dirty_bitmap_inconsistent(bm)) {
2168 warn_report("Skipping inconsistent bitmap '%s'", name);
2171 qmp_block_dirty_bitmap_add(dst->node_name, name,
2172 true, bdrv_dirty_bitmap_granularity(bm),
2174 true, !bdrv_dirty_bitmap_enabled(bm),
2177 error_reportf_err(err, "Failed to create bitmap %s: ", name);
2181 do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2184 error_reportf_err(err, "Failed to populate bitmap %s: ", name);
2185 qmp_block_dirty_bitmap_remove(dst->node_name, name, NULL);
2193 #define MAX_BUF_SECTORS 32768
2195 static void set_rate_limit(BlockBackend *blk, int64_t rate_limit)
2199 throttle_config_init(&cfg);
2200 cfg.buckets[THROTTLE_BPS_WRITE].avg = rate_limit;
2202 blk_io_limits_enable(blk, CONVERT_THROTTLE_GROUP);
2203 blk_set_io_limits(blk, &cfg);
2206 static int img_convert(int argc, char **argv)
2208 int c, bs_i, flags, src_flags = BDRV_O_NO_SHARE;
2209 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
2210 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2211 *out_filename, *out_baseimg_param, *snapshot_name = NULL,
2212 *backing_fmt = NULL;
2213 BlockDriver *drv = NULL, *proto_drv = NULL;
2214 BlockDriverInfo bdi;
2215 BlockDriverState *out_bs;
2216 QemuOpts *opts = NULL, *sn_opts = NULL;
2217 QemuOptsList *create_opts = NULL;
2218 QDict *open_opts = NULL;
2219 char *options = NULL;
2220 Error *local_err = NULL;
2221 bool writethrough, src_writethrough, image_opts = false,
2222 skip_create = false, progress = false, tgt_image_opts = false;
2223 int64_t ret = -EINVAL;
2224 bool force_share = false;
2225 bool explict_min_sparse = false;
2226 bool bitmaps = false;
2227 bool skip_broken = false;
2228 int64_t rate_limit = 0;
2230 ImgConvertState s = (ImgConvertState) {
2231 /* Need at least 4k of zeros for sparse detection */
2233 .copy_range = false,
2234 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2235 .wr_in_order = true,
2236 .num_coroutines = 8,
2240 static const struct option long_options[] = {
2241 {"help", no_argument, 0, 'h'},
2242 {"object", required_argument, 0, OPTION_OBJECT},
2243 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2244 {"force-share", no_argument, 0, 'U'},
2245 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
2246 {"salvage", no_argument, 0, OPTION_SALVAGE},
2247 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
2248 {"bitmaps", no_argument, 0, OPTION_BITMAPS},
2249 {"skip-broken-bitmaps", no_argument, 0, OPTION_SKIP_BROKEN},
2252 c = getopt_long(argc, argv, ":hf:O:B:CcF:o:l:S:pt:T:qnm:WUr:",
2253 long_options, NULL);
2259 missing_argument(argv[optind - 1]);
2262 unrecognized_option(argv[optind - 1]);
2274 out_baseimg = optarg;
2277 s.copy_range = true;
2280 s.compressed = true;
2283 backing_fmt = optarg;
2286 if (accumulate_options(&options, optarg) < 0) {
2291 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2292 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2295 error_report("Failed in parsing snapshot param '%s'",
2300 snapshot_name = optarg;
2307 sval = cvtnum("buffer size for sparse output", optarg);
2310 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
2311 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2312 error_report("Invalid buffer size for sparse output specified. "
2313 "Valid sizes are multiples of %llu up to %llu. Select "
2314 "0 to disable sparse detection (fully allocates output).",
2315 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
2319 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2320 explict_min_sparse = true;
2339 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2340 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2341 error_report("Invalid number of coroutines. Allowed number of"
2342 " coroutines is between 1 and %d", MAX_COROUTINES);
2347 s.wr_in_order = false;
2353 rate_limit = cvtnum("rate limit", optarg);
2354 if (rate_limit < 0) {
2359 user_creatable_process_cmdline(optarg);
2361 case OPTION_IMAGE_OPTS:
2364 case OPTION_SALVAGE:
2367 case OPTION_TARGET_IMAGE_OPTS:
2368 tgt_image_opts = true;
2370 case OPTION_TARGET_IS_ZERO:
2372 * The user asserting that the target is blank has the
2373 * same effect as the target driver supporting zero
2376 s.has_zero_init = true;
2378 case OPTION_BITMAPS:
2381 case OPTION_SKIP_BROKEN:
2387 if (!out_fmt && !tgt_image_opts) {
2391 if (skip_broken && !bitmaps) {
2392 error_report("Use of --skip-broken-bitmaps requires --bitmaps");
2396 if (s.compressed && s.copy_range) {
2397 error_report("Cannot enable copy offloading when -c is used");
2401 if (explict_min_sparse && s.copy_range) {
2402 error_report("Cannot enable copy offloading when -S is used");
2406 if (s.copy_range && s.salvage) {
2407 error_report("Cannot use copy offloading in salvaging mode");
2411 if (tgt_image_opts && !skip_create) {
2412 error_report("--target-image-opts requires use of -n flag");
2416 if (skip_create && options) {
2417 error_report("-o has no effect when skipping image creation");
2421 if (s.has_zero_init && !skip_create) {
2422 error_report("--target-is-zero requires use of -n flag");
2426 s.src_num = argc - optind - 1;
2427 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2429 if (options && has_help_option(options)) {
2431 ret = print_block_option_help(out_filename, out_fmt);
2434 error_report("Option help requires a format be specified");
2439 if (s.src_num < 1) {
2440 error_report("Must specify image file name");
2444 /* ret is still -EINVAL until here */
2445 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2447 error_report("Invalid source cache option: %s", src_cache);
2451 /* Initialize before goto out */
2455 qemu_progress_init(progress, 1.0);
2456 qemu_progress_print(0, 100);
2458 s.src = g_new0(BlockBackend *, s.src_num);
2459 s.src_sectors = g_new(int64_t, s.src_num);
2460 s.src_alignment = g_new(int, s.src_num);
2462 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2463 BlockDriverState *src_bs;
2464 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2465 fmt, src_flags, src_writethrough, s.quiet,
2471 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2472 if (s.src_sectors[bs_i] < 0) {
2473 error_report("Could not get size of %s: %s",
2474 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2478 src_bs = blk_bs(s.src[bs_i]);
2479 s.src_alignment[bs_i] = DIV_ROUND_UP(src_bs->bl.request_alignment,
2481 if (!bdrv_get_info(src_bs, &bdi)) {
2482 s.src_alignment[bs_i] = MAX(s.src_alignment[bs_i],
2483 bdi.cluster_size / BDRV_SECTOR_SIZE);
2485 s.total_sectors += s.src_sectors[bs_i];
2489 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2490 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2491 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2493 } else if (snapshot_name != NULL) {
2494 if (s.src_num > 1) {
2495 error_report("No support for concatenating multiple snapshot");
2500 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2504 error_reportf_err(local_err, "Failed to load snapshot: ");
2510 /* Find driver and parse its options */
2511 drv = bdrv_find_format(out_fmt);
2513 error_report("Unknown file format '%s'", out_fmt);
2518 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2520 error_report_err(local_err);
2525 if (!drv->create_opts) {
2526 error_report("Format driver '%s' does not support image creation",
2532 if (!proto_drv->create_opts) {
2533 error_report("Protocol driver '%s' does not support image creation",
2534 proto_drv->format_name);
2539 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2540 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2542 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2544 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
2545 error_report_err(local_err);
2551 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
2552 s.total_sectors * BDRV_SECTOR_SIZE, &error_abort);
2553 ret = add_old_style_options(out_fmt, opts, out_baseimg, backing_fmt);
2559 /* Get backing file name if -o backing_file was used */
2560 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2561 if (out_baseimg_param) {
2562 out_baseimg = out_baseimg_param;
2564 s.target_has_backing = (bool) out_baseimg;
2566 if (s.has_zero_init && s.target_has_backing) {
2567 error_report("Cannot use --target-is-zero when the destination "
2568 "image has a backing file");
2572 if (s.src_num > 1 && out_baseimg) {
2573 error_report("Having a backing file for the target makes no sense when "
2574 "concatenating multiple input images");
2579 if (out_baseimg_param) {
2580 if (!qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT)) {
2581 error_report("Use of backing file requires explicit "
2588 /* Check if compression is supported */
2591 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2592 const char *encryptfmt =
2593 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2594 const char *preallocation =
2595 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2597 if (drv && !block_driver_can_compress(drv)) {
2598 error_report("Compression not supported for this file format");
2603 if (encryption || encryptfmt) {
2604 error_report("Compression and encryption not supported at "
2611 && strcmp(preallocation, "off"))
2613 error_report("Compression and preallocation not supported at "
2620 /* Determine if bitmaps need copying */
2622 if (s.src_num > 1) {
2623 error_report("Copying bitmaps only possible with single source");
2627 ret = convert_check_bitmaps(blk_bs(s.src[0]), skip_broken);
2634 * The later open call will need any decryption secrets, and
2635 * bdrv_create() will purge "opts", so extract them now before
2639 open_opts = qdict_new();
2640 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2642 /* Create the new image */
2643 ret = bdrv_create(drv, out_filename, opts, &local_err);
2645 error_reportf_err(local_err, "%s: error while converting %s: ",
2646 out_filename, out_fmt);
2651 s.target_is_new = !skip_create;
2653 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2654 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2656 error_report("Invalid cache option: %s", cache);
2660 if (flags & BDRV_O_NOCACHE) {
2662 * If we open the target with O_DIRECT, it may be necessary to
2663 * extend its size to align to the physical sector size.
2665 flags |= BDRV_O_RESIZE;
2669 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2670 flags, writethrough, s.quiet, false);
2672 /* TODO ultimately we should allow --target-image-opts
2673 * to be used even when -n is not given.
2674 * That has to wait for bdrv_create to be improved
2675 * to allow filenames in option syntax
2677 s.target = img_open_file(out_filename, open_opts, out_fmt,
2678 flags, writethrough, s.quiet, false);
2679 open_opts = NULL; /* blk_new_open will have freed it */
2685 out_bs = blk_bs(s.target);
2687 if (bitmaps && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2688 error_report("Format driver '%s' does not support bitmaps",
2689 out_bs->drv->format_name);
2694 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
2695 error_report("Compression not supported for this file format");
2700 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2701 * or discard_alignment of the out_bs is greater. Limit to
2702 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2703 s.buf_sectors = MIN(MAX_BUF_SECTORS,
2705 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2706 out_bs->bl.pdiscard_alignment >>
2707 BDRV_SECTOR_BITS)));
2709 /* try to align the write requests to the destination to avoid unnecessary
2711 s.alignment = MAX(pow2floor(s.min_sparse),
2712 DIV_ROUND_UP(out_bs->bl.request_alignment,
2714 assert(is_power_of_2(s.alignment));
2717 int64_t output_sectors = blk_nb_sectors(s.target);
2718 if (output_sectors < 0) {
2719 error_report("unable to get output image length: %s",
2720 strerror(-output_sectors));
2723 } else if (output_sectors < s.total_sectors) {
2724 error_report("output file is smaller than input file");
2730 if (s.target_has_backing && s.target_is_new) {
2731 /* Errors are treated as "backing length unknown" (which means
2732 * s.target_backing_sectors has to be negative, which it will
2733 * be automatically). The backing file length is used only
2734 * for optimizations, so such a case is not fatal. */
2735 s.target_backing_sectors =
2736 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs));
2738 s.target_backing_sectors = -1;
2741 ret = bdrv_get_info(out_bs, &bdi);
2744 error_report("could not get block driver info");
2748 s.compressed = s.compressed || bdi.needs_compressed_writes;
2749 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2753 set_rate_limit(s.target, rate_limit);
2756 ret = convert_do_copy(&s);
2758 /* Now copy the bitmaps */
2759 if (bitmaps && ret == 0) {
2760 ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs, skip_broken);
2765 qemu_progress_print(100, 0);
2767 qemu_progress_end();
2768 qemu_opts_del(opts);
2769 qemu_opts_free(create_opts);
2770 qobject_unref(open_opts);
2771 blk_unref(s.target);
2773 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2774 blk_unref(s.src[bs_i]);
2778 g_free(s.src_sectors);
2779 g_free(s.src_alignment);
2781 qemu_opts_del(sn_opts);
2788 static void dump_snapshots(BlockDriverState *bs)
2790 QEMUSnapshotInfo *sn_tab, *sn;
2793 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2796 printf("Snapshot list:\n");
2797 bdrv_snapshot_dump(NULL);
2799 for(i = 0; i < nb_sns; i++) {
2801 bdrv_snapshot_dump(sn);
2807 static void dump_json_image_info_list(ImageInfoList *list)
2811 Visitor *v = qobject_output_visitor_new(&obj);
2813 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2814 visit_complete(v, &obj);
2815 str = qobject_to_json_pretty(obj, true);
2816 assert(str != NULL);
2817 printf("%s\n", str->str);
2820 g_string_free(str, true);
2823 static void dump_json_image_info(ImageInfo *info)
2827 Visitor *v = qobject_output_visitor_new(&obj);
2829 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2830 visit_complete(v, &obj);
2831 str = qobject_to_json_pretty(obj, true);
2832 assert(str != NULL);
2833 printf("%s\n", str->str);
2836 g_string_free(str, true);
2839 static void dump_human_image_info_list(ImageInfoList *list)
2841 ImageInfoList *elem;
2844 for (elem = list; elem; elem = elem->next) {
2850 bdrv_image_info_dump(elem->value);
2854 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2856 return strcmp(a, b) == 0;
2860 * Open an image file chain and return an ImageInfoList
2862 * @filename: topmost image filename
2863 * @fmt: topmost image format (may be NULL to autodetect)
2864 * @chain: true - enumerate entire backing file chain
2865 * false - only topmost image file
2867 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2868 * image file. If there was an error a message will have been printed to
2871 static ImageInfoList *collect_image_info_list(bool image_opts,
2872 const char *filename,
2874 bool chain, bool force_share)
2876 ImageInfoList *head = NULL;
2877 ImageInfoList **tail = &head;
2878 GHashTable *filenames;
2881 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2885 BlockDriverState *bs;
2888 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2889 error_report("Backing file '%s' creates an infinite loop.",
2893 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2895 blk = img_open(image_opts, filename, fmt,
2896 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2903 bdrv_query_image_info(bs, &info, &err);
2905 error_report_err(err);
2910 QAPI_LIST_APPEND(tail, info);
2914 /* Clear parameters that only apply to the topmost image */
2915 filename = fmt = NULL;
2919 if (info->full_backing_filename) {
2920 filename = info->full_backing_filename;
2921 } else if (info->backing_filename) {
2922 error_report("Could not determine absolute backing filename,"
2923 " but backing filename '%s' present",
2924 info->backing_filename);
2927 if (info->backing_filename_format) {
2928 fmt = info->backing_filename_format;
2932 g_hash_table_destroy(filenames);
2936 qapi_free_ImageInfoList(head);
2937 g_hash_table_destroy(filenames);
2941 static int img_info(int argc, char **argv)
2944 OutputFormat output_format = OFORMAT_HUMAN;
2946 const char *filename, *fmt, *output;
2947 ImageInfoList *list;
2948 bool image_opts = false;
2949 bool force_share = false;
2954 int option_index = 0;
2955 static const struct option long_options[] = {
2956 {"help", no_argument, 0, 'h'},
2957 {"format", required_argument, 0, 'f'},
2958 {"output", required_argument, 0, OPTION_OUTPUT},
2959 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2960 {"object", required_argument, 0, OPTION_OBJECT},
2961 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2962 {"force-share", no_argument, 0, 'U'},
2965 c = getopt_long(argc, argv, ":f:hU",
2966 long_options, &option_index);
2972 missing_argument(argv[optind - 1]);
2975 unrecognized_option(argv[optind - 1]);
2989 case OPTION_BACKING_CHAIN:
2993 user_creatable_process_cmdline(optarg);
2995 case OPTION_IMAGE_OPTS:
3000 if (optind != argc - 1) {
3001 error_exit("Expecting one image file name");
3003 filename = argv[optind++];
3005 if (output && !strcmp(output, "json")) {
3006 output_format = OFORMAT_JSON;
3007 } else if (output && !strcmp(output, "human")) {
3008 output_format = OFORMAT_HUMAN;
3009 } else if (output) {
3010 error_report("--output must be used with human or json as argument.");
3014 list = collect_image_info_list(image_opts, filename, fmt, chain,
3020 switch (output_format) {
3022 dump_human_image_info_list(list);
3026 dump_json_image_info_list(list);
3028 dump_json_image_info(list->value);
3033 qapi_free_ImageInfoList(list);
3037 static int dump_map_entry(OutputFormat output_format, MapEntry *e,
3040 switch (output_format) {
3042 if (e->data && !e->has_offset) {
3043 error_report("File contains external, encrypted or compressed clusters.");
3046 if (e->data && !e->zero) {
3047 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
3048 e->start, e->length,
3049 e->has_offset ? e->offset : 0,
3052 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3053 * Modify the flags here to allow more coalescing.
3055 if (next && (!next->data || next->zero)) {
3061 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
3062 " \"depth\": %"PRId64", \"present\": %s, \"zero\": %s,"
3063 " \"data\": %s", e->start, e->length, e->depth,
3064 e->present ? "true" : "false",
3065 e->zero ? "true" : "false",
3066 e->data ? "true" : "false");
3067 if (e->has_offset) {
3068 printf(", \"offset\": %"PRId64"", e->offset);
3080 static int get_block_status(BlockDriverState *bs, int64_t offset,
3081 int64_t bytes, MapEntry *e)
3085 BlockDriverState *file;
3088 char *filename = NULL;
3090 /* As an optimization, we could cache the current range of unallocated
3091 * clusters in each file of the chain, and avoid querying the same
3097 bs = bdrv_skip_filters(bs);
3098 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
3103 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
3106 bs = bdrv_cow_bs(bs);
3115 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3117 if (file && has_offset) {
3118 bdrv_refresh_filename(file);
3119 filename = file->filename;
3125 .data = !!(ret & BDRV_BLOCK_DATA),
3126 .zero = !!(ret & BDRV_BLOCK_ZERO),
3128 .has_offset = has_offset,
3130 .present = !!(ret & BDRV_BLOCK_ALLOCATED),
3131 .filename = filename,
3137 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3139 if (curr->length == 0) {
3142 if (curr->zero != next->zero ||
3143 curr->data != next->data ||
3144 curr->depth != next->depth ||
3145 curr->present != next->present ||
3146 !curr->filename != !next->filename ||
3147 curr->has_offset != next->has_offset) {
3150 if (curr->filename && strcmp(curr->filename, next->filename)) {
3153 if (curr->has_offset && curr->offset + curr->length != next->offset) {
3159 static int img_map(int argc, char **argv)
3162 OutputFormat output_format = OFORMAT_HUMAN;
3164 BlockDriverState *bs;
3165 const char *filename, *fmt, *output;
3167 MapEntry curr = { .length = 0 }, next;
3169 bool image_opts = false;
3170 bool force_share = false;
3171 int64_t start_offset = 0;
3172 int64_t max_length = -1;
3177 int option_index = 0;
3178 static const struct option long_options[] = {
3179 {"help", no_argument, 0, 'h'},
3180 {"format", required_argument, 0, 'f'},
3181 {"output", required_argument, 0, OPTION_OUTPUT},
3182 {"object", required_argument, 0, OPTION_OBJECT},
3183 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3184 {"force-share", no_argument, 0, 'U'},
3185 {"start-offset", required_argument, 0, 's'},
3186 {"max-length", required_argument, 0, 'l'},
3189 c = getopt_long(argc, argv, ":f:s:l:hU",
3190 long_options, &option_index);
3196 missing_argument(argv[optind - 1]);
3199 unrecognized_option(argv[optind - 1]);
3214 start_offset = cvtnum("start offset", optarg);
3215 if (start_offset < 0) {
3220 max_length = cvtnum("max length", optarg);
3221 if (max_length < 0) {
3226 user_creatable_process_cmdline(optarg);
3228 case OPTION_IMAGE_OPTS:
3233 if (optind != argc - 1) {
3234 error_exit("Expecting one image file name");
3236 filename = argv[optind];
3238 if (output && !strcmp(output, "json")) {
3239 output_format = OFORMAT_JSON;
3240 } else if (output && !strcmp(output, "human")) {
3241 output_format = OFORMAT_HUMAN;
3242 } else if (output) {
3243 error_report("--output must be used with human or json as argument.");
3247 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
3253 if (output_format == OFORMAT_HUMAN) {
3254 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3255 } else if (output_format == OFORMAT_JSON) {
3259 length = blk_getlength(blk);
3261 error_report("Failed to get size for '%s'", filename);
3264 if (max_length != -1) {
3265 length = MIN(start_offset + max_length, length);
3268 curr.start = start_offset;
3269 while (curr.start + curr.length < length) {
3270 int64_t offset = curr.start + curr.length;
3271 int64_t n = length - offset;
3273 ret = get_block_status(bs, offset, n, &next);
3275 error_report("Could not read file metadata: %s", strerror(-ret));
3279 if (entry_mergeable(&curr, &next)) {
3280 curr.length += next.length;
3284 if (curr.length > 0) {
3285 ret = dump_map_entry(output_format, &curr, &next);
3293 ret = dump_map_entry(output_format, &curr, NULL);
3294 if (output_format == OFORMAT_JSON) {
3303 #define SNAPSHOT_LIST 1
3304 #define SNAPSHOT_CREATE 2
3305 #define SNAPSHOT_APPLY 3
3306 #define SNAPSHOT_DELETE 4
3308 static int img_snapshot(int argc, char **argv)
3311 BlockDriverState *bs;
3312 QEMUSnapshotInfo sn;
3313 char *filename, *snapshot_name = NULL;
3314 int c, ret = 0, bdrv_oflags;
3318 bool image_opts = false;
3319 bool force_share = false;
3322 bdrv_oflags = BDRV_O_RDWR;
3323 /* Parse commandline parameters */
3325 static const struct option long_options[] = {
3326 {"help", no_argument, 0, 'h'},
3327 {"object", required_argument, 0, OPTION_OBJECT},
3328 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3329 {"force-share", no_argument, 0, 'U'},
3332 c = getopt_long(argc, argv, ":la:c:d:hqU",
3333 long_options, NULL);
3339 missing_argument(argv[optind - 1]);
3342 unrecognized_option(argv[optind - 1]);
3349 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3352 action = SNAPSHOT_LIST;
3353 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
3357 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3360 action = SNAPSHOT_APPLY;
3361 snapshot_name = optarg;
3365 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3368 action = SNAPSHOT_CREATE;
3369 snapshot_name = optarg;
3373 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3376 action = SNAPSHOT_DELETE;
3377 snapshot_name = optarg;
3386 user_creatable_process_cmdline(optarg);
3388 case OPTION_IMAGE_OPTS:
3394 if (optind != argc - 1) {
3395 error_exit("Expecting one image file name");
3397 filename = argv[optind++];
3399 /* Open the image */
3400 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3407 /* Perform the requested action */
3413 case SNAPSHOT_CREATE:
3414 memset(&sn, 0, sizeof(sn));
3415 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3417 rt = g_get_real_time();
3418 sn.date_sec = rt / G_USEC_PER_SEC;
3419 sn.date_nsec = (rt % G_USEC_PER_SEC) * 1000;
3421 ret = bdrv_snapshot_create(bs, &sn);
3423 error_report("Could not create snapshot '%s': %d (%s)",
3424 snapshot_name, ret, strerror(-ret));
3428 case SNAPSHOT_APPLY:
3429 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3431 error_reportf_err(err, "Could not apply snapshot '%s': ",
3436 case SNAPSHOT_DELETE:
3437 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3439 error_report("Could not delete snapshot '%s': snapshot not "
3440 "found", snapshot_name);
3443 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3445 error_reportf_err(err, "Could not delete snapshot '%s': ",
3461 static int img_rebase(int argc, char **argv)
3463 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3464 uint8_t *buf_old = NULL;
3465 uint8_t *buf_new = NULL;
3466 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
3467 BlockDriverState *unfiltered_bs;
3469 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3470 int c, flags, src_flags, ret;
3471 bool writethrough, src_writethrough;
3473 bool force_share = false;
3476 Error *local_err = NULL;
3477 bool image_opts = false;
3479 /* Parse commandline parameters */
3481 cache = BDRV_DEFAULT_CACHE;
3482 src_cache = BDRV_DEFAULT_CACHE;
3486 static const struct option long_options[] = {
3487 {"help", no_argument, 0, 'h'},
3488 {"object", required_argument, 0, OPTION_OBJECT},
3489 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3490 {"force-share", no_argument, 0, 'U'},
3493 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3494 long_options, NULL);
3500 missing_argument(argv[optind - 1]);
3503 unrecognized_option(argv[optind - 1]);
3512 out_basefmt = optarg;
3515 out_baseimg = optarg;
3533 user_creatable_process_cmdline(optarg);
3535 case OPTION_IMAGE_OPTS:
3548 if (optind != argc - 1) {
3549 error_exit("Expecting one image file name");
3551 if (!unsafe && !out_baseimg) {
3552 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3554 filename = argv[optind++];
3556 qemu_progress_init(progress, 2.0);
3557 qemu_progress_print(0, 100);
3559 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3560 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3562 error_report("Invalid cache option: %s", cache);
3567 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3569 error_report("Invalid source cache option: %s", src_cache);
3573 /* The source files are opened read-only, don't care about WCE */
3574 assert((src_flags & BDRV_O_RDWR) == 0);
3575 (void) src_writethrough;
3580 * Ignore the old backing file for unsafe rebase in case we want to correct
3581 * the reference to a renamed or moved backing file.
3583 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3591 unfiltered_bs = bdrv_skip_filters(bs);
3593 if (out_basefmt != NULL) {
3594 if (bdrv_find_format(out_basefmt) == NULL) {
3595 error_report("Invalid format name: '%s'", out_basefmt);
3601 /* For safe rebasing we need to compare old and new backing file */
3603 QDict *options = NULL;
3604 BlockDriverState *base_bs = bdrv_cow_bs(unfiltered_bs);
3607 blk_old_backing = blk_new(qemu_get_aio_context(),
3608 BLK_PERM_CONSISTENT_READ,
3610 ret = blk_insert_bs(blk_old_backing, base_bs,
3613 error_reportf_err(local_err,
3614 "Could not reuse old backing file '%s': ",
3619 blk_old_backing = NULL;
3622 if (out_baseimg[0]) {
3623 const char *overlay_filename;
3624 char *out_real_path;
3626 options = qdict_new();
3628 qdict_put_str(options, "driver", out_basefmt);
3631 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3634 bdrv_refresh_filename(bs);
3635 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3638 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3642 qobject_unref(options);
3643 error_reportf_err(local_err,
3644 "Could not resolve backing filename: ");
3650 * Find out whether we rebase an image on top of a previous image
3653 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
3654 if (prefix_chain_bs) {
3655 qobject_unref(options);
3656 g_free(out_real_path);
3658 blk_new_backing = blk_new(qemu_get_aio_context(),
3659 BLK_PERM_CONSISTENT_READ,
3661 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3664 error_reportf_err(local_err,
3665 "Could not reuse backing file '%s': ",
3670 blk_new_backing = blk_new_open(out_real_path, NULL,
3671 options, src_flags, &local_err);
3672 g_free(out_real_path);
3673 if (!blk_new_backing) {
3674 error_reportf_err(local_err,
3675 "Could not open new backing file '%s': ",
3685 * Check each unallocated cluster in the COW file. If it is unallocated,
3686 * accesses go to the backing file. We must therefore compare this cluster
3687 * in the old and new backing file, and if they differ we need to copy it
3688 * from the old backing file into the COW file.
3690 * If qemu-img crashes during this step, no harm is done. The content of
3691 * the image is the same as the original one at any time.
3695 int64_t old_backing_size = 0;
3696 int64_t new_backing_size = 0;
3699 float local_progress = 0;
3701 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3702 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3704 size = blk_getlength(blk);
3706 error_report("Could not get size of '%s': %s",
3707 filename, strerror(-size));
3711 if (blk_old_backing) {
3712 old_backing_size = blk_getlength(blk_old_backing);
3713 if (old_backing_size < 0) {
3714 char backing_name[PATH_MAX];
3716 bdrv_get_backing_filename(bs, backing_name,
3717 sizeof(backing_name));
3718 error_report("Could not get size of '%s': %s",
3719 backing_name, strerror(-old_backing_size));
3724 if (blk_new_backing) {
3725 new_backing_size = blk_getlength(blk_new_backing);
3726 if (new_backing_size < 0) {
3727 error_report("Could not get size of '%s': %s",
3728 out_baseimg, strerror(-new_backing_size));
3735 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3738 for (offset = 0; offset < size; offset += n) {
3739 bool buf_old_is_zero = false;
3741 /* How many bytes can we handle with the next read? */
3742 n = MIN(IO_BUF_SIZE, size - offset);
3744 /* If the cluster is allocated, we don't need to take action */
3745 ret = bdrv_is_allocated(unfiltered_bs, offset, n, &n);
3747 error_report("error while reading image metadata: %s",
3755 if (prefix_chain_bs) {
3757 * If cluster wasn't changed since prefix_chain, we don't need
3760 ret = bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs),
3761 prefix_chain_bs, false,
3764 error_report("error while reading image metadata: %s",
3774 * Read old and new backing file and take into consideration that
3775 * backing files may be smaller than the COW image.
3777 if (offset >= old_backing_size) {
3778 memset(buf_old, 0, n);
3779 buf_old_is_zero = true;
3781 if (offset + n > old_backing_size) {
3782 n = old_backing_size - offset;
3785 ret = blk_pread(blk_old_backing, offset, n, buf_old, 0);
3787 error_report("error while reading from old backing file");
3792 if (offset >= new_backing_size || !blk_new_backing) {
3793 memset(buf_new, 0, n);
3795 if (offset + n > new_backing_size) {
3796 n = new_backing_size - offset;
3799 ret = blk_pread(blk_new_backing, offset, n, buf_new, 0);
3801 error_report("error while reading from new backing file");
3806 /* If they differ, we need to write to the COW file */
3807 uint64_t written = 0;
3809 while (written < n) {
3812 if (compare_buffers(buf_old + written, buf_new + written,
3813 n - written, &pnum))
3815 if (buf_old_is_zero) {
3816 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3818 ret = blk_pwrite(blk, offset + written, pnum,
3819 buf_old + written, 0);
3822 error_report("Error while writing to COW image: %s",
3830 qemu_progress_print(local_progress, 100);
3835 * Change the backing file. All clusters that are different from the old
3836 * backing file are overwritten in the COW file now, so the visible content
3837 * doesn't change when we switch the backing file.
3839 if (out_baseimg && *out_baseimg) {
3840 ret = bdrv_change_backing_file(unfiltered_bs, out_baseimg, out_basefmt,
3843 ret = bdrv_change_backing_file(unfiltered_bs, NULL, NULL, false);
3846 if (ret == -ENOSPC) {
3847 error_report("Could not change the backing file to '%s': No "
3848 "space left in the file header", out_baseimg);
3849 } else if (ret == -EINVAL && out_baseimg && !out_basefmt) {
3850 error_report("Could not change the backing file to '%s': backing "
3851 "format must be specified", out_baseimg);
3852 } else if (ret < 0) {
3853 error_report("Could not change the backing file to '%s': %s",
3854 out_baseimg, strerror(-ret));
3857 qemu_progress_print(100, 0);
3859 * TODO At this point it is possible to check if any clusters that are
3860 * allocated in the COW file are the same in the backing file. If so, they
3861 * could be dropped from the COW file. Don't do this before switching the
3862 * backing file, in case of a crash this would lead to corruption.
3865 qemu_progress_end();
3868 blk_unref(blk_old_backing);
3869 blk_unref(blk_new_backing);
3871 qemu_vfree(buf_old);
3872 qemu_vfree(buf_new);
3881 static int img_resize(int argc, char **argv)
3884 int c, ret, relative;
3885 const char *filename, *fmt, *size;
3886 int64_t n, total_size, current_size;
3888 BlockBackend *blk = NULL;
3889 PreallocMode prealloc = PREALLOC_MODE_OFF;
3892 static QemuOptsList resize_options = {
3893 .name = "resize_options",
3894 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3897 .name = BLOCK_OPT_SIZE,
3898 .type = QEMU_OPT_SIZE,
3899 .help = "Virtual disk size"
3905 bool image_opts = false;
3906 bool shrink = false;
3908 /* Remove size from argv manually so that negative numbers are not treated
3909 * as options by getopt. */
3911 error_exit("Not enough arguments");
3915 size = argv[--argc];
3917 /* Parse getopt arguments */
3920 static const struct option long_options[] = {
3921 {"help", no_argument, 0, 'h'},
3922 {"object", required_argument, 0, OPTION_OBJECT},
3923 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3924 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3925 {"shrink", no_argument, 0, OPTION_SHRINK},
3928 c = getopt_long(argc, argv, ":f:hq",
3929 long_options, NULL);
3935 missing_argument(argv[optind - 1]);
3938 unrecognized_option(argv[optind - 1]);
3950 user_creatable_process_cmdline(optarg);
3952 case OPTION_IMAGE_OPTS:
3955 case OPTION_PREALLOCATION:
3956 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3957 PREALLOC_MODE__MAX, NULL);
3958 if (prealloc == PREALLOC_MODE__MAX) {
3959 error_report("Invalid preallocation mode '%s'", optarg);
3968 if (optind != argc - 1) {
3969 error_exit("Expecting image file name and size");
3971 filename = argv[optind++];
3973 /* Choose grow, shrink, or absolute resize mode */
3989 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3990 if (!qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err)) {
3991 error_report_err(err);
3993 qemu_opts_del(param);
3996 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3997 qemu_opts_del(param);
3999 blk = img_open(image_opts, filename, fmt,
4000 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
4007 current_size = blk_getlength(blk);
4008 if (current_size < 0) {
4009 error_report("Failed to inquire current image length: %s",
4010 strerror(-current_size));
4016 total_size = current_size + n * relative;
4020 if (total_size <= 0) {
4021 error_report("New image size must be positive");
4026 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
4027 error_report("Preallocation can only be used for growing images");
4032 if (total_size < current_size && !shrink) {
4033 error_report("Use the --shrink option to perform a shrink operation.");
4034 warn_report("Shrinking an image will delete all data beyond the "
4035 "shrunken image's end. Before performing such an "
4036 "operation, make sure there is no important data there.");
4042 * The user expects the image to have the desired size after
4043 * resizing, so pass @exact=true. It is of no use to report
4044 * success when the image has not actually been resized.
4046 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
4048 qprintf(quiet, "Image resized.\n");
4050 error_report_err(err);
4060 static void amend_status_cb(BlockDriverState *bs,
4061 int64_t offset, int64_t total_work_size,
4064 qemu_progress_print(100.f * offset / total_work_size, 0);
4067 static int print_amend_option_help(const char *format)
4071 /* Find driver and parse its options */
4072 drv = bdrv_find_format(format);
4074 error_report("Unknown file format '%s'", format);
4078 if (!drv->bdrv_amend_options) {
4079 error_report("Format driver '%s' does not support option amendment",
4084 /* Every driver supporting amendment must have amend_opts */
4085 assert(drv->amend_opts);
4087 printf("Amend options for '%s':\n", format);
4088 qemu_opts_print_help(drv->amend_opts, false);
4092 static int img_amend(int argc, char **argv)
4096 char *options = NULL;
4097 QemuOptsList *amend_opts = NULL;
4098 QemuOpts *opts = NULL;
4099 const char *fmt = NULL, *filename, *cache;
4102 bool quiet = false, progress = false;
4103 BlockBackend *blk = NULL;
4104 BlockDriverState *bs = NULL;
4105 bool image_opts = false;
4108 cache = BDRV_DEFAULT_CACHE;
4110 static const struct option long_options[] = {
4111 {"help", no_argument, 0, 'h'},
4112 {"object", required_argument, 0, OPTION_OBJECT},
4113 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4114 {"force", no_argument, 0, OPTION_FORCE},
4117 c = getopt_long(argc, argv, ":ho:f:t:pq",
4118 long_options, NULL);
4125 missing_argument(argv[optind - 1]);
4128 unrecognized_option(argv[optind - 1]);
4134 if (accumulate_options(&options, optarg) < 0) {
4136 goto out_no_progress;
4152 user_creatable_process_cmdline(optarg);
4154 case OPTION_IMAGE_OPTS:
4164 error_exit("Must specify options (-o)");
4170 qemu_progress_init(progress, 1.0);
4172 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4173 if (fmt && has_help_option(options)) {
4174 /* If a format is explicitly specified (and possibly no filename is
4175 * given), print option help here */
4176 ret = print_amend_option_help(fmt);
4180 if (optind != argc - 1) {
4181 error_report("Expecting one image file name");
4186 flags = BDRV_O_RDWR;
4187 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
4189 error_report("Invalid cache option: %s", cache);
4193 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4201 fmt = bs->drv->format_name;
4203 if (has_help_option(options)) {
4204 /* If the format was auto-detected, print option help here */
4205 ret = print_amend_option_help(fmt);
4209 if (!bs->drv->bdrv_amend_options) {
4210 error_report("Format driver '%s' does not support option amendment",
4216 /* Every driver supporting amendment must have amend_opts */
4217 assert(bs->drv->amend_opts);
4219 amend_opts = qemu_opts_append(amend_opts, bs->drv->amend_opts);
4220 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
4221 if (!qemu_opts_do_parse(opts, options, NULL, &err)) {
4222 /* Try to parse options using the create options */
4223 amend_opts = qemu_opts_append(amend_opts, bs->drv->create_opts);
4224 qemu_opts_del(opts);
4225 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
4226 if (qemu_opts_do_parse(opts, options, NULL, NULL)) {
4227 error_append_hint(&err,
4228 "This option is only supported for image creation\n");
4231 error_report_err(err);
4236 /* In case the driver does not call amend_status_cb() */
4237 qemu_progress_print(0.f, 0);
4238 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, force, &err);
4239 qemu_progress_print(100.f, 0);
4241 error_report_err(err);
4246 qemu_progress_end();
4250 qemu_opts_del(opts);
4251 qemu_opts_free(amend_opts);
4260 typedef struct BenchData {
4262 uint64_t image_size;
4269 bool drain_on_flush;
4278 static void bench_undrained_flush_cb(void *opaque, int ret)
4281 error_report("Failed flush request: %s", strerror(-ret));
4286 static void bench_cb(void *opaque, int ret)
4288 BenchData *b = opaque;
4292 error_report("Failed request: %s", strerror(-ret));
4297 /* Just finished a flush with drained queue: Start next requests */
4298 assert(b->in_flight == 0);
4299 b->in_flush = false;
4300 } else if (b->in_flight > 0) {
4301 int remaining = b->n - b->in_flight;
4306 /* Time for flush? Drain queue if requested, then flush */
4307 if (b->flush_interval && remaining % b->flush_interval == 0) {
4308 if (!b->in_flight || !b->drain_on_flush) {
4309 BlockCompletionFunc *cb;
4311 if (b->drain_on_flush) {
4315 cb = bench_undrained_flush_cb;
4318 acb = blk_aio_flush(b->blk, cb, b);
4320 error_report("Failed to issue flush request");
4324 if (b->drain_on_flush) {
4330 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4331 int64_t offset = b->offset;
4332 /* blk_aio_* might look for completed I/Os and kick bench_cb
4333 * again, so make sure this operation is counted by in_flight
4334 * and b->offset is ready for the next submission.
4337 b->offset += b->step;
4338 b->offset %= b->image_size;
4340 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
4342 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
4345 error_report("Failed to issue request");
4351 static int img_bench(int argc, char **argv)
4354 const char *fmt = NULL, *filename;
4356 bool image_opts = false;
4357 bool is_write = false;
4361 size_t bufsize = 4096;
4364 int flush_interval = 0;
4365 bool drain_on_flush = true;
4367 BlockBackend *blk = NULL;
4368 BenchData data = {};
4370 bool writethrough = false;
4371 struct timeval t1, t2;
4373 bool force_share = false;
4374 size_t buf_size = 0;
4377 static const struct option long_options[] = {
4378 {"help", no_argument, 0, 'h'},
4379 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
4380 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4381 {"pattern", required_argument, 0, OPTION_PATTERN},
4382 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
4383 {"force-share", no_argument, 0, 'U'},
4386 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4394 missing_argument(argv[optind - 1]);
4397 unrecognized_option(argv[optind - 1]);
4406 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4407 error_report("Invalid request count specified");
4417 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4418 error_report("Invalid queue depth specified");
4428 flags |= BDRV_O_NATIVE_AIO;
4431 ret = bdrv_parse_aio(optarg, &flags);
4433 error_report("Invalid aio option: %s", optarg);
4440 offset = cvtnum("offset", optarg);
4454 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4466 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4475 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4477 error_report("Invalid cache mode");
4483 flags |= BDRV_O_RDWR;
4489 case OPTION_PATTERN:
4493 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4494 error_report("Invalid pattern byte specified");
4500 case OPTION_FLUSH_INTERVAL:
4504 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4505 error_report("Invalid flush interval specified");
4508 flush_interval = res;
4511 case OPTION_NO_DRAIN:
4512 drain_on_flush = false;
4514 case OPTION_IMAGE_OPTS:
4520 if (optind != argc - 1) {
4521 error_exit("Expecting one image file name");
4523 filename = argv[argc - 1];
4525 if (!is_write && flush_interval) {
4526 error_report("--flush-interval is only available in write tests");
4530 if (flush_interval && flush_interval < depth) {
4531 error_report("Flush interval can't be smaller than depth");
4536 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4543 image_size = blk_getlength(blk);
4544 if (image_size < 0) {
4549 data = (BenchData) {
4551 .image_size = image_size,
4553 .step = step ?: bufsize,
4558 .flush_interval = flush_interval,
4559 .drain_on_flush = drain_on_flush,
4561 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4562 "(starting at offset %" PRId64 ", step size %d)\n",
4563 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4564 data.offset, data.step);
4565 if (flush_interval) {
4566 printf("Sending flush every %d requests\n", flush_interval);
4569 buf_size = data.nrreq * data.bufsize;
4570 data.buf = blk_blockalign(blk, buf_size);
4571 memset(data.buf, pattern, data.nrreq * data.bufsize);
4573 blk_register_buf(blk, data.buf, buf_size, &error_fatal);
4575 data.qiov = g_new(QEMUIOVector, data.nrreq);
4576 for (i = 0; i < data.nrreq; i++) {
4577 qemu_iovec_init(&data.qiov[i], 1);
4578 qemu_iovec_add(&data.qiov[i],
4579 data.buf + i * data.bufsize, data.bufsize);
4582 gettimeofday(&t1, NULL);
4585 while (data.n > 0) {
4586 main_loop_wait(false);
4588 gettimeofday(&t2, NULL);
4590 printf("Run completed in %3.3f seconds.\n",
4591 (t2.tv_sec - t1.tv_sec)
4592 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4596 blk_unregister_buf(blk, data.buf, buf_size);
4598 qemu_vfree(data.buf);
4615 typedef struct ImgBitmapAction {
4616 enum ImgBitmapAct act;
4617 const char *src; /* only used for merge */
4618 QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4621 static int img_bitmap(int argc, char **argv)
4625 QemuOpts *opts = NULL;
4626 const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4627 const char *filename, *bitmap;
4628 BlockBackend *blk = NULL, *src = NULL;
4629 BlockDriverState *bs = NULL, *src_bs = NULL;
4630 bool image_opts = false;
4631 int64_t granularity = 0;
4632 bool add = false, merge = false;
4633 QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4634 ImgBitmapAction *act, *act_next;
4637 QSIMPLEQ_INIT(&actions);
4640 static const struct option long_options[] = {
4641 {"help", no_argument, 0, 'h'},
4642 {"object", required_argument, 0, OPTION_OBJECT},
4643 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4644 {"add", no_argument, 0, OPTION_ADD},
4645 {"remove", no_argument, 0, OPTION_REMOVE},
4646 {"clear", no_argument, 0, OPTION_CLEAR},
4647 {"enable", no_argument, 0, OPTION_ENABLE},
4648 {"disable", no_argument, 0, OPTION_DISABLE},
4649 {"merge", required_argument, 0, OPTION_MERGE},
4650 {"granularity", required_argument, 0, 'g'},
4651 {"source-file", required_argument, 0, 'b'},
4652 {"source-format", required_argument, 0, 'F'},
4655 c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4662 missing_argument(argv[optind - 1]);
4665 unrecognized_option(argv[optind - 1]);
4671 src_filename = optarg;
4680 granularity = cvtnum("granularity", optarg);
4681 if (granularity < 0) {
4686 act = g_new0(ImgBitmapAction, 1);
4687 act->act = BITMAP_ADD;
4688 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4692 act = g_new0(ImgBitmapAction, 1);
4693 act->act = BITMAP_REMOVE;
4694 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4697 act = g_new0(ImgBitmapAction, 1);
4698 act->act = BITMAP_CLEAR;
4699 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4702 act = g_new0(ImgBitmapAction, 1);
4703 act->act = BITMAP_ENABLE;
4704 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4706 case OPTION_DISABLE:
4707 act = g_new0(ImgBitmapAction, 1);
4708 act->act = BITMAP_DISABLE;
4709 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4712 act = g_new0(ImgBitmapAction, 1);
4713 act->act = BITMAP_MERGE;
4715 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4719 user_creatable_process_cmdline(optarg);
4721 case OPTION_IMAGE_OPTS:
4727 if (QSIMPLEQ_EMPTY(&actions)) {
4728 error_report("Need at least one of --add, --remove, --clear, "
4729 "--enable, --disable, or --merge");
4733 if (granularity && !add) {
4734 error_report("granularity only supported with --add");
4737 if (src_fmt && !src_filename) {
4738 error_report("-F only supported with -b");
4741 if (src_filename && !merge) {
4742 error_report("Merge bitmap source file only supported with "
4747 if (optind != argc - 2) {
4748 error_report("Expecting filename and bitmap name");
4752 filename = argv[optind];
4753 bitmap = argv[optind + 1];
4756 * No need to open backing chains; we will be manipulating bitmaps
4757 * directly in this image without reference to image contents.
4759 blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR | BDRV_O_NO_BACKING,
4760 false, false, false);
4766 src = img_open(false, src_filename, src_fmt, BDRV_O_NO_BACKING,
4767 false, false, false);
4771 src_bs = blk_bs(src);
4776 QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4779 qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4780 !!granularity, granularity, true, true,
4781 false, false, &err);
4785 qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4789 qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4793 qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4796 case BITMAP_DISABLE:
4797 qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4801 do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4806 g_assert_not_reached();
4810 error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4822 qemu_opts_del(opts);
4838 int bsz; /* Block size */
4846 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4850 static int img_dd_bs(const char *arg,
4851 struct DdIo *in, struct DdIo *out,
4856 res = cvtnum_full("bs", arg, 1, INT_MAX);
4861 in->bsz = out->bsz = res;
4866 static int img_dd_count(const char *arg,
4867 struct DdIo *in, struct DdIo *out,
4870 dd->count = cvtnum("count", arg);
4872 if (dd->count < 0) {
4879 static int img_dd_if(const char *arg,
4880 struct DdIo *in, struct DdIo *out,
4883 in->filename = g_strdup(arg);
4888 static int img_dd_of(const char *arg,
4889 struct DdIo *in, struct DdIo *out,
4892 out->filename = g_strdup(arg);
4897 static int img_dd_skip(const char *arg,
4898 struct DdIo *in, struct DdIo *out,
4901 in->offset = cvtnum("skip", arg);
4903 if (in->offset < 0) {
4910 static int img_dd(int argc, char **argv)
4915 BlockDriver *drv = NULL, *proto_drv = NULL;
4916 BlockBackend *blk1 = NULL, *blk2 = NULL;
4917 QemuOpts *opts = NULL;
4918 QemuOptsList *create_opts = NULL;
4919 Error *local_err = NULL;
4920 bool image_opts = false;
4922 const char *out_fmt = "raw";
4923 const char *fmt = NULL;
4925 int64_t out_pos, in_pos;
4926 bool force_share = false;
4927 struct DdInfo dd = {
4932 .bsz = 512, /* Block size is by default 512 bytes */
4944 const struct DdOpts options[] = {
4945 { "bs", img_dd_bs, C_BS },
4946 { "count", img_dd_count, C_COUNT },
4947 { "if", img_dd_if, C_IF },
4948 { "of", img_dd_of, C_OF },
4949 { "skip", img_dd_skip, C_SKIP },
4952 const struct option long_options[] = {
4953 { "help", no_argument, 0, 'h'},
4954 { "object", required_argument, 0, OPTION_OBJECT},
4955 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4956 { "force-share", no_argument, 0, 'U'},
4960 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4972 missing_argument(argv[optind - 1]);
4975 unrecognized_option(argv[optind - 1]);
4984 user_creatable_process_cmdline(optarg);
4986 case OPTION_IMAGE_OPTS:
4992 for (i = optind; i < argc; i++) {
4994 arg = g_strdup(argv[i]);
4996 tmp = strchr(arg, '=');
4998 error_report("unrecognized operand %s", arg);
5005 for (j = 0; options[j].name != NULL; j++) {
5006 if (!strcmp(arg, options[j].name)) {
5010 if (options[j].name == NULL) {
5011 error_report("unrecognized operand %s", arg);
5016 if (options[j].f(tmp, &in, &out, &dd) != 0) {
5020 dd.flags |= options[j].flag;
5025 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
5026 error_report("Must specify both input and output files");
5031 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
5039 drv = bdrv_find_format(out_fmt);
5041 error_report("Unknown file format");
5045 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
5048 error_report_err(local_err);
5052 if (!drv->create_opts) {
5053 error_report("Format driver '%s' does not support image creation",
5058 if (!proto_drv->create_opts) {
5059 error_report("Protocol driver '%s' does not support image creation",
5060 proto_drv->format_name);
5064 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5065 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5067 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5069 size = blk_getlength(blk1);
5071 error_report("Failed to get size for '%s'", in.filename);
5076 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5077 dd.count * in.bsz < size) {
5078 size = dd.count * in.bsz;
5081 /* Overflow means the specified offset is beyond input image's size */
5082 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5083 size < in.bsz * in.offset)) {
5084 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5086 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5087 size - in.bsz * in.offset, &error_abort);
5090 ret = bdrv_create(drv, out.filename, opts, &local_err);
5092 error_reportf_err(local_err,
5093 "%s: error while creating output image: ",
5099 /* TODO, we can't honour --image-opts for the target,
5100 * since it needs to be given in a format compatible
5101 * with the bdrv_create() call above which does not
5102 * support image-opts style.
5104 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
5105 false, false, false);
5112 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5113 size < in.offset * in.bsz)) {
5114 /* We give a warning if the skip option is bigger than the input
5115 * size and create an empty output disk image (i.e. like dd(1)).
5117 error_report("%s: cannot skip to specified offset", in.filename);
5120 in_pos = in.offset * in.bsz;
5123 in.buf = g_new(uint8_t, in.bsz);
5125 for (out_pos = 0; in_pos < size; ) {
5126 int bytes = (in_pos + in.bsz > size) ? size - in_pos : in.bsz;
5128 ret = blk_pread(blk1, in_pos, bytes, in.buf, 0);
5130 error_report("error while reading from input image file: %s",
5136 ret = blk_pwrite(blk2, out_pos, bytes, in.buf, 0);
5138 error_report("error while writing to output image file: %s",
5147 qemu_opts_del(opts);
5148 qemu_opts_free(create_opts);
5151 g_free(in.filename);
5152 g_free(out.filename);
5162 static void dump_json_block_measure_info(BlockMeasureInfo *info)
5166 Visitor *v = qobject_output_visitor_new(&obj);
5168 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5169 visit_complete(v, &obj);
5170 str = qobject_to_json_pretty(obj, true);
5171 assert(str != NULL);
5172 printf("%s\n", str->str);
5175 g_string_free(str, true);
5178 static int img_measure(int argc, char **argv)
5180 static const struct option long_options[] = {
5181 {"help", no_argument, 0, 'h'},
5182 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5183 {"object", required_argument, 0, OPTION_OBJECT},
5184 {"output", required_argument, 0, OPTION_OUTPUT},
5185 {"size", required_argument, 0, OPTION_SIZE},
5186 {"force-share", no_argument, 0, 'U'},
5189 OutputFormat output_format = OFORMAT_HUMAN;
5190 BlockBackend *in_blk = NULL;
5192 const char *filename = NULL;
5193 const char *fmt = NULL;
5194 const char *out_fmt = "raw";
5195 char *options = NULL;
5196 char *snapshot_name = NULL;
5197 bool force_share = false;
5198 QemuOpts *opts = NULL;
5199 QemuOpts *object_opts = NULL;
5200 QemuOpts *sn_opts = NULL;
5201 QemuOptsList *create_opts = NULL;
5202 bool image_opts = false;
5203 uint64_t img_size = UINT64_MAX;
5204 BlockMeasureInfo *info = NULL;
5205 Error *local_err = NULL;
5209 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5210 long_options, NULL)) != -1) {
5223 if (accumulate_options(&options, optarg) < 0) {
5228 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5229 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5232 error_report("Failed in parsing snapshot param '%s'",
5237 snapshot_name = optarg;
5244 user_creatable_process_cmdline(optarg);
5246 case OPTION_IMAGE_OPTS:
5250 if (!strcmp(optarg, "json")) {
5251 output_format = OFORMAT_JSON;
5252 } else if (!strcmp(optarg, "human")) {
5253 output_format = OFORMAT_HUMAN;
5255 error_report("--output must be used with human or json "
5264 sval = cvtnum("image size", optarg);
5268 img_size = (uint64_t)sval;
5274 if (argc - optind > 1) {
5275 error_report("At most one filename argument is allowed.");
5277 } else if (argc - optind == 1) {
5278 filename = argv[optind];
5281 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5282 error_report("--image-opts, -f, and -l require a filename argument.");
5285 if (filename && img_size != UINT64_MAX) {
5286 error_report("--size N cannot be used together with a filename.");
5289 if (!filename && img_size == UINT64_MAX) {
5290 error_report("Either --size N or one filename must be specified.");
5295 in_blk = img_open(image_opts, filename, fmt, 0,
5296 false, false, force_share);
5302 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5303 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5304 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5306 } else if (snapshot_name != NULL) {
5307 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5308 snapshot_name, &local_err);
5311 error_reportf_err(local_err, "Failed to load snapshot: ");
5316 drv = bdrv_find_format(out_fmt);
5318 error_report("Unknown file format '%s'", out_fmt);
5321 if (!drv->create_opts) {
5322 error_report("Format driver '%s' does not support image creation",
5327 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5328 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5329 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5331 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
5332 error_report_err(local_err);
5333 error_report("Invalid options for file format '%s'", out_fmt);
5337 if (img_size != UINT64_MAX) {
5338 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5341 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5343 error_report_err(local_err);
5347 if (output_format == OFORMAT_HUMAN) {
5348 printf("required size: %" PRIu64 "\n", info->required);
5349 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
5350 if (info->has_bitmaps) {
5351 printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5354 dump_json_block_measure_info(info);
5360 qapi_free_BlockMeasureInfo(info);
5361 qemu_opts_del(object_opts);
5362 qemu_opts_del(opts);
5363 qemu_opts_del(sn_opts);
5364 qemu_opts_free(create_opts);
5370 static const img_cmd_t img_cmds[] = {
5371 #define DEF(option, callback, arg_string) \
5372 { option, callback },
5373 #include "qemu-img-cmds.h"
5378 int main(int argc, char **argv)
5380 const img_cmd_t *cmd;
5381 const char *cmdname;
5383 static const struct option long_options[] = {
5384 {"help", no_argument, 0, 'h'},
5385 {"version", no_argument, 0, 'V'},
5386 {"trace", required_argument, NULL, 'T'},
5391 signal(SIGPIPE, SIG_IGN);
5395 error_init(argv[0]);
5396 module_call_init(MODULE_INIT_TRACE);
5397 qemu_init_exec_dir(argv[0]);
5399 qemu_init_main_loop(&error_fatal);
5401 qcrypto_init(&error_fatal);
5403 module_call_init(MODULE_INIT_QOM);
5406 error_exit("Not enough arguments");
5409 qemu_add_opts(&qemu_source_opts);
5410 qemu_add_opts(&qemu_trace_opts);
5412 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
5415 missing_argument(argv[optind - 1]);
5418 unrecognized_option(argv[optind - 1]);
5424 printf(QEMU_IMG_VERSION);
5427 trace_opt_parse(optarg);
5432 cmdname = argv[optind];
5434 /* reset getopt_long scanning */
5440 qemu_reset_optind();
5442 if (!trace_init_backends()) {
5446 qemu_set_log(LOG_TRACE, &error_fatal);
5448 /* find the command */
5449 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5450 if (!strcmp(cmdname, cmd->name)) {
5451 return cmd->handler(argc, argv);
5456 error_exit("Command not found: %s", cmdname);