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/sockets.h"
45 #include "qemu/units.h"
46 #include "qom/object_interfaces.h"
47 #include "sysemu/block-backend.h"
48 #include "block/block_int.h"
49 #include "block/blockjob.h"
50 #include "block/qapi.h"
51 #include "crypto/init.h"
52 #include "trace/control.h"
54 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
55 "\n" QEMU_COPYRIGHT "\n"
57 typedef struct img_cmd_t {
59 int (*handler)(int argc, char **argv);
64 OPTION_BACKING_CHAIN = 257,
66 OPTION_IMAGE_OPTS = 259,
68 OPTION_FLUSH_INTERVAL = 261,
69 OPTION_NO_DRAIN = 262,
70 OPTION_TARGET_IMAGE_OPTS = 263,
72 OPTION_PREALLOCATION = 265,
75 OPTION_TARGET_IS_ZERO = 268,
86 typedef enum OutputFormat {
91 /* Default to cache=writeback as data integrity is not important for qemu-img */
92 #define BDRV_DEFAULT_CACHE "writeback"
94 static void format_print(void *opaque, const char *name)
99 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
104 error_vreport(fmt, ap);
107 error_printf("Try 'qemu-img --help' for more information\n");
111 static void QEMU_NORETURN missing_argument(const char *option)
113 error_exit("missing argument for option '%s'", option);
116 static void QEMU_NORETURN unrecognized_option(const char *option)
118 error_exit("unrecognized option '%s'", option);
121 /* Please keep in synch with docs/tools/qemu-img.rst */
122 static void QEMU_NORETURN help(void)
124 const char *help_msg =
126 "usage: qemu-img [standard options] command [command options]\n"
127 "QEMU disk image utility\n"
129 " '-h', '--help' display this help and exit\n"
130 " '-V', '--version' output version information and exit\n"
131 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
132 " specify tracing options\n"
135 #define DEF(option, callback, arg_string) \
137 #include "qemu-img-cmds.h"
140 "Command parameters:\n"
141 " 'filename' is a disk image filename\n"
142 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
143 " manual page for a description of the object properties. The most common\n"
144 " object type is a 'secret', which is used to supply passwords and/or\n"
145 " encryption keys.\n"
146 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
147 " 'cache' is the cache mode used to write the output disk image, the valid\n"
148 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
149 " 'directsync' and 'unsafe' (default for convert)\n"
150 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
151 " options are the same as for the 'cache' option\n"
152 " 'size' is the disk image size in bytes. Optional suffixes\n"
153 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
154 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
155 " supported. 'b' is ignored.\n"
156 " 'output_filename' is the destination disk image filename\n"
157 " 'output_fmt' is the destination format\n"
158 " 'options' is a comma separated list of format specific options in a\n"
159 " name=value format. Use -o ? for an overview of the options supported by the\n"
161 " 'snapshot_param' is param used for internal snapshot, format\n"
162 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
164 " '-c' indicates that target image must be compressed (qcow format only)\n"
165 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
166 " new backing file match exactly. The image doesn't need a working\n"
167 " backing file before rebasing in this case (useful for renaming the\n"
168 " backing file). For image creation, allow creating without attempting\n"
169 " to open the backing file.\n"
170 " '-h' with or without a command shows this help and lists the supported formats\n"
171 " '-p' show progress of command (only certain commands)\n"
172 " '-q' use Quiet mode - do not print any output (except errors)\n"
173 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
174 " contain only zeros for qemu-img to create a sparse image during\n"
175 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
176 " unallocated or zero sectors, and the destination image will always be\n"
178 " '--output' takes the format in which the output must be done (human or json)\n"
179 " '-n' skips the target volume creation (useful if the volume is created\n"
180 " prior to running qemu-img)\n"
182 "Parameters to bitmap subcommand:\n"
183 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
184 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
185 " or '--merge source'\n"
186 " '-g granularity' sets the granularity for '--add' actions\n"
187 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
188 " bitmaps from an alternative file\n"
190 "Parameters to check subcommand:\n"
191 " '-r' tries to repair any inconsistencies that are found during the check.\n"
192 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
193 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
194 " hiding corruption that has already occurred.\n"
196 "Parameters to convert subcommand:\n"
197 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
198 " '-m' specifies how many coroutines work in parallel during the convert\n"
199 " process (defaults to 8)\n"
200 " '-W' allow to write to the target out of order rather than sequential\n"
202 "Parameters to snapshot subcommand:\n"
203 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
204 " '-a' applies a snapshot (revert disk to saved state)\n"
205 " '-c' creates a snapshot\n"
206 " '-d' deletes a snapshot\n"
207 " '-l' lists all snapshots in the given image\n"
209 "Parameters to compare subcommand:\n"
210 " '-f' first image format\n"
211 " '-F' second image format\n"
212 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
214 "Parameters to dd subcommand:\n"
215 " 'bs=BYTES' read and write up to BYTES bytes at a time "
217 " 'count=N' copy only N input blocks\n"
218 " 'if=FILE' read from FILE\n"
219 " 'of=FILE' write to FILE\n"
220 " 'skip=N' skip N bs-sized blocks at the start of input\n";
222 printf("%s\nSupported formats:", help_msg);
223 bdrv_iterate_format(format_print, NULL, false);
224 printf("\n\n" QEMU_HELP_BOTTOM "\n");
228 static QemuOptsList qemu_object_opts = {
230 .implied_opt_name = "qom-type",
231 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
237 static bool qemu_img_object_print_help(const char *type, QemuOpts *opts)
239 if (user_creatable_print_help(type, opts)) {
246 * Is @optarg safe for accumulate_options()?
247 * It is when multiple of them can be joined together separated by ','.
248 * To make that work, @optarg must not start with ',' (or else a
249 * separating ',' preceding it gets escaped), and it must not end with
250 * an odd number of ',' (or else a separating ',' following it gets
251 * escaped), or be empty (or else a separating ',' preceding it can
252 * escape a separating ',' following it).
255 static bool is_valid_option_list(const char *optarg)
257 size_t len = strlen(optarg);
260 if (!optarg[0] || optarg[0] == ',') {
264 for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
273 static int accumulate_options(char **options, char *optarg)
277 if (!is_valid_option_list(optarg)) {
278 error_report("Invalid option list: %s", optarg);
283 *options = g_strdup(optarg);
285 new_options = g_strdup_printf("%s,%s", *options, optarg);
287 *options = new_options;
292 static QemuOptsList qemu_source_opts = {
294 .implied_opt_name = "file",
295 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
301 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
307 ret = vprintf(fmt, args);
314 static int print_block_option_help(const char *filename, const char *fmt)
316 BlockDriver *drv, *proto_drv;
317 QemuOptsList *create_opts = NULL;
318 Error *local_err = NULL;
320 /* Find driver and parse its options */
321 drv = bdrv_find_format(fmt);
323 error_report("Unknown file format '%s'", fmt);
327 if (!drv->create_opts) {
328 error_report("Format driver '%s' does not support image creation", fmt);
332 create_opts = qemu_opts_append(create_opts, drv->create_opts);
334 proto_drv = bdrv_find_protocol(filename, true, &local_err);
336 error_report_err(local_err);
337 qemu_opts_free(create_opts);
340 if (!proto_drv->create_opts) {
341 error_report("Protocol driver '%s' does not support image creation",
342 proto_drv->format_name);
343 qemu_opts_free(create_opts);
346 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
350 printf("Supported options:\n");
352 printf("Supported %s options:\n", fmt);
354 qemu_opts_print_help(create_opts, false);
355 qemu_opts_free(create_opts);
359 "The protocol level may support further options.\n"
360 "Specify the target filename to include those options.\n");
367 static BlockBackend *img_open_opts(const char *optstr,
368 QemuOpts *opts, int flags, bool writethrough,
369 bool quiet, bool force_share)
372 Error *local_err = NULL;
374 options = qemu_opts_to_qdict(opts, NULL);
376 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
377 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
378 error_report("--force-share/-U conflicts with image options");
379 qobject_unref(options);
382 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
384 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
386 error_reportf_err(local_err, "Could not open '%s': ", optstr);
389 blk_set_enable_write_cache(blk, !writethrough);
394 static BlockBackend *img_open_file(const char *filename,
396 const char *fmt, int flags,
397 bool writethrough, bool quiet,
401 Error *local_err = NULL;
404 options = qdict_new();
407 qdict_put_str(options, "driver", fmt);
411 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
413 blk = blk_new_open(filename, NULL, options, flags, &local_err);
415 error_reportf_err(local_err, "Could not open '%s': ", filename);
418 blk_set_enable_write_cache(blk, !writethrough);
424 static int img_add_key_secrets(void *opaque,
425 const char *name, const char *value,
428 QDict *options = opaque;
430 if (g_str_has_suffix(name, "key-secret")) {
431 qdict_put_str(options, name, value);
438 static BlockBackend *img_open(bool image_opts,
439 const char *filename,
440 const char *fmt, int flags, bool writethrough,
441 bool quiet, bool force_share)
447 error_report("--image-opts and --format are mutually exclusive");
450 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
455 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
458 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
465 static int add_old_style_options(const char *fmt, QemuOpts *opts,
466 const char *base_filename,
467 const char *base_fmt)
470 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
472 error_report("Backing file not supported for file format '%s'",
478 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
479 error_report("Backing file format not supported for file "
487 static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
493 err = qemu_strtosz(value, NULL, &res);
494 if (err < 0 && err != -ERANGE) {
495 error_report("Invalid %s specified. You may use "
496 "k, M, G, T, P or E suffixes for", name);
497 error_report("kilobytes, megabytes, gigabytes, terabytes, "
498 "petabytes and exabytes.");
501 if (err == -ERANGE || res > max || res < min) {
502 error_report("Invalid %s specified. Must be between %" PRId64
503 " and %" PRId64 ".", name, min, max);
509 static int64_t cvtnum(const char *name, const char *value)
511 return cvtnum_full(name, value, 0, INT64_MAX);
514 static int img_create(int argc, char **argv)
517 uint64_t img_size = -1;
518 const char *fmt = "raw";
519 const char *base_fmt = NULL;
520 const char *filename;
521 const char *base_filename = NULL;
522 char *options = NULL;
523 Error *local_err = NULL;
528 static const struct option long_options[] = {
529 {"help", no_argument, 0, 'h'},
530 {"object", required_argument, 0, OPTION_OBJECT},
533 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
540 missing_argument(argv[optind - 1]);
543 unrecognized_option(argv[optind - 1]);
552 base_filename = optarg;
558 if (accumulate_options(&options, optarg) < 0) {
566 flags |= BDRV_O_NO_BACKING;
568 case OPTION_OBJECT: {
570 opts = qemu_opts_parse_noisily(&qemu_object_opts,
579 /* Get the filename */
580 filename = (optind < argc) ? argv[optind] : NULL;
581 if (options && has_help_option(options)) {
583 return print_block_option_help(filename, fmt);
586 if (optind >= argc) {
587 error_exit("Expecting image file name");
591 if (qemu_opts_foreach(&qemu_object_opts,
592 user_creatable_add_opts_foreach,
593 qemu_img_object_print_help, &error_fatal)) {
597 /* Get image size, if specified */
601 sval = cvtnum("image size", argv[optind++]);
605 img_size = (uint64_t)sval;
607 if (optind != argc) {
608 error_exit("Unexpected argument: %s", argv[optind]);
611 bdrv_img_create(filename, fmt, base_filename, base_fmt,
612 options, img_size, flags, quiet, &local_err);
614 error_reportf_err(local_err, "%s: ", filename);
626 static void dump_json_image_check(ImageCheck *check, bool quiet)
630 Visitor *v = qobject_output_visitor_new(&obj);
632 visit_type_ImageCheck(v, NULL, &check, &error_abort);
633 visit_complete(v, &obj);
634 str = qobject_to_json_pretty(obj);
636 qprintf(quiet, "%s\n", qstring_get_str(str));
642 static void dump_human_image_check(ImageCheck *check, bool quiet)
644 if (!(check->corruptions || check->leaks || check->check_errors)) {
645 qprintf(quiet, "No errors were found on the image.\n");
647 if (check->corruptions) {
648 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
649 "Data may be corrupted, or further writes to the image "
656 "\n%" PRId64 " leaked clusters were found on the image.\n"
657 "This means waste of disk space, but no harm to data.\n",
661 if (check->check_errors) {
664 " internal errors have occurred during the check.\n",
665 check->check_errors);
669 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
670 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
671 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
672 check->allocated_clusters, check->total_clusters,
673 check->allocated_clusters * 100.0 / check->total_clusters,
674 check->fragmented_clusters * 100.0 / check->allocated_clusters,
675 check->compressed_clusters * 100.0 /
676 check->allocated_clusters);
679 if (check->image_end_offset) {
681 "Image end offset: %" PRId64 "\n", check->image_end_offset);
685 static int collect_image_check(BlockDriverState *bs,
687 const char *filename,
692 BdrvCheckResult result;
694 ret = bdrv_check(bs, &result, fix);
699 check->filename = g_strdup(filename);
700 check->format = g_strdup(bdrv_get_format_name(bs));
701 check->check_errors = result.check_errors;
702 check->corruptions = result.corruptions;
703 check->has_corruptions = result.corruptions != 0;
704 check->leaks = result.leaks;
705 check->has_leaks = result.leaks != 0;
706 check->corruptions_fixed = result.corruptions_fixed;
707 check->has_corruptions_fixed = result.corruptions_fixed != 0;
708 check->leaks_fixed = result.leaks_fixed;
709 check->has_leaks_fixed = result.leaks_fixed != 0;
710 check->image_end_offset = result.image_end_offset;
711 check->has_image_end_offset = result.image_end_offset != 0;
712 check->total_clusters = result.bfi.total_clusters;
713 check->has_total_clusters = result.bfi.total_clusters != 0;
714 check->allocated_clusters = result.bfi.allocated_clusters;
715 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
716 check->fragmented_clusters = result.bfi.fragmented_clusters;
717 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
718 check->compressed_clusters = result.bfi.compressed_clusters;
719 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
725 * Checks an image for consistency. Exit codes:
727 * 0 - Check completed, image is good
728 * 1 - Check not completed because of internal errors
729 * 2 - Check completed, image is corrupted
730 * 3 - Check completed, image has leaked clusters, but is good otherwise
731 * 63 - Checks are not supported by the image format
733 static int img_check(int argc, char **argv)
736 OutputFormat output_format = OFORMAT_HUMAN;
737 const char *filename, *fmt, *output, *cache;
739 BlockDriverState *bs;
741 int flags = BDRV_O_CHECK;
745 bool image_opts = false;
746 bool force_share = false;
750 cache = BDRV_DEFAULT_CACHE;
753 int option_index = 0;
754 static const struct option long_options[] = {
755 {"help", no_argument, 0, 'h'},
756 {"format", required_argument, 0, 'f'},
757 {"repair", required_argument, 0, 'r'},
758 {"output", required_argument, 0, OPTION_OUTPUT},
759 {"object", required_argument, 0, OPTION_OBJECT},
760 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
761 {"force-share", no_argument, 0, 'U'},
764 c = getopt_long(argc, argv, ":hf:r:T:qU",
765 long_options, &option_index);
771 missing_argument(argv[optind - 1]);
774 unrecognized_option(argv[optind - 1]);
783 flags |= BDRV_O_RDWR;
785 if (!strcmp(optarg, "leaks")) {
786 fix = BDRV_FIX_LEAKS;
787 } else if (!strcmp(optarg, "all")) {
788 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
790 error_exit("Unknown option value for -r "
791 "(expecting 'leaks' or 'all'): %s", optarg);
806 case OPTION_OBJECT: {
808 opts = qemu_opts_parse_noisily(&qemu_object_opts,
814 case OPTION_IMAGE_OPTS:
819 if (optind != argc - 1) {
820 error_exit("Expecting one image file name");
822 filename = argv[optind++];
824 if (output && !strcmp(output, "json")) {
825 output_format = OFORMAT_JSON;
826 } else if (output && !strcmp(output, "human")) {
827 output_format = OFORMAT_HUMAN;
829 error_report("--output must be used with human or json as argument.");
833 if (qemu_opts_foreach(&qemu_object_opts,
834 user_creatable_add_opts_foreach,
835 qemu_img_object_print_help, &error_fatal)) {
839 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
841 error_report("Invalid source cache option: %s", cache);
845 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
852 check = g_new0(ImageCheck, 1);
853 ret = collect_image_check(bs, check, filename, fmt, fix);
855 if (ret == -ENOTSUP) {
856 error_report("This image format does not support checks");
861 if (check->corruptions_fixed || check->leaks_fixed) {
862 int corruptions_fixed, leaks_fixed;
863 bool has_leaks_fixed, has_corruptions_fixed;
865 leaks_fixed = check->leaks_fixed;
866 has_leaks_fixed = check->has_leaks_fixed;
867 corruptions_fixed = check->corruptions_fixed;
868 has_corruptions_fixed = check->has_corruptions_fixed;
870 if (output_format == OFORMAT_HUMAN) {
872 "The following inconsistencies were found and repaired:\n\n"
873 " %" PRId64 " leaked clusters\n"
874 " %" PRId64 " corruptions\n\n"
875 "Double checking the fixed image now...\n",
877 check->corruptions_fixed);
880 qapi_free_ImageCheck(check);
881 check = g_new0(ImageCheck, 1);
882 ret = collect_image_check(bs, check, filename, fmt, 0);
884 check->leaks_fixed = leaks_fixed;
885 check->has_leaks_fixed = has_leaks_fixed;
886 check->corruptions_fixed = corruptions_fixed;
887 check->has_corruptions_fixed = has_corruptions_fixed;
891 switch (output_format) {
893 dump_human_image_check(check, quiet);
896 dump_json_image_check(check, quiet);
901 if (ret || check->check_errors) {
903 error_report("Check failed: %s", strerror(-ret));
905 error_report("Check failed");
911 if (check->corruptions) {
913 } else if (check->leaks) {
920 qapi_free_ImageCheck(check);
925 typedef struct CommonBlockJobCBInfo {
926 BlockDriverState *bs;
928 } CommonBlockJobCBInfo;
930 static void common_block_job_cb(void *opaque, int ret)
932 CommonBlockJobCBInfo *cbi = opaque;
935 error_setg_errno(cbi->errp, -ret, "Block job failed");
939 static void run_block_job(BlockJob *job, Error **errp)
941 AioContext *aio_context = blk_get_aio_context(job->blk);
944 aio_context_acquire(aio_context);
947 float progress = 0.0f;
948 aio_poll(aio_context, true);
949 if (job->job.progress.total) {
950 progress = (float)job->job.progress.current /
951 job->job.progress.total * 100.f;
953 qemu_progress_print(progress, 0);
954 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
956 if (!job_is_completed(&job->job)) {
957 ret = job_complete_sync(&job->job, errp);
961 job_unref(&job->job);
962 aio_context_release(aio_context);
964 /* publish completion progress only when success */
966 qemu_progress_print(100.f, 0);
970 static int img_commit(int argc, char **argv)
973 const char *filename, *fmt, *cache, *base;
975 BlockDriverState *bs, *base_bs;
977 bool progress = false, quiet = false, drop = false;
979 Error *local_err = NULL;
980 CommonBlockJobCBInfo cbi;
981 bool image_opts = false;
982 AioContext *aio_context;
985 cache = BDRV_DEFAULT_CACHE;
988 static const struct option long_options[] = {
989 {"help", no_argument, 0, 'h'},
990 {"object", required_argument, 0, OPTION_OBJECT},
991 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
994 c = getopt_long(argc, argv, ":f:ht:b:dpq",
1001 missing_argument(argv[optind - 1]);
1004 unrecognized_option(argv[optind - 1]);
1029 case OPTION_OBJECT: {
1031 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1037 case OPTION_IMAGE_OPTS:
1043 /* Progress is not shown in Quiet mode */
1048 if (optind != argc - 1) {
1049 error_exit("Expecting one image file name");
1051 filename = argv[optind++];
1053 if (qemu_opts_foreach(&qemu_object_opts,
1054 user_creatable_add_opts_foreach,
1055 qemu_img_object_print_help, &error_fatal)) {
1059 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
1060 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1062 error_report("Invalid cache option: %s", cache);
1066 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1073 qemu_progress_init(progress, 1.f);
1074 qemu_progress_print(0.f, 100);
1077 base_bs = bdrv_find_backing_image(bs, base);
1079 error_setg(&local_err,
1080 "Did not find '%s' in the backing chain of '%s'",
1085 /* This is different from QMP, which by default uses the deepest file in
1086 * the backing chain (i.e., the very base); however, the traditional
1087 * behavior of qemu-img commit is using the immediate backing file. */
1088 base_bs = bdrv_backing_chain_next(bs);
1090 error_setg(&local_err, "Image does not have a backing file");
1095 cbi = (CommonBlockJobCBInfo){
1100 aio_context = bdrv_get_aio_context(bs);
1101 aio_context_acquire(aio_context);
1102 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
1103 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1104 &cbi, false, &local_err);
1105 aio_context_release(aio_context);
1110 /* When the block job completes, the BlockBackend reference will point to
1111 * the old backing file. In order to avoid that the top image is already
1112 * deleted, so we can still empty it afterwards, increment the reference
1113 * counter here preemptively. */
1118 job = block_job_get("commit");
1120 run_block_job(job, &local_err);
1126 BlockBackend *old_backing_blk;
1128 old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1130 if (!old_backing_blk) {
1133 ret = blk_make_empty(old_backing_blk, &local_err);
1134 blk_unref(old_backing_blk);
1135 if (ret == -ENOTSUP) {
1136 error_free(local_err);
1138 } else if (ret < 0) {
1149 qemu_progress_end();
1154 error_report_err(local_err);
1158 qprintf(quiet, "Image committed.\n");
1163 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1164 * of the first sector boundary within buf where the sector contains a
1165 * non-zero byte. This function is robust to a buffer that is not
1168 static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1171 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1173 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1174 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1178 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1185 * Returns true iff the first sector pointed to by 'buf' contains at least
1188 * 'pnum' is set to the number of sectors (including and immediately following
1189 * the first one) that are known to be in the same allocated/unallocated state.
1190 * The function will try to align the end offset to alignment boundaries so
1191 * that the request will at least end aligned and consequtive requests will
1192 * also start at an aligned offset.
1194 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1195 int64_t sector_num, int alignment)
1204 is_zero = buffer_is_zero(buf, 512);
1205 for(i = 1; i < n; i++) {
1207 if (is_zero != buffer_is_zero(buf, 512)) {
1212 tail = (sector_num + i) & (alignment - 1);
1214 if (is_zero && i <= tail) {
1215 /* treat unallocated areas which only consist
1216 * of a small tail as allocated. */
1220 /* align up end offset of allocated areas. */
1221 i += alignment - tail;
1224 /* align down end offset of zero areas. */
1233 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1234 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1235 * breaking up write requests for only small sparse areas.
1237 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1238 int min, int64_t sector_num, int alignment)
1241 int num_checked, num_used;
1247 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1253 buf += BDRV_SECTOR_SIZE * *pnum;
1255 sector_num += *pnum;
1256 num_checked = num_used;
1259 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1261 buf += BDRV_SECTOR_SIZE * *pnum;
1263 sector_num += *pnum;
1264 num_checked += *pnum;
1266 num_used = num_checked;
1267 } else if (*pnum >= min) {
1277 * Compares two buffers sector by sector. Returns 0 if the first
1278 * sector of each buffer matches, non-zero otherwise.
1280 * pnum is set to the sector-aligned size of the buffer prefix that
1281 * has the same matching status as the first sector.
1283 static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1284 int64_t bytes, int64_t *pnum)
1287 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
1291 res = !!memcmp(buf1, buf2, i);
1293 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
1295 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
1305 #define IO_BUF_SIZE (2 * MiB)
1308 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1310 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1311 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1312 * failure), and 4 on error (the exit status for read errors), after emitting
1315 * @param blk: BlockBackend for the image
1316 * @param offset: Starting offset to check
1317 * @param bytes: Number of bytes to check
1318 * @param filename: Name of disk file we are checking (logging purpose)
1319 * @param buffer: Allocated buffer for storing read data
1320 * @param quiet: Flag for quiet mode
1322 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1323 int64_t bytes, const char *filename,
1324 uint8_t *buffer, bool quiet)
1329 ret = blk_pread(blk, offset, buffer, bytes);
1331 error_report("Error while reading offset %" PRId64 " of %s: %s",
1332 offset, filename, strerror(-ret));
1335 idx = find_nonzero(buffer, bytes);
1337 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1346 * Compares two images. Exit codes:
1348 * 0 - Images are identical
1350 * >1 - Error occurred
1352 static int img_compare(int argc, char **argv)
1354 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1355 BlockBackend *blk1, *blk2;
1356 BlockDriverState *bs1, *bs2;
1357 int64_t total_size1, total_size2;
1358 uint8_t *buf1 = NULL, *buf2 = NULL;
1359 int64_t pnum1, pnum2;
1360 int allocated1, allocated2;
1361 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1362 bool progress = false, quiet = false, strict = false;
1369 uint64_t progress_base;
1370 bool image_opts = false;
1371 bool force_share = false;
1373 cache = BDRV_DEFAULT_CACHE;
1375 static const struct option long_options[] = {
1376 {"help", no_argument, 0, 'h'},
1377 {"object", required_argument, 0, OPTION_OBJECT},
1378 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1379 {"force-share", no_argument, 0, 'U'},
1382 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1383 long_options, NULL);
1389 missing_argument(argv[optind - 1]);
1392 unrecognized_option(argv[optind - 1]);
1418 case OPTION_OBJECT: {
1420 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1427 case OPTION_IMAGE_OPTS:
1433 /* Progress is not shown in Quiet mode */
1439 if (optind != argc - 2) {
1440 error_exit("Expecting two image file names");
1442 filename1 = argv[optind++];
1443 filename2 = argv[optind++];
1445 if (qemu_opts_foreach(&qemu_object_opts,
1446 user_creatable_add_opts_foreach,
1447 qemu_img_object_print_help, &error_fatal)) {
1452 /* Initialize before goto out */
1453 qemu_progress_init(progress, 2.0);
1456 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1458 error_report("Invalid source cache option: %s", cache);
1463 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1470 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1479 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1480 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1481 total_size1 = blk_getlength(blk1);
1482 if (total_size1 < 0) {
1483 error_report("Can't get size of %s: %s",
1484 filename1, strerror(-total_size1));
1488 total_size2 = blk_getlength(blk2);
1489 if (total_size2 < 0) {
1490 error_report("Can't get size of %s: %s",
1491 filename2, strerror(-total_size2));
1495 total_size = MIN(total_size1, total_size2);
1496 progress_base = MAX(total_size1, total_size2);
1498 qemu_progress_print(0, 100);
1500 if (strict && total_size1 != total_size2) {
1502 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1506 while (offset < total_size) {
1507 int status1, status2;
1509 status1 = bdrv_block_status_above(bs1, NULL, offset,
1510 total_size1 - offset, &pnum1, NULL,
1514 error_report("Sector allocation test failed for %s", filename1);
1517 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1519 status2 = bdrv_block_status_above(bs2, NULL, offset,
1520 total_size2 - offset, &pnum2, NULL,
1524 error_report("Sector allocation test failed for %s", filename2);
1527 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1529 assert(pnum1 && pnum2);
1530 chunk = MIN(pnum1, pnum2);
1533 if (status1 != status2) {
1535 qprintf(quiet, "Strict mode: Offset %" PRId64
1536 " block status mismatch!\n", offset);
1540 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1542 } else if (allocated1 == allocated2) {
1546 chunk = MIN(chunk, IO_BUF_SIZE);
1547 ret = blk_pread(blk1, offset, buf1, chunk);
1549 error_report("Error while reading offset %" PRId64
1551 offset, filename1, strerror(-ret));
1555 ret = blk_pread(blk2, offset, buf2, chunk);
1557 error_report("Error while reading offset %" PRId64
1559 offset, filename2, strerror(-ret));
1563 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1564 if (ret || pnum != chunk) {
1565 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1566 offset + (ret ? 0 : pnum));
1572 chunk = MIN(chunk, IO_BUF_SIZE);
1574 ret = check_empty_sectors(blk1, offset, chunk,
1575 filename1, buf1, quiet);
1577 ret = check_empty_sectors(blk2, offset, chunk,
1578 filename2, buf1, quiet);
1585 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1588 if (total_size1 != total_size2) {
1589 BlockBackend *blk_over;
1590 const char *filename_over;
1592 qprintf(quiet, "Warning: Image size mismatch!\n");
1593 if (total_size1 > total_size2) {
1595 filename_over = filename1;
1598 filename_over = filename2;
1601 while (offset < progress_base) {
1602 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1603 progress_base - offset, &chunk,
1607 error_report("Sector allocation test failed for %s",
1612 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1613 chunk = MIN(chunk, IO_BUF_SIZE);
1614 ret = check_empty_sectors(blk_over, offset, chunk,
1615 filename_over, buf1, quiet);
1621 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1625 qprintf(quiet, "Images are identical.\n");
1635 qemu_progress_end();
1640 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1641 static void do_dirty_bitmap_merge(const char *dst_node, const char *dst_name,
1642 const char *src_node, const char *src_name,
1645 BlockDirtyBitmapMergeSource *merge_src;
1646 BlockDirtyBitmapMergeSourceList *list;
1648 merge_src = g_new0(BlockDirtyBitmapMergeSource, 1);
1649 merge_src->type = QTYPE_QDICT;
1650 merge_src->u.external.node = g_strdup(src_node);
1651 merge_src->u.external.name = g_strdup(src_name);
1652 list = g_new0(BlockDirtyBitmapMergeSourceList, 1);
1653 list->value = merge_src;
1654 qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
1655 qapi_free_BlockDirtyBitmapMergeSourceList(list);
1658 enum ImgConvertBlockStatus {
1664 #define MAX_COROUTINES 16
1666 typedef struct ImgConvertState {
1668 int64_t *src_sectors;
1670 int64_t total_sectors;
1671 int64_t allocated_sectors;
1672 int64_t allocated_done;
1675 enum ImgConvertBlockStatus status;
1676 int64_t sector_next_status;
1677 BlockBackend *target;
1681 bool target_has_backing;
1682 int64_t target_backing_sectors; /* negative if unknown */
1689 size_t cluster_sectors;
1691 long num_coroutines;
1692 int running_coroutines;
1693 Coroutine *co[MAX_COROUTINES];
1694 int64_t wait_sector_num[MAX_COROUTINES];
1699 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1700 int *src_cur, int64_t *src_cur_offset)
1703 *src_cur_offset = 0;
1704 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1705 *src_cur_offset += s->src_sectors[*src_cur];
1707 assert(*src_cur < s->src_num);
1711 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1713 int64_t src_cur_offset;
1714 int ret, n, src_cur;
1715 bool post_backing_zero = false;
1717 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1719 assert(s->total_sectors > sector_num);
1720 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1722 if (s->target_backing_sectors >= 0) {
1723 if (sector_num >= s->target_backing_sectors) {
1724 post_backing_zero = true;
1725 } else if (sector_num + n > s->target_backing_sectors) {
1726 /* Split requests around target_backing_sectors (because
1727 * starting from there, zeros are handled differently) */
1728 n = s->target_backing_sectors - sector_num;
1732 if (s->sector_next_status <= sector_num) {
1733 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1735 BlockDriverState *src_bs = blk_bs(s->src[src_cur]);
1736 BlockDriverState *base;
1738 if (s->target_has_backing) {
1739 base = bdrv_cow_bs(bdrv_skip_filters(src_bs));
1745 count = n * BDRV_SECTOR_SIZE;
1747 ret = bdrv_block_status_above(src_bs, base, offset, count, &count,
1754 warn_report("error while reading block status at "
1755 "offset %" PRIu64 ": %s", offset,
1758 /* Just try to read the data, then */
1759 ret = BDRV_BLOCK_DATA;
1760 count = BDRV_SECTOR_SIZE;
1762 /* Retry on a shorter range */
1763 n = DIV_ROUND_UP(n, 4);
1766 error_report("error while reading block status at offset "
1767 "%" PRIu64 ": %s", offset, strerror(-ret));
1773 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1775 if (ret & BDRV_BLOCK_ZERO) {
1776 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
1777 } else if (ret & BDRV_BLOCK_DATA) {
1778 s->status = BLK_DATA;
1780 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1783 s->sector_next_status = sector_num + n;
1786 n = MIN(n, s->sector_next_status - sector_num);
1787 if (s->status == BLK_DATA) {
1788 n = MIN(n, s->buf_sectors);
1791 /* We need to write complete clusters for compressed images, so if an
1792 * unallocated area is shorter than that, we must consider the whole
1793 * cluster allocated. */
1794 if (s->compressed) {
1795 if (n < s->cluster_sectors) {
1796 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1797 s->status = BLK_DATA;
1799 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1806 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1807 int nb_sectors, uint8_t *buf)
1809 uint64_t single_read_until = 0;
1812 assert(nb_sectors <= s->buf_sectors);
1813 while (nb_sectors > 0) {
1816 int64_t bs_sectors, src_cur_offset;
1819 /* In the case of compression with multiple source files, we can get a
1820 * nb_sectors that spreads into the next part. So we must be able to
1821 * read across multiple BDSes for one convert_read() call. */
1822 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1823 blk = s->src[src_cur];
1824 bs_sectors = s->src_sectors[src_cur];
1826 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1828 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1829 if (single_read_until > offset) {
1833 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
1837 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1841 warn_report("error while reading offset %" PRIu64
1842 ": %s", offset, strerror(-ret));
1844 memset(buf, 0, BDRV_SECTOR_SIZE);
1853 buf += n * BDRV_SECTOR_SIZE;
1860 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1861 int nb_sectors, uint8_t *buf,
1862 enum ImgConvertBlockStatus status)
1866 while (nb_sectors > 0) {
1868 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1871 case BLK_BACKING_FILE:
1872 /* If we have a backing file, leave clusters unallocated that are
1873 * unallocated in the source image, so that the backing file is
1874 * visible at the respective offset. */
1875 assert(s->target_has_backing);
1879 /* If we're told to keep the target fully allocated (-S 0) or there
1880 * is real non-zero data, we must write it. Otherwise we can treat
1881 * it as zero sectors.
1882 * Compressed clusters need to be written as a whole, so in that
1883 * case we can only save the write if the buffer is completely
1885 if (!s->min_sparse ||
1887 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1888 sector_num, s->alignment)) ||
1890 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1892 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1893 n << BDRV_SECTOR_BITS, buf, flags);
1902 if (s->has_zero_init) {
1903 assert(!s->target_has_backing);
1906 ret = blk_co_pwrite_zeroes(s->target,
1907 sector_num << BDRV_SECTOR_BITS,
1908 n << BDRV_SECTOR_BITS,
1909 BDRV_REQ_MAY_UNMAP);
1918 buf += n * BDRV_SECTOR_SIZE;
1924 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1929 while (nb_sectors > 0) {
1932 int64_t bs_sectors, src_cur_offset;
1935 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1936 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1937 blk = s->src[src_cur];
1938 bs_sectors = s->src_sectors[src_cur];
1940 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1942 ret = blk_co_copy_range(blk, offset, s->target,
1943 sector_num << BDRV_SECTOR_BITS,
1944 n << BDRV_SECTOR_BITS, 0, 0);
1955 static void coroutine_fn convert_co_do_copy(void *opaque)
1957 ImgConvertState *s = opaque;
1958 uint8_t *buf = NULL;
1962 for (i = 0; i < s->num_coroutines; i++) {
1963 if (s->co[i] == qemu_coroutine_self()) {
1970 s->running_coroutines++;
1971 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1976 enum ImgConvertBlockStatus status;
1979 qemu_co_mutex_lock(&s->lock);
1980 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1981 qemu_co_mutex_unlock(&s->lock);
1984 n = convert_iteration_sectors(s, s->sector_num);
1986 qemu_co_mutex_unlock(&s->lock);
1990 /* save current sector and allocation status to local variables */
1991 sector_num = s->sector_num;
1993 if (!s->min_sparse && s->status == BLK_ZERO) {
1994 n = MIN(n, s->buf_sectors);
1996 /* increment global sector counter so that other coroutines can
1997 * already continue reading beyond this request */
1999 qemu_co_mutex_unlock(&s->lock);
2001 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
2002 s->allocated_done += n;
2003 qemu_progress_print(100.0 * s->allocated_done /
2004 s->allocated_sectors, 0);
2008 copy_range = s->copy_range && s->status == BLK_DATA;
2009 if (status == BLK_DATA && !copy_range) {
2010 ret = convert_co_read(s, sector_num, n, buf);
2012 error_report("error while reading at byte %lld: %s",
2013 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2016 } else if (!s->min_sparse && status == BLK_ZERO) {
2018 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
2021 if (s->wr_in_order) {
2022 /* keep writes in order */
2023 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
2024 s->wait_sector_num[index] = sector_num;
2025 qemu_coroutine_yield();
2027 s->wait_sector_num[index] = -1;
2030 if (s->ret == -EINPROGRESS) {
2032 ret = convert_co_copy_range(s, sector_num, n);
2034 s->copy_range = false;
2038 ret = convert_co_write(s, sector_num, n, buf, status);
2041 error_report("error while writing at byte %lld: %s",
2042 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2047 if (s->wr_in_order) {
2048 /* reenter the coroutine that might have waited
2049 * for this write to complete */
2050 s->wr_offs = sector_num + n;
2051 for (i = 0; i < s->num_coroutines; i++) {
2052 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2054 * A -> B -> A cannot occur because A has
2055 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2056 * B will never enter A during this time window.
2058 qemu_coroutine_enter(s->co[i]);
2066 s->co[index] = NULL;
2067 s->running_coroutines--;
2068 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2069 /* the convert job finished successfully */
2074 static int convert_do_copy(ImgConvertState *s)
2077 int64_t sector_num = 0;
2079 /* Check whether we have zero initialisation or can get it efficiently */
2080 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2081 !s->target_has_backing) {
2082 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
2085 /* Allocate buffer for copied data. For compressed images, only one cluster
2086 * can be copied at a time. */
2087 if (s->compressed) {
2088 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2089 error_report("invalid cluster size");
2092 s->buf_sectors = s->cluster_sectors;
2095 while (sector_num < s->total_sectors) {
2096 n = convert_iteration_sectors(s, sector_num);
2100 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2102 s->allocated_sectors += n;
2108 s->sector_next_status = 0;
2109 s->ret = -EINPROGRESS;
2111 qemu_co_mutex_init(&s->lock);
2112 for (i = 0; i < s->num_coroutines; i++) {
2113 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2114 s->wait_sector_num[i] = -1;
2115 qemu_coroutine_enter(s->co[i]);
2118 while (s->running_coroutines) {
2119 main_loop_wait(false);
2122 if (s->compressed && !s->ret) {
2123 /* signal EOF to align */
2124 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
2133 static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst)
2135 BdrvDirtyBitmap *bm;
2138 FOR_EACH_DIRTY_BITMAP(src, bm) {
2141 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2144 name = bdrv_dirty_bitmap_name(bm);
2145 qmp_block_dirty_bitmap_add(dst->node_name, name,
2146 true, bdrv_dirty_bitmap_granularity(bm),
2148 true, !bdrv_dirty_bitmap_enabled(bm),
2151 error_reportf_err(err, "Failed to create bitmap %s: ", name);
2155 do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2158 error_reportf_err(err, "Failed to populate bitmap %s: ", name);
2166 #define MAX_BUF_SECTORS 32768
2168 static int img_convert(int argc, char **argv)
2170 int c, bs_i, flags, src_flags = 0;
2171 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
2172 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2173 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
2174 BlockDriver *drv = NULL, *proto_drv = NULL;
2175 BlockDriverInfo bdi;
2176 BlockDriverState *out_bs;
2177 QemuOpts *opts = NULL, *sn_opts = NULL;
2178 QemuOptsList *create_opts = NULL;
2179 QDict *open_opts = NULL;
2180 char *options = NULL;
2181 Error *local_err = NULL;
2182 bool writethrough, src_writethrough, image_opts = false,
2183 skip_create = false, progress = false, tgt_image_opts = false;
2184 int64_t ret = -EINVAL;
2185 bool force_share = false;
2186 bool explict_min_sparse = false;
2187 bool bitmaps = false;
2189 ImgConvertState s = (ImgConvertState) {
2190 /* Need at least 4k of zeros for sparse detection */
2192 .copy_range = false,
2193 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2194 .wr_in_order = true,
2195 .num_coroutines = 8,
2199 static const struct option long_options[] = {
2200 {"help", no_argument, 0, 'h'},
2201 {"object", required_argument, 0, OPTION_OBJECT},
2202 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2203 {"force-share", no_argument, 0, 'U'},
2204 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
2205 {"salvage", no_argument, 0, OPTION_SALVAGE},
2206 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
2207 {"bitmaps", no_argument, 0, OPTION_BITMAPS},
2210 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2211 long_options, NULL);
2217 missing_argument(argv[optind - 1]);
2220 unrecognized_option(argv[optind - 1]);
2232 out_baseimg = optarg;
2235 s.copy_range = true;
2238 s.compressed = true;
2241 if (accumulate_options(&options, optarg) < 0) {
2246 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2247 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2250 error_report("Failed in parsing snapshot param '%s'",
2255 snapshot_name = optarg;
2262 sval = cvtnum("buffer size for sparse output", optarg);
2265 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
2266 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2267 error_report("Invalid buffer size for sparse output specified. "
2268 "Valid sizes are multiples of %llu up to %llu. Select "
2269 "0 to disable sparse detection (fully allocates output).",
2270 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
2274 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2275 explict_min_sparse = true;
2294 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2295 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2296 error_report("Invalid number of coroutines. Allowed number of"
2297 " coroutines is between 1 and %d", MAX_COROUTINES);
2302 s.wr_in_order = false;
2307 case OPTION_OBJECT: {
2308 QemuOpts *object_opts;
2309 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2316 case OPTION_IMAGE_OPTS:
2319 case OPTION_SALVAGE:
2322 case OPTION_TARGET_IMAGE_OPTS:
2323 tgt_image_opts = true;
2325 case OPTION_TARGET_IS_ZERO:
2327 * The user asserting that the target is blank has the
2328 * same effect as the target driver supporting zero
2331 s.has_zero_init = true;
2333 case OPTION_BITMAPS:
2339 if (!out_fmt && !tgt_image_opts) {
2343 if (qemu_opts_foreach(&qemu_object_opts,
2344 user_creatable_add_opts_foreach,
2345 qemu_img_object_print_help, &error_fatal)) {
2349 if (s.compressed && s.copy_range) {
2350 error_report("Cannot enable copy offloading when -c is used");
2354 if (explict_min_sparse && s.copy_range) {
2355 error_report("Cannot enable copy offloading when -S is used");
2359 if (s.copy_range && s.salvage) {
2360 error_report("Cannot use copy offloading in salvaging mode");
2364 if (tgt_image_opts && !skip_create) {
2365 error_report("--target-image-opts requires use of -n flag");
2369 if (skip_create && options) {
2370 error_report("-o has no effect when skipping image creation");
2374 if (s.has_zero_init && !skip_create) {
2375 error_report("--target-is-zero requires use of -n flag");
2379 s.src_num = argc - optind - 1;
2380 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2382 if (options && has_help_option(options)) {
2384 ret = print_block_option_help(out_filename, out_fmt);
2387 error_report("Option help requires a format be specified");
2392 if (s.src_num < 1) {
2393 error_report("Must specify image file name");
2397 /* ret is still -EINVAL until here */
2398 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2400 error_report("Invalid source cache option: %s", src_cache);
2404 /* Initialize before goto out */
2408 qemu_progress_init(progress, 1.0);
2409 qemu_progress_print(0, 100);
2411 s.src = g_new0(BlockBackend *, s.src_num);
2412 s.src_sectors = g_new(int64_t, s.src_num);
2414 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2415 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2416 fmt, src_flags, src_writethrough, s.quiet,
2422 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2423 if (s.src_sectors[bs_i] < 0) {
2424 error_report("Could not get size of %s: %s",
2425 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2429 s.total_sectors += s.src_sectors[bs_i];
2433 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2434 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2435 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2437 } else if (snapshot_name != NULL) {
2438 if (s.src_num > 1) {
2439 error_report("No support for concatenating multiple snapshot");
2444 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2448 error_reportf_err(local_err, "Failed to load snapshot: ");
2454 /* Find driver and parse its options */
2455 drv = bdrv_find_format(out_fmt);
2457 error_report("Unknown file format '%s'", out_fmt);
2462 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2464 error_report_err(local_err);
2469 if (!drv->create_opts) {
2470 error_report("Format driver '%s' does not support image creation",
2476 if (!proto_drv->create_opts) {
2477 error_report("Protocol driver '%s' does not support image creation",
2478 proto_drv->format_name);
2483 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2484 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2486 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2488 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
2489 error_report_err(local_err);
2495 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2497 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2503 /* Get backing file name if -o backing_file was used */
2504 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2505 if (out_baseimg_param) {
2506 out_baseimg = out_baseimg_param;
2508 s.target_has_backing = (bool) out_baseimg;
2510 if (s.has_zero_init && s.target_has_backing) {
2511 error_report("Cannot use --target-is-zero when the destination "
2512 "image has a backing file");
2516 if (s.src_num > 1 && out_baseimg) {
2517 error_report("Having a backing file for the target makes no sense when "
2518 "concatenating multiple input images");
2523 if (out_baseimg_param) {
2524 if (!qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT)) {
2525 warn_report("Deprecated use of backing file without explicit "
2530 /* Check if compression is supported */
2533 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2534 const char *encryptfmt =
2535 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2536 const char *preallocation =
2537 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2539 if (drv && !block_driver_can_compress(drv)) {
2540 error_report("Compression not supported for this file format");
2545 if (encryption || encryptfmt) {
2546 error_report("Compression and encryption not supported at "
2553 && strcmp(preallocation, "off"))
2555 error_report("Compression and preallocation not supported at "
2562 /* Determine if bitmaps need copying */
2564 if (s.src_num > 1) {
2565 error_report("Copying bitmaps only possible with single source");
2569 if (!bdrv_supports_persistent_dirty_bitmap(blk_bs(s.src[0]))) {
2570 error_report("Source lacks bitmap support");
2577 * The later open call will need any decryption secrets, and
2578 * bdrv_create() will purge "opts", so extract them now before
2582 open_opts = qdict_new();
2583 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2585 /* Create the new image */
2586 ret = bdrv_create(drv, out_filename, opts, &local_err);
2588 error_reportf_err(local_err, "%s: error while converting %s: ",
2589 out_filename, out_fmt);
2594 s.target_is_new = !skip_create;
2596 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2597 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2599 error_report("Invalid cache option: %s", cache);
2604 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2605 flags, writethrough, s.quiet, false);
2607 /* TODO ultimately we should allow --target-image-opts
2608 * to be used even when -n is not given.
2609 * That has to wait for bdrv_create to be improved
2610 * to allow filenames in option syntax
2612 s.target = img_open_file(out_filename, open_opts, out_fmt,
2613 flags, writethrough, s.quiet, false);
2614 open_opts = NULL; /* blk_new_open will have freed it */
2620 out_bs = blk_bs(s.target);
2622 if (bitmaps && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2623 error_report("Format driver '%s' does not support bitmaps",
2624 out_bs->drv->format_name);
2629 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
2630 error_report("Compression not supported for this file format");
2635 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2636 * or discard_alignment of the out_bs is greater. Limit to
2637 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2638 s.buf_sectors = MIN(MAX_BUF_SECTORS,
2640 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2641 out_bs->bl.pdiscard_alignment >>
2642 BDRV_SECTOR_BITS)));
2644 /* try to align the write requests to the destination to avoid unnecessary
2646 s.alignment = MAX(pow2floor(s.min_sparse),
2647 DIV_ROUND_UP(out_bs->bl.request_alignment,
2649 assert(is_power_of_2(s.alignment));
2652 int64_t output_sectors = blk_nb_sectors(s.target);
2653 if (output_sectors < 0) {
2654 error_report("unable to get output image length: %s",
2655 strerror(-output_sectors));
2658 } else if (output_sectors < s.total_sectors) {
2659 error_report("output file is smaller than input file");
2665 if (s.target_has_backing && s.target_is_new) {
2666 /* Errors are treated as "backing length unknown" (which means
2667 * s.target_backing_sectors has to be negative, which it will
2668 * be automatically). The backing file length is used only
2669 * for optimizations, so such a case is not fatal. */
2670 s.target_backing_sectors =
2671 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs));
2673 s.target_backing_sectors = -1;
2676 ret = bdrv_get_info(out_bs, &bdi);
2679 error_report("could not get block driver info");
2683 s.compressed = s.compressed || bdi.needs_compressed_writes;
2684 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2687 ret = convert_do_copy(&s);
2689 /* Now copy the bitmaps */
2690 if (bitmaps && ret == 0) {
2691 ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs);
2696 qemu_progress_print(100, 0);
2698 qemu_progress_end();
2699 qemu_opts_del(opts);
2700 qemu_opts_free(create_opts);
2701 qemu_opts_del(sn_opts);
2702 qobject_unref(open_opts);
2703 blk_unref(s.target);
2705 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2706 blk_unref(s.src[bs_i]);
2710 g_free(s.src_sectors);
2718 static void dump_snapshots(BlockDriverState *bs)
2720 QEMUSnapshotInfo *sn_tab, *sn;
2723 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2726 printf("Snapshot list:\n");
2727 bdrv_snapshot_dump(NULL);
2729 for(i = 0; i < nb_sns; i++) {
2731 bdrv_snapshot_dump(sn);
2737 static void dump_json_image_info_list(ImageInfoList *list)
2741 Visitor *v = qobject_output_visitor_new(&obj);
2743 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2744 visit_complete(v, &obj);
2745 str = qobject_to_json_pretty(obj);
2746 assert(str != NULL);
2747 printf("%s\n", qstring_get_str(str));
2753 static void dump_json_image_info(ImageInfo *info)
2757 Visitor *v = qobject_output_visitor_new(&obj);
2759 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2760 visit_complete(v, &obj);
2761 str = qobject_to_json_pretty(obj);
2762 assert(str != NULL);
2763 printf("%s\n", qstring_get_str(str));
2769 static void dump_human_image_info_list(ImageInfoList *list)
2771 ImageInfoList *elem;
2774 for (elem = list; elem; elem = elem->next) {
2780 bdrv_image_info_dump(elem->value);
2784 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2786 return strcmp(a, b) == 0;
2790 * Open an image file chain and return an ImageInfoList
2792 * @filename: topmost image filename
2793 * @fmt: topmost image format (may be NULL to autodetect)
2794 * @chain: true - enumerate entire backing file chain
2795 * false - only topmost image file
2797 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2798 * image file. If there was an error a message will have been printed to
2801 static ImageInfoList *collect_image_info_list(bool image_opts,
2802 const char *filename,
2804 bool chain, bool force_share)
2806 ImageInfoList *head = NULL;
2807 ImageInfoList **last = &head;
2808 GHashTable *filenames;
2811 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2815 BlockDriverState *bs;
2817 ImageInfoList *elem;
2819 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2820 error_report("Backing file '%s' creates an infinite loop.",
2824 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2826 blk = img_open(image_opts, filename, fmt,
2827 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2834 bdrv_query_image_info(bs, &info, &err);
2836 error_report_err(err);
2841 elem = g_new0(ImageInfoList, 1);
2848 /* Clear parameters that only apply to the topmost image */
2849 filename = fmt = NULL;
2853 if (info->has_full_backing_filename) {
2854 filename = info->full_backing_filename;
2855 } else if (info->has_backing_filename) {
2856 error_report("Could not determine absolute backing filename,"
2857 " but backing filename '%s' present",
2858 info->backing_filename);
2861 if (info->has_backing_filename_format) {
2862 fmt = info->backing_filename_format;
2866 g_hash_table_destroy(filenames);
2870 qapi_free_ImageInfoList(head);
2871 g_hash_table_destroy(filenames);
2875 static int img_info(int argc, char **argv)
2878 OutputFormat output_format = OFORMAT_HUMAN;
2880 const char *filename, *fmt, *output;
2881 ImageInfoList *list;
2882 bool image_opts = false;
2883 bool force_share = false;
2888 int option_index = 0;
2889 static const struct option long_options[] = {
2890 {"help", no_argument, 0, 'h'},
2891 {"format", required_argument, 0, 'f'},
2892 {"output", required_argument, 0, OPTION_OUTPUT},
2893 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2894 {"object", required_argument, 0, OPTION_OBJECT},
2895 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2896 {"force-share", no_argument, 0, 'U'},
2899 c = getopt_long(argc, argv, ":f:hU",
2900 long_options, &option_index);
2906 missing_argument(argv[optind - 1]);
2909 unrecognized_option(argv[optind - 1]);
2923 case OPTION_BACKING_CHAIN:
2926 case OPTION_OBJECT: {
2928 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2934 case OPTION_IMAGE_OPTS:
2939 if (optind != argc - 1) {
2940 error_exit("Expecting one image file name");
2942 filename = argv[optind++];
2944 if (output && !strcmp(output, "json")) {
2945 output_format = OFORMAT_JSON;
2946 } else if (output && !strcmp(output, "human")) {
2947 output_format = OFORMAT_HUMAN;
2948 } else if (output) {
2949 error_report("--output must be used with human or json as argument.");
2953 if (qemu_opts_foreach(&qemu_object_opts,
2954 user_creatable_add_opts_foreach,
2955 qemu_img_object_print_help, &error_fatal)) {
2959 list = collect_image_info_list(image_opts, filename, fmt, chain,
2965 switch (output_format) {
2967 dump_human_image_info_list(list);
2971 dump_json_image_info_list(list);
2973 dump_json_image_info(list->value);
2978 qapi_free_ImageInfoList(list);
2982 static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2985 switch (output_format) {
2987 if (e->data && !e->has_offset) {
2988 error_report("File contains external, encrypted or compressed clusters.");
2991 if (e->data && !e->zero) {
2992 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2993 e->start, e->length,
2994 e->has_offset ? e->offset : 0,
2995 e->has_filename ? e->filename : "");
2997 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2998 * Modify the flags here to allow more coalescing.
3000 if (next && (!next->data || next->zero)) {
3006 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
3007 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
3008 e->start, e->length, e->depth,
3009 e->zero ? "true" : "false",
3010 e->data ? "true" : "false");
3011 if (e->has_offset) {
3012 printf(", \"offset\": %"PRId64"", e->offset);
3024 static int get_block_status(BlockDriverState *bs, int64_t offset,
3025 int64_t bytes, MapEntry *e)
3029 BlockDriverState *file;
3032 char *filename = NULL;
3034 /* As an optimization, we could cache the current range of unallocated
3035 * clusters in each file of the chain, and avoid querying the same
3041 bs = bdrv_skip_filters(bs);
3042 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
3047 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
3050 bs = bdrv_cow_bs(bs);
3059 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3061 if (file && has_offset) {
3062 bdrv_refresh_filename(file);
3063 filename = file->filename;
3069 .data = !!(ret & BDRV_BLOCK_DATA),
3070 .zero = !!(ret & BDRV_BLOCK_ZERO),
3072 .has_offset = has_offset,
3074 .has_filename = filename,
3075 .filename = filename,
3081 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3083 if (curr->length == 0) {
3086 if (curr->zero != next->zero ||
3087 curr->data != next->data ||
3088 curr->depth != next->depth ||
3089 curr->has_filename != next->has_filename ||
3090 curr->has_offset != next->has_offset) {
3093 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
3096 if (curr->has_offset && curr->offset + curr->length != next->offset) {
3102 static int img_map(int argc, char **argv)
3105 OutputFormat output_format = OFORMAT_HUMAN;
3107 BlockDriverState *bs;
3108 const char *filename, *fmt, *output;
3110 MapEntry curr = { .length = 0 }, next;
3112 bool image_opts = false;
3113 bool force_share = false;
3114 int64_t start_offset = 0;
3115 int64_t max_length = -1;
3120 int option_index = 0;
3121 static const struct option long_options[] = {
3122 {"help", no_argument, 0, 'h'},
3123 {"format", required_argument, 0, 'f'},
3124 {"output", required_argument, 0, OPTION_OUTPUT},
3125 {"object", required_argument, 0, OPTION_OBJECT},
3126 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3127 {"force-share", no_argument, 0, 'U'},
3128 {"start-offset", required_argument, 0, 's'},
3129 {"max-length", required_argument, 0, 'l'},
3132 c = getopt_long(argc, argv, ":f:s:l:hU",
3133 long_options, &option_index);
3139 missing_argument(argv[optind - 1]);
3142 unrecognized_option(argv[optind - 1]);
3157 start_offset = cvtnum("start offset", optarg);
3158 if (start_offset < 0) {
3163 max_length = cvtnum("max length", optarg);
3164 if (max_length < 0) {
3168 case OPTION_OBJECT: {
3170 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3176 case OPTION_IMAGE_OPTS:
3181 if (optind != argc - 1) {
3182 error_exit("Expecting one image file name");
3184 filename = argv[optind];
3186 if (output && !strcmp(output, "json")) {
3187 output_format = OFORMAT_JSON;
3188 } else if (output && !strcmp(output, "human")) {
3189 output_format = OFORMAT_HUMAN;
3190 } else if (output) {
3191 error_report("--output must be used with human or json as argument.");
3195 if (qemu_opts_foreach(&qemu_object_opts,
3196 user_creatable_add_opts_foreach,
3197 qemu_img_object_print_help, &error_fatal)) {
3201 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
3207 if (output_format == OFORMAT_HUMAN) {
3208 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3209 } else if (output_format == OFORMAT_JSON) {
3213 length = blk_getlength(blk);
3215 error_report("Failed to get size for '%s'", filename);
3218 if (max_length != -1) {
3219 length = MIN(start_offset + max_length, length);
3222 curr.start = start_offset;
3223 while (curr.start + curr.length < length) {
3224 int64_t offset = curr.start + curr.length;
3225 int64_t n = length - offset;
3227 ret = get_block_status(bs, offset, n, &next);
3229 error_report("Could not read file metadata: %s", strerror(-ret));
3233 if (entry_mergeable(&curr, &next)) {
3234 curr.length += next.length;
3238 if (curr.length > 0) {
3239 ret = dump_map_entry(output_format, &curr, &next);
3247 ret = dump_map_entry(output_format, &curr, NULL);
3248 if (output_format == OFORMAT_JSON) {
3257 #define SNAPSHOT_LIST 1
3258 #define SNAPSHOT_CREATE 2
3259 #define SNAPSHOT_APPLY 3
3260 #define SNAPSHOT_DELETE 4
3262 static int img_snapshot(int argc, char **argv)
3265 BlockDriverState *bs;
3266 QEMUSnapshotInfo sn;
3267 char *filename, *snapshot_name = NULL;
3268 int c, ret = 0, bdrv_oflags;
3273 bool image_opts = false;
3274 bool force_share = false;
3276 bdrv_oflags = BDRV_O_RDWR;
3277 /* Parse commandline parameters */
3279 static const struct option long_options[] = {
3280 {"help", no_argument, 0, 'h'},
3281 {"object", required_argument, 0, OPTION_OBJECT},
3282 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3283 {"force-share", no_argument, 0, 'U'},
3286 c = getopt_long(argc, argv, ":la:c:d:hqU",
3287 long_options, NULL);
3293 missing_argument(argv[optind - 1]);
3296 unrecognized_option(argv[optind - 1]);
3303 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3306 action = SNAPSHOT_LIST;
3307 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
3311 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3314 action = SNAPSHOT_APPLY;
3315 snapshot_name = optarg;
3319 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3322 action = SNAPSHOT_CREATE;
3323 snapshot_name = optarg;
3327 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3330 action = SNAPSHOT_DELETE;
3331 snapshot_name = optarg;
3339 case OPTION_OBJECT: {
3341 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3347 case OPTION_IMAGE_OPTS:
3353 if (optind != argc - 1) {
3354 error_exit("Expecting one image file name");
3356 filename = argv[optind++];
3358 if (qemu_opts_foreach(&qemu_object_opts,
3359 user_creatable_add_opts_foreach,
3360 qemu_img_object_print_help, &error_fatal)) {
3364 /* Open the image */
3365 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3372 /* Perform the requested action */
3378 case SNAPSHOT_CREATE:
3379 memset(&sn, 0, sizeof(sn));
3380 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3382 qemu_gettimeofday(&tv);
3383 sn.date_sec = tv.tv_sec;
3384 sn.date_nsec = tv.tv_usec * 1000;
3386 ret = bdrv_snapshot_create(bs, &sn);
3388 error_report("Could not create snapshot '%s': %d (%s)",
3389 snapshot_name, ret, strerror(-ret));
3393 case SNAPSHOT_APPLY:
3394 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3396 error_reportf_err(err, "Could not apply snapshot '%s': ",
3401 case SNAPSHOT_DELETE:
3402 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3404 error_report("Could not delete snapshot '%s': snapshot not "
3405 "found", snapshot_name);
3408 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3410 error_reportf_err(err, "Could not delete snapshot '%s': ",
3426 static int img_rebase(int argc, char **argv)
3428 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3429 uint8_t *buf_old = NULL;
3430 uint8_t *buf_new = NULL;
3431 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
3432 BlockDriverState *unfiltered_bs;
3434 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3435 int c, flags, src_flags, ret;
3436 bool writethrough, src_writethrough;
3438 bool force_share = false;
3441 Error *local_err = NULL;
3442 bool image_opts = false;
3444 /* Parse commandline parameters */
3446 cache = BDRV_DEFAULT_CACHE;
3447 src_cache = BDRV_DEFAULT_CACHE;
3451 static const struct option long_options[] = {
3452 {"help", no_argument, 0, 'h'},
3453 {"object", required_argument, 0, OPTION_OBJECT},
3454 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3455 {"force-share", no_argument, 0, 'U'},
3458 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3459 long_options, NULL);
3465 missing_argument(argv[optind - 1]);
3468 unrecognized_option(argv[optind - 1]);
3477 out_basefmt = optarg;
3480 out_baseimg = optarg;
3497 case OPTION_OBJECT: {
3499 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3505 case OPTION_IMAGE_OPTS:
3518 if (optind != argc - 1) {
3519 error_exit("Expecting one image file name");
3521 if (!unsafe && !out_baseimg) {
3522 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3524 filename = argv[optind++];
3526 if (qemu_opts_foreach(&qemu_object_opts,
3527 user_creatable_add_opts_foreach,
3528 qemu_img_object_print_help, &error_fatal)) {
3532 qemu_progress_init(progress, 2.0);
3533 qemu_progress_print(0, 100);
3535 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3536 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3538 error_report("Invalid cache option: %s", cache);
3543 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3545 error_report("Invalid source cache option: %s", src_cache);
3549 /* The source files are opened read-only, don't care about WCE */
3550 assert((src_flags & BDRV_O_RDWR) == 0);
3551 (void) src_writethrough;
3556 * Ignore the old backing file for unsafe rebase in case we want to correct
3557 * the reference to a renamed or moved backing file.
3559 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3567 unfiltered_bs = bdrv_skip_filters(bs);
3569 if (out_basefmt != NULL) {
3570 if (bdrv_find_format(out_basefmt) == NULL) {
3571 error_report("Invalid format name: '%s'", out_basefmt);
3577 /* For safe rebasing we need to compare old and new backing file */
3579 QDict *options = NULL;
3580 BlockDriverState *base_bs = bdrv_cow_bs(unfiltered_bs);
3583 blk_old_backing = blk_new(qemu_get_aio_context(),
3584 BLK_PERM_CONSISTENT_READ,
3586 ret = blk_insert_bs(blk_old_backing, base_bs,
3589 error_reportf_err(local_err,
3590 "Could not reuse old backing file '%s': ",
3595 blk_old_backing = NULL;
3598 if (out_baseimg[0]) {
3599 const char *overlay_filename;
3600 char *out_real_path;
3602 options = qdict_new();
3604 qdict_put_str(options, "driver", out_basefmt);
3607 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3610 bdrv_refresh_filename(bs);
3611 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3614 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3618 qobject_unref(options);
3619 error_reportf_err(local_err,
3620 "Could not resolve backing filename: ");
3626 * Find out whether we rebase an image on top of a previous image
3629 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
3630 if (prefix_chain_bs) {
3631 qobject_unref(options);
3632 g_free(out_real_path);
3634 blk_new_backing = blk_new(qemu_get_aio_context(),
3635 BLK_PERM_CONSISTENT_READ,
3637 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3640 error_reportf_err(local_err,
3641 "Could not reuse backing file '%s': ",
3646 blk_new_backing = blk_new_open(out_real_path, NULL,
3647 options, src_flags, &local_err);
3648 g_free(out_real_path);
3649 if (!blk_new_backing) {
3650 error_reportf_err(local_err,
3651 "Could not open new backing file '%s': ",
3661 * Check each unallocated cluster in the COW file. If it is unallocated,
3662 * accesses go to the backing file. We must therefore compare this cluster
3663 * in the old and new backing file, and if they differ we need to copy it
3664 * from the old backing file into the COW file.
3666 * If qemu-img crashes during this step, no harm is done. The content of
3667 * the image is the same as the original one at any time.
3671 int64_t old_backing_size = 0;
3672 int64_t new_backing_size = 0;
3675 float local_progress = 0;
3677 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3678 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3680 size = blk_getlength(blk);
3682 error_report("Could not get size of '%s': %s",
3683 filename, strerror(-size));
3687 if (blk_old_backing) {
3688 old_backing_size = blk_getlength(blk_old_backing);
3689 if (old_backing_size < 0) {
3690 char backing_name[PATH_MAX];
3692 bdrv_get_backing_filename(bs, backing_name,
3693 sizeof(backing_name));
3694 error_report("Could not get size of '%s': %s",
3695 backing_name, strerror(-old_backing_size));
3700 if (blk_new_backing) {
3701 new_backing_size = blk_getlength(blk_new_backing);
3702 if (new_backing_size < 0) {
3703 error_report("Could not get size of '%s': %s",
3704 out_baseimg, strerror(-new_backing_size));
3711 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3714 for (offset = 0; offset < size; offset += n) {
3715 bool buf_old_is_zero = false;
3717 /* How many bytes can we handle with the next read? */
3718 n = MIN(IO_BUF_SIZE, size - offset);
3720 /* If the cluster is allocated, we don't need to take action */
3721 ret = bdrv_is_allocated(unfiltered_bs, offset, n, &n);
3723 error_report("error while reading image metadata: %s",
3731 if (prefix_chain_bs) {
3733 * If cluster wasn't changed since prefix_chain, we don't need
3736 ret = bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs),
3737 prefix_chain_bs, false,
3740 error_report("error while reading image metadata: %s",
3750 * Read old and new backing file and take into consideration that
3751 * backing files may be smaller than the COW image.
3753 if (offset >= old_backing_size) {
3754 memset(buf_old, 0, n);
3755 buf_old_is_zero = true;
3757 if (offset + n > old_backing_size) {
3758 n = old_backing_size - offset;
3761 ret = blk_pread(blk_old_backing, offset, buf_old, n);
3763 error_report("error while reading from old backing file");
3768 if (offset >= new_backing_size || !blk_new_backing) {
3769 memset(buf_new, 0, n);
3771 if (offset + n > new_backing_size) {
3772 n = new_backing_size - offset;
3775 ret = blk_pread(blk_new_backing, offset, buf_new, n);
3777 error_report("error while reading from new backing file");
3782 /* If they differ, we need to write to the COW file */
3783 uint64_t written = 0;
3785 while (written < n) {
3788 if (compare_buffers(buf_old + written, buf_new + written,
3789 n - written, &pnum))
3791 if (buf_old_is_zero) {
3792 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3794 ret = blk_pwrite(blk, offset + written,
3795 buf_old + written, pnum, 0);
3798 error_report("Error while writing to COW image: %s",
3806 qemu_progress_print(local_progress, 100);
3811 * Change the backing file. All clusters that are different from the old
3812 * backing file are overwritten in the COW file now, so the visible content
3813 * doesn't change when we switch the backing file.
3815 if (out_baseimg && *out_baseimg) {
3816 ret = bdrv_change_backing_file(unfiltered_bs, out_baseimg, out_basefmt,
3819 ret = bdrv_change_backing_file(unfiltered_bs, NULL, NULL, false);
3822 if (ret == -ENOSPC) {
3823 error_report("Could not change the backing file to '%s': No "
3824 "space left in the file header", out_baseimg);
3825 } else if (ret < 0) {
3826 error_report("Could not change the backing file to '%s': %s",
3827 out_baseimg, strerror(-ret));
3830 qemu_progress_print(100, 0);
3832 * TODO At this point it is possible to check if any clusters that are
3833 * allocated in the COW file are the same in the backing file. If so, they
3834 * could be dropped from the COW file. Don't do this before switching the
3835 * backing file, in case of a crash this would lead to corruption.
3838 qemu_progress_end();
3841 blk_unref(blk_old_backing);
3842 blk_unref(blk_new_backing);
3844 qemu_vfree(buf_old);
3845 qemu_vfree(buf_new);
3854 static int img_resize(int argc, char **argv)
3857 int c, ret, relative;
3858 const char *filename, *fmt, *size;
3859 int64_t n, total_size, current_size;
3861 BlockBackend *blk = NULL;
3862 PreallocMode prealloc = PREALLOC_MODE_OFF;
3865 static QemuOptsList resize_options = {
3866 .name = "resize_options",
3867 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3870 .name = BLOCK_OPT_SIZE,
3871 .type = QEMU_OPT_SIZE,
3872 .help = "Virtual disk size"
3878 bool image_opts = false;
3879 bool shrink = false;
3881 /* Remove size from argv manually so that negative numbers are not treated
3882 * as options by getopt. */
3884 error_exit("Not enough arguments");
3888 size = argv[--argc];
3890 /* Parse getopt arguments */
3893 static const struct option long_options[] = {
3894 {"help", no_argument, 0, 'h'},
3895 {"object", required_argument, 0, OPTION_OBJECT},
3896 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3897 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3898 {"shrink", no_argument, 0, OPTION_SHRINK},
3901 c = getopt_long(argc, argv, ":f:hq",
3902 long_options, NULL);
3908 missing_argument(argv[optind - 1]);
3911 unrecognized_option(argv[optind - 1]);
3922 case OPTION_OBJECT: {
3924 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3930 case OPTION_IMAGE_OPTS:
3933 case OPTION_PREALLOCATION:
3934 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3935 PREALLOC_MODE__MAX, NULL);
3936 if (prealloc == PREALLOC_MODE__MAX) {
3937 error_report("Invalid preallocation mode '%s'", optarg);
3946 if (optind != argc - 1) {
3947 error_exit("Expecting image file name and size");
3949 filename = argv[optind++];
3951 if (qemu_opts_foreach(&qemu_object_opts,
3952 user_creatable_add_opts_foreach,
3953 qemu_img_object_print_help, &error_fatal)) {
3957 /* Choose grow, shrink, or absolute resize mode */
3973 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3974 if (!qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err)) {
3975 error_report_err(err);
3977 qemu_opts_del(param);
3980 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3981 qemu_opts_del(param);
3983 blk = img_open(image_opts, filename, fmt,
3984 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3991 current_size = blk_getlength(blk);
3992 if (current_size < 0) {
3993 error_report("Failed to inquire current image length: %s",
3994 strerror(-current_size));
4000 total_size = current_size + n * relative;
4004 if (total_size <= 0) {
4005 error_report("New image size must be positive");
4010 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
4011 error_report("Preallocation can only be used for growing images");
4016 if (total_size < current_size && !shrink) {
4017 error_report("Use the --shrink option to perform a shrink operation.");
4018 warn_report("Shrinking an image will delete all data beyond the "
4019 "shrunken image's end. Before performing such an "
4020 "operation, make sure there is no important data there.");
4026 * The user expects the image to have the desired size after
4027 * resizing, so pass @exact=true. It is of no use to report
4028 * success when the image has not actually been resized.
4030 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
4032 qprintf(quiet, "Image resized.\n");
4034 error_report_err(err);
4044 static void amend_status_cb(BlockDriverState *bs,
4045 int64_t offset, int64_t total_work_size,
4048 qemu_progress_print(100.f * offset / total_work_size, 0);
4051 static int print_amend_option_help(const char *format)
4055 /* Find driver and parse its options */
4056 drv = bdrv_find_format(format);
4058 error_report("Unknown file format '%s'", format);
4062 if (!drv->bdrv_amend_options) {
4063 error_report("Format driver '%s' does not support option amendment",
4068 /* Every driver supporting amendment must have amend_opts */
4069 assert(drv->amend_opts);
4071 printf("Amend options for '%s':\n", format);
4072 qemu_opts_print_help(drv->amend_opts, false);
4076 static int img_amend(int argc, char **argv)
4080 char *options = NULL;
4081 QemuOptsList *amend_opts = NULL;
4082 QemuOpts *opts = NULL;
4083 const char *fmt = NULL, *filename, *cache;
4086 bool quiet = false, progress = false;
4087 BlockBackend *blk = NULL;
4088 BlockDriverState *bs = NULL;
4089 bool image_opts = false;
4092 cache = BDRV_DEFAULT_CACHE;
4094 static const struct option long_options[] = {
4095 {"help", no_argument, 0, 'h'},
4096 {"object", required_argument, 0, OPTION_OBJECT},
4097 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4098 {"force", no_argument, 0, OPTION_FORCE},
4101 c = getopt_long(argc, argv, ":ho:f:t:pq",
4102 long_options, NULL);
4109 missing_argument(argv[optind - 1]);
4112 unrecognized_option(argv[optind - 1]);
4118 if (accumulate_options(&options, optarg) < 0) {
4120 goto out_no_progress;
4136 opts = qemu_opts_parse_noisily(&qemu_object_opts,
4140 goto out_no_progress;
4143 case OPTION_IMAGE_OPTS:
4153 error_exit("Must specify options (-o)");
4156 if (qemu_opts_foreach(&qemu_object_opts,
4157 user_creatable_add_opts_foreach,
4158 qemu_img_object_print_help, &error_fatal)) {
4160 goto out_no_progress;
4166 qemu_progress_init(progress, 1.0);
4168 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4169 if (fmt && has_help_option(options)) {
4170 /* If a format is explicitly specified (and possibly no filename is
4171 * given), print option help here */
4172 ret = print_amend_option_help(fmt);
4176 if (optind != argc - 1) {
4177 error_report("Expecting one image file name");
4182 flags = BDRV_O_RDWR;
4183 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
4185 error_report("Invalid cache option: %s", cache);
4189 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4197 fmt = bs->drv->format_name;
4199 if (has_help_option(options)) {
4200 /* If the format was auto-detected, print option help here */
4201 ret = print_amend_option_help(fmt);
4205 if (!bs->drv->bdrv_amend_options) {
4206 error_report("Format driver '%s' does not support option amendment",
4212 /* Every driver supporting amendment must have amend_opts */
4213 assert(bs->drv->amend_opts);
4215 amend_opts = qemu_opts_append(amend_opts, bs->drv->amend_opts);
4216 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
4217 if (!qemu_opts_do_parse(opts, options, NULL, &err)) {
4218 /* Try to parse options using the create options */
4219 amend_opts = qemu_opts_append(amend_opts, bs->drv->create_opts);
4220 qemu_opts_del(opts);
4221 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
4222 if (qemu_opts_do_parse(opts, options, NULL, NULL)) {
4223 error_append_hint(&err,
4224 "This option is only supported for image creation\n");
4227 error_report_err(err);
4232 /* In case the driver does not call amend_status_cb() */
4233 qemu_progress_print(0.f, 0);
4234 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, force, &err);
4235 qemu_progress_print(100.f, 0);
4237 error_report_err(err);
4242 qemu_progress_end();
4246 qemu_opts_del(opts);
4247 qemu_opts_free(amend_opts);
4256 typedef struct BenchData {
4258 uint64_t image_size;
4265 bool drain_on_flush;
4274 static void bench_undrained_flush_cb(void *opaque, int ret)
4277 error_report("Failed flush request: %s", strerror(-ret));
4282 static void bench_cb(void *opaque, int ret)
4284 BenchData *b = opaque;
4288 error_report("Failed request: %s", strerror(-ret));
4293 /* Just finished a flush with drained queue: Start next requests */
4294 assert(b->in_flight == 0);
4295 b->in_flush = false;
4296 } else if (b->in_flight > 0) {
4297 int remaining = b->n - b->in_flight;
4302 /* Time for flush? Drain queue if requested, then flush */
4303 if (b->flush_interval && remaining % b->flush_interval == 0) {
4304 if (!b->in_flight || !b->drain_on_flush) {
4305 BlockCompletionFunc *cb;
4307 if (b->drain_on_flush) {
4311 cb = bench_undrained_flush_cb;
4314 acb = blk_aio_flush(b->blk, cb, b);
4316 error_report("Failed to issue flush request");
4320 if (b->drain_on_flush) {
4326 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4327 int64_t offset = b->offset;
4328 /* blk_aio_* might look for completed I/Os and kick bench_cb
4329 * again, so make sure this operation is counted by in_flight
4330 * and b->offset is ready for the next submission.
4333 b->offset += b->step;
4334 b->offset %= b->image_size;
4336 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
4338 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
4341 error_report("Failed to issue request");
4347 static int img_bench(int argc, char **argv)
4350 const char *fmt = NULL, *filename;
4352 bool image_opts = false;
4353 bool is_write = false;
4357 size_t bufsize = 4096;
4360 int flush_interval = 0;
4361 bool drain_on_flush = true;
4363 BlockBackend *blk = NULL;
4364 BenchData data = {};
4366 bool writethrough = false;
4367 struct timeval t1, t2;
4369 bool force_share = false;
4373 static const struct option long_options[] = {
4374 {"help", no_argument, 0, 'h'},
4375 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
4376 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4377 {"pattern", required_argument, 0, OPTION_PATTERN},
4378 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
4379 {"force-share", no_argument, 0, 'U'},
4382 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4390 missing_argument(argv[optind - 1]);
4393 unrecognized_option(argv[optind - 1]);
4402 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4403 error_report("Invalid request count specified");
4413 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4414 error_report("Invalid queue depth specified");
4424 flags |= BDRV_O_NATIVE_AIO;
4427 ret = bdrv_parse_aio(optarg, &flags);
4429 error_report("Invalid aio option: %s", optarg);
4436 offset = cvtnum("offset", optarg);
4450 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4462 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4471 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4473 error_report("Invalid cache mode");
4479 flags |= BDRV_O_RDWR;
4485 case OPTION_PATTERN:
4489 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4490 error_report("Invalid pattern byte specified");
4496 case OPTION_FLUSH_INTERVAL:
4500 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4501 error_report("Invalid flush interval specified");
4504 flush_interval = res;
4507 case OPTION_NO_DRAIN:
4508 drain_on_flush = false;
4510 case OPTION_IMAGE_OPTS:
4516 if (optind != argc - 1) {
4517 error_exit("Expecting one image file name");
4519 filename = argv[argc - 1];
4521 if (!is_write && flush_interval) {
4522 error_report("--flush-interval is only available in write tests");
4526 if (flush_interval && flush_interval < depth) {
4527 error_report("Flush interval can't be smaller than depth");
4532 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4539 image_size = blk_getlength(blk);
4540 if (image_size < 0) {
4545 data = (BenchData) {
4547 .image_size = image_size,
4549 .step = step ?: bufsize,
4554 .flush_interval = flush_interval,
4555 .drain_on_flush = drain_on_flush,
4557 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4558 "(starting at offset %" PRId64 ", step size %d)\n",
4559 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4560 data.offset, data.step);
4561 if (flush_interval) {
4562 printf("Sending flush every %d requests\n", flush_interval);
4565 buf_size = data.nrreq * data.bufsize;
4566 data.buf = blk_blockalign(blk, buf_size);
4567 memset(data.buf, pattern, data.nrreq * data.bufsize);
4569 blk_register_buf(blk, data.buf, buf_size);
4571 data.qiov = g_new(QEMUIOVector, data.nrreq);
4572 for (i = 0; i < data.nrreq; i++) {
4573 qemu_iovec_init(&data.qiov[i], 1);
4574 qemu_iovec_add(&data.qiov[i],
4575 data.buf + i * data.bufsize, data.bufsize);
4578 gettimeofday(&t1, NULL);
4581 while (data.n > 0) {
4582 main_loop_wait(false);
4584 gettimeofday(&t2, NULL);
4586 printf("Run completed in %3.3f seconds.\n",
4587 (t2.tv_sec - t1.tv_sec)
4588 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4592 blk_unregister_buf(blk, data.buf);
4594 qemu_vfree(data.buf);
4611 typedef struct ImgBitmapAction {
4612 enum ImgBitmapAct act;
4613 const char *src; /* only used for merge */
4614 QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4617 static int img_bitmap(int argc, char **argv)
4621 QemuOpts *opts = NULL;
4622 const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4623 const char *filename, *bitmap;
4624 BlockBackend *blk = NULL, *src = NULL;
4625 BlockDriverState *bs = NULL, *src_bs = NULL;
4626 bool image_opts = false;
4627 int64_t granularity = 0;
4628 bool add = false, merge = false;
4629 QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4630 ImgBitmapAction *act, *act_next;
4633 QSIMPLEQ_INIT(&actions);
4636 static const struct option long_options[] = {
4637 {"help", no_argument, 0, 'h'},
4638 {"object", required_argument, 0, OPTION_OBJECT},
4639 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4640 {"add", no_argument, 0, OPTION_ADD},
4641 {"remove", no_argument, 0, OPTION_REMOVE},
4642 {"clear", no_argument, 0, OPTION_CLEAR},
4643 {"enable", no_argument, 0, OPTION_ENABLE},
4644 {"disable", no_argument, 0, OPTION_DISABLE},
4645 {"merge", required_argument, 0, OPTION_MERGE},
4646 {"granularity", required_argument, 0, 'g'},
4647 {"source-file", required_argument, 0, 'b'},
4648 {"source-format", required_argument, 0, 'F'},
4651 c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4658 missing_argument(argv[optind - 1]);
4661 unrecognized_option(argv[optind - 1]);
4667 src_filename = optarg;
4676 granularity = cvtnum("granularity", optarg);
4677 if (granularity < 0) {
4682 act = g_new0(ImgBitmapAction, 1);
4683 act->act = BITMAP_ADD;
4684 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4688 act = g_new0(ImgBitmapAction, 1);
4689 act->act = BITMAP_REMOVE;
4690 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4693 act = g_new0(ImgBitmapAction, 1);
4694 act->act = BITMAP_CLEAR;
4695 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4698 act = g_new0(ImgBitmapAction, 1);
4699 act->act = BITMAP_ENABLE;
4700 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4702 case OPTION_DISABLE:
4703 act = g_new0(ImgBitmapAction, 1);
4704 act->act = BITMAP_DISABLE;
4705 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4708 act = g_new0(ImgBitmapAction, 1);
4709 act->act = BITMAP_MERGE;
4711 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4715 opts = qemu_opts_parse_noisily(&qemu_object_opts, optarg, true);
4720 case OPTION_IMAGE_OPTS:
4726 if (qemu_opts_foreach(&qemu_object_opts,
4727 user_creatable_add_opts_foreach,
4728 qemu_img_object_print_help, &error_fatal)) {
4732 if (QSIMPLEQ_EMPTY(&actions)) {
4733 error_report("Need at least one of --add, --remove, --clear, "
4734 "--enable, --disable, or --merge");
4738 if (granularity && !add) {
4739 error_report("granularity only supported with --add");
4742 if (src_fmt && !src_filename) {
4743 error_report("-F only supported with -b");
4746 if (src_filename && !merge) {
4747 error_report("Merge bitmap source file only supported with "
4752 if (optind != argc - 2) {
4753 error_report("Expecting filename and bitmap name");
4757 filename = argv[optind];
4758 bitmap = argv[optind + 1];
4760 blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR, false, false,
4767 src = img_open(false, src_filename, src_fmt, 0, false, false, false);
4771 src_bs = blk_bs(src);
4776 QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4779 qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4780 !!granularity, granularity, true, true,
4781 false, false, &err);
4785 qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4789 qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4793 qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4796 case BITMAP_DISABLE:
4797 qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4801 do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4806 g_assert_not_reached();
4810 error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4822 qemu_opts_del(opts);
4838 int bsz; /* Block size */
4846 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4850 static int img_dd_bs(const char *arg,
4851 struct DdIo *in, struct DdIo *out,
4856 res = cvtnum_full("bs", arg, 1, INT_MAX);
4861 in->bsz = out->bsz = res;
4866 static int img_dd_count(const char *arg,
4867 struct DdIo *in, struct DdIo *out,
4870 dd->count = cvtnum("count", arg);
4872 if (dd->count < 0) {
4879 static int img_dd_if(const char *arg,
4880 struct DdIo *in, struct DdIo *out,
4883 in->filename = g_strdup(arg);
4888 static int img_dd_of(const char *arg,
4889 struct DdIo *in, struct DdIo *out,
4892 out->filename = g_strdup(arg);
4897 static int img_dd_skip(const char *arg,
4898 struct DdIo *in, struct DdIo *out,
4901 in->offset = cvtnum("skip", arg);
4903 if (in->offset < 0) {
4910 static int img_dd(int argc, char **argv)
4915 BlockDriver *drv = NULL, *proto_drv = NULL;
4916 BlockBackend *blk1 = NULL, *blk2 = NULL;
4917 QemuOpts *opts = NULL;
4918 QemuOptsList *create_opts = NULL;
4919 Error *local_err = NULL;
4920 bool image_opts = false;
4922 const char *out_fmt = "raw";
4923 const char *fmt = NULL;
4925 int64_t block_count = 0, out_pos, in_pos;
4926 bool force_share = false;
4927 struct DdInfo dd = {
4932 .bsz = 512, /* Block size is by default 512 bytes */
4944 const struct DdOpts options[] = {
4945 { "bs", img_dd_bs, C_BS },
4946 { "count", img_dd_count, C_COUNT },
4947 { "if", img_dd_if, C_IF },
4948 { "of", img_dd_of, C_OF },
4949 { "skip", img_dd_skip, C_SKIP },
4952 const struct option long_options[] = {
4953 { "help", no_argument, 0, 'h'},
4954 { "object", required_argument, 0, OPTION_OBJECT},
4955 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4956 { "force-share", no_argument, 0, 'U'},
4960 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4972 missing_argument(argv[optind - 1]);
4975 unrecognized_option(argv[optind - 1]);
4984 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4989 case OPTION_IMAGE_OPTS:
4995 for (i = optind; i < argc; i++) {
4997 arg = g_strdup(argv[i]);
4999 tmp = strchr(arg, '=');
5001 error_report("unrecognized operand %s", arg);
5008 for (j = 0; options[j].name != NULL; j++) {
5009 if (!strcmp(arg, options[j].name)) {
5013 if (options[j].name == NULL) {
5014 error_report("unrecognized operand %s", arg);
5019 if (options[j].f(tmp, &in, &out, &dd) != 0) {
5023 dd.flags |= options[j].flag;
5028 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
5029 error_report("Must specify both input and output files");
5034 if (qemu_opts_foreach(&qemu_object_opts,
5035 user_creatable_add_opts_foreach,
5036 qemu_img_object_print_help, &error_fatal)) {
5041 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
5049 drv = bdrv_find_format(out_fmt);
5051 error_report("Unknown file format");
5055 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
5058 error_report_err(local_err);
5062 if (!drv->create_opts) {
5063 error_report("Format driver '%s' does not support image creation",
5068 if (!proto_drv->create_opts) {
5069 error_report("Protocol driver '%s' does not support image creation",
5070 proto_drv->format_name);
5074 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5075 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5077 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5079 size = blk_getlength(blk1);
5081 error_report("Failed to get size for '%s'", in.filename);
5086 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5087 dd.count * in.bsz < size) {
5088 size = dd.count * in.bsz;
5091 /* Overflow means the specified offset is beyond input image's size */
5092 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5093 size < in.bsz * in.offset)) {
5094 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5096 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5097 size - in.bsz * in.offset, &error_abort);
5100 ret = bdrv_create(drv, out.filename, opts, &local_err);
5102 error_reportf_err(local_err,
5103 "%s: error while creating output image: ",
5109 /* TODO, we can't honour --image-opts for the target,
5110 * since it needs to be given in a format compatible
5111 * with the bdrv_create() call above which does not
5112 * support image-opts style.
5114 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
5115 false, false, false);
5122 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5123 size < in.offset * in.bsz)) {
5124 /* We give a warning if the skip option is bigger than the input
5125 * size and create an empty output disk image (i.e. like dd(1)).
5127 error_report("%s: cannot skip to specified offset", in.filename);
5130 in_pos = in.offset * in.bsz;
5133 in.buf = g_new(uint8_t, in.bsz);
5135 for (out_pos = 0; in_pos < size; block_count++) {
5136 int in_ret, out_ret;
5138 if (in_pos + in.bsz > size) {
5139 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
5141 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
5144 error_report("error while reading from input image file: %s",
5151 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
5154 error_report("error while writing to output image file: %s",
5155 strerror(-out_ret));
5164 qemu_opts_del(opts);
5165 qemu_opts_free(create_opts);
5168 g_free(in.filename);
5169 g_free(out.filename);
5179 static void dump_json_block_measure_info(BlockMeasureInfo *info)
5183 Visitor *v = qobject_output_visitor_new(&obj);
5185 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5186 visit_complete(v, &obj);
5187 str = qobject_to_json_pretty(obj);
5188 assert(str != NULL);
5189 printf("%s\n", qstring_get_str(str));
5195 static int img_measure(int argc, char **argv)
5197 static const struct option long_options[] = {
5198 {"help", no_argument, 0, 'h'},
5199 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5200 {"object", required_argument, 0, OPTION_OBJECT},
5201 {"output", required_argument, 0, OPTION_OUTPUT},
5202 {"size", required_argument, 0, OPTION_SIZE},
5203 {"force-share", no_argument, 0, 'U'},
5206 OutputFormat output_format = OFORMAT_HUMAN;
5207 BlockBackend *in_blk = NULL;
5209 const char *filename = NULL;
5210 const char *fmt = NULL;
5211 const char *out_fmt = "raw";
5212 char *options = NULL;
5213 char *snapshot_name = NULL;
5214 bool force_share = false;
5215 QemuOpts *opts = NULL;
5216 QemuOpts *object_opts = NULL;
5217 QemuOpts *sn_opts = NULL;
5218 QemuOptsList *create_opts = NULL;
5219 bool image_opts = false;
5220 uint64_t img_size = UINT64_MAX;
5221 BlockMeasureInfo *info = NULL;
5222 Error *local_err = NULL;
5226 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5227 long_options, NULL)) != -1) {
5240 if (accumulate_options(&options, optarg) < 0) {
5245 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5246 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5249 error_report("Failed in parsing snapshot param '%s'",
5254 snapshot_name = optarg;
5261 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
5267 case OPTION_IMAGE_OPTS:
5271 if (!strcmp(optarg, "json")) {
5272 output_format = OFORMAT_JSON;
5273 } else if (!strcmp(optarg, "human")) {
5274 output_format = OFORMAT_HUMAN;
5276 error_report("--output must be used with human or json "
5285 sval = cvtnum("image size", optarg);
5289 img_size = (uint64_t)sval;
5295 if (qemu_opts_foreach(&qemu_object_opts,
5296 user_creatable_add_opts_foreach,
5297 qemu_img_object_print_help, &error_fatal)) {
5301 if (argc - optind > 1) {
5302 error_report("At most one filename argument is allowed.");
5304 } else if (argc - optind == 1) {
5305 filename = argv[optind];
5308 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5309 error_report("--image-opts, -f, and -l require a filename argument.");
5312 if (filename && img_size != UINT64_MAX) {
5313 error_report("--size N cannot be used together with a filename.");
5316 if (!filename && img_size == UINT64_MAX) {
5317 error_report("Either --size N or one filename must be specified.");
5322 in_blk = img_open(image_opts, filename, fmt, 0,
5323 false, false, force_share);
5329 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5330 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5331 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5333 } else if (snapshot_name != NULL) {
5334 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5335 snapshot_name, &local_err);
5338 error_reportf_err(local_err, "Failed to load snapshot: ");
5343 drv = bdrv_find_format(out_fmt);
5345 error_report("Unknown file format '%s'", out_fmt);
5348 if (!drv->create_opts) {
5349 error_report("Format driver '%s' does not support image creation",
5354 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5355 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5356 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5358 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
5359 error_report_err(local_err);
5360 error_report("Invalid options for file format '%s'", out_fmt);
5364 if (img_size != UINT64_MAX) {
5365 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5368 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5370 error_report_err(local_err);
5374 if (output_format == OFORMAT_HUMAN) {
5375 printf("required size: %" PRIu64 "\n", info->required);
5376 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
5377 if (info->has_bitmaps) {
5378 printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5381 dump_json_block_measure_info(info);
5387 qapi_free_BlockMeasureInfo(info);
5388 qemu_opts_del(object_opts);
5389 qemu_opts_del(opts);
5390 qemu_opts_del(sn_opts);
5391 qemu_opts_free(create_opts);
5397 static const img_cmd_t img_cmds[] = {
5398 #define DEF(option, callback, arg_string) \
5399 { option, callback },
5400 #include "qemu-img-cmds.h"
5405 int main(int argc, char **argv)
5407 const img_cmd_t *cmd;
5408 const char *cmdname;
5409 Error *local_error = NULL;
5410 char *trace_file = NULL;
5412 static const struct option long_options[] = {
5413 {"help", no_argument, 0, 'h'},
5414 {"version", no_argument, 0, 'V'},
5415 {"trace", required_argument, NULL, 'T'},
5420 signal(SIGPIPE, SIG_IGN);
5424 error_init(argv[0]);
5425 module_call_init(MODULE_INIT_TRACE);
5426 qemu_init_exec_dir(argv[0]);
5428 if (qemu_init_main_loop(&local_error)) {
5429 error_report_err(local_error);
5433 qcrypto_init(&error_fatal);
5435 module_call_init(MODULE_INIT_QOM);
5438 error_exit("Not enough arguments");
5441 qemu_add_opts(&qemu_object_opts);
5442 qemu_add_opts(&qemu_source_opts);
5443 qemu_add_opts(&qemu_trace_opts);
5445 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
5448 missing_argument(argv[optind - 1]);
5451 unrecognized_option(argv[optind - 1]);
5457 printf(QEMU_IMG_VERSION);
5461 trace_file = trace_opt_parse(optarg);
5466 cmdname = argv[optind];
5468 /* reset getopt_long scanning */
5474 qemu_reset_optind();
5476 if (!trace_init_backends()) {
5479 trace_init_file(trace_file);
5480 qemu_set_log(LOG_TRACE);
5482 /* find the command */
5483 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5484 if (!strcmp(cmdname, cmd->name)) {
5485 return cmd->handler(argc, argv);
5490 error_exit("Command not found: %s", cmdname);