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 @list safe for accumulate_options()?
239 * It is when multiple of them can be joined together separated by ','.
240 * To make that work, @list 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 *list)
249 size_t len = strlen(list);
252 if (!list[0] || list[0] == ',') {
256 for (i = len; i > 0 && list[i - 1] == ','; i--) {
265 static int accumulate_options(char **options, char *list)
269 if (!is_valid_option_list(list)) {
270 error_report("Invalid option list: %s", list);
275 *options = g_strdup(list);
277 new_options = g_strdup_printf("%s,%s", *options, list);
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,
455 blk_set_force_allow_inactivate(blk);
462 static int add_old_style_options(const char *fmt, QemuOpts *opts,
463 const char *base_filename,
464 const char *base_fmt)
467 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
469 error_report("Backing file not supported for file format '%s'",
475 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
476 error_report("Backing file format not supported for file "
484 static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
490 err = qemu_strtosz(value, NULL, &res);
491 if (err < 0 && err != -ERANGE) {
492 error_report("Invalid %s specified. You may use "
493 "k, M, G, T, P or E suffixes for", name);
494 error_report("kilobytes, megabytes, gigabytes, terabytes, "
495 "petabytes and exabytes.");
498 if (err == -ERANGE || res > max || res < min) {
499 error_report("Invalid %s specified. Must be between %" PRId64
500 " and %" PRId64 ".", name, min, max);
506 static int64_t cvtnum(const char *name, const char *value)
508 return cvtnum_full(name, value, 0, INT64_MAX);
511 static int img_create(int argc, char **argv)
514 uint64_t img_size = -1;
515 const char *fmt = "raw";
516 const char *base_fmt = NULL;
517 const char *filename;
518 const char *base_filename = NULL;
519 char *options = NULL;
520 Error *local_err = NULL;
525 static const struct option long_options[] = {
526 {"help", no_argument, 0, 'h'},
527 {"object", required_argument, 0, OPTION_OBJECT},
530 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
537 missing_argument(argv[optind - 1]);
540 unrecognized_option(argv[optind - 1]);
549 base_filename = optarg;
555 if (accumulate_options(&options, optarg) < 0) {
563 flags |= BDRV_O_NO_BACKING;
566 user_creatable_process_cmdline(optarg);
571 /* Get the filename */
572 filename = (optind < argc) ? argv[optind] : NULL;
573 if (options && has_help_option(options)) {
575 return print_block_option_help(filename, fmt);
578 if (optind >= argc) {
579 error_exit("Expecting image file name");
583 /* Get image size, if specified */
587 sval = cvtnum("image size", argv[optind++]);
591 img_size = (uint64_t)sval;
593 if (optind != argc) {
594 error_exit("Unexpected argument: %s", argv[optind]);
597 bdrv_img_create(filename, fmt, base_filename, base_fmt,
598 options, img_size, flags, quiet, &local_err);
600 error_reportf_err(local_err, "%s: ", filename);
612 static void dump_json_image_check(ImageCheck *check, bool quiet)
616 Visitor *v = qobject_output_visitor_new(&obj);
618 visit_type_ImageCheck(v, NULL, &check, &error_abort);
619 visit_complete(v, &obj);
620 str = qobject_to_json_pretty(obj, true);
622 qprintf(quiet, "%s\n", str->str);
625 g_string_free(str, true);
628 static void dump_human_image_check(ImageCheck *check, bool quiet)
630 if (!(check->corruptions || check->leaks || check->check_errors)) {
631 qprintf(quiet, "No errors were found on the image.\n");
633 if (check->corruptions) {
634 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
635 "Data may be corrupted, or further writes to the image "
642 "\n%" PRId64 " leaked clusters were found on the image.\n"
643 "This means waste of disk space, but no harm to data.\n",
647 if (check->check_errors) {
650 " internal errors have occurred during the check.\n",
651 check->check_errors);
655 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
656 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
657 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
658 check->allocated_clusters, check->total_clusters,
659 check->allocated_clusters * 100.0 / check->total_clusters,
660 check->fragmented_clusters * 100.0 / check->allocated_clusters,
661 check->compressed_clusters * 100.0 /
662 check->allocated_clusters);
665 if (check->image_end_offset) {
667 "Image end offset: %" PRId64 "\n", check->image_end_offset);
671 static int collect_image_check(BlockDriverState *bs,
673 const char *filename,
678 BdrvCheckResult result;
680 ret = bdrv_check(bs, &result, fix);
685 check->filename = g_strdup(filename);
686 check->format = g_strdup(bdrv_get_format_name(bs));
687 check->check_errors = result.check_errors;
688 check->corruptions = result.corruptions;
689 check->has_corruptions = result.corruptions != 0;
690 check->leaks = result.leaks;
691 check->has_leaks = result.leaks != 0;
692 check->corruptions_fixed = result.corruptions_fixed;
693 check->has_corruptions_fixed = result.corruptions_fixed != 0;
694 check->leaks_fixed = result.leaks_fixed;
695 check->has_leaks_fixed = result.leaks_fixed != 0;
696 check->image_end_offset = result.image_end_offset;
697 check->has_image_end_offset = result.image_end_offset != 0;
698 check->total_clusters = result.bfi.total_clusters;
699 check->has_total_clusters = result.bfi.total_clusters != 0;
700 check->allocated_clusters = result.bfi.allocated_clusters;
701 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
702 check->fragmented_clusters = result.bfi.fragmented_clusters;
703 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
704 check->compressed_clusters = result.bfi.compressed_clusters;
705 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
711 * Checks an image for consistency. Exit codes:
713 * 0 - Check completed, image is good
714 * 1 - Check not completed because of internal errors
715 * 2 - Check completed, image is corrupted
716 * 3 - Check completed, image has leaked clusters, but is good otherwise
717 * 63 - Checks are not supported by the image format
719 static int img_check(int argc, char **argv)
722 OutputFormat output_format = OFORMAT_HUMAN;
723 const char *filename, *fmt, *output, *cache;
725 BlockDriverState *bs;
727 int flags = BDRV_O_CHECK;
731 bool image_opts = false;
732 bool force_share = false;
736 cache = BDRV_DEFAULT_CACHE;
739 int option_index = 0;
740 static const struct option long_options[] = {
741 {"help", no_argument, 0, 'h'},
742 {"format", required_argument, 0, 'f'},
743 {"repair", required_argument, 0, 'r'},
744 {"output", required_argument, 0, OPTION_OUTPUT},
745 {"object", required_argument, 0, OPTION_OBJECT},
746 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
747 {"force-share", no_argument, 0, 'U'},
750 c = getopt_long(argc, argv, ":hf:r:T:qU",
751 long_options, &option_index);
757 missing_argument(argv[optind - 1]);
760 unrecognized_option(argv[optind - 1]);
769 flags |= BDRV_O_RDWR;
771 if (!strcmp(optarg, "leaks")) {
772 fix = BDRV_FIX_LEAKS;
773 } else if (!strcmp(optarg, "all")) {
774 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
776 error_exit("Unknown option value for -r "
777 "(expecting 'leaks' or 'all'): %s", optarg);
793 user_creatable_process_cmdline(optarg);
795 case OPTION_IMAGE_OPTS:
800 if (optind != argc - 1) {
801 error_exit("Expecting one image file name");
803 filename = argv[optind++];
805 if (output && !strcmp(output, "json")) {
806 output_format = OFORMAT_JSON;
807 } else if (output && !strcmp(output, "human")) {
808 output_format = OFORMAT_HUMAN;
810 error_report("--output must be used with human or json as argument.");
814 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
816 error_report("Invalid source cache option: %s", cache);
820 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
827 check = g_new0(ImageCheck, 1);
828 ret = collect_image_check(bs, check, filename, fmt, fix);
830 if (ret == -ENOTSUP) {
831 error_report("This image format does not support checks");
836 if (check->corruptions_fixed || check->leaks_fixed) {
837 int corruptions_fixed, leaks_fixed;
838 bool has_leaks_fixed, has_corruptions_fixed;
840 leaks_fixed = check->leaks_fixed;
841 has_leaks_fixed = check->has_leaks_fixed;
842 corruptions_fixed = check->corruptions_fixed;
843 has_corruptions_fixed = check->has_corruptions_fixed;
845 if (output_format == OFORMAT_HUMAN) {
847 "The following inconsistencies were found and repaired:\n\n"
848 " %" PRId64 " leaked clusters\n"
849 " %" PRId64 " corruptions\n\n"
850 "Double checking the fixed image now...\n",
852 check->corruptions_fixed);
855 qapi_free_ImageCheck(check);
856 check = g_new0(ImageCheck, 1);
857 ret = collect_image_check(bs, check, filename, fmt, 0);
859 check->leaks_fixed = leaks_fixed;
860 check->has_leaks_fixed = has_leaks_fixed;
861 check->corruptions_fixed = corruptions_fixed;
862 check->has_corruptions_fixed = has_corruptions_fixed;
866 switch (output_format) {
868 dump_human_image_check(check, quiet);
871 dump_json_image_check(check, quiet);
876 if (ret || check->check_errors) {
878 error_report("Check failed: %s", strerror(-ret));
880 error_report("Check failed");
886 if (check->corruptions) {
888 } else if (check->leaks) {
895 qapi_free_ImageCheck(check);
900 typedef struct CommonBlockJobCBInfo {
901 BlockDriverState *bs;
903 } CommonBlockJobCBInfo;
905 static void common_block_job_cb(void *opaque, int ret)
907 CommonBlockJobCBInfo *cbi = opaque;
910 error_setg_errno(cbi->errp, -ret, "Block job failed");
914 static void run_block_job(BlockJob *job, Error **errp)
916 uint64_t progress_current, progress_total;
917 AioContext *aio_context = block_job_get_aio_context(job);
921 job_ref_locked(&job->job);
923 float progress = 0.0f;
925 aio_poll(aio_context, true);
927 progress_get_snapshot(&job->job.progress, &progress_current,
929 if (progress_total) {
930 progress = (float)progress_current / progress_total * 100.f;
932 qemu_progress_print(progress, 0);
934 } while (!job_is_ready_locked(&job->job) &&
935 !job_is_completed_locked(&job->job));
937 if (!job_is_completed_locked(&job->job)) {
938 ret = job_complete_sync_locked(&job->job, errp);
942 job_unref_locked(&job->job);
945 /* publish completion progress only when success */
947 qemu_progress_print(100.f, 0);
951 static int img_commit(int argc, char **argv)
954 const char *filename, *fmt, *cache, *base;
956 BlockDriverState *bs, *base_bs;
958 bool progress = false, quiet = false, drop = false;
960 Error *local_err = NULL;
961 CommonBlockJobCBInfo cbi;
962 bool image_opts = false;
963 AioContext *aio_context;
964 int64_t rate_limit = 0;
967 cache = BDRV_DEFAULT_CACHE;
970 static const struct option long_options[] = {
971 {"help", no_argument, 0, 'h'},
972 {"object", required_argument, 0, OPTION_OBJECT},
973 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
976 c = getopt_long(argc, argv, ":f:ht:b:dpqr:",
983 missing_argument(argv[optind - 1]);
986 unrecognized_option(argv[optind - 1]);
1012 rate_limit = cvtnum("rate limit", optarg);
1013 if (rate_limit < 0) {
1018 user_creatable_process_cmdline(optarg);
1020 case OPTION_IMAGE_OPTS:
1026 /* Progress is not shown in Quiet mode */
1031 if (optind != argc - 1) {
1032 error_exit("Expecting one image file name");
1034 filename = argv[optind++];
1036 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
1037 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1039 error_report("Invalid cache option: %s", cache);
1043 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1050 qemu_progress_init(progress, 1.f);
1051 qemu_progress_print(0.f, 100);
1054 base_bs = bdrv_find_backing_image(bs, base);
1056 error_setg(&local_err,
1057 "Did not find '%s' in the backing chain of '%s'",
1062 /* This is different from QMP, which by default uses the deepest file in
1063 * the backing chain (i.e., the very base); however, the traditional
1064 * behavior of qemu-img commit is using the immediate backing file. */
1065 base_bs = bdrv_backing_chain_next(bs);
1067 error_setg(&local_err, "Image does not have a backing file");
1072 cbi = (CommonBlockJobCBInfo){
1077 aio_context = bdrv_get_aio_context(bs);
1078 aio_context_acquire(aio_context);
1079 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, rate_limit,
1080 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1081 &cbi, false, &local_err);
1082 aio_context_release(aio_context);
1087 /* When the block job completes, the BlockBackend reference will point to
1088 * the old backing file. In order to avoid that the top image is already
1089 * deleted, so we can still empty it afterwards, increment the reference
1090 * counter here preemptively. */
1095 job = block_job_get("commit");
1097 run_block_job(job, &local_err);
1103 BlockBackend *old_backing_blk;
1105 old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1107 if (!old_backing_blk) {
1110 ret = blk_make_empty(old_backing_blk, &local_err);
1111 blk_unref(old_backing_blk);
1112 if (ret == -ENOTSUP) {
1113 error_free(local_err);
1115 } else if (ret < 0) {
1126 qemu_progress_end();
1129 * Manually inactivate the image first because this way we can know whether
1130 * an error occurred. blk_unref() doesn't tell us about failures.
1132 ret = bdrv_inactivate_all();
1133 if (ret < 0 && !local_err) {
1134 error_setg_errno(&local_err, -ret, "Error while closing the image");
1139 error_report_err(local_err);
1143 qprintf(quiet, "Image committed.\n");
1148 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1149 * of the first sector boundary within buf where the sector contains a
1150 * non-zero byte. This function is robust to a buffer that is not
1153 static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1156 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1158 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1159 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1163 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1170 * Returns true iff the first sector pointed to by 'buf' contains at least
1173 * 'pnum' is set to the number of sectors (including and immediately following
1174 * the first one) that are known to be in the same allocated/unallocated state.
1175 * The function will try to align the end offset to alignment boundaries so
1176 * that the request will at least end aligned and consecutive requests will
1177 * also start at an aligned offset.
1179 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1180 int64_t sector_num, int alignment)
1189 is_zero = buffer_is_zero(buf, BDRV_SECTOR_SIZE);
1190 for(i = 1; i < n; i++) {
1191 buf += BDRV_SECTOR_SIZE;
1192 if (is_zero != buffer_is_zero(buf, BDRV_SECTOR_SIZE)) {
1199 * The whole buf is the same.
1200 * No reason to split it into chunks, so return now.
1206 tail = (sector_num + i) & (alignment - 1);
1208 if (is_zero && i <= tail) {
1210 * For sure next sector after i is data, and it will rewrite this
1211 * tail anyway due to RMW. So, let's just write data now.
1216 /* If possible, align up end offset of allocated areas. */
1217 i += alignment - tail;
1221 * For sure next sector after i is data, and it will rewrite this
1222 * tail anyway due to RMW. Better is avoid RMW and write zeroes up
1233 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1234 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1235 * breaking up write requests for only small sparse areas.
1237 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1238 int min, int64_t sector_num, int alignment)
1241 int num_checked, num_used;
1247 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1253 buf += BDRV_SECTOR_SIZE * *pnum;
1255 sector_num += *pnum;
1256 num_checked = num_used;
1259 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1261 buf += BDRV_SECTOR_SIZE * *pnum;
1263 sector_num += *pnum;
1264 num_checked += *pnum;
1266 num_used = num_checked;
1267 } else if (*pnum >= min) {
1277 * Compares two buffers chunk by chunk, where @chsize is the chunk size.
1278 * If @chsize is 0, default chunk size of BDRV_SECTOR_SIZE is used.
1279 * Returns 0 if the first chunk of each buffer matches, non-zero otherwise.
1281 * @pnum is set to the size of the buffer prefix aligned to @chsize that
1282 * has the same matching status as the first chunk.
1284 static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1285 int64_t bytes, uint64_t chsize, int64_t *pnum)
1293 chsize = BDRV_SECTOR_SIZE;
1295 i = MIN(bytes, chsize);
1297 res = !!memcmp(buf1, buf2, i);
1299 int64_t len = MIN(bytes - i, chsize);
1301 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
1311 #define IO_BUF_SIZE (2 * MiB)
1314 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1316 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1317 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1318 * failure), and 4 on error (the exit status for read errors), after emitting
1321 * @param blk: BlockBackend for the image
1322 * @param offset: Starting offset to check
1323 * @param bytes: Number of bytes to check
1324 * @param filename: Name of disk file we are checking (logging purpose)
1325 * @param buffer: Allocated buffer for storing read data
1326 * @param quiet: Flag for quiet mode
1328 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1329 int64_t bytes, const char *filename,
1330 uint8_t *buffer, bool quiet)
1335 ret = blk_pread(blk, offset, bytes, buffer, 0);
1337 error_report("Error while reading offset %" PRId64 " of %s: %s",
1338 offset, filename, strerror(-ret));
1341 idx = find_nonzero(buffer, bytes);
1343 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1352 * Compares two images. Exit codes:
1354 * 0 - Images are identical or the requested help was printed
1356 * >1 - Error occurred
1358 static int img_compare(int argc, char **argv)
1360 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1361 BlockBackend *blk1, *blk2;
1362 BlockDriverState *bs1, *bs2;
1363 int64_t total_size1, total_size2;
1364 uint8_t *buf1 = NULL, *buf2 = NULL;
1365 int64_t pnum1, pnum2;
1366 int allocated1, allocated2;
1367 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1368 bool progress = false, quiet = false, strict = false;
1375 uint64_t progress_base;
1376 bool image_opts = false;
1377 bool force_share = false;
1379 cache = BDRV_DEFAULT_CACHE;
1381 static const struct option long_options[] = {
1382 {"help", no_argument, 0, 'h'},
1383 {"object", required_argument, 0, OPTION_OBJECT},
1384 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1385 {"force-share", no_argument, 0, 'U'},
1388 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1389 long_options, NULL);
1395 missing_argument(argv[optind - 1]);
1398 unrecognized_option(argv[optind - 1]);
1426 Error *local_err = NULL;
1428 if (!user_creatable_add_from_str(optarg, &local_err)) {
1430 error_report_err(local_err);
1433 /* Help was printed */
1439 case OPTION_IMAGE_OPTS:
1445 /* Progress is not shown in Quiet mode */
1451 if (optind != argc - 2) {
1452 error_exit("Expecting two image file names");
1454 filename1 = argv[optind++];
1455 filename2 = argv[optind++];
1457 /* Initialize before goto out */
1458 qemu_progress_init(progress, 2.0);
1461 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1463 error_report("Invalid source cache option: %s", cache);
1468 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1475 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1484 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1485 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1486 total_size1 = blk_getlength(blk1);
1487 if (total_size1 < 0) {
1488 error_report("Can't get size of %s: %s",
1489 filename1, strerror(-total_size1));
1493 total_size2 = blk_getlength(blk2);
1494 if (total_size2 < 0) {
1495 error_report("Can't get size of %s: %s",
1496 filename2, strerror(-total_size2));
1500 total_size = MIN(total_size1, total_size2);
1501 progress_base = MAX(total_size1, total_size2);
1503 qemu_progress_print(0, 100);
1505 if (strict && total_size1 != total_size2) {
1507 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1511 while (offset < total_size) {
1512 int status1, status2;
1514 status1 = bdrv_block_status_above(bs1, NULL, offset,
1515 total_size1 - offset, &pnum1, NULL,
1519 error_report("Sector allocation test failed for %s", filename1);
1522 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1524 status2 = bdrv_block_status_above(bs2, NULL, offset,
1525 total_size2 - offset, &pnum2, NULL,
1529 error_report("Sector allocation test failed for %s", filename2);
1532 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1534 assert(pnum1 && pnum2);
1535 chunk = MIN(pnum1, pnum2);
1538 if (status1 != status2) {
1540 qprintf(quiet, "Strict mode: Offset %" PRId64
1541 " block status mismatch!\n", offset);
1545 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1547 } else if (allocated1 == allocated2) {
1551 chunk = MIN(chunk, IO_BUF_SIZE);
1552 ret = blk_pread(blk1, offset, chunk, buf1, 0);
1554 error_report("Error while reading offset %" PRId64
1556 offset, filename1, strerror(-ret));
1560 ret = blk_pread(blk2, offset, chunk, buf2, 0);
1562 error_report("Error while reading offset %" PRId64
1564 offset, filename2, strerror(-ret));
1568 ret = compare_buffers(buf1, buf2, chunk, 0, &pnum);
1569 if (ret || pnum != chunk) {
1570 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1571 offset + (ret ? 0 : pnum));
1577 chunk = MIN(chunk, IO_BUF_SIZE);
1579 ret = check_empty_sectors(blk1, offset, chunk,
1580 filename1, buf1, quiet);
1582 ret = check_empty_sectors(blk2, offset, chunk,
1583 filename2, buf1, quiet);
1590 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1593 if (total_size1 != total_size2) {
1594 BlockBackend *blk_over;
1595 const char *filename_over;
1597 qprintf(quiet, "Warning: Image size mismatch!\n");
1598 if (total_size1 > total_size2) {
1600 filename_over = filename1;
1603 filename_over = filename2;
1606 while (offset < progress_base) {
1607 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1608 progress_base - offset, &chunk,
1612 error_report("Sector allocation test failed for %s",
1617 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1618 chunk = MIN(chunk, IO_BUF_SIZE);
1619 ret = check_empty_sectors(blk_over, offset, chunk,
1620 filename_over, buf1, quiet);
1626 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1630 qprintf(quiet, "Images are identical.\n");
1640 qemu_progress_end();
1644 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1645 static void do_dirty_bitmap_merge(const char *dst_node, const char *dst_name,
1646 const char *src_node, const char *src_name,
1649 BlockDirtyBitmapOrStr *merge_src;
1650 BlockDirtyBitmapOrStrList *list = NULL;
1652 merge_src = g_new0(BlockDirtyBitmapOrStr, 1);
1653 merge_src->type = QTYPE_QDICT;
1654 merge_src->u.external.node = g_strdup(src_node);
1655 merge_src->u.external.name = g_strdup(src_name);
1656 QAPI_LIST_PREPEND(list, merge_src);
1657 qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
1658 qapi_free_BlockDirtyBitmapOrStrList(list);
1661 enum ImgConvertBlockStatus {
1667 #define MAX_COROUTINES 16
1668 #define CONVERT_THROTTLE_GROUP "img_convert"
1670 typedef struct ImgConvertState {
1672 int64_t *src_sectors;
1675 int64_t total_sectors;
1676 int64_t allocated_sectors;
1677 int64_t allocated_done;
1680 enum ImgConvertBlockStatus status;
1681 int64_t sector_next_status;
1682 BlockBackend *target;
1686 bool target_has_backing;
1687 int64_t target_backing_sectors; /* negative if unknown */
1694 size_t cluster_sectors;
1696 long num_coroutines;
1697 int running_coroutines;
1698 Coroutine *co[MAX_COROUTINES];
1699 int64_t wait_sector_num[MAX_COROUTINES];
1704 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1705 int *src_cur, int64_t *src_cur_offset)
1708 *src_cur_offset = 0;
1709 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1710 *src_cur_offset += s->src_sectors[*src_cur];
1712 assert(*src_cur < s->src_num);
1716 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1718 int64_t src_cur_offset;
1719 int ret, n, src_cur;
1720 bool post_backing_zero = false;
1722 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1724 assert(s->total_sectors > sector_num);
1725 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1727 if (s->target_backing_sectors >= 0) {
1728 if (sector_num >= s->target_backing_sectors) {
1729 post_backing_zero = true;
1730 } else if (sector_num + n > s->target_backing_sectors) {
1731 /* Split requests around target_backing_sectors (because
1732 * starting from there, zeros are handled differently) */
1733 n = s->target_backing_sectors - sector_num;
1737 if (s->sector_next_status <= sector_num) {
1738 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1741 BlockDriverState *src_bs = blk_bs(s->src[src_cur]);
1742 BlockDriverState *base;
1744 if (s->target_has_backing) {
1745 base = bdrv_cow_bs(bdrv_skip_filters(src_bs));
1751 count = n * BDRV_SECTOR_SIZE;
1753 ret = bdrv_block_status_above(src_bs, base, offset, count, &count,
1760 warn_report("error while reading block status at "
1761 "offset %" PRIu64 ": %s", offset,
1764 /* Just try to read the data, then */
1765 ret = BDRV_BLOCK_DATA;
1766 count = BDRV_SECTOR_SIZE;
1768 /* Retry on a shorter range */
1769 n = DIV_ROUND_UP(n, 4);
1772 error_report("error while reading block status at offset "
1773 "%" PRIu64 ": %s", offset, strerror(-ret));
1779 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1782 * Avoid that s->sector_next_status becomes unaligned to the source
1783 * request alignment and/or cluster size to avoid unnecessary read
1786 tail = (sector_num - src_cur_offset + n) % s->src_alignment[src_cur];
1791 if (ret & BDRV_BLOCK_ZERO) {
1792 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
1793 } else if (ret & BDRV_BLOCK_DATA) {
1794 s->status = BLK_DATA;
1796 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1799 s->sector_next_status = sector_num + n;
1802 n = MIN(n, s->sector_next_status - sector_num);
1803 if (s->status == BLK_DATA) {
1804 n = MIN(n, s->buf_sectors);
1807 /* We need to write complete clusters for compressed images, so if an
1808 * unallocated area is shorter than that, we must consider the whole
1809 * cluster allocated. */
1810 if (s->compressed) {
1811 if (n < s->cluster_sectors) {
1812 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1813 s->status = BLK_DATA;
1815 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1822 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1823 int nb_sectors, uint8_t *buf)
1825 uint64_t single_read_until = 0;
1828 assert(nb_sectors <= s->buf_sectors);
1829 while (nb_sectors > 0) {
1832 int64_t bs_sectors, src_cur_offset;
1835 /* In the case of compression with multiple source files, we can get a
1836 * nb_sectors that spreads into the next part. So we must be able to
1837 * read across multiple BDSes for one convert_read() call. */
1838 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1839 blk = s->src[src_cur];
1840 bs_sectors = s->src_sectors[src_cur];
1842 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1844 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1845 if (single_read_until > offset) {
1849 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
1853 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1857 warn_report("error while reading offset %" PRIu64
1858 ": %s", offset, strerror(-ret));
1860 memset(buf, 0, BDRV_SECTOR_SIZE);
1869 buf += n * BDRV_SECTOR_SIZE;
1876 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1877 int nb_sectors, uint8_t *buf,
1878 enum ImgConvertBlockStatus status)
1882 while (nb_sectors > 0) {
1884 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1887 case BLK_BACKING_FILE:
1888 /* If we have a backing file, leave clusters unallocated that are
1889 * unallocated in the source image, so that the backing file is
1890 * visible at the respective offset. */
1891 assert(s->target_has_backing);
1895 /* If we're told to keep the target fully allocated (-S 0) or there
1896 * is real non-zero data, we must write it. Otherwise we can treat
1897 * it as zero sectors.
1898 * Compressed clusters need to be written as a whole, so in that
1899 * case we can only save the write if the buffer is completely
1901 if (!s->min_sparse ||
1903 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1904 sector_num, s->alignment)) ||
1906 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1908 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1909 n << BDRV_SECTOR_BITS, buf, flags);
1918 if (s->has_zero_init) {
1919 assert(!s->target_has_backing);
1922 ret = blk_co_pwrite_zeroes(s->target,
1923 sector_num << BDRV_SECTOR_BITS,
1924 n << BDRV_SECTOR_BITS,
1925 BDRV_REQ_MAY_UNMAP);
1934 buf += n * BDRV_SECTOR_SIZE;
1940 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1945 while (nb_sectors > 0) {
1948 int64_t bs_sectors, src_cur_offset;
1951 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1952 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1953 blk = s->src[src_cur];
1954 bs_sectors = s->src_sectors[src_cur];
1956 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1958 ret = blk_co_copy_range(blk, offset, s->target,
1959 sector_num << BDRV_SECTOR_BITS,
1960 n << BDRV_SECTOR_BITS, 0, 0);
1971 static void coroutine_fn convert_co_do_copy(void *opaque)
1973 ImgConvertState *s = opaque;
1974 uint8_t *buf = NULL;
1978 for (i = 0; i < s->num_coroutines; i++) {
1979 if (s->co[i] == qemu_coroutine_self()) {
1986 s->running_coroutines++;
1987 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1992 enum ImgConvertBlockStatus status;
1995 qemu_co_mutex_lock(&s->lock);
1996 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1997 qemu_co_mutex_unlock(&s->lock);
2000 WITH_GRAPH_RDLOCK_GUARD() {
2001 n = convert_iteration_sectors(s, s->sector_num);
2004 qemu_co_mutex_unlock(&s->lock);
2008 /* save current sector and allocation status to local variables */
2009 sector_num = s->sector_num;
2011 if (!s->min_sparse && s->status == BLK_ZERO) {
2012 n = MIN(n, s->buf_sectors);
2014 /* increment global sector counter so that other coroutines can
2015 * already continue reading beyond this request */
2017 qemu_co_mutex_unlock(&s->lock);
2019 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
2020 s->allocated_done += n;
2021 qemu_progress_print(100.0 * s->allocated_done /
2022 s->allocated_sectors, 0);
2026 copy_range = s->copy_range && s->status == BLK_DATA;
2027 if (status == BLK_DATA && !copy_range) {
2028 ret = convert_co_read(s, sector_num, n, buf);
2030 error_report("error while reading at byte %lld: %s",
2031 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2034 } else if (!s->min_sparse && status == BLK_ZERO) {
2036 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
2039 if (s->wr_in_order) {
2040 /* keep writes in order */
2041 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
2042 s->wait_sector_num[index] = sector_num;
2043 qemu_coroutine_yield();
2045 s->wait_sector_num[index] = -1;
2048 if (s->ret == -EINPROGRESS) {
2050 WITH_GRAPH_RDLOCK_GUARD() {
2051 ret = convert_co_copy_range(s, sector_num, n);
2054 s->copy_range = false;
2058 ret = convert_co_write(s, sector_num, n, buf, status);
2061 error_report("error while writing at byte %lld: %s",
2062 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2067 if (s->wr_in_order) {
2068 /* reenter the coroutine that might have waited
2069 * for this write to complete */
2070 s->wr_offs = sector_num + n;
2071 for (i = 0; i < s->num_coroutines; i++) {
2072 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2074 * A -> B -> A cannot occur because A has
2075 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2076 * B will never enter A during this time window.
2078 qemu_coroutine_enter(s->co[i]);
2086 s->co[index] = NULL;
2087 s->running_coroutines--;
2088 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2089 /* the convert job finished successfully */
2094 static int convert_do_copy(ImgConvertState *s)
2097 int64_t sector_num = 0;
2099 /* Check whether we have zero initialisation or can get it efficiently */
2100 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2101 !s->target_has_backing) {
2102 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
2105 /* Allocate buffer for copied data. For compressed images, only one cluster
2106 * can be copied at a time. */
2107 if (s->compressed) {
2108 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2109 error_report("invalid cluster size");
2112 s->buf_sectors = s->cluster_sectors;
2115 while (sector_num < s->total_sectors) {
2116 n = convert_iteration_sectors(s, sector_num);
2120 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2122 s->allocated_sectors += n;
2128 s->sector_next_status = 0;
2129 s->ret = -EINPROGRESS;
2131 qemu_co_mutex_init(&s->lock);
2132 for (i = 0; i < s->num_coroutines; i++) {
2133 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2134 s->wait_sector_num[i] = -1;
2135 qemu_coroutine_enter(s->co[i]);
2138 while (s->running_coroutines) {
2139 main_loop_wait(false);
2142 if (s->compressed && !s->ret) {
2143 /* signal EOF to align */
2144 ret = blk_pwrite_compressed(s->target, 0, 0, NULL);
2153 /* Check that bitmaps can be copied, or output an error */
2154 static int convert_check_bitmaps(BlockDriverState *src, bool skip_broken)
2156 BdrvDirtyBitmap *bm;
2158 if (!bdrv_supports_persistent_dirty_bitmap(src)) {
2159 error_report("Source lacks bitmap support");
2162 FOR_EACH_DIRTY_BITMAP(src, bm) {
2163 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2166 if (!skip_broken && bdrv_dirty_bitmap_inconsistent(bm)) {
2167 error_report("Cannot copy inconsistent bitmap '%s'",
2168 bdrv_dirty_bitmap_name(bm));
2169 error_printf("Try --skip-broken-bitmaps, or "
2170 "use 'qemu-img bitmap --remove' to delete it\n");
2177 static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst,
2180 BdrvDirtyBitmap *bm;
2183 FOR_EACH_DIRTY_BITMAP(src, bm) {
2186 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2189 name = bdrv_dirty_bitmap_name(bm);
2190 if (skip_broken && bdrv_dirty_bitmap_inconsistent(bm)) {
2191 warn_report("Skipping inconsistent bitmap '%s'", name);
2194 qmp_block_dirty_bitmap_add(dst->node_name, name,
2195 true, bdrv_dirty_bitmap_granularity(bm),
2197 true, !bdrv_dirty_bitmap_enabled(bm),
2200 error_reportf_err(err, "Failed to create bitmap %s: ", name);
2204 do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2207 error_reportf_err(err, "Failed to populate bitmap %s: ", name);
2208 qmp_block_dirty_bitmap_remove(dst->node_name, name, NULL);
2216 #define MAX_BUF_SECTORS 32768
2218 static void set_rate_limit(BlockBackend *blk, int64_t rate_limit)
2222 throttle_config_init(&cfg);
2223 cfg.buckets[THROTTLE_BPS_WRITE].avg = rate_limit;
2225 blk_io_limits_enable(blk, CONVERT_THROTTLE_GROUP);
2226 blk_set_io_limits(blk, &cfg);
2229 static int img_convert(int argc, char **argv)
2231 int c, bs_i, flags, src_flags = BDRV_O_NO_SHARE;
2232 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
2233 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2234 *out_filename, *out_baseimg_param, *snapshot_name = NULL,
2235 *backing_fmt = NULL;
2236 BlockDriver *drv = NULL, *proto_drv = NULL;
2237 BlockDriverInfo bdi;
2238 BlockDriverState *out_bs;
2239 QemuOpts *opts = NULL, *sn_opts = NULL;
2240 QemuOptsList *create_opts = NULL;
2241 QDict *open_opts = NULL;
2242 char *options = NULL;
2243 Error *local_err = NULL;
2244 bool writethrough, src_writethrough, image_opts = false,
2245 skip_create = false, progress = false, tgt_image_opts = false;
2246 int64_t ret = -EINVAL;
2247 bool force_share = false;
2248 bool explict_min_sparse = false;
2249 bool bitmaps = false;
2250 bool skip_broken = false;
2251 int64_t rate_limit = 0;
2253 ImgConvertState s = (ImgConvertState) {
2254 /* Need at least 4k of zeros for sparse detection */
2256 .copy_range = false,
2257 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2258 .wr_in_order = true,
2259 .num_coroutines = 8,
2263 static const struct option long_options[] = {
2264 {"help", no_argument, 0, 'h'},
2265 {"object", required_argument, 0, OPTION_OBJECT},
2266 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2267 {"force-share", no_argument, 0, 'U'},
2268 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
2269 {"salvage", no_argument, 0, OPTION_SALVAGE},
2270 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
2271 {"bitmaps", no_argument, 0, OPTION_BITMAPS},
2272 {"skip-broken-bitmaps", no_argument, 0, OPTION_SKIP_BROKEN},
2275 c = getopt_long(argc, argv, ":hf:O:B:CcF:o:l:S:pt:T:qnm:WUr:",
2276 long_options, NULL);
2282 missing_argument(argv[optind - 1]);
2285 unrecognized_option(argv[optind - 1]);
2297 out_baseimg = optarg;
2300 s.copy_range = true;
2303 s.compressed = true;
2306 backing_fmt = optarg;
2309 if (accumulate_options(&options, optarg) < 0) {
2314 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2315 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2318 error_report("Failed in parsing snapshot param '%s'",
2323 snapshot_name = optarg;
2330 sval = cvtnum("buffer size for sparse output", optarg);
2333 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
2334 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2335 error_report("Invalid buffer size for sparse output specified. "
2336 "Valid sizes are multiples of %llu up to %llu. Select "
2337 "0 to disable sparse detection (fully allocates output).",
2338 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
2342 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2343 explict_min_sparse = true;
2362 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2363 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2364 error_report("Invalid number of coroutines. Allowed number of"
2365 " coroutines is between 1 and %d", MAX_COROUTINES);
2370 s.wr_in_order = false;
2376 rate_limit = cvtnum("rate limit", optarg);
2377 if (rate_limit < 0) {
2382 user_creatable_process_cmdline(optarg);
2384 case OPTION_IMAGE_OPTS:
2387 case OPTION_SALVAGE:
2390 case OPTION_TARGET_IMAGE_OPTS:
2391 tgt_image_opts = true;
2393 case OPTION_TARGET_IS_ZERO:
2395 * The user asserting that the target is blank has the
2396 * same effect as the target driver supporting zero
2399 s.has_zero_init = true;
2401 case OPTION_BITMAPS:
2404 case OPTION_SKIP_BROKEN:
2410 if (!out_fmt && !tgt_image_opts) {
2414 if (skip_broken && !bitmaps) {
2415 error_report("Use of --skip-broken-bitmaps requires --bitmaps");
2419 if (s.compressed && s.copy_range) {
2420 error_report("Cannot enable copy offloading when -c is used");
2424 if (explict_min_sparse && s.copy_range) {
2425 error_report("Cannot enable copy offloading when -S is used");
2429 if (s.copy_range && s.salvage) {
2430 error_report("Cannot use copy offloading in salvaging mode");
2434 if (tgt_image_opts && !skip_create) {
2435 error_report("--target-image-opts requires use of -n flag");
2439 if (skip_create && options) {
2440 error_report("-o has no effect when skipping image creation");
2444 if (s.has_zero_init && !skip_create) {
2445 error_report("--target-is-zero requires use of -n flag");
2449 s.src_num = argc - optind - 1;
2450 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2452 if (options && has_help_option(options)) {
2454 ret = print_block_option_help(out_filename, out_fmt);
2457 error_report("Option help requires a format be specified");
2462 if (s.src_num < 1) {
2463 error_report("Must specify image file name");
2467 /* ret is still -EINVAL until here */
2468 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2470 error_report("Invalid source cache option: %s", src_cache);
2474 /* Initialize before goto out */
2478 qemu_progress_init(progress, 1.0);
2479 qemu_progress_print(0, 100);
2481 s.src = g_new0(BlockBackend *, s.src_num);
2482 s.src_sectors = g_new(int64_t, s.src_num);
2483 s.src_alignment = g_new(int, s.src_num);
2485 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2486 BlockDriverState *src_bs;
2487 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2488 fmt, src_flags, src_writethrough, s.quiet,
2494 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2495 if (s.src_sectors[bs_i] < 0) {
2496 error_report("Could not get size of %s: %s",
2497 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2501 src_bs = blk_bs(s.src[bs_i]);
2502 s.src_alignment[bs_i] = DIV_ROUND_UP(src_bs->bl.request_alignment,
2504 if (!bdrv_get_info(src_bs, &bdi)) {
2505 s.src_alignment[bs_i] = MAX(s.src_alignment[bs_i],
2506 bdi.cluster_size / BDRV_SECTOR_SIZE);
2508 s.total_sectors += s.src_sectors[bs_i];
2512 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2513 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2514 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2516 } else if (snapshot_name != NULL) {
2517 if (s.src_num > 1) {
2518 error_report("No support for concatenating multiple snapshot");
2523 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2527 error_reportf_err(local_err, "Failed to load snapshot: ");
2533 /* Find driver and parse its options */
2534 drv = bdrv_find_format(out_fmt);
2536 error_report("Unknown file format '%s'", out_fmt);
2541 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2543 error_report_err(local_err);
2548 if (!drv->create_opts) {
2549 error_report("Format driver '%s' does not support image creation",
2555 if (!proto_drv->create_opts) {
2556 error_report("Protocol driver '%s' does not support image creation",
2557 proto_drv->format_name);
2562 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2563 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2565 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2567 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
2568 error_report_err(local_err);
2574 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
2575 s.total_sectors * BDRV_SECTOR_SIZE, &error_abort);
2576 ret = add_old_style_options(out_fmt, opts, out_baseimg, backing_fmt);
2582 /* Get backing file name if -o backing_file was used */
2583 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2584 if (out_baseimg_param) {
2585 out_baseimg = out_baseimg_param;
2587 s.target_has_backing = (bool) out_baseimg;
2589 if (s.has_zero_init && s.target_has_backing) {
2590 error_report("Cannot use --target-is-zero when the destination "
2591 "image has a backing file");
2595 if (s.src_num > 1 && out_baseimg) {
2596 error_report("Having a backing file for the target makes no sense when "
2597 "concatenating multiple input images");
2602 if (out_baseimg_param) {
2603 if (!qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT)) {
2604 error_report("Use of backing file requires explicit "
2611 /* Check if compression is supported */
2614 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2615 const char *encryptfmt =
2616 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2617 const char *preallocation =
2618 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2620 if (drv && !block_driver_can_compress(drv)) {
2621 error_report("Compression not supported for this file format");
2626 if (encryption || encryptfmt) {
2627 error_report("Compression and encryption not supported at "
2634 && strcmp(preallocation, "off"))
2636 error_report("Compression and preallocation not supported at "
2643 /* Determine if bitmaps need copying */
2645 if (s.src_num > 1) {
2646 error_report("Copying bitmaps only possible with single source");
2650 ret = convert_check_bitmaps(blk_bs(s.src[0]), skip_broken);
2657 * The later open call will need any decryption secrets, and
2658 * bdrv_create() will purge "opts", so extract them now before
2662 open_opts = qdict_new();
2663 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2665 /* Create the new image */
2666 ret = bdrv_create(drv, out_filename, opts, &local_err);
2668 error_reportf_err(local_err, "%s: error while converting %s: ",
2669 out_filename, out_fmt);
2674 s.target_is_new = !skip_create;
2676 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2677 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2679 error_report("Invalid cache option: %s", cache);
2683 if (flags & BDRV_O_NOCACHE) {
2685 * If we open the target with O_DIRECT, it may be necessary to
2686 * extend its size to align to the physical sector size.
2688 flags |= BDRV_O_RESIZE;
2692 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2693 flags, writethrough, s.quiet, false);
2695 /* TODO ultimately we should allow --target-image-opts
2696 * to be used even when -n is not given.
2697 * That has to wait for bdrv_create to be improved
2698 * to allow filenames in option syntax
2700 s.target = img_open_file(out_filename, open_opts, out_fmt,
2701 flags, writethrough, s.quiet, false);
2702 open_opts = NULL; /* blk_new_open will have freed it */
2708 out_bs = blk_bs(s.target);
2710 if (bitmaps && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2711 error_report("Format driver '%s' does not support bitmaps",
2712 out_bs->drv->format_name);
2717 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
2718 error_report("Compression not supported for this file format");
2723 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2724 * or discard_alignment of the out_bs is greater. Limit to
2725 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2726 s.buf_sectors = MIN(MAX_BUF_SECTORS,
2728 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2729 out_bs->bl.pdiscard_alignment >>
2730 BDRV_SECTOR_BITS)));
2732 /* try to align the write requests to the destination to avoid unnecessary
2734 s.alignment = MAX(pow2floor(s.min_sparse),
2735 DIV_ROUND_UP(out_bs->bl.request_alignment,
2737 assert(is_power_of_2(s.alignment));
2740 int64_t output_sectors = blk_nb_sectors(s.target);
2741 if (output_sectors < 0) {
2742 error_report("unable to get output image length: %s",
2743 strerror(-output_sectors));
2746 } else if (output_sectors < s.total_sectors) {
2747 error_report("output file is smaller than input file");
2753 if (s.target_has_backing && s.target_is_new) {
2754 /* Errors are treated as "backing length unknown" (which means
2755 * s.target_backing_sectors has to be negative, which it will
2756 * be automatically). The backing file length is used only
2757 * for optimizations, so such a case is not fatal. */
2758 s.target_backing_sectors =
2759 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs));
2761 s.target_backing_sectors = -1;
2764 ret = bdrv_get_info(out_bs, &bdi);
2767 error_report("could not get block driver info");
2771 s.compressed = s.compressed || bdi.needs_compressed_writes;
2772 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2776 set_rate_limit(s.target, rate_limit);
2779 ret = convert_do_copy(&s);
2781 /* Now copy the bitmaps */
2782 if (bitmaps && ret == 0) {
2783 ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs, skip_broken);
2788 qemu_progress_print(100, 0);
2790 qemu_progress_end();
2791 qemu_opts_del(opts);
2792 qemu_opts_free(create_opts);
2793 qobject_unref(open_opts);
2794 blk_unref(s.target);
2796 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2797 blk_unref(s.src[bs_i]);
2801 g_free(s.src_sectors);
2802 g_free(s.src_alignment);
2804 qemu_opts_del(sn_opts);
2811 static void dump_snapshots(BlockDriverState *bs)
2813 QEMUSnapshotInfo *sn_tab, *sn;
2816 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2819 printf("Snapshot list:\n");
2820 bdrv_snapshot_dump(NULL);
2822 for(i = 0; i < nb_sns; i++) {
2824 bdrv_snapshot_dump(sn);
2830 static void dump_json_block_graph_info_list(BlockGraphInfoList *list)
2834 Visitor *v = qobject_output_visitor_new(&obj);
2836 visit_type_BlockGraphInfoList(v, NULL, &list, &error_abort);
2837 visit_complete(v, &obj);
2838 str = qobject_to_json_pretty(obj, true);
2839 assert(str != NULL);
2840 printf("%s\n", str->str);
2843 g_string_free(str, true);
2846 static void dump_json_block_graph_info(BlockGraphInfo *info)
2850 Visitor *v = qobject_output_visitor_new(&obj);
2852 visit_type_BlockGraphInfo(v, NULL, &info, &error_abort);
2853 visit_complete(v, &obj);
2854 str = qobject_to_json_pretty(obj, true);
2855 assert(str != NULL);
2856 printf("%s\n", str->str);
2859 g_string_free(str, true);
2862 static void dump_human_image_info(BlockGraphInfo *info, int indentation,
2865 BlockChildInfoList *children_list;
2867 bdrv_node_info_dump(qapi_BlockGraphInfo_base(info), indentation,
2868 info->children == NULL);
2870 for (children_list = info->children; children_list;
2871 children_list = children_list->next)
2873 BlockChildInfo *child = children_list->value;
2874 g_autofree char *child_path = NULL;
2876 printf("%*sChild node '%s%s':\n",
2877 indentation * 4, "", path, child->name);
2878 child_path = g_strdup_printf("%s%s/", path, child->name);
2879 dump_human_image_info(child->info, indentation + 1, child_path);
2883 static void dump_human_image_info_list(BlockGraphInfoList *list)
2885 BlockGraphInfoList *elem;
2888 for (elem = list; elem; elem = elem->next) {
2894 dump_human_image_info(elem->value, 0, "/");
2898 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2900 return strcmp(a, b) == 0;
2904 * Open an image file chain and return an BlockGraphInfoList
2906 * @filename: topmost image filename
2907 * @fmt: topmost image format (may be NULL to autodetect)
2908 * @chain: true - enumerate entire backing file chain
2909 * false - only topmost image file
2911 * Returns a list of BlockNodeInfo objects or NULL if there was an error
2912 * opening an image file. If there was an error a message will have been
2913 * printed to stderr.
2915 static BlockGraphInfoList *collect_image_info_list(bool image_opts,
2916 const char *filename,
2918 bool chain, bool force_share)
2920 BlockGraphInfoList *head = NULL;
2921 BlockGraphInfoList **tail = &head;
2922 GHashTable *filenames;
2925 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2929 BlockDriverState *bs;
2930 BlockGraphInfo *info;
2932 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2933 error_report("Backing file '%s' creates an infinite loop.",
2937 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2939 blk = img_open(image_opts, filename, fmt,
2940 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2948 * Note that the returned BlockGraphInfo object will not have
2949 * information about this image's backing node, because we have opened
2950 * it with BDRV_O_NO_BACKING. Printing this object will therefore not
2951 * duplicate the backing chain information that we obtain by walking
2952 * the chain manually here.
2954 bdrv_graph_rdlock_main_loop();
2955 bdrv_query_block_graph_info(bs, &info, &err);
2956 bdrv_graph_rdunlock_main_loop();
2959 error_report_err(err);
2964 QAPI_LIST_APPEND(tail, info);
2968 /* Clear parameters that only apply to the topmost image */
2969 filename = fmt = NULL;
2973 if (info->full_backing_filename) {
2974 filename = info->full_backing_filename;
2975 } else if (info->backing_filename) {
2976 error_report("Could not determine absolute backing filename,"
2977 " but backing filename '%s' present",
2978 info->backing_filename);
2981 if (info->backing_filename_format) {
2982 fmt = info->backing_filename_format;
2986 g_hash_table_destroy(filenames);
2990 qapi_free_BlockGraphInfoList(head);
2991 g_hash_table_destroy(filenames);
2995 static int img_info(int argc, char **argv)
2998 OutputFormat output_format = OFORMAT_HUMAN;
3000 const char *filename, *fmt, *output;
3001 BlockGraphInfoList *list;
3002 bool image_opts = false;
3003 bool force_share = false;
3008 int option_index = 0;
3009 static const struct option long_options[] = {
3010 {"help", no_argument, 0, 'h'},
3011 {"format", required_argument, 0, 'f'},
3012 {"output", required_argument, 0, OPTION_OUTPUT},
3013 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
3014 {"object", required_argument, 0, OPTION_OBJECT},
3015 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3016 {"force-share", no_argument, 0, 'U'},
3019 c = getopt_long(argc, argv, ":f:hU",
3020 long_options, &option_index);
3026 missing_argument(argv[optind - 1]);
3029 unrecognized_option(argv[optind - 1]);
3043 case OPTION_BACKING_CHAIN:
3047 user_creatable_process_cmdline(optarg);
3049 case OPTION_IMAGE_OPTS:
3054 if (optind != argc - 1) {
3055 error_exit("Expecting one image file name");
3057 filename = argv[optind++];
3059 if (output && !strcmp(output, "json")) {
3060 output_format = OFORMAT_JSON;
3061 } else if (output && !strcmp(output, "human")) {
3062 output_format = OFORMAT_HUMAN;
3063 } else if (output) {
3064 error_report("--output must be used with human or json as argument.");
3068 list = collect_image_info_list(image_opts, filename, fmt, chain,
3074 switch (output_format) {
3076 dump_human_image_info_list(list);
3080 dump_json_block_graph_info_list(list);
3082 dump_json_block_graph_info(list->value);
3087 qapi_free_BlockGraphInfoList(list);
3091 static int dump_map_entry(OutputFormat output_format, MapEntry *e,
3094 switch (output_format) {
3096 if (e->data && !e->has_offset) {
3097 error_report("File contains external, encrypted or compressed clusters.");
3100 if (e->data && !e->zero) {
3101 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
3102 e->start, e->length,
3103 e->has_offset ? e->offset : 0,
3106 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3107 * Modify the flags here to allow more coalescing.
3109 if (next && (!next->data || next->zero)) {
3115 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
3116 " \"depth\": %"PRId64", \"present\": %s, \"zero\": %s,"
3117 " \"data\": %s, \"compressed\": %s",
3118 e->start, e->length, e->depth,
3119 e->present ? "true" : "false",
3120 e->zero ? "true" : "false",
3121 e->data ? "true" : "false",
3122 e->compressed ? "true" : "false");
3123 if (e->has_offset) {
3124 printf(", \"offset\": %"PRId64"", e->offset);
3136 static int get_block_status(BlockDriverState *bs, int64_t offset,
3137 int64_t bytes, MapEntry *e)
3141 BlockDriverState *file;
3144 char *filename = NULL;
3146 /* As an optimization, we could cache the current range of unallocated
3147 * clusters in each file of the chain, and avoid querying the same
3153 bs = bdrv_skip_filters(bs);
3154 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
3159 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
3162 bs = bdrv_cow_bs(bs);
3171 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3173 if (file && has_offset) {
3174 bdrv_graph_rdlock_main_loop();
3175 bdrv_refresh_filename(file);
3176 bdrv_graph_rdunlock_main_loop();
3177 filename = file->filename;
3183 .data = !!(ret & BDRV_BLOCK_DATA),
3184 .zero = !!(ret & BDRV_BLOCK_ZERO),
3185 .compressed = !!(ret & BDRV_BLOCK_COMPRESSED),
3187 .has_offset = has_offset,
3189 .present = !!(ret & BDRV_BLOCK_ALLOCATED),
3190 .filename = filename,
3196 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3198 if (curr->length == 0) {
3201 if (curr->zero != next->zero ||
3202 curr->data != next->data ||
3203 curr->compressed != next->compressed ||
3204 curr->depth != next->depth ||
3205 curr->present != next->present ||
3206 !curr->filename != !next->filename ||
3207 curr->has_offset != next->has_offset) {
3210 if (curr->filename && strcmp(curr->filename, next->filename)) {
3213 if (curr->has_offset && curr->offset + curr->length != next->offset) {
3219 static int img_map(int argc, char **argv)
3222 OutputFormat output_format = OFORMAT_HUMAN;
3224 BlockDriverState *bs;
3225 const char *filename, *fmt, *output;
3227 MapEntry curr = { .length = 0 }, next;
3229 bool image_opts = false;
3230 bool force_share = false;
3231 int64_t start_offset = 0;
3232 int64_t max_length = -1;
3237 int option_index = 0;
3238 static const struct option long_options[] = {
3239 {"help", no_argument, 0, 'h'},
3240 {"format", required_argument, 0, 'f'},
3241 {"output", required_argument, 0, OPTION_OUTPUT},
3242 {"object", required_argument, 0, OPTION_OBJECT},
3243 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3244 {"force-share", no_argument, 0, 'U'},
3245 {"start-offset", required_argument, 0, 's'},
3246 {"max-length", required_argument, 0, 'l'},
3249 c = getopt_long(argc, argv, ":f:s:l:hU",
3250 long_options, &option_index);
3256 missing_argument(argv[optind - 1]);
3259 unrecognized_option(argv[optind - 1]);
3274 start_offset = cvtnum("start offset", optarg);
3275 if (start_offset < 0) {
3280 max_length = cvtnum("max length", optarg);
3281 if (max_length < 0) {
3286 user_creatable_process_cmdline(optarg);
3288 case OPTION_IMAGE_OPTS:
3293 if (optind != argc - 1) {
3294 error_exit("Expecting one image file name");
3296 filename = argv[optind];
3298 if (output && !strcmp(output, "json")) {
3299 output_format = OFORMAT_JSON;
3300 } else if (output && !strcmp(output, "human")) {
3301 output_format = OFORMAT_HUMAN;
3302 } else if (output) {
3303 error_report("--output must be used with human or json as argument.");
3307 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
3313 if (output_format == OFORMAT_HUMAN) {
3314 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3315 } else if (output_format == OFORMAT_JSON) {
3319 length = blk_getlength(blk);
3321 error_report("Failed to get size for '%s'", filename);
3324 if (max_length != -1) {
3325 length = MIN(start_offset + max_length, length);
3328 curr.start = start_offset;
3329 while (curr.start + curr.length < length) {
3330 int64_t offset = curr.start + curr.length;
3331 int64_t n = length - offset;
3333 ret = get_block_status(bs, offset, n, &next);
3335 error_report("Could not read file metadata: %s", strerror(-ret));
3339 if (entry_mergeable(&curr, &next)) {
3340 curr.length += next.length;
3344 if (curr.length > 0) {
3345 ret = dump_map_entry(output_format, &curr, &next);
3353 ret = dump_map_entry(output_format, &curr, NULL);
3354 if (output_format == OFORMAT_JSON) {
3363 #define SNAPSHOT_LIST 1
3364 #define SNAPSHOT_CREATE 2
3365 #define SNAPSHOT_APPLY 3
3366 #define SNAPSHOT_DELETE 4
3368 static int img_snapshot(int argc, char **argv)
3371 BlockDriverState *bs;
3372 QEMUSnapshotInfo sn;
3373 char *filename, *snapshot_name = NULL;
3374 int c, ret = 0, bdrv_oflags;
3378 bool image_opts = false;
3379 bool force_share = false;
3382 bdrv_oflags = BDRV_O_RDWR;
3383 /* Parse commandline parameters */
3385 static const struct option long_options[] = {
3386 {"help", no_argument, 0, 'h'},
3387 {"object", required_argument, 0, OPTION_OBJECT},
3388 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3389 {"force-share", no_argument, 0, 'U'},
3392 c = getopt_long(argc, argv, ":la:c:d:hqU",
3393 long_options, NULL);
3399 missing_argument(argv[optind - 1]);
3402 unrecognized_option(argv[optind - 1]);
3409 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3412 action = SNAPSHOT_LIST;
3413 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
3417 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3420 action = SNAPSHOT_APPLY;
3421 snapshot_name = optarg;
3425 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3428 action = SNAPSHOT_CREATE;
3429 snapshot_name = optarg;
3433 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3436 action = SNAPSHOT_DELETE;
3437 snapshot_name = optarg;
3446 user_creatable_process_cmdline(optarg);
3448 case OPTION_IMAGE_OPTS:
3454 if (optind != argc - 1) {
3455 error_exit("Expecting one image file name");
3457 filename = argv[optind++];
3459 /* Open the image */
3460 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3467 /* Perform the requested action */
3473 case SNAPSHOT_CREATE:
3474 memset(&sn, 0, sizeof(sn));
3475 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3477 rt = g_get_real_time();
3478 sn.date_sec = rt / G_USEC_PER_SEC;
3479 sn.date_nsec = (rt % G_USEC_PER_SEC) * 1000;
3481 bdrv_graph_rdlock_main_loop();
3482 ret = bdrv_snapshot_create(bs, &sn);
3483 bdrv_graph_rdunlock_main_loop();
3486 error_report("Could not create snapshot '%s': %s",
3487 snapshot_name, strerror(-ret));
3491 case SNAPSHOT_APPLY:
3492 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3494 error_reportf_err(err, "Could not apply snapshot '%s': ",
3499 case SNAPSHOT_DELETE:
3500 bdrv_graph_rdlock_main_loop();
3501 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3503 error_report("Could not delete snapshot '%s': snapshot not "
3504 "found", snapshot_name);
3507 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3509 error_reportf_err(err, "Could not delete snapshot '%s': ",
3514 bdrv_graph_rdunlock_main_loop();
3526 static int img_rebase(int argc, char **argv)
3528 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3529 uint8_t *buf_old = NULL;
3530 uint8_t *buf_new = NULL;
3531 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
3532 BlockDriverState *unfiltered_bs;
3533 BlockDriverInfo bdi = {0};
3535 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3536 int c, flags, src_flags, ret;
3537 bool writethrough, src_writethrough;
3539 bool force_share = false;
3542 Error *local_err = NULL;
3543 bool image_opts = false;
3544 int64_t write_align;
3546 /* Parse commandline parameters */
3548 cache = BDRV_DEFAULT_CACHE;
3549 src_cache = BDRV_DEFAULT_CACHE;
3553 static const struct option long_options[] = {
3554 {"help", no_argument, 0, 'h'},
3555 {"object", required_argument, 0, OPTION_OBJECT},
3556 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3557 {"force-share", no_argument, 0, 'U'},
3560 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3561 long_options, NULL);
3567 missing_argument(argv[optind - 1]);
3570 unrecognized_option(argv[optind - 1]);
3579 out_basefmt = optarg;
3582 out_baseimg = optarg;
3600 user_creatable_process_cmdline(optarg);
3602 case OPTION_IMAGE_OPTS:
3615 if (optind != argc - 1) {
3616 error_exit("Expecting one image file name");
3618 if (!unsafe && !out_baseimg) {
3619 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3621 filename = argv[optind++];
3623 qemu_progress_init(progress, 2.0);
3624 qemu_progress_print(0, 100);
3626 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3627 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3629 error_report("Invalid cache option: %s", cache);
3634 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3636 error_report("Invalid source cache option: %s", src_cache);
3640 /* The source files are opened read-only, don't care about WCE */
3641 assert((src_flags & BDRV_O_RDWR) == 0);
3642 (void) src_writethrough;
3647 * Ignore the old backing file for unsafe rebase in case we want to correct
3648 * the reference to a renamed or moved backing file.
3650 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3658 unfiltered_bs = bdrv_skip_filters(bs);
3660 if (out_basefmt != NULL) {
3661 if (bdrv_find_format(out_basefmt) == NULL) {
3662 error_report("Invalid format name: '%s'", out_basefmt);
3669 * We need overlay subcluster size to make sure write requests are
3672 ret = bdrv_get_info(unfiltered_bs, &bdi);
3674 error_report("could not get block driver info");
3676 } else if (bdi.subcluster_size == 0) {
3677 bdi.subcluster_size = 1;
3680 write_align = bdi.subcluster_size;
3682 /* For safe rebasing we need to compare old and new backing file */
3684 QDict *options = NULL;
3685 BlockDriverState *base_bs = bdrv_cow_bs(unfiltered_bs);
3688 blk_old_backing = blk_new(qemu_get_aio_context(),
3689 BLK_PERM_CONSISTENT_READ,
3691 ret = blk_insert_bs(blk_old_backing, base_bs,
3694 error_reportf_err(local_err,
3695 "Could not reuse old backing file '%s': ",
3700 blk_old_backing = NULL;
3703 if (out_baseimg[0]) {
3704 const char *overlay_filename;
3705 char *out_real_path;
3707 options = qdict_new();
3709 qdict_put_str(options, "driver", out_basefmt);
3712 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3715 bdrv_graph_rdlock_main_loop();
3716 bdrv_refresh_filename(bs);
3717 bdrv_graph_rdunlock_main_loop();
3718 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3721 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3725 qobject_unref(options);
3726 error_reportf_err(local_err,
3727 "Could not resolve backing filename: ");
3733 * Find out whether we rebase an image on top of a previous image
3736 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
3737 if (prefix_chain_bs) {
3738 qobject_unref(options);
3739 g_free(out_real_path);
3741 blk_new_backing = blk_new(qemu_get_aio_context(),
3742 BLK_PERM_CONSISTENT_READ,
3744 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3747 error_reportf_err(local_err,
3748 "Could not reuse backing file '%s': ",
3753 blk_new_backing = blk_new_open(out_real_path, NULL,
3754 options, src_flags, &local_err);
3755 g_free(out_real_path);
3756 if (!blk_new_backing) {
3757 error_reportf_err(local_err,
3758 "Could not open new backing file '%s': ",
3768 * Check each unallocated cluster in the COW file. If it is unallocated,
3769 * accesses go to the backing file. We must therefore compare this cluster
3770 * in the old and new backing file, and if they differ we need to copy it
3771 * from the old backing file into the COW file.
3773 * If qemu-img crashes during this step, no harm is done. The content of
3774 * the image is the same as the original one at any time.
3778 int64_t old_backing_size = 0;
3779 int64_t new_backing_size = 0;
3781 int64_t n, n_old = 0, n_new = 0;
3782 float local_progress = 0;
3784 if (blk_old_backing && bdrv_opt_mem_align(blk_bs(blk_old_backing)) >
3785 bdrv_opt_mem_align(blk_bs(blk))) {
3786 buf_old = blk_blockalign(blk_old_backing, IO_BUF_SIZE);
3788 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3790 buf_new = blk_blockalign(blk_new_backing, IO_BUF_SIZE);
3792 size = blk_getlength(blk);
3794 error_report("Could not get size of '%s': %s",
3795 filename, strerror(-size));
3799 if (blk_old_backing) {
3800 old_backing_size = blk_getlength(blk_old_backing);
3801 if (old_backing_size < 0) {
3802 char backing_name[PATH_MAX];
3804 bdrv_get_backing_filename(bs, backing_name,
3805 sizeof(backing_name));
3806 error_report("Could not get size of '%s': %s",
3807 backing_name, strerror(-old_backing_size));
3812 if (blk_new_backing) {
3813 new_backing_size = blk_getlength(blk_new_backing);
3814 if (new_backing_size < 0) {
3815 error_report("Could not get size of '%s': %s",
3816 out_baseimg, strerror(-new_backing_size));
3823 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3826 for (offset = 0; offset < size; offset += n) {
3827 bool old_backing_eof = false;
3830 /* How many bytes can we handle with the next read? */
3831 n = MIN(IO_BUF_SIZE, size - offset);
3833 /* If the cluster is allocated, we don't need to take action */
3834 ret = bdrv_is_allocated(unfiltered_bs, offset, n, &n);
3836 error_report("error while reading image metadata: %s",
3844 if (prefix_chain_bs) {
3848 * If cluster wasn't changed since prefix_chain, we don't need
3851 ret = bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs),
3852 prefix_chain_bs, false,
3855 error_report("error while reading image metadata: %s",
3864 * If we've reached EOF of the old backing, it means that
3865 * offsets beyond the old backing size were read as zeroes.
3866 * Now we will need to explicitly zero the cluster in
3867 * order to preserve that state after the rebase.
3874 * At this point we know that the region [offset; offset + n)
3875 * is unallocated within the target image. This region might be
3876 * unaligned to the target image's (sub)cluster boundaries, as
3877 * old backing may have smaller clusters (or have subclusters).
3878 * We extend it to the aligned boundaries to avoid CoW on
3879 * partial writes in blk_pwrite(),
3881 n += offset - QEMU_ALIGN_DOWN(offset, write_align);
3882 offset = QEMU_ALIGN_DOWN(offset, write_align);
3883 n += QEMU_ALIGN_UP(offset + n, write_align) - (offset + n);
3884 n = MIN(n, size - offset);
3885 assert(!bdrv_is_allocated(unfiltered_bs, offset, n, &n_alloc) &&
3889 * Much like with the target image, we'll try to read as much
3890 * of the old and new backings as we can.
3892 n_old = MIN(n, MAX(0, old_backing_size - (int64_t) offset));
3893 n_new = MIN(n, MAX(0, new_backing_size - (int64_t) offset));
3896 * Read old and new backing file and take into consideration that
3897 * backing files may be smaller than the COW image.
3899 memset(buf_old + n_old, 0, n - n_old);
3901 old_backing_eof = true;
3903 ret = blk_pread(blk_old_backing, offset, n_old, buf_old, 0);
3905 error_report("error while reading from old backing file");
3910 memset(buf_new + n_new, 0, n - n_new);
3912 ret = blk_pread(blk_new_backing, offset, n_new, buf_new, 0);
3914 error_report("error while reading from new backing file");
3919 /* If they differ, we need to write to the COW file */
3920 uint64_t written = 0;
3922 while (written < n) {
3925 if (compare_buffers(buf_old + written, buf_new + written,
3926 n - written, write_align, &pnum))
3928 if (old_backing_eof) {
3929 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3931 assert(written + pnum <= IO_BUF_SIZE);
3932 ret = blk_pwrite(blk, offset + written, pnum,
3933 buf_old + written, 0);
3936 error_report("Error while writing to COW image: %s",
3943 if (offset + written >= old_backing_size) {
3944 old_backing_eof = true;
3947 qemu_progress_print(local_progress, 100);
3952 * Change the backing file. All clusters that are different from the old
3953 * backing file are overwritten in the COW file now, so the visible content
3954 * doesn't change when we switch the backing file.
3956 if (out_baseimg && *out_baseimg) {
3957 ret = bdrv_change_backing_file(unfiltered_bs, out_baseimg, out_basefmt,
3960 ret = bdrv_change_backing_file(unfiltered_bs, NULL, NULL, false);
3963 if (ret == -ENOSPC) {
3964 error_report("Could not change the backing file to '%s': No "
3965 "space left in the file header", out_baseimg);
3966 } else if (ret == -EINVAL && out_baseimg && !out_basefmt) {
3967 error_report("Could not change the backing file to '%s': backing "
3968 "format must be specified", out_baseimg);
3969 } else if (ret < 0) {
3970 error_report("Could not change the backing file to '%s': %s",
3971 out_baseimg, strerror(-ret));
3974 qemu_progress_print(100, 0);
3976 * TODO At this point it is possible to check if any clusters that are
3977 * allocated in the COW file are the same in the backing file. If so, they
3978 * could be dropped from the COW file. Don't do this before switching the
3979 * backing file, in case of a crash this would lead to corruption.
3982 qemu_progress_end();
3985 blk_unref(blk_old_backing);
3986 blk_unref(blk_new_backing);
3988 qemu_vfree(buf_old);
3989 qemu_vfree(buf_new);
3998 static int img_resize(int argc, char **argv)
4001 int c, ret, relative;
4002 const char *filename, *fmt, *size;
4003 int64_t n, total_size, current_size;
4005 BlockBackend *blk = NULL;
4006 PreallocMode prealloc = PREALLOC_MODE_OFF;
4009 static QemuOptsList resize_options = {
4010 .name = "resize_options",
4011 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
4014 .name = BLOCK_OPT_SIZE,
4015 .type = QEMU_OPT_SIZE,
4016 .help = "Virtual disk size"
4022 bool image_opts = false;
4023 bool shrink = false;
4025 /* Remove size from argv manually so that negative numbers are not treated
4026 * as options by getopt. */
4028 error_exit("Not enough arguments");
4032 size = argv[--argc];
4034 /* Parse getopt arguments */
4037 static const struct option long_options[] = {
4038 {"help", no_argument, 0, 'h'},
4039 {"object", required_argument, 0, OPTION_OBJECT},
4040 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4041 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
4042 {"shrink", no_argument, 0, OPTION_SHRINK},
4045 c = getopt_long(argc, argv, ":f:hq",
4046 long_options, NULL);
4052 missing_argument(argv[optind - 1]);
4055 unrecognized_option(argv[optind - 1]);
4067 user_creatable_process_cmdline(optarg);
4069 case OPTION_IMAGE_OPTS:
4072 case OPTION_PREALLOCATION:
4073 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
4074 PREALLOC_MODE__MAX, NULL);
4075 if (prealloc == PREALLOC_MODE__MAX) {
4076 error_report("Invalid preallocation mode '%s'", optarg);
4085 if (optind != argc - 1) {
4086 error_exit("Expecting image file name and size");
4088 filename = argv[optind++];
4090 /* Choose grow, shrink, or absolute resize mode */
4106 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
4107 if (!qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err)) {
4108 error_report_err(err);
4110 qemu_opts_del(param);
4113 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
4114 qemu_opts_del(param);
4116 blk = img_open(image_opts, filename, fmt,
4117 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
4124 current_size = blk_getlength(blk);
4125 if (current_size < 0) {
4126 error_report("Failed to inquire current image length: %s",
4127 strerror(-current_size));
4133 total_size = current_size + n * relative;
4137 if (total_size <= 0) {
4138 error_report("New image size must be positive");
4143 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
4144 error_report("Preallocation can only be used for growing images");
4149 if (total_size < current_size && !shrink) {
4150 error_report("Use the --shrink option to perform a shrink operation.");
4151 warn_report("Shrinking an image will delete all data beyond the "
4152 "shrunken image's end. Before performing such an "
4153 "operation, make sure there is no important data there.");
4159 * The user expects the image to have the desired size after
4160 * resizing, so pass @exact=true. It is of no use to report
4161 * success when the image has not actually been resized.
4163 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
4165 qprintf(quiet, "Image resized.\n");
4167 error_report_err(err);
4177 static void amend_status_cb(BlockDriverState *bs,
4178 int64_t offset, int64_t total_work_size,
4181 qemu_progress_print(100.f * offset / total_work_size, 0);
4184 static int print_amend_option_help(const char *format)
4188 GRAPH_RDLOCK_GUARD_MAINLOOP();
4190 /* Find driver and parse its options */
4191 drv = bdrv_find_format(format);
4193 error_report("Unknown file format '%s'", format);
4197 if (!drv->bdrv_amend_options) {
4198 error_report("Format driver '%s' does not support option amendment",
4203 /* Every driver supporting amendment must have amend_opts */
4204 assert(drv->amend_opts);
4206 printf("Amend options for '%s':\n", format);
4207 qemu_opts_print_help(drv->amend_opts, false);
4211 static int img_amend(int argc, char **argv)
4215 char *options = NULL;
4216 QemuOptsList *amend_opts = NULL;
4217 QemuOpts *opts = NULL;
4218 const char *fmt = NULL, *filename, *cache;
4221 bool quiet = false, progress = false;
4222 BlockBackend *blk = NULL;
4223 BlockDriverState *bs = NULL;
4224 bool image_opts = false;
4227 cache = BDRV_DEFAULT_CACHE;
4229 static const struct option long_options[] = {
4230 {"help", no_argument, 0, 'h'},
4231 {"object", required_argument, 0, OPTION_OBJECT},
4232 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4233 {"force", no_argument, 0, OPTION_FORCE},
4236 c = getopt_long(argc, argv, ":ho:f:t:pq",
4237 long_options, NULL);
4244 missing_argument(argv[optind - 1]);
4247 unrecognized_option(argv[optind - 1]);
4253 if (accumulate_options(&options, optarg) < 0) {
4255 goto out_no_progress;
4271 user_creatable_process_cmdline(optarg);
4273 case OPTION_IMAGE_OPTS:
4283 error_exit("Must specify options (-o)");
4289 qemu_progress_init(progress, 1.0);
4291 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4292 if (fmt && has_help_option(options)) {
4293 /* If a format is explicitly specified (and possibly no filename is
4294 * given), print option help here */
4295 ret = print_amend_option_help(fmt);
4299 if (optind != argc - 1) {
4300 error_report("Expecting one image file name");
4305 flags = BDRV_O_RDWR;
4306 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
4308 error_report("Invalid cache option: %s", cache);
4312 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4320 fmt = bs->drv->format_name;
4322 if (has_help_option(options)) {
4323 /* If the format was auto-detected, print option help here */
4324 ret = print_amend_option_help(fmt);
4328 bdrv_graph_rdlock_main_loop();
4329 if (!bs->drv->bdrv_amend_options) {
4330 error_report("Format driver '%s' does not support option amendment",
4332 bdrv_graph_rdunlock_main_loop();
4337 /* Every driver supporting amendment must have amend_opts */
4338 assert(bs->drv->amend_opts);
4340 amend_opts = qemu_opts_append(amend_opts, bs->drv->amend_opts);
4341 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
4342 if (!qemu_opts_do_parse(opts, options, NULL, &err)) {
4343 /* Try to parse options using the create options */
4344 amend_opts = qemu_opts_append(amend_opts, bs->drv->create_opts);
4345 qemu_opts_del(opts);
4346 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
4347 if (qemu_opts_do_parse(opts, options, NULL, NULL)) {
4348 error_append_hint(&err,
4349 "This option is only supported for image creation\n");
4352 bdrv_graph_rdunlock_main_loop();
4353 error_report_err(err);
4358 /* In case the driver does not call amend_status_cb() */
4359 qemu_progress_print(0.f, 0);
4360 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, force, &err);
4361 qemu_progress_print(100.f, 0);
4362 bdrv_graph_rdunlock_main_loop();
4365 error_report_err(err);
4370 qemu_progress_end();
4374 qemu_opts_del(opts);
4375 qemu_opts_free(amend_opts);
4384 typedef struct BenchData {
4386 uint64_t image_size;
4393 bool drain_on_flush;
4402 static void bench_undrained_flush_cb(void *opaque, int ret)
4405 error_report("Failed flush request: %s", strerror(-ret));
4410 static void bench_cb(void *opaque, int ret)
4412 BenchData *b = opaque;
4416 error_report("Failed request: %s", strerror(-ret));
4421 /* Just finished a flush with drained queue: Start next requests */
4422 assert(b->in_flight == 0);
4423 b->in_flush = false;
4424 } else if (b->in_flight > 0) {
4425 int remaining = b->n - b->in_flight;
4430 /* Time for flush? Drain queue if requested, then flush */
4431 if (b->flush_interval && remaining % b->flush_interval == 0) {
4432 if (!b->in_flight || !b->drain_on_flush) {
4433 BlockCompletionFunc *cb;
4435 if (b->drain_on_flush) {
4439 cb = bench_undrained_flush_cb;
4442 acb = blk_aio_flush(b->blk, cb, b);
4444 error_report("Failed to issue flush request");
4448 if (b->drain_on_flush) {
4454 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4455 int64_t offset = b->offset;
4456 /* blk_aio_* might look for completed I/Os and kick bench_cb
4457 * again, so make sure this operation is counted by in_flight
4458 * and b->offset is ready for the next submission.
4461 b->offset += b->step;
4462 b->offset %= b->image_size;
4464 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
4466 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
4469 error_report("Failed to issue request");
4475 static int img_bench(int argc, char **argv)
4478 const char *fmt = NULL, *filename;
4480 bool image_opts = false;
4481 bool is_write = false;
4485 size_t bufsize = 4096;
4488 int flush_interval = 0;
4489 bool drain_on_flush = true;
4491 BlockBackend *blk = NULL;
4492 BenchData data = {};
4494 bool writethrough = false;
4495 struct timeval t1, t2;
4497 bool force_share = false;
4498 size_t buf_size = 0;
4501 static const struct option long_options[] = {
4502 {"help", no_argument, 0, 'h'},
4503 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
4504 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4505 {"pattern", required_argument, 0, OPTION_PATTERN},
4506 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
4507 {"force-share", no_argument, 0, 'U'},
4510 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4518 missing_argument(argv[optind - 1]);
4521 unrecognized_option(argv[optind - 1]);
4530 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4531 error_report("Invalid request count specified");
4541 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4542 error_report("Invalid queue depth specified");
4552 flags |= BDRV_O_NATIVE_AIO;
4555 ret = bdrv_parse_aio(optarg, &flags);
4557 error_report("Invalid aio option: %s", optarg);
4564 offset = cvtnum("offset", optarg);
4578 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4590 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4599 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4601 error_report("Invalid cache mode");
4607 flags |= BDRV_O_RDWR;
4613 case OPTION_PATTERN:
4617 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4618 error_report("Invalid pattern byte specified");
4624 case OPTION_FLUSH_INTERVAL:
4628 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4629 error_report("Invalid flush interval specified");
4632 flush_interval = res;
4635 case OPTION_NO_DRAIN:
4636 drain_on_flush = false;
4638 case OPTION_IMAGE_OPTS:
4644 if (optind != argc - 1) {
4645 error_exit("Expecting one image file name");
4647 filename = argv[argc - 1];
4649 if (!is_write && flush_interval) {
4650 error_report("--flush-interval is only available in write tests");
4654 if (flush_interval && flush_interval < depth) {
4655 error_report("Flush interval can't be smaller than depth");
4660 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4667 image_size = blk_getlength(blk);
4668 if (image_size < 0) {
4673 data = (BenchData) {
4675 .image_size = image_size,
4677 .step = step ?: bufsize,
4682 .flush_interval = flush_interval,
4683 .drain_on_flush = drain_on_flush,
4685 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4686 "(starting at offset %" PRId64 ", step size %d)\n",
4687 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4688 data.offset, data.step);
4689 if (flush_interval) {
4690 printf("Sending flush every %d requests\n", flush_interval);
4693 buf_size = data.nrreq * data.bufsize;
4694 data.buf = blk_blockalign(blk, buf_size);
4695 memset(data.buf, pattern, data.nrreq * data.bufsize);
4697 blk_register_buf(blk, data.buf, buf_size, &error_fatal);
4699 data.qiov = g_new(QEMUIOVector, data.nrreq);
4700 for (i = 0; i < data.nrreq; i++) {
4701 qemu_iovec_init(&data.qiov[i], 1);
4702 qemu_iovec_add(&data.qiov[i],
4703 data.buf + i * data.bufsize, data.bufsize);
4706 gettimeofday(&t1, NULL);
4709 while (data.n > 0) {
4710 main_loop_wait(false);
4712 gettimeofday(&t2, NULL);
4714 printf("Run completed in %3.3f seconds.\n",
4715 (t2.tv_sec - t1.tv_sec)
4716 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4720 blk_unregister_buf(blk, data.buf, buf_size);
4722 qemu_vfree(data.buf);
4739 typedef struct ImgBitmapAction {
4740 enum ImgBitmapAct act;
4741 const char *src; /* only used for merge */
4742 QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4745 static int img_bitmap(int argc, char **argv)
4749 QemuOpts *opts = NULL;
4750 const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4751 const char *filename, *bitmap;
4752 BlockBackend *blk = NULL, *src = NULL;
4753 BlockDriverState *bs = NULL, *src_bs = NULL;
4754 bool image_opts = false;
4755 int64_t granularity = 0;
4756 bool add = false, merge = false;
4757 QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4758 ImgBitmapAction *act, *act_next;
4762 QSIMPLEQ_INIT(&actions);
4765 static const struct option long_options[] = {
4766 {"help", no_argument, 0, 'h'},
4767 {"object", required_argument, 0, OPTION_OBJECT},
4768 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4769 {"add", no_argument, 0, OPTION_ADD},
4770 {"remove", no_argument, 0, OPTION_REMOVE},
4771 {"clear", no_argument, 0, OPTION_CLEAR},
4772 {"enable", no_argument, 0, OPTION_ENABLE},
4773 {"disable", no_argument, 0, OPTION_DISABLE},
4774 {"merge", required_argument, 0, OPTION_MERGE},
4775 {"granularity", required_argument, 0, 'g'},
4776 {"source-file", required_argument, 0, 'b'},
4777 {"source-format", required_argument, 0, 'F'},
4780 c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4787 missing_argument(argv[optind - 1]);
4790 unrecognized_option(argv[optind - 1]);
4796 src_filename = optarg;
4805 granularity = cvtnum("granularity", optarg);
4806 if (granularity < 0) {
4811 act = g_new0(ImgBitmapAction, 1);
4812 act->act = BITMAP_ADD;
4813 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4817 act = g_new0(ImgBitmapAction, 1);
4818 act->act = BITMAP_REMOVE;
4819 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4822 act = g_new0(ImgBitmapAction, 1);
4823 act->act = BITMAP_CLEAR;
4824 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4827 act = g_new0(ImgBitmapAction, 1);
4828 act->act = BITMAP_ENABLE;
4829 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4831 case OPTION_DISABLE:
4832 act = g_new0(ImgBitmapAction, 1);
4833 act->act = BITMAP_DISABLE;
4834 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4837 act = g_new0(ImgBitmapAction, 1);
4838 act->act = BITMAP_MERGE;
4840 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4844 user_creatable_process_cmdline(optarg);
4846 case OPTION_IMAGE_OPTS:
4852 if (QSIMPLEQ_EMPTY(&actions)) {
4853 error_report("Need at least one of --add, --remove, --clear, "
4854 "--enable, --disable, or --merge");
4858 if (granularity && !add) {
4859 error_report("granularity only supported with --add");
4862 if (src_fmt && !src_filename) {
4863 error_report("-F only supported with -b");
4866 if (src_filename && !merge) {
4867 error_report("Merge bitmap source file only supported with "
4872 if (optind != argc - 2) {
4873 error_report("Expecting filename and bitmap name");
4877 filename = argv[optind];
4878 bitmap = argv[optind + 1];
4881 * No need to open backing chains; we will be manipulating bitmaps
4882 * directly in this image without reference to image contents.
4884 blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR | BDRV_O_NO_BACKING,
4885 false, false, false);
4891 src = img_open(false, src_filename, src_fmt, BDRV_O_NO_BACKING,
4892 false, false, false);
4896 src_bs = blk_bs(src);
4901 QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4904 qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4905 !!granularity, granularity, true, true,
4906 false, false, &err);
4910 qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4914 qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4918 qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4921 case BITMAP_DISABLE:
4922 qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4926 do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4931 g_assert_not_reached();
4935 error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4946 * Manually inactivate the images first because this way we can know whether
4947 * an error occurred. blk_unref() doesn't tell us about failures.
4949 inactivate_ret = bdrv_inactivate_all();
4950 if (inactivate_ret < 0) {
4951 error_report("Error while closing the image: %s", strerror(-inactivate_ret));
4957 qemu_opts_del(opts);
4973 int bsz; /* Block size */
4981 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4985 static int img_dd_bs(const char *arg,
4986 struct DdIo *in, struct DdIo *out,
4991 res = cvtnum_full("bs", arg, 1, INT_MAX);
4996 in->bsz = out->bsz = res;
5001 static int img_dd_count(const char *arg,
5002 struct DdIo *in, struct DdIo *out,
5005 dd->count = cvtnum("count", arg);
5007 if (dd->count < 0) {
5014 static int img_dd_if(const char *arg,
5015 struct DdIo *in, struct DdIo *out,
5018 in->filename = g_strdup(arg);
5023 static int img_dd_of(const char *arg,
5024 struct DdIo *in, struct DdIo *out,
5027 out->filename = g_strdup(arg);
5032 static int img_dd_skip(const char *arg,
5033 struct DdIo *in, struct DdIo *out,
5036 in->offset = cvtnum("skip", arg);
5038 if (in->offset < 0) {
5045 static int img_dd(int argc, char **argv)
5050 BlockDriver *drv = NULL, *proto_drv = NULL;
5051 BlockBackend *blk1 = NULL, *blk2 = NULL;
5052 QemuOpts *opts = NULL;
5053 QemuOptsList *create_opts = NULL;
5054 Error *local_err = NULL;
5055 bool image_opts = false;
5057 const char *out_fmt = "raw";
5058 const char *fmt = NULL;
5060 int64_t out_pos, in_pos;
5061 bool force_share = false;
5062 struct DdInfo dd = {
5067 .bsz = 512, /* Block size is by default 512 bytes */
5079 const struct DdOpts options[] = {
5080 { "bs", img_dd_bs, C_BS },
5081 { "count", img_dd_count, C_COUNT },
5082 { "if", img_dd_if, C_IF },
5083 { "of", img_dd_of, C_OF },
5084 { "skip", img_dd_skip, C_SKIP },
5087 const struct option long_options[] = {
5088 { "help", no_argument, 0, 'h'},
5089 { "object", required_argument, 0, OPTION_OBJECT},
5090 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5091 { "force-share", no_argument, 0, 'U'},
5095 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
5107 missing_argument(argv[optind - 1]);
5110 unrecognized_option(argv[optind - 1]);
5119 user_creatable_process_cmdline(optarg);
5121 case OPTION_IMAGE_OPTS:
5127 for (i = optind; i < argc; i++) {
5129 arg = g_strdup(argv[i]);
5131 tmp = strchr(arg, '=');
5133 error_report("unrecognized operand %s", arg);
5140 for (j = 0; options[j].name != NULL; j++) {
5141 if (!strcmp(arg, options[j].name)) {
5145 if (options[j].name == NULL) {
5146 error_report("unrecognized operand %s", arg);
5151 if (options[j].f(tmp, &in, &out, &dd) != 0) {
5155 dd.flags |= options[j].flag;
5160 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
5161 error_report("Must specify both input and output files");
5166 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
5174 drv = bdrv_find_format(out_fmt);
5176 error_report("Unknown file format");
5180 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
5183 error_report_err(local_err);
5187 if (!drv->create_opts) {
5188 error_report("Format driver '%s' does not support image creation",
5193 if (!proto_drv->create_opts) {
5194 error_report("Protocol driver '%s' does not support image creation",
5195 proto_drv->format_name);
5199 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5200 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5202 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5204 size = blk_getlength(blk1);
5206 error_report("Failed to get size for '%s'", in.filename);
5211 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5212 dd.count * in.bsz < size) {
5213 size = dd.count * in.bsz;
5216 /* Overflow means the specified offset is beyond input image's size */
5217 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5218 size < in.bsz * in.offset)) {
5219 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5221 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5222 size - in.bsz * in.offset, &error_abort);
5225 ret = bdrv_create(drv, out.filename, opts, &local_err);
5227 error_reportf_err(local_err,
5228 "%s: error while creating output image: ",
5234 /* TODO, we can't honour --image-opts for the target,
5235 * since it needs to be given in a format compatible
5236 * with the bdrv_create() call above which does not
5237 * support image-opts style.
5239 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
5240 false, false, false);
5247 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5248 size < in.offset * in.bsz)) {
5249 /* We give a warning if the skip option is bigger than the input
5250 * size and create an empty output disk image (i.e. like dd(1)).
5252 error_report("%s: cannot skip to specified offset", in.filename);
5255 in_pos = in.offset * in.bsz;
5258 in.buf = g_new(uint8_t, in.bsz);
5260 for (out_pos = 0; in_pos < size; ) {
5261 int bytes = (in_pos + in.bsz > size) ? size - in_pos : in.bsz;
5263 ret = blk_pread(blk1, in_pos, bytes, in.buf, 0);
5265 error_report("error while reading from input image file: %s",
5271 ret = blk_pwrite(blk2, out_pos, bytes, in.buf, 0);
5273 error_report("error while writing to output image file: %s",
5282 qemu_opts_del(opts);
5283 qemu_opts_free(create_opts);
5286 g_free(in.filename);
5287 g_free(out.filename);
5297 static void dump_json_block_measure_info(BlockMeasureInfo *info)
5301 Visitor *v = qobject_output_visitor_new(&obj);
5303 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5304 visit_complete(v, &obj);
5305 str = qobject_to_json_pretty(obj, true);
5306 assert(str != NULL);
5307 printf("%s\n", str->str);
5310 g_string_free(str, true);
5313 static int img_measure(int argc, char **argv)
5315 static const struct option long_options[] = {
5316 {"help", no_argument, 0, 'h'},
5317 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5318 {"object", required_argument, 0, OPTION_OBJECT},
5319 {"output", required_argument, 0, OPTION_OUTPUT},
5320 {"size", required_argument, 0, OPTION_SIZE},
5321 {"force-share", no_argument, 0, 'U'},
5324 OutputFormat output_format = OFORMAT_HUMAN;
5325 BlockBackend *in_blk = NULL;
5327 const char *filename = NULL;
5328 const char *fmt = NULL;
5329 const char *out_fmt = "raw";
5330 char *options = NULL;
5331 char *snapshot_name = NULL;
5332 bool force_share = false;
5333 QemuOpts *opts = NULL;
5334 QemuOpts *object_opts = NULL;
5335 QemuOpts *sn_opts = NULL;
5336 QemuOptsList *create_opts = NULL;
5337 bool image_opts = false;
5338 uint64_t img_size = UINT64_MAX;
5339 BlockMeasureInfo *info = NULL;
5340 Error *local_err = NULL;
5344 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5345 long_options, NULL)) != -1) {
5358 if (accumulate_options(&options, optarg) < 0) {
5363 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5364 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5367 error_report("Failed in parsing snapshot param '%s'",
5372 snapshot_name = optarg;
5379 user_creatable_process_cmdline(optarg);
5381 case OPTION_IMAGE_OPTS:
5385 if (!strcmp(optarg, "json")) {
5386 output_format = OFORMAT_JSON;
5387 } else if (!strcmp(optarg, "human")) {
5388 output_format = OFORMAT_HUMAN;
5390 error_report("--output must be used with human or json "
5399 sval = cvtnum("image size", optarg);
5403 img_size = (uint64_t)sval;
5409 if (argc - optind > 1) {
5410 error_report("At most one filename argument is allowed.");
5412 } else if (argc - optind == 1) {
5413 filename = argv[optind];
5416 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5417 error_report("--image-opts, -f, and -l require a filename argument.");
5420 if (filename && img_size != UINT64_MAX) {
5421 error_report("--size N cannot be used together with a filename.");
5424 if (!filename && img_size == UINT64_MAX) {
5425 error_report("Either --size N or one filename must be specified.");
5430 in_blk = img_open(image_opts, filename, fmt, 0,
5431 false, false, force_share);
5437 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5438 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5439 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5441 } else if (snapshot_name != NULL) {
5442 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5443 snapshot_name, &local_err);
5446 error_reportf_err(local_err, "Failed to load snapshot: ");
5451 drv = bdrv_find_format(out_fmt);
5453 error_report("Unknown file format '%s'", out_fmt);
5456 if (!drv->create_opts) {
5457 error_report("Format driver '%s' does not support image creation",
5462 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5463 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5464 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5466 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
5467 error_report_err(local_err);
5468 error_report("Invalid options for file format '%s'", out_fmt);
5472 if (img_size != UINT64_MAX) {
5473 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5476 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5478 error_report_err(local_err);
5482 if (output_format == OFORMAT_HUMAN) {
5483 printf("required size: %" PRIu64 "\n", info->required);
5484 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
5485 if (info->has_bitmaps) {
5486 printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5489 dump_json_block_measure_info(info);
5495 qapi_free_BlockMeasureInfo(info);
5496 qemu_opts_del(object_opts);
5497 qemu_opts_del(opts);
5498 qemu_opts_del(sn_opts);
5499 qemu_opts_free(create_opts);
5505 static const img_cmd_t img_cmds[] = {
5506 #define DEF(option, callback, arg_string) \
5507 { option, callback },
5508 #include "qemu-img-cmds.h"
5513 int main(int argc, char **argv)
5515 const img_cmd_t *cmd;
5516 const char *cmdname;
5518 static const struct option long_options[] = {
5519 {"help", no_argument, 0, 'h'},
5520 {"version", no_argument, 0, 'V'},
5521 {"trace", required_argument, NULL, 'T'},
5526 signal(SIGPIPE, SIG_IGN);
5530 error_init(argv[0]);
5531 module_call_init(MODULE_INIT_TRACE);
5532 qemu_init_exec_dir(argv[0]);
5534 qemu_init_main_loop(&error_fatal);
5536 qcrypto_init(&error_fatal);
5538 module_call_init(MODULE_INIT_QOM);
5541 error_exit("Not enough arguments");
5544 qemu_add_opts(&qemu_source_opts);
5545 qemu_add_opts(&qemu_trace_opts);
5547 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
5550 missing_argument(argv[optind - 1]);
5553 unrecognized_option(argv[optind - 1]);
5559 printf(QEMU_IMG_VERSION);
5562 trace_opt_parse(optarg);
5567 cmdname = argv[optind];
5569 /* reset getopt_long scanning */
5575 qemu_reset_optind();
5577 if (!trace_init_backends()) {
5581 qemu_set_log(LOG_TRACE, &error_fatal);
5583 /* find the command */
5584 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5585 if (!strcmp(cmdname, cmd->name)) {
5586 return cmd->handler(argc, argv);
5591 error_exit("Command not found: %s", cmdname);