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-common.h"
29 #include "qemu-version.h"
30 #include "qapi/error.h"
31 #include "qapi/qapi-commands-block-core.h"
32 #include "qapi/qapi-visit-block-core.h"
33 #include "qapi/qobject-output-visitor.h"
34 #include "qapi/qmp/qjson.h"
35 #include "qapi/qmp/qdict.h"
36 #include "qapi/qmp/qstring.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/units.h"
45 #include "qom/object_interfaces.h"
46 #include "sysemu/block-backend.h"
47 #include "block/block_int.h"
48 #include "block/blockjob.h"
49 #include "block/qapi.h"
50 #include "crypto/init.h"
51 #include "trace/control.h"
53 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
54 "\n" QEMU_COPYRIGHT "\n"
56 typedef struct img_cmd_t {
58 int (*handler)(int argc, char **argv);
63 OPTION_BACKING_CHAIN = 257,
65 OPTION_IMAGE_OPTS = 259,
67 OPTION_FLUSH_INTERVAL = 261,
68 OPTION_NO_DRAIN = 262,
69 OPTION_TARGET_IMAGE_OPTS = 263,
71 OPTION_PREALLOCATION = 265,
74 OPTION_TARGET_IS_ZERO = 268,
85 typedef enum OutputFormat {
90 /* Default to cache=writeback as data integrity is not important for qemu-img */
91 #define BDRV_DEFAULT_CACHE "writeback"
93 static void format_print(void *opaque, const char *name)
98 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
103 error_vreport(fmt, ap);
106 error_printf("Try 'qemu-img --help' for more information\n");
110 static void QEMU_NORETURN missing_argument(const char *option)
112 error_exit("missing argument for option '%s'", option);
115 static void QEMU_NORETURN unrecognized_option(const char *option)
117 error_exit("unrecognized option '%s'", option);
120 /* Please keep in synch with docs/tools/qemu-img.rst */
121 static void QEMU_NORETURN help(void)
123 const char *help_msg =
125 "usage: qemu-img [standard options] command [command options]\n"
126 "QEMU disk image utility\n"
128 " '-h', '--help' display this help and exit\n"
129 " '-V', '--version' output version information and exit\n"
130 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
131 " specify tracing options\n"
134 #define DEF(option, callback, arg_string) \
136 #include "qemu-img-cmds.h"
139 "Command parameters:\n"
140 " 'filename' is a disk image filename\n"
141 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
142 " manual page for a description of the object properties. The most common\n"
143 " object type is a 'secret', which is used to supply passwords and/or\n"
144 " encryption keys.\n"
145 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
146 " 'cache' is the cache mode used to write the output disk image, the valid\n"
147 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
148 " 'directsync' and 'unsafe' (default for convert)\n"
149 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
150 " options are the same as for the 'cache' option\n"
151 " 'size' is the disk image size in bytes. Optional suffixes\n"
152 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
153 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
154 " supported. 'b' is ignored.\n"
155 " 'output_filename' is the destination disk image filename\n"
156 " 'output_fmt' is the destination format\n"
157 " 'options' is a comma separated list of format specific options in a\n"
158 " name=value format. Use -o ? for an overview of the options supported by the\n"
160 " 'snapshot_param' is param used for internal snapshot, format\n"
161 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
163 " '-c' indicates that target image must be compressed (qcow format only)\n"
164 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
165 " new backing file match exactly. The image doesn't need a working\n"
166 " backing file before rebasing in this case (useful for renaming the\n"
167 " backing file). For image creation, allow creating without attempting\n"
168 " to open the backing file.\n"
169 " '-h' with or without a command shows this help and lists the supported formats\n"
170 " '-p' show progress of command (only certain commands)\n"
171 " '-q' use Quiet mode - do not print any output (except errors)\n"
172 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
173 " contain only zeros for qemu-img to create a sparse image during\n"
174 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
175 " unallocated or zero sectors, and the destination image will always be\n"
177 " '--output' takes the format in which the output must be done (human or json)\n"
178 " '-n' skips the target volume creation (useful if the volume is created\n"
179 " prior to running qemu-img)\n"
181 "Parameters to bitmap subcommand:\n"
182 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
183 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
184 " or '--merge source'\n"
185 " '-g granularity' sets the granularity for '--add' actions\n"
186 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
187 " bitmaps from an alternative file\n"
189 "Parameters to check subcommand:\n"
190 " '-r' tries to repair any inconsistencies that are found during the check.\n"
191 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
192 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
193 " hiding corruption that has already occurred.\n"
195 "Parameters to convert subcommand:\n"
196 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
197 " '-m' specifies how many coroutines work in parallel during the convert\n"
198 " process (defaults to 8)\n"
199 " '-W' allow to write to the target out of order rather than sequential\n"
201 "Parameters to snapshot subcommand:\n"
202 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
203 " '-a' applies a snapshot (revert disk to saved state)\n"
204 " '-c' creates a snapshot\n"
205 " '-d' deletes a snapshot\n"
206 " '-l' lists all snapshots in the given image\n"
208 "Parameters to compare subcommand:\n"
209 " '-f' first image format\n"
210 " '-F' second image format\n"
211 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
213 "Parameters to dd subcommand:\n"
214 " 'bs=BYTES' read and write up to BYTES bytes at a time "
216 " 'count=N' copy only N input blocks\n"
217 " 'if=FILE' read from FILE\n"
218 " 'of=FILE' write to FILE\n"
219 " 'skip=N' skip N bs-sized blocks at the start of input\n";
221 printf("%s\nSupported formats:", help_msg);
222 bdrv_iterate_format(format_print, NULL, false);
223 printf("\n\n" QEMU_HELP_BOTTOM "\n");
227 static QemuOptsList qemu_object_opts = {
229 .implied_opt_name = "qom-type",
230 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
236 static bool qemu_img_object_print_help(const char *type, QemuOpts *opts)
238 if (user_creatable_print_help(type, opts)) {
245 * Is @optarg safe for accumulate_options()?
246 * It is when multiple of them can be joined together separated by ','.
247 * To make that work, @optarg must not start with ',' (or else a
248 * separating ',' preceding it gets escaped), and it must not end with
249 * an odd number of ',' (or else a separating ',' following it gets
250 * escaped), or be empty (or else a separating ',' preceding it can
251 * escape a separating ',' following it).
254 static bool is_valid_option_list(const char *optarg)
256 size_t len = strlen(optarg);
259 if (!optarg[0] || optarg[0] == ',') {
263 for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
272 static int accumulate_options(char **options, char *optarg)
276 if (!is_valid_option_list(optarg)) {
277 error_report("Invalid option list: %s", optarg);
282 *options = g_strdup(optarg);
284 new_options = g_strdup_printf("%s,%s", *options, optarg);
286 *options = new_options;
291 static QemuOptsList qemu_source_opts = {
293 .implied_opt_name = "file",
294 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
300 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
306 ret = vprintf(fmt, args);
313 static int print_block_option_help(const char *filename, const char *fmt)
315 BlockDriver *drv, *proto_drv;
316 QemuOptsList *create_opts = NULL;
317 Error *local_err = NULL;
319 /* Find driver and parse its options */
320 drv = bdrv_find_format(fmt);
322 error_report("Unknown file format '%s'", fmt);
326 if (!drv->create_opts) {
327 error_report("Format driver '%s' does not support image creation", fmt);
331 create_opts = qemu_opts_append(create_opts, drv->create_opts);
333 proto_drv = bdrv_find_protocol(filename, true, &local_err);
335 error_report_err(local_err);
336 qemu_opts_free(create_opts);
339 if (!proto_drv->create_opts) {
340 error_report("Protocol driver '%s' does not support image creation",
341 proto_drv->format_name);
342 qemu_opts_free(create_opts);
345 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
349 printf("Supported options:\n");
351 printf("Supported %s options:\n", fmt);
353 qemu_opts_print_help(create_opts, false);
354 qemu_opts_free(create_opts);
358 "The protocol level may support further options.\n"
359 "Specify the target filename to include those options.\n");
366 static BlockBackend *img_open_opts(const char *optstr,
367 QemuOpts *opts, int flags, bool writethrough,
368 bool quiet, bool force_share)
371 Error *local_err = NULL;
373 options = qemu_opts_to_qdict(opts, NULL);
375 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
376 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
377 error_report("--force-share/-U conflicts with image options");
378 qobject_unref(options);
381 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
383 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
385 error_reportf_err(local_err, "Could not open '%s': ", optstr);
388 blk_set_enable_write_cache(blk, !writethrough);
393 static BlockBackend *img_open_file(const char *filename,
395 const char *fmt, int flags,
396 bool writethrough, bool quiet,
400 Error *local_err = NULL;
403 options = qdict_new();
406 qdict_put_str(options, "driver", fmt);
410 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
412 blk = blk_new_open(filename, NULL, options, flags, &local_err);
414 error_reportf_err(local_err, "Could not open '%s': ", filename);
417 blk_set_enable_write_cache(blk, !writethrough);
423 static int img_add_key_secrets(void *opaque,
424 const char *name, const char *value,
427 QDict *options = opaque;
429 if (g_str_has_suffix(name, "key-secret")) {
430 qdict_put_str(options, name, value);
437 static BlockBackend *img_open(bool image_opts,
438 const char *filename,
439 const char *fmt, int flags, bool writethrough,
440 bool quiet, bool force_share)
446 error_report("--image-opts and --format are mutually exclusive");
449 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
454 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
457 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
464 static int add_old_style_options(const char *fmt, QemuOpts *opts,
465 const char *base_filename,
466 const char *base_fmt)
471 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
473 error_report("Backing file not supported for file format '%s'",
480 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
482 error_report("Backing file format not supported for file "
491 static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
497 err = qemu_strtosz(value, NULL, &res);
498 if (err < 0 && err != -ERANGE) {
499 error_report("Invalid %s specified. You may use "
500 "k, M, G, T, P or E suffixes for", name);
501 error_report("kilobytes, megabytes, gigabytes, terabytes, "
502 "petabytes and exabytes.");
505 if (err == -ERANGE || res > max || res < min) {
506 error_report("Invalid %s specified. Must be between %" PRId64
507 " and %" PRId64 ".", name, min, max);
513 static int64_t cvtnum(const char *name, const char *value)
515 return cvtnum_full(name, value, 0, INT64_MAX);
518 static int img_create(int argc, char **argv)
521 uint64_t img_size = -1;
522 const char *fmt = "raw";
523 const char *base_fmt = NULL;
524 const char *filename;
525 const char *base_filename = NULL;
526 char *options = NULL;
527 Error *local_err = NULL;
532 static const struct option long_options[] = {
533 {"help", no_argument, 0, 'h'},
534 {"object", required_argument, 0, OPTION_OBJECT},
537 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
544 missing_argument(argv[optind - 1]);
547 unrecognized_option(argv[optind - 1]);
556 base_filename = optarg;
562 if (accumulate_options(&options, optarg) < 0) {
570 flags |= BDRV_O_NO_BACKING;
572 case OPTION_OBJECT: {
574 opts = qemu_opts_parse_noisily(&qemu_object_opts,
583 /* Get the filename */
584 filename = (optind < argc) ? argv[optind] : NULL;
585 if (options && has_help_option(options)) {
587 return print_block_option_help(filename, fmt);
590 if (optind >= argc) {
591 error_exit("Expecting image file name");
595 if (qemu_opts_foreach(&qemu_object_opts,
596 user_creatable_add_opts_foreach,
597 qemu_img_object_print_help, &error_fatal)) {
601 /* Get image size, if specified */
605 sval = cvtnum("image size", argv[optind++]);
609 img_size = (uint64_t)sval;
611 if (optind != argc) {
612 error_exit("Unexpected argument: %s", argv[optind]);
615 bdrv_img_create(filename, fmt, base_filename, base_fmt,
616 options, img_size, flags, quiet, &local_err);
618 error_reportf_err(local_err, "%s: ", filename);
630 static void dump_json_image_check(ImageCheck *check, bool quiet)
634 Visitor *v = qobject_output_visitor_new(&obj);
636 visit_type_ImageCheck(v, NULL, &check, &error_abort);
637 visit_complete(v, &obj);
638 str = qobject_to_json_pretty(obj);
640 qprintf(quiet, "%s\n", qstring_get_str(str));
646 static void dump_human_image_check(ImageCheck *check, bool quiet)
648 if (!(check->corruptions || check->leaks || check->check_errors)) {
649 qprintf(quiet, "No errors were found on the image.\n");
651 if (check->corruptions) {
652 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
653 "Data may be corrupted, or further writes to the image "
660 "\n%" PRId64 " leaked clusters were found on the image.\n"
661 "This means waste of disk space, but no harm to data.\n",
665 if (check->check_errors) {
668 " internal errors have occurred during the check.\n",
669 check->check_errors);
673 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
674 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
675 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
676 check->allocated_clusters, check->total_clusters,
677 check->allocated_clusters * 100.0 / check->total_clusters,
678 check->fragmented_clusters * 100.0 / check->allocated_clusters,
679 check->compressed_clusters * 100.0 /
680 check->allocated_clusters);
683 if (check->image_end_offset) {
685 "Image end offset: %" PRId64 "\n", check->image_end_offset);
689 static int collect_image_check(BlockDriverState *bs,
691 const char *filename,
696 BdrvCheckResult result;
698 ret = bdrv_check(bs, &result, fix);
703 check->filename = g_strdup(filename);
704 check->format = g_strdup(bdrv_get_format_name(bs));
705 check->check_errors = result.check_errors;
706 check->corruptions = result.corruptions;
707 check->has_corruptions = result.corruptions != 0;
708 check->leaks = result.leaks;
709 check->has_leaks = result.leaks != 0;
710 check->corruptions_fixed = result.corruptions_fixed;
711 check->has_corruptions_fixed = result.corruptions_fixed != 0;
712 check->leaks_fixed = result.leaks_fixed;
713 check->has_leaks_fixed = result.leaks_fixed != 0;
714 check->image_end_offset = result.image_end_offset;
715 check->has_image_end_offset = result.image_end_offset != 0;
716 check->total_clusters = result.bfi.total_clusters;
717 check->has_total_clusters = result.bfi.total_clusters != 0;
718 check->allocated_clusters = result.bfi.allocated_clusters;
719 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
720 check->fragmented_clusters = result.bfi.fragmented_clusters;
721 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
722 check->compressed_clusters = result.bfi.compressed_clusters;
723 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
729 * Checks an image for consistency. Exit codes:
731 * 0 - Check completed, image is good
732 * 1 - Check not completed because of internal errors
733 * 2 - Check completed, image is corrupted
734 * 3 - Check completed, image has leaked clusters, but is good otherwise
735 * 63 - Checks are not supported by the image format
737 static int img_check(int argc, char **argv)
740 OutputFormat output_format = OFORMAT_HUMAN;
741 const char *filename, *fmt, *output, *cache;
743 BlockDriverState *bs;
745 int flags = BDRV_O_CHECK;
749 bool image_opts = false;
750 bool force_share = false;
754 cache = BDRV_DEFAULT_CACHE;
757 int option_index = 0;
758 static const struct option long_options[] = {
759 {"help", no_argument, 0, 'h'},
760 {"format", required_argument, 0, 'f'},
761 {"repair", required_argument, 0, 'r'},
762 {"output", required_argument, 0, OPTION_OUTPUT},
763 {"object", required_argument, 0, OPTION_OBJECT},
764 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
765 {"force-share", no_argument, 0, 'U'},
768 c = getopt_long(argc, argv, ":hf:r:T:qU",
769 long_options, &option_index);
775 missing_argument(argv[optind - 1]);
778 unrecognized_option(argv[optind - 1]);
787 flags |= BDRV_O_RDWR;
789 if (!strcmp(optarg, "leaks")) {
790 fix = BDRV_FIX_LEAKS;
791 } else if (!strcmp(optarg, "all")) {
792 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
794 error_exit("Unknown option value for -r "
795 "(expecting 'leaks' or 'all'): %s", optarg);
810 case OPTION_OBJECT: {
812 opts = qemu_opts_parse_noisily(&qemu_object_opts,
818 case OPTION_IMAGE_OPTS:
823 if (optind != argc - 1) {
824 error_exit("Expecting one image file name");
826 filename = argv[optind++];
828 if (output && !strcmp(output, "json")) {
829 output_format = OFORMAT_JSON;
830 } else if (output && !strcmp(output, "human")) {
831 output_format = OFORMAT_HUMAN;
833 error_report("--output must be used with human or json as argument.");
837 if (qemu_opts_foreach(&qemu_object_opts,
838 user_creatable_add_opts_foreach,
839 qemu_img_object_print_help, &error_fatal)) {
843 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
845 error_report("Invalid source cache option: %s", cache);
849 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
856 check = g_new0(ImageCheck, 1);
857 ret = collect_image_check(bs, check, filename, fmt, fix);
859 if (ret == -ENOTSUP) {
860 error_report("This image format does not support checks");
865 if (check->corruptions_fixed || check->leaks_fixed) {
866 int corruptions_fixed, leaks_fixed;
867 bool has_leaks_fixed, has_corruptions_fixed;
869 leaks_fixed = check->leaks_fixed;
870 has_leaks_fixed = check->has_leaks_fixed;
871 corruptions_fixed = check->corruptions_fixed;
872 has_corruptions_fixed = check->has_corruptions_fixed;
874 if (output_format == OFORMAT_HUMAN) {
876 "The following inconsistencies were found and repaired:\n\n"
877 " %" PRId64 " leaked clusters\n"
878 " %" PRId64 " corruptions\n\n"
879 "Double checking the fixed image now...\n",
881 check->corruptions_fixed);
884 qapi_free_ImageCheck(check);
885 check = g_new0(ImageCheck, 1);
886 ret = collect_image_check(bs, check, filename, fmt, 0);
888 check->leaks_fixed = leaks_fixed;
889 check->has_leaks_fixed = has_leaks_fixed;
890 check->corruptions_fixed = corruptions_fixed;
891 check->has_corruptions_fixed = has_corruptions_fixed;
895 switch (output_format) {
897 dump_human_image_check(check, quiet);
900 dump_json_image_check(check, quiet);
905 if (ret || check->check_errors) {
907 error_report("Check failed: %s", strerror(-ret));
909 error_report("Check failed");
915 if (check->corruptions) {
917 } else if (check->leaks) {
924 qapi_free_ImageCheck(check);
929 typedef struct CommonBlockJobCBInfo {
930 BlockDriverState *bs;
932 } CommonBlockJobCBInfo;
934 static void common_block_job_cb(void *opaque, int ret)
936 CommonBlockJobCBInfo *cbi = opaque;
939 error_setg_errno(cbi->errp, -ret, "Block job failed");
943 static void run_block_job(BlockJob *job, Error **errp)
945 AioContext *aio_context = blk_get_aio_context(job->blk);
948 aio_context_acquire(aio_context);
951 float progress = 0.0f;
952 aio_poll(aio_context, true);
953 if (job->job.progress.total) {
954 progress = (float)job->job.progress.current /
955 job->job.progress.total * 100.f;
957 qemu_progress_print(progress, 0);
958 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
960 if (!job_is_completed(&job->job)) {
961 ret = job_complete_sync(&job->job, errp);
965 job_unref(&job->job);
966 aio_context_release(aio_context);
968 /* publish completion progress only when success */
970 qemu_progress_print(100.f, 0);
974 static int img_commit(int argc, char **argv)
977 const char *filename, *fmt, *cache, *base;
979 BlockDriverState *bs, *base_bs;
981 bool progress = false, quiet = false, drop = false;
983 Error *local_err = NULL;
984 CommonBlockJobCBInfo cbi;
985 bool image_opts = false;
986 AioContext *aio_context;
989 cache = BDRV_DEFAULT_CACHE;
992 static const struct option long_options[] = {
993 {"help", no_argument, 0, 'h'},
994 {"object", required_argument, 0, OPTION_OBJECT},
995 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
998 c = getopt_long(argc, argv, ":f:ht:b:dpq",
1005 missing_argument(argv[optind - 1]);
1008 unrecognized_option(argv[optind - 1]);
1033 case OPTION_OBJECT: {
1035 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1041 case OPTION_IMAGE_OPTS:
1047 /* Progress is not shown in Quiet mode */
1052 if (optind != argc - 1) {
1053 error_exit("Expecting one image file name");
1055 filename = argv[optind++];
1057 if (qemu_opts_foreach(&qemu_object_opts,
1058 user_creatable_add_opts_foreach,
1059 qemu_img_object_print_help, &error_fatal)) {
1063 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
1064 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1066 error_report("Invalid cache option: %s", cache);
1070 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1077 qemu_progress_init(progress, 1.f);
1078 qemu_progress_print(0.f, 100);
1081 base_bs = bdrv_find_backing_image(bs, base);
1083 error_setg(&local_err,
1084 "Did not find '%s' in the backing chain of '%s'",
1089 /* This is different from QMP, which by default uses the deepest file in
1090 * the backing chain (i.e., the very base); however, the traditional
1091 * behavior of qemu-img commit is using the immediate backing file. */
1092 base_bs = backing_bs(bs);
1094 error_setg(&local_err, "Image does not have a backing file");
1099 cbi = (CommonBlockJobCBInfo){
1104 aio_context = bdrv_get_aio_context(bs);
1105 aio_context_acquire(aio_context);
1106 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
1107 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1108 &cbi, false, &local_err);
1109 aio_context_release(aio_context);
1114 /* When the block job completes, the BlockBackend reference will point to
1115 * the old backing file. In order to avoid that the top image is already
1116 * deleted, so we can still empty it afterwards, increment the reference
1117 * counter here preemptively. */
1122 job = block_job_get("commit");
1124 run_block_job(job, &local_err);
1130 BlockBackend *old_backing_blk;
1132 old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1134 if (!old_backing_blk) {
1137 ret = blk_make_empty(old_backing_blk, &local_err);
1138 blk_unref(old_backing_blk);
1139 if (ret == -ENOTSUP) {
1140 error_free(local_err);
1142 } else if (ret < 0) {
1153 qemu_progress_end();
1158 error_report_err(local_err);
1162 qprintf(quiet, "Image committed.\n");
1167 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1168 * of the first sector boundary within buf where the sector contains a
1169 * non-zero byte. This function is robust to a buffer that is not
1172 static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1175 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1177 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1178 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1182 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1189 * Returns true iff the first sector pointed to by 'buf' contains at least
1192 * 'pnum' is set to the number of sectors (including and immediately following
1193 * the first one) that are known to be in the same allocated/unallocated state.
1194 * The function will try to align the end offset to alignment boundaries so
1195 * that the request will at least end aligned and consequtive requests will
1196 * also start at an aligned offset.
1198 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1199 int64_t sector_num, int alignment)
1208 is_zero = buffer_is_zero(buf, 512);
1209 for(i = 1; i < n; i++) {
1211 if (is_zero != buffer_is_zero(buf, 512)) {
1216 tail = (sector_num + i) & (alignment - 1);
1218 if (is_zero && i <= tail) {
1219 /* treat unallocated areas which only consist
1220 * of a small tail as allocated. */
1224 /* align up end offset of allocated areas. */
1225 i += alignment - tail;
1228 /* align down end offset of zero areas. */
1237 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1238 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1239 * breaking up write requests for only small sparse areas.
1241 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1242 int min, int64_t sector_num, int alignment)
1245 int num_checked, num_used;
1251 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1257 buf += BDRV_SECTOR_SIZE * *pnum;
1259 sector_num += *pnum;
1260 num_checked = num_used;
1263 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1265 buf += BDRV_SECTOR_SIZE * *pnum;
1267 sector_num += *pnum;
1268 num_checked += *pnum;
1270 num_used = num_checked;
1271 } else if (*pnum >= min) {
1281 * Compares two buffers sector by sector. Returns 0 if the first
1282 * sector of each buffer matches, non-zero otherwise.
1284 * pnum is set to the sector-aligned size of the buffer prefix that
1285 * has the same matching status as the first sector.
1287 static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1288 int64_t bytes, int64_t *pnum)
1291 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
1295 res = !!memcmp(buf1, buf2, i);
1297 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
1299 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
1309 #define IO_BUF_SIZE (2 * MiB)
1312 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1314 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1315 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1316 * failure), and 4 on error (the exit status for read errors), after emitting
1319 * @param blk: BlockBackend for the image
1320 * @param offset: Starting offset to check
1321 * @param bytes: Number of bytes to check
1322 * @param filename: Name of disk file we are checking (logging purpose)
1323 * @param buffer: Allocated buffer for storing read data
1324 * @param quiet: Flag for quiet mode
1326 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1327 int64_t bytes, const char *filename,
1328 uint8_t *buffer, bool quiet)
1333 ret = blk_pread(blk, offset, buffer, bytes);
1335 error_report("Error while reading offset %" PRId64 " of %s: %s",
1336 offset, filename, strerror(-ret));
1339 idx = find_nonzero(buffer, bytes);
1341 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1350 * Compares two images. Exit codes:
1352 * 0 - Images are identical
1354 * >1 - Error occurred
1356 static int img_compare(int argc, char **argv)
1358 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1359 BlockBackend *blk1, *blk2;
1360 BlockDriverState *bs1, *bs2;
1361 int64_t total_size1, total_size2;
1362 uint8_t *buf1 = NULL, *buf2 = NULL;
1363 int64_t pnum1, pnum2;
1364 int allocated1, allocated2;
1365 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1366 bool progress = false, quiet = false, strict = false;
1373 uint64_t progress_base;
1374 bool image_opts = false;
1375 bool force_share = false;
1377 cache = BDRV_DEFAULT_CACHE;
1379 static const struct option long_options[] = {
1380 {"help", no_argument, 0, 'h'},
1381 {"object", required_argument, 0, OPTION_OBJECT},
1382 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1383 {"force-share", no_argument, 0, 'U'},
1386 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1387 long_options, NULL);
1393 missing_argument(argv[optind - 1]);
1396 unrecognized_option(argv[optind - 1]);
1422 case OPTION_OBJECT: {
1424 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1431 case OPTION_IMAGE_OPTS:
1437 /* Progress is not shown in Quiet mode */
1443 if (optind != argc - 2) {
1444 error_exit("Expecting two image file names");
1446 filename1 = argv[optind++];
1447 filename2 = argv[optind++];
1449 if (qemu_opts_foreach(&qemu_object_opts,
1450 user_creatable_add_opts_foreach,
1451 qemu_img_object_print_help, &error_fatal)) {
1456 /* Initialize before goto out */
1457 qemu_progress_init(progress, 2.0);
1460 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1462 error_report("Invalid source cache option: %s", cache);
1467 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1474 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1483 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1484 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1485 total_size1 = blk_getlength(blk1);
1486 if (total_size1 < 0) {
1487 error_report("Can't get size of %s: %s",
1488 filename1, strerror(-total_size1));
1492 total_size2 = blk_getlength(blk2);
1493 if (total_size2 < 0) {
1494 error_report("Can't get size of %s: %s",
1495 filename2, strerror(-total_size2));
1499 total_size = MIN(total_size1, total_size2);
1500 progress_base = MAX(total_size1, total_size2);
1502 qemu_progress_print(0, 100);
1504 if (strict && total_size1 != total_size2) {
1506 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1510 while (offset < total_size) {
1511 int status1, status2;
1513 status1 = bdrv_block_status_above(bs1, NULL, offset,
1514 total_size1 - offset, &pnum1, NULL,
1518 error_report("Sector allocation test failed for %s", filename1);
1521 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1523 status2 = bdrv_block_status_above(bs2, NULL, offset,
1524 total_size2 - offset, &pnum2, NULL,
1528 error_report("Sector allocation test failed for %s", filename2);
1531 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1533 assert(pnum1 && pnum2);
1534 chunk = MIN(pnum1, pnum2);
1537 if (status1 != status2) {
1539 qprintf(quiet, "Strict mode: Offset %" PRId64
1540 " block status mismatch!\n", offset);
1544 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1546 } else if (allocated1 == allocated2) {
1550 chunk = MIN(chunk, IO_BUF_SIZE);
1551 ret = blk_pread(blk1, offset, buf1, chunk);
1553 error_report("Error while reading offset %" PRId64
1555 offset, filename1, strerror(-ret));
1559 ret = blk_pread(blk2, offset, buf2, chunk);
1561 error_report("Error while reading offset %" PRId64
1563 offset, filename2, strerror(-ret));
1567 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1568 if (ret || pnum != chunk) {
1569 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1570 offset + (ret ? 0 : pnum));
1576 chunk = MIN(chunk, IO_BUF_SIZE);
1578 ret = check_empty_sectors(blk1, offset, chunk,
1579 filename1, buf1, quiet);
1581 ret = check_empty_sectors(blk2, offset, chunk,
1582 filename2, buf1, quiet);
1589 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1592 if (total_size1 != total_size2) {
1593 BlockBackend *blk_over;
1594 const char *filename_over;
1596 qprintf(quiet, "Warning: Image size mismatch!\n");
1597 if (total_size1 > total_size2) {
1599 filename_over = filename1;
1602 filename_over = filename2;
1605 while (offset < progress_base) {
1606 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1607 progress_base - offset, &chunk,
1611 error_report("Sector allocation test failed for %s",
1616 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1617 chunk = MIN(chunk, IO_BUF_SIZE);
1618 ret = check_empty_sectors(blk_over, offset, chunk,
1619 filename_over, buf1, quiet);
1625 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1629 qprintf(quiet, "Images are identical.\n");
1639 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 BlockDirtyBitmapMergeSource *merge_src;
1650 BlockDirtyBitmapMergeSourceList *list;
1652 merge_src = g_new0(BlockDirtyBitmapMergeSource, 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 list = g_new0(BlockDirtyBitmapMergeSourceList, 1);
1657 list->value = merge_src;
1658 qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
1659 qapi_free_BlockDirtyBitmapMergeSourceList(list);
1662 enum ImgConvertBlockStatus {
1668 #define MAX_COROUTINES 16
1670 typedef struct ImgConvertState {
1672 int64_t *src_sectors;
1674 int64_t total_sectors;
1675 int64_t allocated_sectors;
1676 int64_t allocated_done;
1679 enum ImgConvertBlockStatus status;
1680 int64_t sector_next_status;
1681 BlockBackend *target;
1685 bool target_has_backing;
1686 int64_t target_backing_sectors; /* negative if unknown */
1693 size_t cluster_sectors;
1695 long num_coroutines;
1696 int running_coroutines;
1697 Coroutine *co[MAX_COROUTINES];
1698 int64_t wait_sector_num[MAX_COROUTINES];
1703 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1704 int *src_cur, int64_t *src_cur_offset)
1707 *src_cur_offset = 0;
1708 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1709 *src_cur_offset += s->src_sectors[*src_cur];
1711 assert(*src_cur < s->src_num);
1715 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1717 int64_t src_cur_offset;
1718 int ret, n, src_cur;
1719 bool post_backing_zero = false;
1721 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1723 assert(s->total_sectors > sector_num);
1724 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1726 if (s->target_backing_sectors >= 0) {
1727 if (sector_num >= s->target_backing_sectors) {
1728 post_backing_zero = true;
1729 } else if (sector_num + n > s->target_backing_sectors) {
1730 /* Split requests around target_backing_sectors (because
1731 * starting from there, zeros are handled differently) */
1732 n = s->target_backing_sectors - sector_num;
1736 if (s->sector_next_status <= sector_num) {
1737 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1741 count = n * BDRV_SECTOR_SIZE;
1743 if (s->target_has_backing) {
1744 ret = bdrv_block_status(blk_bs(s->src[src_cur]), offset,
1745 count, &count, NULL, NULL);
1747 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1748 offset, count, &count, NULL,
1756 warn_report("error while reading block status at "
1757 "offset %" PRIu64 ": %s", offset,
1760 /* Just try to read the data, then */
1761 ret = BDRV_BLOCK_DATA;
1762 count = BDRV_SECTOR_SIZE;
1764 /* Retry on a shorter range */
1765 n = DIV_ROUND_UP(n, 4);
1768 error_report("error while reading block status at offset "
1769 "%" PRIu64 ": %s", offset, strerror(-ret));
1775 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1777 if (ret & BDRV_BLOCK_ZERO) {
1778 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
1779 } else if (ret & BDRV_BLOCK_DATA) {
1780 s->status = BLK_DATA;
1782 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1785 s->sector_next_status = sector_num + n;
1788 n = MIN(n, s->sector_next_status - sector_num);
1789 if (s->status == BLK_DATA) {
1790 n = MIN(n, s->buf_sectors);
1793 /* We need to write complete clusters for compressed images, so if an
1794 * unallocated area is shorter than that, we must consider the whole
1795 * cluster allocated. */
1796 if (s->compressed) {
1797 if (n < s->cluster_sectors) {
1798 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1799 s->status = BLK_DATA;
1801 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1808 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1809 int nb_sectors, uint8_t *buf)
1811 uint64_t single_read_until = 0;
1814 assert(nb_sectors <= s->buf_sectors);
1815 while (nb_sectors > 0) {
1818 int64_t bs_sectors, src_cur_offset;
1821 /* In the case of compression with multiple source files, we can get a
1822 * nb_sectors that spreads into the next part. So we must be able to
1823 * read across multiple BDSes for one convert_read() call. */
1824 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1825 blk = s->src[src_cur];
1826 bs_sectors = s->src_sectors[src_cur];
1828 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1830 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1831 if (single_read_until > offset) {
1835 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
1839 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1843 warn_report("error while reading offset %" PRIu64
1844 ": %s", offset, strerror(-ret));
1846 memset(buf, 0, BDRV_SECTOR_SIZE);
1855 buf += n * BDRV_SECTOR_SIZE;
1862 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1863 int nb_sectors, uint8_t *buf,
1864 enum ImgConvertBlockStatus status)
1868 while (nb_sectors > 0) {
1870 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1873 case BLK_BACKING_FILE:
1874 /* If we have a backing file, leave clusters unallocated that are
1875 * unallocated in the source image, so that the backing file is
1876 * visible at the respective offset. */
1877 assert(s->target_has_backing);
1881 /* If we're told to keep the target fully allocated (-S 0) or there
1882 * is real non-zero data, we must write it. Otherwise we can treat
1883 * it as zero sectors.
1884 * Compressed clusters need to be written as a whole, so in that
1885 * case we can only save the write if the buffer is completely
1887 if (!s->min_sparse ||
1889 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1890 sector_num, s->alignment)) ||
1892 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1894 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1895 n << BDRV_SECTOR_BITS, buf, flags);
1904 if (s->has_zero_init) {
1905 assert(!s->target_has_backing);
1908 ret = blk_co_pwrite_zeroes(s->target,
1909 sector_num << BDRV_SECTOR_BITS,
1910 n << BDRV_SECTOR_BITS,
1911 BDRV_REQ_MAY_UNMAP);
1920 buf += n * BDRV_SECTOR_SIZE;
1926 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1931 while (nb_sectors > 0) {
1934 int64_t bs_sectors, src_cur_offset;
1937 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1938 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1939 blk = s->src[src_cur];
1940 bs_sectors = s->src_sectors[src_cur];
1942 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1944 ret = blk_co_copy_range(blk, offset, s->target,
1945 sector_num << BDRV_SECTOR_BITS,
1946 n << BDRV_SECTOR_BITS, 0, 0);
1957 static void coroutine_fn convert_co_do_copy(void *opaque)
1959 ImgConvertState *s = opaque;
1960 uint8_t *buf = NULL;
1964 for (i = 0; i < s->num_coroutines; i++) {
1965 if (s->co[i] == qemu_coroutine_self()) {
1972 s->running_coroutines++;
1973 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1978 enum ImgConvertBlockStatus status;
1981 qemu_co_mutex_lock(&s->lock);
1982 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1983 qemu_co_mutex_unlock(&s->lock);
1986 n = convert_iteration_sectors(s, s->sector_num);
1988 qemu_co_mutex_unlock(&s->lock);
1992 /* save current sector and allocation status to local variables */
1993 sector_num = s->sector_num;
1995 if (!s->min_sparse && s->status == BLK_ZERO) {
1996 n = MIN(n, s->buf_sectors);
1998 /* increment global sector counter so that other coroutines can
1999 * already continue reading beyond this request */
2001 qemu_co_mutex_unlock(&s->lock);
2003 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
2004 s->allocated_done += n;
2005 qemu_progress_print(100.0 * s->allocated_done /
2006 s->allocated_sectors, 0);
2010 copy_range = s->copy_range && s->status == BLK_DATA;
2011 if (status == BLK_DATA && !copy_range) {
2012 ret = convert_co_read(s, sector_num, n, buf);
2014 error_report("error while reading at byte %lld: %s",
2015 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2018 } else if (!s->min_sparse && status == BLK_ZERO) {
2020 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
2023 if (s->wr_in_order) {
2024 /* keep writes in order */
2025 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
2026 s->wait_sector_num[index] = sector_num;
2027 qemu_coroutine_yield();
2029 s->wait_sector_num[index] = -1;
2032 if (s->ret == -EINPROGRESS) {
2034 ret = convert_co_copy_range(s, sector_num, n);
2036 s->copy_range = false;
2040 ret = convert_co_write(s, sector_num, n, buf, status);
2043 error_report("error while writing at byte %lld: %s",
2044 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2049 if (s->wr_in_order) {
2050 /* reenter the coroutine that might have waited
2051 * for this write to complete */
2052 s->wr_offs = sector_num + n;
2053 for (i = 0; i < s->num_coroutines; i++) {
2054 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2056 * A -> B -> A cannot occur because A has
2057 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2058 * B will never enter A during this time window.
2060 qemu_coroutine_enter(s->co[i]);
2068 s->co[index] = NULL;
2069 s->running_coroutines--;
2070 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2071 /* the convert job finished successfully */
2076 static int convert_do_copy(ImgConvertState *s)
2079 int64_t sector_num = 0;
2081 /* Check whether we have zero initialisation or can get it efficiently */
2082 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2083 !s->target_has_backing) {
2084 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
2087 /* Allocate buffer for copied data. For compressed images, only one cluster
2088 * can be copied at a time. */
2089 if (s->compressed) {
2090 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2091 error_report("invalid cluster size");
2094 s->buf_sectors = s->cluster_sectors;
2097 while (sector_num < s->total_sectors) {
2098 n = convert_iteration_sectors(s, sector_num);
2102 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2104 s->allocated_sectors += n;
2110 s->sector_next_status = 0;
2111 s->ret = -EINPROGRESS;
2113 qemu_co_mutex_init(&s->lock);
2114 for (i = 0; i < s->num_coroutines; i++) {
2115 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2116 s->wait_sector_num[i] = -1;
2117 qemu_coroutine_enter(s->co[i]);
2120 while (s->running_coroutines) {
2121 main_loop_wait(false);
2124 if (s->compressed && !s->ret) {
2125 /* signal EOF to align */
2126 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
2135 static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst)
2137 BdrvDirtyBitmap *bm;
2140 FOR_EACH_DIRTY_BITMAP(src, bm) {
2143 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2146 name = bdrv_dirty_bitmap_name(bm);
2147 qmp_block_dirty_bitmap_add(dst->node_name, name,
2148 true, bdrv_dirty_bitmap_granularity(bm),
2150 true, !bdrv_dirty_bitmap_enabled(bm),
2153 error_reportf_err(err, "Failed to create bitmap %s: ", name);
2157 do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2160 error_reportf_err(err, "Failed to populate bitmap %s: ", name);
2168 #define MAX_BUF_SECTORS 32768
2170 static int img_convert(int argc, char **argv)
2172 int c, bs_i, flags, src_flags = 0;
2173 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
2174 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2175 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
2176 BlockDriver *drv = NULL, *proto_drv = NULL;
2177 BlockDriverInfo bdi;
2178 BlockDriverState *out_bs;
2179 QemuOpts *opts = NULL, *sn_opts = NULL;
2180 QemuOptsList *create_opts = NULL;
2181 QDict *open_opts = NULL;
2182 char *options = NULL;
2183 Error *local_err = NULL;
2184 bool writethrough, src_writethrough, image_opts = false,
2185 skip_create = false, progress = false, tgt_image_opts = false;
2186 int64_t ret = -EINVAL;
2187 bool force_share = false;
2188 bool explict_min_sparse = false;
2189 bool bitmaps = false;
2191 ImgConvertState s = (ImgConvertState) {
2192 /* Need at least 4k of zeros for sparse detection */
2194 .copy_range = false,
2195 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2196 .wr_in_order = true,
2197 .num_coroutines = 8,
2201 static const struct option long_options[] = {
2202 {"help", no_argument, 0, 'h'},
2203 {"object", required_argument, 0, OPTION_OBJECT},
2204 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2205 {"force-share", no_argument, 0, 'U'},
2206 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
2207 {"salvage", no_argument, 0, OPTION_SALVAGE},
2208 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
2209 {"bitmaps", no_argument, 0, OPTION_BITMAPS},
2212 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2213 long_options, NULL);
2219 missing_argument(argv[optind - 1]);
2222 unrecognized_option(argv[optind - 1]);
2234 out_baseimg = optarg;
2237 s.copy_range = true;
2240 s.compressed = true;
2243 if (accumulate_options(&options, optarg) < 0) {
2248 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2249 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2252 error_report("Failed in parsing snapshot param '%s'",
2257 snapshot_name = optarg;
2264 sval = cvtnum("buffer size for sparse output", optarg);
2267 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
2268 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2269 error_report("Invalid buffer size for sparse output specified. "
2270 "Valid sizes are multiples of %llu up to %llu. Select "
2271 "0 to disable sparse detection (fully allocates output).",
2272 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
2276 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2277 explict_min_sparse = true;
2296 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2297 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2298 error_report("Invalid number of coroutines. Allowed number of"
2299 " coroutines is between 1 and %d", MAX_COROUTINES);
2304 s.wr_in_order = false;
2309 case OPTION_OBJECT: {
2310 QemuOpts *object_opts;
2311 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2318 case OPTION_IMAGE_OPTS:
2321 case OPTION_SALVAGE:
2324 case OPTION_TARGET_IMAGE_OPTS:
2325 tgt_image_opts = true;
2327 case OPTION_TARGET_IS_ZERO:
2329 * The user asserting that the target is blank has the
2330 * same effect as the target driver supporting zero
2333 s.has_zero_init = true;
2335 case OPTION_BITMAPS:
2341 if (!out_fmt && !tgt_image_opts) {
2345 if (qemu_opts_foreach(&qemu_object_opts,
2346 user_creatable_add_opts_foreach,
2347 qemu_img_object_print_help, &error_fatal)) {
2351 if (s.compressed && s.copy_range) {
2352 error_report("Cannot enable copy offloading when -c is used");
2356 if (explict_min_sparse && s.copy_range) {
2357 error_report("Cannot enable copy offloading when -S is used");
2361 if (s.copy_range && s.salvage) {
2362 error_report("Cannot use copy offloading in salvaging mode");
2366 if (tgt_image_opts && !skip_create) {
2367 error_report("--target-image-opts requires use of -n flag");
2371 if (skip_create && options) {
2372 warn_report("-o has no effect when skipping image creation");
2373 warn_report("This will become an error in future QEMU versions.");
2376 if (s.has_zero_init && !skip_create) {
2377 error_report("--target-is-zero requires use of -n flag");
2381 s.src_num = argc - optind - 1;
2382 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2384 if (options && has_help_option(options)) {
2386 ret = print_block_option_help(out_filename, out_fmt);
2389 error_report("Option help requires a format be specified");
2394 if (s.src_num < 1) {
2395 error_report("Must specify image file name");
2399 /* ret is still -EINVAL until here */
2400 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2402 error_report("Invalid source cache option: %s", src_cache);
2406 /* Initialize before goto out */
2410 qemu_progress_init(progress, 1.0);
2411 qemu_progress_print(0, 100);
2413 s.src = g_new0(BlockBackend *, s.src_num);
2414 s.src_sectors = g_new(int64_t, s.src_num);
2416 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2417 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2418 fmt, src_flags, src_writethrough, s.quiet,
2424 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2425 if (s.src_sectors[bs_i] < 0) {
2426 error_report("Could not get size of %s: %s",
2427 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2431 s.total_sectors += s.src_sectors[bs_i];
2435 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2436 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2437 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2439 } else if (snapshot_name != NULL) {
2440 if (s.src_num > 1) {
2441 error_report("No support for concatenating multiple snapshot");
2446 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2450 error_reportf_err(local_err, "Failed to load snapshot: ");
2456 /* Find driver and parse its options */
2457 drv = bdrv_find_format(out_fmt);
2459 error_report("Unknown file format '%s'", out_fmt);
2464 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2466 error_report_err(local_err);
2471 if (!drv->create_opts) {
2472 error_report("Format driver '%s' does not support image creation",
2478 if (!proto_drv->create_opts) {
2479 error_report("Protocol driver '%s' does not support image creation",
2480 proto_drv->format_name);
2485 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2486 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2488 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2490 qemu_opts_do_parse(opts, options, NULL, &local_err);
2492 error_report_err(local_err);
2498 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2500 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2506 /* Get backing file name if -o backing_file was used */
2507 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2508 if (out_baseimg_param) {
2509 out_baseimg = out_baseimg_param;
2511 s.target_has_backing = (bool) out_baseimg;
2513 if (s.has_zero_init && s.target_has_backing) {
2514 error_report("Cannot use --target-is-zero when the destination "
2515 "image has a backing file");
2519 if (s.src_num > 1 && out_baseimg) {
2520 error_report("Having a backing file for the target makes no sense when "
2521 "concatenating multiple input images");
2526 /* Check if compression is supported */
2529 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2530 const char *encryptfmt =
2531 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2532 const char *preallocation =
2533 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2535 if (drv && !block_driver_can_compress(drv)) {
2536 error_report("Compression not supported for this file format");
2541 if (encryption || encryptfmt) {
2542 error_report("Compression and encryption not supported at "
2549 && strcmp(preallocation, "off"))
2551 error_report("Compression and preallocation not supported at "
2558 /* Determine if bitmaps need copying */
2560 if (s.src_num > 1) {
2561 error_report("Copying bitmaps only possible with single source");
2565 if (!bdrv_supports_persistent_dirty_bitmap(blk_bs(s.src[0]))) {
2566 error_report("Source lacks bitmap support");
2573 * The later open call will need any decryption secrets, and
2574 * bdrv_create() will purge "opts", so extract them now before
2578 open_opts = qdict_new();
2579 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2581 /* Create the new image */
2582 ret = bdrv_create(drv, out_filename, opts, &local_err);
2584 error_reportf_err(local_err, "%s: error while converting %s: ",
2585 out_filename, out_fmt);
2590 s.target_is_new = !skip_create;
2592 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2593 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2595 error_report("Invalid cache option: %s", cache);
2600 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2601 flags, writethrough, s.quiet, false);
2603 /* TODO ultimately we should allow --target-image-opts
2604 * to be used even when -n is not given.
2605 * That has to wait for bdrv_create to be improved
2606 * to allow filenames in option syntax
2608 s.target = img_open_file(out_filename, open_opts, out_fmt,
2609 flags, writethrough, s.quiet, false);
2610 open_opts = NULL; /* blk_new_open will have freed it */
2616 out_bs = blk_bs(s.target);
2618 if (bitmaps && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2619 error_report("Format driver '%s' does not support bitmaps",
2620 out_bs->drv->format_name);
2625 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
2626 error_report("Compression not supported for this file format");
2631 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2632 * or discard_alignment of the out_bs is greater. Limit to
2633 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2634 s.buf_sectors = MIN(MAX_BUF_SECTORS,
2636 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2637 out_bs->bl.pdiscard_alignment >>
2638 BDRV_SECTOR_BITS)));
2640 /* try to align the write requests to the destination to avoid unnecessary
2642 s.alignment = MAX(pow2floor(s.min_sparse),
2643 DIV_ROUND_UP(out_bs->bl.request_alignment,
2645 assert(is_power_of_2(s.alignment));
2648 int64_t output_sectors = blk_nb_sectors(s.target);
2649 if (output_sectors < 0) {
2650 error_report("unable to get output image length: %s",
2651 strerror(-output_sectors));
2654 } else if (output_sectors < s.total_sectors) {
2655 error_report("output file is smaller than input file");
2661 if (s.target_has_backing && s.target_is_new) {
2662 /* Errors are treated as "backing length unknown" (which means
2663 * s.target_backing_sectors has to be negative, which it will
2664 * be automatically). The backing file length is used only
2665 * for optimizations, so such a case is not fatal. */
2666 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2668 s.target_backing_sectors = -1;
2671 ret = bdrv_get_info(out_bs, &bdi);
2674 error_report("could not get block driver info");
2678 s.compressed = s.compressed || bdi.needs_compressed_writes;
2679 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2682 ret = convert_do_copy(&s);
2684 /* Now copy the bitmaps */
2685 if (bitmaps && ret == 0) {
2686 ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs);
2691 qemu_progress_print(100, 0);
2693 qemu_progress_end();
2694 qemu_opts_del(opts);
2695 qemu_opts_free(create_opts);
2696 qemu_opts_del(sn_opts);
2697 qobject_unref(open_opts);
2698 blk_unref(s.target);
2700 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2701 blk_unref(s.src[bs_i]);
2705 g_free(s.src_sectors);
2713 static void dump_snapshots(BlockDriverState *bs)
2715 QEMUSnapshotInfo *sn_tab, *sn;
2718 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2721 printf("Snapshot list:\n");
2722 bdrv_snapshot_dump(NULL);
2724 for(i = 0; i < nb_sns; i++) {
2726 bdrv_snapshot_dump(sn);
2732 static void dump_json_image_info_list(ImageInfoList *list)
2736 Visitor *v = qobject_output_visitor_new(&obj);
2738 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2739 visit_complete(v, &obj);
2740 str = qobject_to_json_pretty(obj);
2741 assert(str != NULL);
2742 printf("%s\n", qstring_get_str(str));
2748 static void dump_json_image_info(ImageInfo *info)
2752 Visitor *v = qobject_output_visitor_new(&obj);
2754 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2755 visit_complete(v, &obj);
2756 str = qobject_to_json_pretty(obj);
2757 assert(str != NULL);
2758 printf("%s\n", qstring_get_str(str));
2764 static void dump_human_image_info_list(ImageInfoList *list)
2766 ImageInfoList *elem;
2769 for (elem = list; elem; elem = elem->next) {
2775 bdrv_image_info_dump(elem->value);
2779 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2781 return strcmp(a, b) == 0;
2785 * Open an image file chain and return an ImageInfoList
2787 * @filename: topmost image filename
2788 * @fmt: topmost image format (may be NULL to autodetect)
2789 * @chain: true - enumerate entire backing file chain
2790 * false - only topmost image file
2792 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2793 * image file. If there was an error a message will have been printed to
2796 static ImageInfoList *collect_image_info_list(bool image_opts,
2797 const char *filename,
2799 bool chain, bool force_share)
2801 ImageInfoList *head = NULL;
2802 ImageInfoList **last = &head;
2803 GHashTable *filenames;
2806 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2810 BlockDriverState *bs;
2812 ImageInfoList *elem;
2814 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2815 error_report("Backing file '%s' creates an infinite loop.",
2819 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2821 blk = img_open(image_opts, filename, fmt,
2822 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2829 bdrv_query_image_info(bs, &info, &err);
2831 error_report_err(err);
2836 elem = g_new0(ImageInfoList, 1);
2843 /* Clear parameters that only apply to the topmost image */
2844 filename = fmt = NULL;
2848 if (info->has_full_backing_filename) {
2849 filename = info->full_backing_filename;
2850 } else if (info->has_backing_filename) {
2851 error_report("Could not determine absolute backing filename,"
2852 " but backing filename '%s' present",
2853 info->backing_filename);
2856 if (info->has_backing_filename_format) {
2857 fmt = info->backing_filename_format;
2861 g_hash_table_destroy(filenames);
2865 qapi_free_ImageInfoList(head);
2866 g_hash_table_destroy(filenames);
2870 static int img_info(int argc, char **argv)
2873 OutputFormat output_format = OFORMAT_HUMAN;
2875 const char *filename, *fmt, *output;
2876 ImageInfoList *list;
2877 bool image_opts = false;
2878 bool force_share = false;
2883 int option_index = 0;
2884 static const struct option long_options[] = {
2885 {"help", no_argument, 0, 'h'},
2886 {"format", required_argument, 0, 'f'},
2887 {"output", required_argument, 0, OPTION_OUTPUT},
2888 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2889 {"object", required_argument, 0, OPTION_OBJECT},
2890 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2891 {"force-share", no_argument, 0, 'U'},
2894 c = getopt_long(argc, argv, ":f:hU",
2895 long_options, &option_index);
2901 missing_argument(argv[optind - 1]);
2904 unrecognized_option(argv[optind - 1]);
2918 case OPTION_BACKING_CHAIN:
2921 case OPTION_OBJECT: {
2923 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2929 case OPTION_IMAGE_OPTS:
2934 if (optind != argc - 1) {
2935 error_exit("Expecting one image file name");
2937 filename = argv[optind++];
2939 if (output && !strcmp(output, "json")) {
2940 output_format = OFORMAT_JSON;
2941 } else if (output && !strcmp(output, "human")) {
2942 output_format = OFORMAT_HUMAN;
2943 } else if (output) {
2944 error_report("--output must be used with human or json as argument.");
2948 if (qemu_opts_foreach(&qemu_object_opts,
2949 user_creatable_add_opts_foreach,
2950 qemu_img_object_print_help, &error_fatal)) {
2954 list = collect_image_info_list(image_opts, filename, fmt, chain,
2960 switch (output_format) {
2962 dump_human_image_info_list(list);
2966 dump_json_image_info_list(list);
2968 dump_json_image_info(list->value);
2973 qapi_free_ImageInfoList(list);
2977 static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2980 switch (output_format) {
2982 if (e->data && !e->has_offset) {
2983 error_report("File contains external, encrypted or compressed clusters.");
2986 if (e->data && !e->zero) {
2987 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2988 e->start, e->length,
2989 e->has_offset ? e->offset : 0,
2990 e->has_filename ? e->filename : "");
2992 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2993 * Modify the flags here to allow more coalescing.
2995 if (next && (!next->data || next->zero)) {
3001 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
3002 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
3003 e->start, e->length, e->depth,
3004 e->zero ? "true" : "false",
3005 e->data ? "true" : "false");
3006 if (e->has_offset) {
3007 printf(", \"offset\": %"PRId64"", e->offset);
3019 static int get_block_status(BlockDriverState *bs, int64_t offset,
3020 int64_t bytes, MapEntry *e)
3024 BlockDriverState *file;
3027 char *filename = NULL;
3029 /* As an optimization, we could cache the current range of unallocated
3030 * clusters in each file of the chain, and avoid querying the same
3036 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
3041 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
3044 bs = backing_bs(bs);
3053 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3055 if (file && has_offset) {
3056 bdrv_refresh_filename(file);
3057 filename = file->filename;
3063 .data = !!(ret & BDRV_BLOCK_DATA),
3064 .zero = !!(ret & BDRV_BLOCK_ZERO),
3066 .has_offset = has_offset,
3068 .has_filename = filename,
3069 .filename = filename,
3075 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3077 if (curr->length == 0) {
3080 if (curr->zero != next->zero ||
3081 curr->data != next->data ||
3082 curr->depth != next->depth ||
3083 curr->has_filename != next->has_filename ||
3084 curr->has_offset != next->has_offset) {
3087 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
3090 if (curr->has_offset && curr->offset + curr->length != next->offset) {
3096 static int img_map(int argc, char **argv)
3099 OutputFormat output_format = OFORMAT_HUMAN;
3101 BlockDriverState *bs;
3102 const char *filename, *fmt, *output;
3104 MapEntry curr = { .length = 0 }, next;
3106 bool image_opts = false;
3107 bool force_share = false;
3108 int64_t start_offset = 0;
3109 int64_t max_length = -1;
3114 int option_index = 0;
3115 static const struct option long_options[] = {
3116 {"help", no_argument, 0, 'h'},
3117 {"format", required_argument, 0, 'f'},
3118 {"output", required_argument, 0, OPTION_OUTPUT},
3119 {"object", required_argument, 0, OPTION_OBJECT},
3120 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3121 {"force-share", no_argument, 0, 'U'},
3122 {"start-offset", required_argument, 0, 's'},
3123 {"max-length", required_argument, 0, 'l'},
3126 c = getopt_long(argc, argv, ":f:s:l:hU",
3127 long_options, &option_index);
3133 missing_argument(argv[optind - 1]);
3136 unrecognized_option(argv[optind - 1]);
3151 start_offset = cvtnum("start offset", optarg);
3152 if (start_offset < 0) {
3157 max_length = cvtnum("max length", optarg);
3158 if (max_length < 0) {
3162 case OPTION_OBJECT: {
3164 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3170 case OPTION_IMAGE_OPTS:
3175 if (optind != argc - 1) {
3176 error_exit("Expecting one image file name");
3178 filename = argv[optind];
3180 if (output && !strcmp(output, "json")) {
3181 output_format = OFORMAT_JSON;
3182 } else if (output && !strcmp(output, "human")) {
3183 output_format = OFORMAT_HUMAN;
3184 } else if (output) {
3185 error_report("--output must be used with human or json as argument.");
3189 if (qemu_opts_foreach(&qemu_object_opts,
3190 user_creatable_add_opts_foreach,
3191 qemu_img_object_print_help, &error_fatal)) {
3195 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
3201 if (output_format == OFORMAT_HUMAN) {
3202 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3203 } else if (output_format == OFORMAT_JSON) {
3207 length = blk_getlength(blk);
3209 error_report("Failed to get size for '%s'", filename);
3212 if (max_length != -1) {
3213 length = MIN(start_offset + max_length, length);
3216 curr.start = start_offset;
3217 while (curr.start + curr.length < length) {
3218 int64_t offset = curr.start + curr.length;
3221 /* Probe up to 1 GiB at a time. */
3222 n = MIN(1 * GiB, length - offset);
3223 ret = get_block_status(bs, offset, n, &next);
3226 error_report("Could not read file metadata: %s", strerror(-ret));
3230 if (entry_mergeable(&curr, &next)) {
3231 curr.length += next.length;
3235 if (curr.length > 0) {
3236 ret = dump_map_entry(output_format, &curr, &next);
3244 ret = dump_map_entry(output_format, &curr, NULL);
3245 if (output_format == OFORMAT_JSON) {
3254 #define SNAPSHOT_LIST 1
3255 #define SNAPSHOT_CREATE 2
3256 #define SNAPSHOT_APPLY 3
3257 #define SNAPSHOT_DELETE 4
3259 static int img_snapshot(int argc, char **argv)
3262 BlockDriverState *bs;
3263 QEMUSnapshotInfo sn;
3264 char *filename, *snapshot_name = NULL;
3265 int c, ret = 0, bdrv_oflags;
3270 bool image_opts = false;
3271 bool force_share = false;
3273 bdrv_oflags = BDRV_O_RDWR;
3274 /* Parse commandline parameters */
3276 static const struct option long_options[] = {
3277 {"help", no_argument, 0, 'h'},
3278 {"object", required_argument, 0, OPTION_OBJECT},
3279 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3280 {"force-share", no_argument, 0, 'U'},
3283 c = getopt_long(argc, argv, ":la:c:d:hqU",
3284 long_options, NULL);
3290 missing_argument(argv[optind - 1]);
3293 unrecognized_option(argv[optind - 1]);
3300 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3303 action = SNAPSHOT_LIST;
3304 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
3308 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3311 action = SNAPSHOT_APPLY;
3312 snapshot_name = optarg;
3316 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3319 action = SNAPSHOT_CREATE;
3320 snapshot_name = optarg;
3324 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3327 action = SNAPSHOT_DELETE;
3328 snapshot_name = optarg;
3336 case OPTION_OBJECT: {
3338 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3344 case OPTION_IMAGE_OPTS:
3350 if (optind != argc - 1) {
3351 error_exit("Expecting one image file name");
3353 filename = argv[optind++];
3355 if (qemu_opts_foreach(&qemu_object_opts,
3356 user_creatable_add_opts_foreach,
3357 qemu_img_object_print_help, &error_fatal)) {
3361 /* Open the image */
3362 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3369 /* Perform the requested action */
3375 case SNAPSHOT_CREATE:
3376 memset(&sn, 0, sizeof(sn));
3377 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3379 qemu_gettimeofday(&tv);
3380 sn.date_sec = tv.tv_sec;
3381 sn.date_nsec = tv.tv_usec * 1000;
3383 ret = bdrv_snapshot_create(bs, &sn);
3385 error_report("Could not create snapshot '%s': %d (%s)",
3386 snapshot_name, ret, strerror(-ret));
3390 case SNAPSHOT_APPLY:
3391 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3393 error_reportf_err(err, "Could not apply snapshot '%s': ",
3398 case SNAPSHOT_DELETE:
3399 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3401 error_report("Could not delete snapshot '%s': snapshot not "
3402 "found", snapshot_name);
3405 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3407 error_reportf_err(err, "Could not delete snapshot '%s': ",
3423 static int img_rebase(int argc, char **argv)
3425 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3426 uint8_t *buf_old = NULL;
3427 uint8_t *buf_new = NULL;
3428 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
3430 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3431 int c, flags, src_flags, ret;
3432 bool writethrough, src_writethrough;
3434 bool force_share = false;
3437 Error *local_err = NULL;
3438 bool image_opts = false;
3440 /* Parse commandline parameters */
3442 cache = BDRV_DEFAULT_CACHE;
3443 src_cache = BDRV_DEFAULT_CACHE;
3447 static const struct option long_options[] = {
3448 {"help", no_argument, 0, 'h'},
3449 {"object", required_argument, 0, OPTION_OBJECT},
3450 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3451 {"force-share", no_argument, 0, 'U'},
3454 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3455 long_options, NULL);
3461 missing_argument(argv[optind - 1]);
3464 unrecognized_option(argv[optind - 1]);
3473 out_basefmt = optarg;
3476 out_baseimg = optarg;
3493 case OPTION_OBJECT: {
3495 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3501 case OPTION_IMAGE_OPTS:
3514 if (optind != argc - 1) {
3515 error_exit("Expecting one image file name");
3517 if (!unsafe && !out_baseimg) {
3518 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3520 filename = argv[optind++];
3522 if (qemu_opts_foreach(&qemu_object_opts,
3523 user_creatable_add_opts_foreach,
3524 qemu_img_object_print_help, &error_fatal)) {
3528 qemu_progress_init(progress, 2.0);
3529 qemu_progress_print(0, 100);
3531 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3532 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3534 error_report("Invalid cache option: %s", cache);
3539 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3541 error_report("Invalid source cache option: %s", src_cache);
3545 /* The source files are opened read-only, don't care about WCE */
3546 assert((src_flags & BDRV_O_RDWR) == 0);
3547 (void) src_writethrough;
3552 * Ignore the old backing file for unsafe rebase in case we want to correct
3553 * the reference to a renamed or moved backing file.
3555 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3563 if (out_basefmt != NULL) {
3564 if (bdrv_find_format(out_basefmt) == NULL) {
3565 error_report("Invalid format name: '%s'", out_basefmt);
3571 /* For safe rebasing we need to compare old and new backing file */
3573 QDict *options = NULL;
3574 BlockDriverState *base_bs = backing_bs(bs);
3577 blk_old_backing = blk_new(qemu_get_aio_context(),
3578 BLK_PERM_CONSISTENT_READ,
3580 ret = blk_insert_bs(blk_old_backing, base_bs,
3583 error_reportf_err(local_err,
3584 "Could not reuse old backing file '%s': ",
3589 blk_old_backing = NULL;
3592 if (out_baseimg[0]) {
3593 const char *overlay_filename;
3594 char *out_real_path;
3596 options = qdict_new();
3598 qdict_put_str(options, "driver", out_basefmt);
3601 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3604 bdrv_refresh_filename(bs);
3605 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3608 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3612 qobject_unref(options);
3613 error_reportf_err(local_err,
3614 "Could not resolve backing filename: ");
3620 * Find out whether we rebase an image on top of a previous image
3623 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
3624 if (prefix_chain_bs) {
3625 qobject_unref(options);
3626 g_free(out_real_path);
3628 blk_new_backing = blk_new(qemu_get_aio_context(),
3629 BLK_PERM_CONSISTENT_READ,
3631 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3634 error_reportf_err(local_err,
3635 "Could not reuse backing file '%s': ",
3640 blk_new_backing = blk_new_open(out_real_path, NULL,
3641 options, src_flags, &local_err);
3642 g_free(out_real_path);
3643 if (!blk_new_backing) {
3644 error_reportf_err(local_err,
3645 "Could not open new backing file '%s': ",
3655 * Check each unallocated cluster in the COW file. If it is unallocated,
3656 * accesses go to the backing file. We must therefore compare this cluster
3657 * in the old and new backing file, and if they differ we need to copy it
3658 * from the old backing file into the COW file.
3660 * If qemu-img crashes during this step, no harm is done. The content of
3661 * the image is the same as the original one at any time.
3665 int64_t old_backing_size = 0;
3666 int64_t new_backing_size = 0;
3669 float local_progress = 0;
3671 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3672 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3674 size = blk_getlength(blk);
3676 error_report("Could not get size of '%s': %s",
3677 filename, strerror(-size));
3681 if (blk_old_backing) {
3682 old_backing_size = blk_getlength(blk_old_backing);
3683 if (old_backing_size < 0) {
3684 char backing_name[PATH_MAX];
3686 bdrv_get_backing_filename(bs, backing_name,
3687 sizeof(backing_name));
3688 error_report("Could not get size of '%s': %s",
3689 backing_name, strerror(-old_backing_size));
3694 if (blk_new_backing) {
3695 new_backing_size = blk_getlength(blk_new_backing);
3696 if (new_backing_size < 0) {
3697 error_report("Could not get size of '%s': %s",
3698 out_baseimg, strerror(-new_backing_size));
3705 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3708 for (offset = 0; offset < size; offset += n) {
3709 bool buf_old_is_zero = false;
3711 /* How many bytes can we handle with the next read? */
3712 n = MIN(IO_BUF_SIZE, size - offset);
3714 /* If the cluster is allocated, we don't need to take action */
3715 ret = bdrv_is_allocated(bs, offset, n, &n);
3717 error_report("error while reading image metadata: %s",
3725 if (prefix_chain_bs) {
3727 * If cluster wasn't changed since prefix_chain, we don't need
3730 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
3731 false, offset, n, &n);
3733 error_report("error while reading image metadata: %s",
3743 * Read old and new backing file and take into consideration that
3744 * backing files may be smaller than the COW image.
3746 if (offset >= old_backing_size) {
3747 memset(buf_old, 0, n);
3748 buf_old_is_zero = true;
3750 if (offset + n > old_backing_size) {
3751 n = old_backing_size - offset;
3754 ret = blk_pread(blk_old_backing, offset, buf_old, n);
3756 error_report("error while reading from old backing file");
3761 if (offset >= new_backing_size || !blk_new_backing) {
3762 memset(buf_new, 0, n);
3764 if (offset + n > new_backing_size) {
3765 n = new_backing_size - offset;
3768 ret = blk_pread(blk_new_backing, offset, buf_new, n);
3770 error_report("error while reading from new backing file");
3775 /* If they differ, we need to write to the COW file */
3776 uint64_t written = 0;
3778 while (written < n) {
3781 if (compare_buffers(buf_old + written, buf_new + written,
3782 n - written, &pnum))
3784 if (buf_old_is_zero) {
3785 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3787 ret = blk_pwrite(blk, offset + written,
3788 buf_old + written, pnum, 0);
3791 error_report("Error while writing to COW image: %s",
3799 qemu_progress_print(local_progress, 100);
3804 * Change the backing file. All clusters that are different from the old
3805 * backing file are overwritten in the COW file now, so the visible content
3806 * doesn't change when we switch the backing file.
3808 if (out_baseimg && *out_baseimg) {
3809 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3811 ret = bdrv_change_backing_file(bs, NULL, NULL);
3814 if (ret == -ENOSPC) {
3815 error_report("Could not change the backing file to '%s': No "
3816 "space left in the file header", out_baseimg);
3817 } else if (ret < 0) {
3818 error_report("Could not change the backing file to '%s': %s",
3819 out_baseimg, strerror(-ret));
3822 qemu_progress_print(100, 0);
3824 * TODO At this point it is possible to check if any clusters that are
3825 * allocated in the COW file are the same in the backing file. If so, they
3826 * could be dropped from the COW file. Don't do this before switching the
3827 * backing file, in case of a crash this would lead to corruption.
3830 qemu_progress_end();
3833 blk_unref(blk_old_backing);
3834 blk_unref(blk_new_backing);
3836 qemu_vfree(buf_old);
3837 qemu_vfree(buf_new);
3846 static int img_resize(int argc, char **argv)
3849 int c, ret, relative;
3850 const char *filename, *fmt, *size;
3851 int64_t n, total_size, current_size;
3853 BlockBackend *blk = NULL;
3854 PreallocMode prealloc = PREALLOC_MODE_OFF;
3857 static QemuOptsList resize_options = {
3858 .name = "resize_options",
3859 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3862 .name = BLOCK_OPT_SIZE,
3863 .type = QEMU_OPT_SIZE,
3864 .help = "Virtual disk size"
3870 bool image_opts = false;
3871 bool shrink = false;
3873 /* Remove size from argv manually so that negative numbers are not treated
3874 * as options by getopt. */
3876 error_exit("Not enough arguments");
3880 size = argv[--argc];
3882 /* Parse getopt arguments */
3885 static const struct option long_options[] = {
3886 {"help", no_argument, 0, 'h'},
3887 {"object", required_argument, 0, OPTION_OBJECT},
3888 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3889 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3890 {"shrink", no_argument, 0, OPTION_SHRINK},
3893 c = getopt_long(argc, argv, ":f:hq",
3894 long_options, NULL);
3900 missing_argument(argv[optind - 1]);
3903 unrecognized_option(argv[optind - 1]);
3914 case OPTION_OBJECT: {
3916 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3922 case OPTION_IMAGE_OPTS:
3925 case OPTION_PREALLOCATION:
3926 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3927 PREALLOC_MODE__MAX, NULL);
3928 if (prealloc == PREALLOC_MODE__MAX) {
3929 error_report("Invalid preallocation mode '%s'", optarg);
3938 if (optind != argc - 1) {
3939 error_exit("Expecting image file name and size");
3941 filename = argv[optind++];
3943 if (qemu_opts_foreach(&qemu_object_opts,
3944 user_creatable_add_opts_foreach,
3945 qemu_img_object_print_help, &error_fatal)) {
3949 /* Choose grow, shrink, or absolute resize mode */
3965 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3966 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3968 error_report_err(err);
3970 qemu_opts_del(param);
3973 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3974 qemu_opts_del(param);
3976 blk = img_open(image_opts, filename, fmt,
3977 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3984 current_size = blk_getlength(blk);
3985 if (current_size < 0) {
3986 error_report("Failed to inquire current image length: %s",
3987 strerror(-current_size));
3993 total_size = current_size + n * relative;
3997 if (total_size <= 0) {
3998 error_report("New image size must be positive");
4003 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
4004 error_report("Preallocation can only be used for growing images");
4009 if (total_size < current_size && !shrink) {
4010 warn_report("Shrinking an image will delete all data beyond the "
4011 "shrunken image's end. Before performing such an "
4012 "operation, make sure there is no important data there.");
4014 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
4016 "Use the --shrink option to perform a shrink operation.");
4020 warn_report("Using the --shrink option will suppress this message. "
4021 "Note that future versions of qemu-img may refuse to "
4022 "shrink images without this option.");
4027 * The user expects the image to have the desired size after
4028 * resizing, so pass @exact=true. It is of no use to report
4029 * success when the image has not actually been resized.
4031 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
4033 qprintf(quiet, "Image resized.\n");
4035 error_report_err(err);
4045 static void amend_status_cb(BlockDriverState *bs,
4046 int64_t offset, int64_t total_work_size,
4049 qemu_progress_print(100.f * offset / total_work_size, 0);
4052 static int print_amend_option_help(const char *format)
4056 /* Find driver and parse its options */
4057 drv = bdrv_find_format(format);
4059 error_report("Unknown file format '%s'", format);
4063 if (!drv->bdrv_amend_options) {
4064 error_report("Format driver '%s' does not support option amendment",
4069 /* Every driver supporting amendment must have amend_opts */
4070 assert(drv->amend_opts);
4072 printf("Amend options for '%s':\n", format);
4073 qemu_opts_print_help(drv->amend_opts, false);
4077 static int img_amend(int argc, char **argv)
4081 char *options = NULL;
4082 QemuOptsList *amend_opts = NULL;
4083 QemuOpts *opts = NULL;
4084 const char *fmt = NULL, *filename, *cache;
4087 bool quiet = false, progress = false;
4088 BlockBackend *blk = NULL;
4089 BlockDriverState *bs = NULL;
4090 bool image_opts = false;
4093 cache = BDRV_DEFAULT_CACHE;
4095 static const struct option long_options[] = {
4096 {"help", no_argument, 0, 'h'},
4097 {"object", required_argument, 0, OPTION_OBJECT},
4098 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4099 {"force", no_argument, 0, OPTION_FORCE},
4102 c = getopt_long(argc, argv, ":ho:f:t:pq",
4103 long_options, NULL);
4110 missing_argument(argv[optind - 1]);
4113 unrecognized_option(argv[optind - 1]);
4119 if (accumulate_options(&options, optarg) < 0) {
4121 goto out_no_progress;
4137 opts = qemu_opts_parse_noisily(&qemu_object_opts,
4141 goto out_no_progress;
4144 case OPTION_IMAGE_OPTS:
4154 error_exit("Must specify options (-o)");
4157 if (qemu_opts_foreach(&qemu_object_opts,
4158 user_creatable_add_opts_foreach,
4159 qemu_img_object_print_help, &error_fatal)) {
4161 goto out_no_progress;
4167 qemu_progress_init(progress, 1.0);
4169 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4170 if (fmt && has_help_option(options)) {
4171 /* If a format is explicitly specified (and possibly no filename is
4172 * given), print option help here */
4173 ret = print_amend_option_help(fmt);
4177 if (optind != argc - 1) {
4178 error_report("Expecting one image file name");
4183 flags = BDRV_O_RDWR;
4184 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
4186 error_report("Invalid cache option: %s", cache);
4190 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4198 fmt = bs->drv->format_name;
4200 if (has_help_option(options)) {
4201 /* If the format was auto-detected, print option help here */
4202 ret = print_amend_option_help(fmt);
4206 if (!bs->drv->bdrv_amend_options) {
4207 error_report("Format driver '%s' does not support option amendment",
4213 /* Every driver supporting amendment must have amend_opts */
4214 assert(bs->drv->amend_opts);
4216 amend_opts = qemu_opts_append(amend_opts, bs->drv->amend_opts);
4217 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
4218 qemu_opts_do_parse(opts, options, NULL, &err);
4221 /* Try to parse options using the create options */
4223 amend_opts = qemu_opts_append(amend_opts, bs->drv->create_opts);
4224 qemu_opts_del(opts);
4225 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
4226 qemu_opts_do_parse(opts, options, NULL, &err1);
4229 error_append_hint(&err,
4230 "This option is only supported for image creation\n");
4235 error_report_err(err);
4240 /* In case the driver does not call amend_status_cb() */
4241 qemu_progress_print(0.f, 0);
4242 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, force, &err);
4243 qemu_progress_print(100.f, 0);
4245 error_report_err(err);
4250 qemu_progress_end();
4254 qemu_opts_del(opts);
4255 qemu_opts_free(amend_opts);
4264 typedef struct BenchData {
4266 uint64_t image_size;
4273 bool drain_on_flush;
4282 static void bench_undrained_flush_cb(void *opaque, int ret)
4285 error_report("Failed flush request: %s", strerror(-ret));
4290 static void bench_cb(void *opaque, int ret)
4292 BenchData *b = opaque;
4296 error_report("Failed request: %s", strerror(-ret));
4301 /* Just finished a flush with drained queue: Start next requests */
4302 assert(b->in_flight == 0);
4303 b->in_flush = false;
4304 } else if (b->in_flight > 0) {
4305 int remaining = b->n - b->in_flight;
4310 /* Time for flush? Drain queue if requested, then flush */
4311 if (b->flush_interval && remaining % b->flush_interval == 0) {
4312 if (!b->in_flight || !b->drain_on_flush) {
4313 BlockCompletionFunc *cb;
4315 if (b->drain_on_flush) {
4319 cb = bench_undrained_flush_cb;
4322 acb = blk_aio_flush(b->blk, cb, b);
4324 error_report("Failed to issue flush request");
4328 if (b->drain_on_flush) {
4334 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4335 int64_t offset = b->offset;
4336 /* blk_aio_* might look for completed I/Os and kick bench_cb
4337 * again, so make sure this operation is counted by in_flight
4338 * and b->offset is ready for the next submission.
4341 b->offset += b->step;
4342 b->offset %= b->image_size;
4344 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
4346 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
4349 error_report("Failed to issue request");
4355 static int img_bench(int argc, char **argv)
4358 const char *fmt = NULL, *filename;
4360 bool image_opts = false;
4361 bool is_write = false;
4365 size_t bufsize = 4096;
4368 int flush_interval = 0;
4369 bool drain_on_flush = true;
4371 BlockBackend *blk = NULL;
4372 BenchData data = {};
4374 bool writethrough = false;
4375 struct timeval t1, t2;
4377 bool force_share = false;
4381 static const struct option long_options[] = {
4382 {"help", no_argument, 0, 'h'},
4383 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
4384 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4385 {"pattern", required_argument, 0, OPTION_PATTERN},
4386 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
4387 {"force-share", no_argument, 0, 'U'},
4390 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4398 missing_argument(argv[optind - 1]);
4401 unrecognized_option(argv[optind - 1]);
4410 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4411 error_report("Invalid request count specified");
4421 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4422 error_report("Invalid queue depth specified");
4432 flags |= BDRV_O_NATIVE_AIO;
4435 ret = bdrv_parse_aio(optarg, &flags);
4437 error_report("Invalid aio option: %s", optarg);
4444 offset = cvtnum("offset", optarg);
4458 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4470 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4479 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4481 error_report("Invalid cache mode");
4487 flags |= BDRV_O_RDWR;
4493 case OPTION_PATTERN:
4497 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4498 error_report("Invalid pattern byte specified");
4504 case OPTION_FLUSH_INTERVAL:
4508 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4509 error_report("Invalid flush interval specified");
4512 flush_interval = res;
4515 case OPTION_NO_DRAIN:
4516 drain_on_flush = false;
4518 case OPTION_IMAGE_OPTS:
4524 if (optind != argc - 1) {
4525 error_exit("Expecting one image file name");
4527 filename = argv[argc - 1];
4529 if (!is_write && flush_interval) {
4530 error_report("--flush-interval is only available in write tests");
4534 if (flush_interval && flush_interval < depth) {
4535 error_report("Flush interval can't be smaller than depth");
4540 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4547 image_size = blk_getlength(blk);
4548 if (image_size < 0) {
4553 data = (BenchData) {
4555 .image_size = image_size,
4557 .step = step ?: bufsize,
4562 .flush_interval = flush_interval,
4563 .drain_on_flush = drain_on_flush,
4565 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4566 "(starting at offset %" PRId64 ", step size %d)\n",
4567 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4568 data.offset, data.step);
4569 if (flush_interval) {
4570 printf("Sending flush every %d requests\n", flush_interval);
4573 buf_size = data.nrreq * data.bufsize;
4574 data.buf = blk_blockalign(blk, buf_size);
4575 memset(data.buf, pattern, data.nrreq * data.bufsize);
4577 blk_register_buf(blk, data.buf, buf_size);
4579 data.qiov = g_new(QEMUIOVector, data.nrreq);
4580 for (i = 0; i < data.nrreq; i++) {
4581 qemu_iovec_init(&data.qiov[i], 1);
4582 qemu_iovec_add(&data.qiov[i],
4583 data.buf + i * data.bufsize, data.bufsize);
4586 gettimeofday(&t1, NULL);
4589 while (data.n > 0) {
4590 main_loop_wait(false);
4592 gettimeofday(&t2, NULL);
4594 printf("Run completed in %3.3f seconds.\n",
4595 (t2.tv_sec - t1.tv_sec)
4596 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4600 blk_unregister_buf(blk, data.buf);
4602 qemu_vfree(data.buf);
4619 typedef struct ImgBitmapAction {
4620 enum ImgBitmapAct act;
4621 const char *src; /* only used for merge */
4622 QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4625 static int img_bitmap(int argc, char **argv)
4629 QemuOpts *opts = NULL;
4630 const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4631 const char *filename, *bitmap;
4632 BlockBackend *blk = NULL, *src = NULL;
4633 BlockDriverState *bs = NULL, *src_bs = NULL;
4634 bool image_opts = false;
4635 int64_t granularity = 0;
4636 bool add = false, merge = false;
4637 QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4638 ImgBitmapAction *act, *act_next;
4641 QSIMPLEQ_INIT(&actions);
4644 static const struct option long_options[] = {
4645 {"help", no_argument, 0, 'h'},
4646 {"object", required_argument, 0, OPTION_OBJECT},
4647 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4648 {"add", no_argument, 0, OPTION_ADD},
4649 {"remove", no_argument, 0, OPTION_REMOVE},
4650 {"clear", no_argument, 0, OPTION_CLEAR},
4651 {"enable", no_argument, 0, OPTION_ENABLE},
4652 {"disable", no_argument, 0, OPTION_DISABLE},
4653 {"merge", required_argument, 0, OPTION_MERGE},
4654 {"granularity", required_argument, 0, 'g'},
4655 {"source-file", required_argument, 0, 'b'},
4656 {"source-format", required_argument, 0, 'F'},
4659 c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4666 missing_argument(argv[optind - 1]);
4669 unrecognized_option(argv[optind - 1]);
4675 src_filename = optarg;
4684 granularity = cvtnum("granularity", optarg);
4685 if (granularity < 0) {
4690 act = g_new0(ImgBitmapAction, 1);
4691 act->act = BITMAP_ADD;
4692 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4696 act = g_new0(ImgBitmapAction, 1);
4697 act->act = BITMAP_REMOVE;
4698 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4701 act = g_new0(ImgBitmapAction, 1);
4702 act->act = BITMAP_CLEAR;
4703 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4706 act = g_new0(ImgBitmapAction, 1);
4707 act->act = BITMAP_ENABLE;
4708 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4710 case OPTION_DISABLE:
4711 act = g_new0(ImgBitmapAction, 1);
4712 act->act = BITMAP_DISABLE;
4713 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4716 act = g_new0(ImgBitmapAction, 1);
4717 act->act = BITMAP_MERGE;
4719 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4723 opts = qemu_opts_parse_noisily(&qemu_object_opts, optarg, true);
4728 case OPTION_IMAGE_OPTS:
4734 if (qemu_opts_foreach(&qemu_object_opts,
4735 user_creatable_add_opts_foreach,
4736 qemu_img_object_print_help, &error_fatal)) {
4740 if (QSIMPLEQ_EMPTY(&actions)) {
4741 error_report("Need at least one of --add, --remove, --clear, "
4742 "--enable, --disable, or --merge");
4746 if (granularity && !add) {
4747 error_report("granularity only supported with --add");
4750 if (src_fmt && !src_filename) {
4751 error_report("-F only supported with -b");
4754 if (src_filename && !merge) {
4755 error_report("Merge bitmap source file only supported with "
4760 if (optind != argc - 2) {
4761 error_report("Expecting filename and bitmap name");
4765 filename = argv[optind];
4766 bitmap = argv[optind + 1];
4768 blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR, false, false,
4775 src = img_open(false, src_filename, src_fmt, 0, false, false, false);
4779 src_bs = blk_bs(src);
4784 QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4787 qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4788 !!granularity, granularity, true, true,
4789 false, false, &err);
4793 qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4797 qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4801 qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4804 case BITMAP_DISABLE:
4805 qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4809 do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4814 g_assert_not_reached();
4818 error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4830 qemu_opts_del(opts);
4846 int bsz; /* Block size */
4854 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4858 static int img_dd_bs(const char *arg,
4859 struct DdIo *in, struct DdIo *out,
4864 res = cvtnum_full("bs", arg, 1, INT_MAX);
4869 in->bsz = out->bsz = res;
4874 static int img_dd_count(const char *arg,
4875 struct DdIo *in, struct DdIo *out,
4878 dd->count = cvtnum("count", arg);
4880 if (dd->count < 0) {
4887 static int img_dd_if(const char *arg,
4888 struct DdIo *in, struct DdIo *out,
4891 in->filename = g_strdup(arg);
4896 static int img_dd_of(const char *arg,
4897 struct DdIo *in, struct DdIo *out,
4900 out->filename = g_strdup(arg);
4905 static int img_dd_skip(const char *arg,
4906 struct DdIo *in, struct DdIo *out,
4909 in->offset = cvtnum("skip", arg);
4911 if (in->offset < 0) {
4918 static int img_dd(int argc, char **argv)
4923 BlockDriver *drv = NULL, *proto_drv = NULL;
4924 BlockBackend *blk1 = NULL, *blk2 = NULL;
4925 QemuOpts *opts = NULL;
4926 QemuOptsList *create_opts = NULL;
4927 Error *local_err = NULL;
4928 bool image_opts = false;
4930 const char *out_fmt = "raw";
4931 const char *fmt = NULL;
4933 int64_t block_count = 0, out_pos, in_pos;
4934 bool force_share = false;
4935 struct DdInfo dd = {
4940 .bsz = 512, /* Block size is by default 512 bytes */
4952 const struct DdOpts options[] = {
4953 { "bs", img_dd_bs, C_BS },
4954 { "count", img_dd_count, C_COUNT },
4955 { "if", img_dd_if, C_IF },
4956 { "of", img_dd_of, C_OF },
4957 { "skip", img_dd_skip, C_SKIP },
4960 const struct option long_options[] = {
4961 { "help", no_argument, 0, 'h'},
4962 { "object", required_argument, 0, OPTION_OBJECT},
4963 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4964 { "force-share", no_argument, 0, 'U'},
4968 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4980 missing_argument(argv[optind - 1]);
4983 unrecognized_option(argv[optind - 1]);
4992 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4997 case OPTION_IMAGE_OPTS:
5003 for (i = optind; i < argc; i++) {
5005 arg = g_strdup(argv[i]);
5007 tmp = strchr(arg, '=');
5009 error_report("unrecognized operand %s", arg);
5016 for (j = 0; options[j].name != NULL; j++) {
5017 if (!strcmp(arg, options[j].name)) {
5021 if (options[j].name == NULL) {
5022 error_report("unrecognized operand %s", arg);
5027 if (options[j].f(tmp, &in, &out, &dd) != 0) {
5031 dd.flags |= options[j].flag;
5036 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
5037 error_report("Must specify both input and output files");
5042 if (qemu_opts_foreach(&qemu_object_opts,
5043 user_creatable_add_opts_foreach,
5044 qemu_img_object_print_help, &error_fatal)) {
5049 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
5057 drv = bdrv_find_format(out_fmt);
5059 error_report("Unknown file format");
5063 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
5066 error_report_err(local_err);
5070 if (!drv->create_opts) {
5071 error_report("Format driver '%s' does not support image creation",
5076 if (!proto_drv->create_opts) {
5077 error_report("Protocol driver '%s' does not support image creation",
5078 proto_drv->format_name);
5082 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5083 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5085 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5087 size = blk_getlength(blk1);
5089 error_report("Failed to get size for '%s'", in.filename);
5094 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5095 dd.count * in.bsz < size) {
5096 size = dd.count * in.bsz;
5099 /* Overflow means the specified offset is beyond input image's size */
5100 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5101 size < in.bsz * in.offset)) {
5102 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5104 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5105 size - in.bsz * in.offset, &error_abort);
5108 ret = bdrv_create(drv, out.filename, opts, &local_err);
5110 error_reportf_err(local_err,
5111 "%s: error while creating output image: ",
5117 /* TODO, we can't honour --image-opts for the target,
5118 * since it needs to be given in a format compatible
5119 * with the bdrv_create() call above which does not
5120 * support image-opts style.
5122 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
5123 false, false, false);
5130 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5131 size < in.offset * in.bsz)) {
5132 /* We give a warning if the skip option is bigger than the input
5133 * size and create an empty output disk image (i.e. like dd(1)).
5135 error_report("%s: cannot skip to specified offset", in.filename);
5138 in_pos = in.offset * in.bsz;
5141 in.buf = g_new(uint8_t, in.bsz);
5143 for (out_pos = 0; in_pos < size; block_count++) {
5144 int in_ret, out_ret;
5146 if (in_pos + in.bsz > size) {
5147 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
5149 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
5152 error_report("error while reading from input image file: %s",
5159 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
5162 error_report("error while writing to output image file: %s",
5163 strerror(-out_ret));
5172 qemu_opts_del(opts);
5173 qemu_opts_free(create_opts);
5176 g_free(in.filename);
5177 g_free(out.filename);
5187 static void dump_json_block_measure_info(BlockMeasureInfo *info)
5191 Visitor *v = qobject_output_visitor_new(&obj);
5193 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5194 visit_complete(v, &obj);
5195 str = qobject_to_json_pretty(obj);
5196 assert(str != NULL);
5197 printf("%s\n", qstring_get_str(str));
5203 static int img_measure(int argc, char **argv)
5205 static const struct option long_options[] = {
5206 {"help", no_argument, 0, 'h'},
5207 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5208 {"object", required_argument, 0, OPTION_OBJECT},
5209 {"output", required_argument, 0, OPTION_OUTPUT},
5210 {"size", required_argument, 0, OPTION_SIZE},
5211 {"force-share", no_argument, 0, 'U'},
5214 OutputFormat output_format = OFORMAT_HUMAN;
5215 BlockBackend *in_blk = NULL;
5217 const char *filename = NULL;
5218 const char *fmt = NULL;
5219 const char *out_fmt = "raw";
5220 char *options = NULL;
5221 char *snapshot_name = NULL;
5222 bool force_share = false;
5223 QemuOpts *opts = NULL;
5224 QemuOpts *object_opts = NULL;
5225 QemuOpts *sn_opts = NULL;
5226 QemuOptsList *create_opts = NULL;
5227 bool image_opts = false;
5228 uint64_t img_size = UINT64_MAX;
5229 BlockMeasureInfo *info = NULL;
5230 Error *local_err = NULL;
5234 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5235 long_options, NULL)) != -1) {
5248 if (accumulate_options(&options, optarg) < 0) {
5253 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5254 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5257 error_report("Failed in parsing snapshot param '%s'",
5262 snapshot_name = optarg;
5269 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
5275 case OPTION_IMAGE_OPTS:
5279 if (!strcmp(optarg, "json")) {
5280 output_format = OFORMAT_JSON;
5281 } else if (!strcmp(optarg, "human")) {
5282 output_format = OFORMAT_HUMAN;
5284 error_report("--output must be used with human or json "
5293 sval = cvtnum("image size", optarg);
5297 img_size = (uint64_t)sval;
5303 if (qemu_opts_foreach(&qemu_object_opts,
5304 user_creatable_add_opts_foreach,
5305 qemu_img_object_print_help, &error_fatal)) {
5309 if (argc - optind > 1) {
5310 error_report("At most one filename argument is allowed.");
5312 } else if (argc - optind == 1) {
5313 filename = argv[optind];
5316 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5317 error_report("--image-opts, -f, and -l require a filename argument.");
5320 if (filename && img_size != UINT64_MAX) {
5321 error_report("--size N cannot be used together with a filename.");
5324 if (!filename && img_size == UINT64_MAX) {
5325 error_report("Either --size N or one filename must be specified.");
5330 in_blk = img_open(image_opts, filename, fmt, 0,
5331 false, false, force_share);
5337 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5338 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5339 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5341 } else if (snapshot_name != NULL) {
5342 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5343 snapshot_name, &local_err);
5346 error_reportf_err(local_err, "Failed to load snapshot: ");
5351 drv = bdrv_find_format(out_fmt);
5353 error_report("Unknown file format '%s'", out_fmt);
5356 if (!drv->create_opts) {
5357 error_report("Format driver '%s' does not support image creation",
5362 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5363 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5364 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5366 qemu_opts_do_parse(opts, options, NULL, &local_err);
5368 error_report_err(local_err);
5369 error_report("Invalid options for file format '%s'", out_fmt);
5373 if (img_size != UINT64_MAX) {
5374 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5377 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5379 error_report_err(local_err);
5383 if (output_format == OFORMAT_HUMAN) {
5384 printf("required size: %" PRIu64 "\n", info->required);
5385 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
5386 if (info->has_bitmaps) {
5387 printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5390 dump_json_block_measure_info(info);
5396 qapi_free_BlockMeasureInfo(info);
5397 qemu_opts_del(object_opts);
5398 qemu_opts_del(opts);
5399 qemu_opts_del(sn_opts);
5400 qemu_opts_free(create_opts);
5406 static const img_cmd_t img_cmds[] = {
5407 #define DEF(option, callback, arg_string) \
5408 { option, callback },
5409 #include "qemu-img-cmds.h"
5414 int main(int argc, char **argv)
5416 const img_cmd_t *cmd;
5417 const char *cmdname;
5418 Error *local_error = NULL;
5419 char *trace_file = NULL;
5421 static const struct option long_options[] = {
5422 {"help", no_argument, 0, 'h'},
5423 {"version", no_argument, 0, 'V'},
5424 {"trace", required_argument, NULL, 'T'},
5429 signal(SIGPIPE, SIG_IGN);
5432 error_init(argv[0]);
5433 module_call_init(MODULE_INIT_TRACE);
5434 qemu_init_exec_dir(argv[0]);
5436 if (qemu_init_main_loop(&local_error)) {
5437 error_report_err(local_error);
5441 qcrypto_init(&error_fatal);
5443 module_call_init(MODULE_INIT_QOM);
5446 error_exit("Not enough arguments");
5449 qemu_add_opts(&qemu_object_opts);
5450 qemu_add_opts(&qemu_source_opts);
5451 qemu_add_opts(&qemu_trace_opts);
5453 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
5456 missing_argument(argv[optind - 1]);
5459 unrecognized_option(argv[optind - 1]);
5465 printf(QEMU_IMG_VERSION);
5469 trace_file = trace_opt_parse(optarg);
5474 cmdname = argv[optind];
5476 /* reset getopt_long scanning */
5482 qemu_reset_optind();
5484 if (!trace_init_backends()) {
5487 trace_init_file(trace_file);
5488 qemu_set_log(LOG_TRACE);
5490 /* find the command */
5491 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5492 if (!strcmp(cmdname, cmd->name)) {
5493 return cmd->handler(argc, argv);
5498 error_exit("Command not found: %s", cmdname);