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-version.h"
29 #include "qapi/error.h"
30 #include "qapi/qapi-visit-block-core.h"
31 #include "qapi/qobject-output-visitor.h"
32 #include "qapi/qmp/qjson.h"
33 #include "qapi/qmp/qdict.h"
34 #include "qapi/qmp/qstring.h"
35 #include "qemu/cutils.h"
36 #include "qemu/config-file.h"
37 #include "qemu/option.h"
38 #include "qemu/error-report.h"
40 #include "qom/object_interfaces.h"
41 #include "sysemu/sysemu.h"
42 #include "sysemu/block-backend.h"
43 #include "block/block_int.h"
44 #include "block/blockjob.h"
45 #include "block/qapi.h"
46 #include "crypto/init.h"
47 #include "trace/control.h"
49 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
50 "\n" QEMU_COPYRIGHT "\n"
52 typedef struct img_cmd_t {
54 int (*handler)(int argc, char **argv);
59 OPTION_BACKING_CHAIN = 257,
61 OPTION_IMAGE_OPTS = 259,
63 OPTION_FLUSH_INTERVAL = 261,
64 OPTION_NO_DRAIN = 262,
65 OPTION_TARGET_IMAGE_OPTS = 263,
67 OPTION_PREALLOCATION = 265,
71 typedef enum OutputFormat {
76 /* Default to cache=writeback as data integrity is not important for qemu-img */
77 #define BDRV_DEFAULT_CACHE "writeback"
79 static void format_print(void *opaque, const char *name)
84 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
88 error_printf("qemu-img: ");
91 error_vprintf(fmt, ap);
94 error_printf("\nTry 'qemu-img --help' for more information\n");
98 static void QEMU_NORETURN missing_argument(const char *option)
100 error_exit("missing argument for option '%s'", option);
103 static void QEMU_NORETURN unrecognized_option(const char *option)
105 error_exit("unrecognized option '%s'", option);
108 /* Please keep in synch with qemu-img.texi */
109 static void QEMU_NORETURN help(void)
111 const char *help_msg =
113 "usage: qemu-img [standard options] command [command options]\n"
114 "QEMU disk image utility\n"
116 " '-h', '--help' display this help and exit\n"
117 " '-V', '--version' output version information and exit\n"
118 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
119 " specify tracing options\n"
122 #define DEF(option, callback, arg_string) \
124 #include "qemu-img-cmds.h"
127 "Command parameters:\n"
128 " 'filename' is a disk image filename\n"
129 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
130 " manual page for a description of the object properties. The most common\n"
131 " object type is a 'secret', which is used to supply passwords and/or\n"
132 " encryption keys.\n"
133 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
134 " 'cache' is the cache mode used to write the output disk image, the valid\n"
135 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
136 " 'directsync' and 'unsafe' (default for convert)\n"
137 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
138 " options are the same as for the 'cache' option\n"
139 " 'size' is the disk image size in bytes. Optional suffixes\n"
140 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
141 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
142 " supported. 'b' is ignored.\n"
143 " 'output_filename' is the destination disk image filename\n"
144 " 'output_fmt' is the destination format\n"
145 " 'options' is a comma separated list of format specific options in a\n"
146 " name=value format. Use -o ? for an overview of the options supported by the\n"
148 " 'snapshot_param' is param used for internal snapshot, format\n"
149 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
151 " '-c' indicates that target image must be compressed (qcow format only)\n"
152 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
153 " new backing file match exactly. The image doesn't need a working\n"
154 " backing file before rebasing in this case (useful for renaming the\n"
155 " backing file). For image creation, allow creating without attempting\n"
156 " to open the backing file.\n"
157 " '-h' with or without a command shows this help and lists the supported formats\n"
158 " '-p' show progress of command (only certain commands)\n"
159 " '-q' use Quiet mode - do not print any output (except errors)\n"
160 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
161 " contain only zeros for qemu-img to create a sparse image during\n"
162 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
163 " unallocated or zero sectors, and the destination image will always be\n"
165 " '--output' takes the format in which the output must be done (human or json)\n"
166 " '-n' skips the target volume creation (useful if the volume is created\n"
167 " prior to running qemu-img)\n"
169 "Parameters to check subcommand:\n"
170 " '-r' tries to repair any inconsistencies that are found during the check.\n"
171 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
172 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
173 " hiding corruption that has already occurred.\n"
175 "Parameters to convert subcommand:\n"
176 " '-m' specifies how many coroutines work in parallel during the convert\n"
177 " process (defaults to 8)\n"
178 " '-W' allow to write to the target out of order rather than sequential\n"
180 "Parameters to snapshot subcommand:\n"
181 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
182 " '-a' applies a snapshot (revert disk to saved state)\n"
183 " '-c' creates a snapshot\n"
184 " '-d' deletes a snapshot\n"
185 " '-l' lists all snapshots in the given image\n"
187 "Parameters to compare subcommand:\n"
188 " '-f' first image format\n"
189 " '-F' second image format\n"
190 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
192 "Parameters to dd subcommand:\n"
193 " 'bs=BYTES' read and write up to BYTES bytes at a time "
195 " 'count=N' copy only N input blocks\n"
196 " 'if=FILE' read from FILE\n"
197 " 'of=FILE' write to FILE\n"
198 " 'skip=N' skip N bs-sized blocks at the start of input\n";
200 printf("%s\nSupported formats:", help_msg);
201 bdrv_iterate_format(format_print, NULL);
202 printf("\n\n" QEMU_HELP_BOTTOM "\n");
206 static QemuOptsList qemu_object_opts = {
208 .implied_opt_name = "qom-type",
209 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
215 static QemuOptsList qemu_source_opts = {
217 .implied_opt_name = "file",
218 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
224 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
230 ret = vprintf(fmt, args);
237 static int print_block_option_help(const char *filename, const char *fmt)
239 BlockDriver *drv, *proto_drv;
240 QemuOptsList *create_opts = NULL;
241 Error *local_err = NULL;
243 /* Find driver and parse its options */
244 drv = bdrv_find_format(fmt);
246 error_report("Unknown file format '%s'", fmt);
250 if (!drv->create_opts) {
251 error_report("Format driver '%s' does not support image creation", fmt);
255 create_opts = qemu_opts_append(create_opts, drv->create_opts);
257 proto_drv = bdrv_find_protocol(filename, true, &local_err);
259 error_report_err(local_err);
260 qemu_opts_free(create_opts);
263 if (!proto_drv->create_opts) {
264 error_report("Protocal driver '%s' does not support image creation",
265 proto_drv->format_name);
268 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
271 printf("Supported options:\n");
272 qemu_opts_print_help(create_opts);
273 qemu_opts_free(create_opts);
278 static BlockBackend *img_open_opts(const char *optstr,
279 QemuOpts *opts, int flags, bool writethrough,
280 bool quiet, bool force_share)
283 Error *local_err = NULL;
285 options = qemu_opts_to_qdict(opts, NULL);
287 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
288 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
289 error_report("--force-share/-U conflicts with image options");
290 qobject_unref(options);
293 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
295 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
297 error_reportf_err(local_err, "Could not open '%s': ", optstr);
300 blk_set_enable_write_cache(blk, !writethrough);
305 static BlockBackend *img_open_file(const char *filename,
307 const char *fmt, int flags,
308 bool writethrough, bool quiet,
312 Error *local_err = NULL;
315 options = qdict_new();
318 qdict_put_str(options, "driver", fmt);
322 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
324 blk = blk_new_open(filename, NULL, options, flags, &local_err);
326 error_reportf_err(local_err, "Could not open '%s': ", filename);
329 blk_set_enable_write_cache(blk, !writethrough);
335 static int img_add_key_secrets(void *opaque,
336 const char *name, const char *value,
339 QDict *options = opaque;
341 if (g_str_has_suffix(name, "key-secret")) {
342 qdict_put_str(options, name, value);
348 static BlockBackend *img_open_new_file(const char *filename,
349 QemuOpts *create_opts,
350 const char *fmt, int flags,
351 bool writethrough, bool quiet,
354 QDict *options = NULL;
356 options = qdict_new();
357 qemu_opt_foreach(create_opts, img_add_key_secrets, options, &error_abort);
359 return img_open_file(filename, options, fmt, flags, writethrough, quiet,
364 static BlockBackend *img_open(bool image_opts,
365 const char *filename,
366 const char *fmt, int flags, bool writethrough,
367 bool quiet, bool force_share)
373 error_report("--image-opts and --format are mutually exclusive");
376 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
381 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
384 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
391 static int add_old_style_options(const char *fmt, QemuOpts *opts,
392 const char *base_filename,
393 const char *base_fmt)
398 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
400 error_report("Backing file not supported for file format '%s'",
407 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
409 error_report("Backing file format not supported for file "
418 static int64_t cvtnum(const char *s)
423 err = qemu_strtosz(s, NULL, &value);
427 if (value > INT64_MAX) {
433 static int img_create(int argc, char **argv)
436 uint64_t img_size = -1;
437 const char *fmt = "raw";
438 const char *base_fmt = NULL;
439 const char *filename;
440 const char *base_filename = NULL;
441 char *options = NULL;
442 Error *local_err = NULL;
447 static const struct option long_options[] = {
448 {"help", no_argument, 0, 'h'},
449 {"object", required_argument, 0, OPTION_OBJECT},
452 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
459 missing_argument(argv[optind - 1]);
462 unrecognized_option(argv[optind - 1]);
471 base_filename = optarg;
477 if (!is_valid_option_list(optarg)) {
478 error_report("Invalid option list: %s", optarg);
482 options = g_strdup(optarg);
484 char *old_options = options;
485 options = g_strdup_printf("%s,%s", options, optarg);
493 flags |= BDRV_O_NO_BACKING;
495 case OPTION_OBJECT: {
497 opts = qemu_opts_parse_noisily(&qemu_object_opts,
506 /* Get the filename */
507 filename = (optind < argc) ? argv[optind] : NULL;
508 if (options && has_help_option(options)) {
510 return print_block_option_help(filename, fmt);
513 if (optind >= argc) {
514 error_exit("Expecting image file name");
518 if (qemu_opts_foreach(&qemu_object_opts,
519 user_creatable_add_opts_foreach,
524 /* Get image size, if specified */
528 sval = cvtnum(argv[optind++]);
530 if (sval == -ERANGE) {
531 error_report("Image size must be less than 8 EiB!");
533 error_report("Invalid image size specified! You may use k, M, "
534 "G, T, P or E suffixes for ");
535 error_report("kilobytes, megabytes, gigabytes, terabytes, "
536 "petabytes and exabytes.");
540 img_size = (uint64_t)sval;
542 if (optind != argc) {
543 error_exit("Unexpected argument: %s", argv[optind]);
546 bdrv_img_create(filename, fmt, base_filename, base_fmt,
547 options, img_size, flags, quiet, &local_err);
549 error_reportf_err(local_err, "%s: ", filename);
561 static void dump_json_image_check(ImageCheck *check, bool quiet)
565 Visitor *v = qobject_output_visitor_new(&obj);
567 visit_type_ImageCheck(v, NULL, &check, &error_abort);
568 visit_complete(v, &obj);
569 str = qobject_to_json_pretty(obj);
571 qprintf(quiet, "%s\n", qstring_get_str(str));
577 static void dump_human_image_check(ImageCheck *check, bool quiet)
579 if (!(check->corruptions || check->leaks || check->check_errors)) {
580 qprintf(quiet, "No errors were found on the image.\n");
582 if (check->corruptions) {
583 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
584 "Data may be corrupted, or further writes to the image "
591 "\n%" PRId64 " leaked clusters were found on the image.\n"
592 "This means waste of disk space, but no harm to data.\n",
596 if (check->check_errors) {
599 " internal errors have occurred during the check.\n",
600 check->check_errors);
604 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
605 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
606 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
607 check->allocated_clusters, check->total_clusters,
608 check->allocated_clusters * 100.0 / check->total_clusters,
609 check->fragmented_clusters * 100.0 / check->allocated_clusters,
610 check->compressed_clusters * 100.0 /
611 check->allocated_clusters);
614 if (check->image_end_offset) {
616 "Image end offset: %" PRId64 "\n", check->image_end_offset);
620 static int collect_image_check(BlockDriverState *bs,
622 const char *filename,
627 BdrvCheckResult result;
629 ret = bdrv_check(bs, &result, fix);
634 check->filename = g_strdup(filename);
635 check->format = g_strdup(bdrv_get_format_name(bs));
636 check->check_errors = result.check_errors;
637 check->corruptions = result.corruptions;
638 check->has_corruptions = result.corruptions != 0;
639 check->leaks = result.leaks;
640 check->has_leaks = result.leaks != 0;
641 check->corruptions_fixed = result.corruptions_fixed;
642 check->has_corruptions_fixed = result.corruptions != 0;
643 check->leaks_fixed = result.leaks_fixed;
644 check->has_leaks_fixed = result.leaks != 0;
645 check->image_end_offset = result.image_end_offset;
646 check->has_image_end_offset = result.image_end_offset != 0;
647 check->total_clusters = result.bfi.total_clusters;
648 check->has_total_clusters = result.bfi.total_clusters != 0;
649 check->allocated_clusters = result.bfi.allocated_clusters;
650 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
651 check->fragmented_clusters = result.bfi.fragmented_clusters;
652 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
653 check->compressed_clusters = result.bfi.compressed_clusters;
654 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
660 * Checks an image for consistency. Exit codes:
662 * 0 - Check completed, image is good
663 * 1 - Check not completed because of internal errors
664 * 2 - Check completed, image is corrupted
665 * 3 - Check completed, image has leaked clusters, but is good otherwise
666 * 63 - Checks are not supported by the image format
668 static int img_check(int argc, char **argv)
671 OutputFormat output_format = OFORMAT_HUMAN;
672 const char *filename, *fmt, *output, *cache;
674 BlockDriverState *bs;
676 int flags = BDRV_O_CHECK;
680 bool image_opts = false;
681 bool force_share = false;
685 cache = BDRV_DEFAULT_CACHE;
688 int option_index = 0;
689 static const struct option long_options[] = {
690 {"help", no_argument, 0, 'h'},
691 {"format", required_argument, 0, 'f'},
692 {"repair", required_argument, 0, 'r'},
693 {"output", required_argument, 0, OPTION_OUTPUT},
694 {"object", required_argument, 0, OPTION_OBJECT},
695 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
696 {"force-share", no_argument, 0, 'U'},
699 c = getopt_long(argc, argv, ":hf:r:T:qU",
700 long_options, &option_index);
706 missing_argument(argv[optind - 1]);
709 unrecognized_option(argv[optind - 1]);
718 flags |= BDRV_O_RDWR;
720 if (!strcmp(optarg, "leaks")) {
721 fix = BDRV_FIX_LEAKS;
722 } else if (!strcmp(optarg, "all")) {
723 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
725 error_exit("Unknown option value for -r "
726 "(expecting 'leaks' or 'all'): %s", optarg);
741 case OPTION_OBJECT: {
743 opts = qemu_opts_parse_noisily(&qemu_object_opts,
749 case OPTION_IMAGE_OPTS:
754 if (optind != argc - 1) {
755 error_exit("Expecting one image file name");
757 filename = argv[optind++];
759 if (output && !strcmp(output, "json")) {
760 output_format = OFORMAT_JSON;
761 } else if (output && !strcmp(output, "human")) {
762 output_format = OFORMAT_HUMAN;
764 error_report("--output must be used with human or json as argument.");
768 if (qemu_opts_foreach(&qemu_object_opts,
769 user_creatable_add_opts_foreach,
774 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
776 error_report("Invalid source cache option: %s", cache);
780 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
787 check = g_new0(ImageCheck, 1);
788 ret = collect_image_check(bs, check, filename, fmt, fix);
790 if (ret == -ENOTSUP) {
791 error_report("This image format does not support checks");
796 if (check->corruptions_fixed || check->leaks_fixed) {
797 int corruptions_fixed, leaks_fixed;
799 leaks_fixed = check->leaks_fixed;
800 corruptions_fixed = check->corruptions_fixed;
802 if (output_format == OFORMAT_HUMAN) {
804 "The following inconsistencies were found and repaired:\n\n"
805 " %" PRId64 " leaked clusters\n"
806 " %" PRId64 " corruptions\n\n"
807 "Double checking the fixed image now...\n",
809 check->corruptions_fixed);
812 ret = collect_image_check(bs, check, filename, fmt, 0);
814 check->leaks_fixed = leaks_fixed;
815 check->corruptions_fixed = corruptions_fixed;
819 switch (output_format) {
821 dump_human_image_check(check, quiet);
824 dump_json_image_check(check, quiet);
829 if (ret || check->check_errors) {
831 error_report("Check failed: %s", strerror(-ret));
833 error_report("Check failed");
839 if (check->corruptions) {
841 } else if (check->leaks) {
848 qapi_free_ImageCheck(check);
853 typedef struct CommonBlockJobCBInfo {
854 BlockDriverState *bs;
856 } CommonBlockJobCBInfo;
858 static void common_block_job_cb(void *opaque, int ret)
860 CommonBlockJobCBInfo *cbi = opaque;
863 error_setg_errno(cbi->errp, -ret, "Block job failed");
867 static void run_block_job(BlockJob *job, Error **errp)
869 AioContext *aio_context = blk_get_aio_context(job->blk);
872 aio_context_acquire(aio_context);
875 float progress = 0.0f;
876 aio_poll(aio_context, true);
877 if (job->job.progress_total) {
878 progress = (float)job->job.progress_current /
879 job->job.progress_total * 100.f;
881 qemu_progress_print(progress, 0);
882 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
884 if (!job_is_completed(&job->job)) {
885 ret = job_complete_sync(&job->job, errp);
889 job_unref(&job->job);
890 aio_context_release(aio_context);
892 /* publish completion progress only when success */
894 qemu_progress_print(100.f, 0);
898 static int img_commit(int argc, char **argv)
901 const char *filename, *fmt, *cache, *base;
903 BlockDriverState *bs, *base_bs;
905 bool progress = false, quiet = false, drop = false;
907 Error *local_err = NULL;
908 CommonBlockJobCBInfo cbi;
909 bool image_opts = false;
910 AioContext *aio_context;
913 cache = BDRV_DEFAULT_CACHE;
916 static const struct option long_options[] = {
917 {"help", no_argument, 0, 'h'},
918 {"object", required_argument, 0, OPTION_OBJECT},
919 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
922 c = getopt_long(argc, argv, ":f:ht:b:dpq",
929 missing_argument(argv[optind - 1]);
932 unrecognized_option(argv[optind - 1]);
957 case OPTION_OBJECT: {
959 opts = qemu_opts_parse_noisily(&qemu_object_opts,
965 case OPTION_IMAGE_OPTS:
971 /* Progress is not shown in Quiet mode */
976 if (optind != argc - 1) {
977 error_exit("Expecting one image file name");
979 filename = argv[optind++];
981 if (qemu_opts_foreach(&qemu_object_opts,
982 user_creatable_add_opts_foreach,
987 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
988 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
990 error_report("Invalid cache option: %s", cache);
994 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1001 qemu_progress_init(progress, 1.f);
1002 qemu_progress_print(0.f, 100);
1005 base_bs = bdrv_find_backing_image(bs, base);
1007 error_setg(&local_err,
1008 "Did not find '%s' in the backing chain of '%s'",
1013 /* This is different from QMP, which by default uses the deepest file in
1014 * the backing chain (i.e., the very base); however, the traditional
1015 * behavior of qemu-img commit is using the immediate backing file. */
1016 base_bs = backing_bs(bs);
1018 error_setg(&local_err, "Image does not have a backing file");
1023 cbi = (CommonBlockJobCBInfo){
1028 aio_context = bdrv_get_aio_context(bs);
1029 aio_context_acquire(aio_context);
1030 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
1031 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1032 &cbi, false, &local_err);
1033 aio_context_release(aio_context);
1038 /* When the block job completes, the BlockBackend reference will point to
1039 * the old backing file. In order to avoid that the top image is already
1040 * deleted, so we can still empty it afterwards, increment the reference
1041 * counter here preemptively. */
1046 job = block_job_get("commit");
1047 run_block_job(job, &local_err);
1052 if (!drop && bs->drv->bdrv_make_empty) {
1053 ret = bs->drv->bdrv_make_empty(bs);
1055 error_setg_errno(&local_err, -ret, "Could not empty %s",
1067 qemu_progress_end();
1072 error_report_err(local_err);
1076 qprintf(quiet, "Image committed.\n");
1081 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1082 * of the first sector boundary within buf where the sector contains a
1083 * non-zero byte. This function is robust to a buffer that is not
1086 static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1089 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1091 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1092 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1096 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1103 * Returns true iff the first sector pointed to by 'buf' contains at least
1106 * 'pnum' is set to the number of sectors (including and immediately following
1107 * the first one) that are known to be in the same allocated/unallocated state.
1108 * The function will try to align the end offset to alignment boundaries so
1109 * that the request will at least end aligned and consequtive requests will
1110 * also start at an aligned offset.
1112 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1113 int64_t sector_num, int alignment)
1122 is_zero = buffer_is_zero(buf, 512);
1123 for(i = 1; i < n; i++) {
1125 if (is_zero != buffer_is_zero(buf, 512)) {
1130 tail = (sector_num + i) & (alignment - 1);
1132 if (is_zero && i <= tail) {
1133 /* treat unallocated areas which only consist
1134 * of a small tail as allocated. */
1138 /* align up end offset of allocated areas. */
1139 i += alignment - tail;
1142 /* align down end offset of zero areas. */
1151 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1152 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1153 * breaking up write requests for only small sparse areas.
1155 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1156 int min, int64_t sector_num, int alignment)
1159 int num_checked, num_used;
1165 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1171 buf += BDRV_SECTOR_SIZE * *pnum;
1173 sector_num += *pnum;
1174 num_checked = num_used;
1177 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1179 buf += BDRV_SECTOR_SIZE * *pnum;
1181 sector_num += *pnum;
1182 num_checked += *pnum;
1184 num_used = num_checked;
1185 } else if (*pnum >= min) {
1195 * Compares two buffers sector by sector. Returns 0 if the first
1196 * sector of each buffer matches, non-zero otherwise.
1198 * pnum is set to the sector-aligned size of the buffer prefix that
1199 * has the same matching status as the first sector.
1201 static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1202 int64_t bytes, int64_t *pnum)
1205 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
1209 res = !!memcmp(buf1, buf2, i);
1211 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
1213 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
1223 #define IO_BUF_SIZE (2 * 1024 * 1024)
1226 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1228 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1229 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1230 * failure), and 4 on error (the exit status for read errors), after emitting
1233 * @param blk: BlockBackend for the image
1234 * @param offset: Starting offset to check
1235 * @param bytes: Number of bytes to check
1236 * @param filename: Name of disk file we are checking (logging purpose)
1237 * @param buffer: Allocated buffer for storing read data
1238 * @param quiet: Flag for quiet mode
1240 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1241 int64_t bytes, const char *filename,
1242 uint8_t *buffer, bool quiet)
1247 ret = blk_pread(blk, offset, buffer, bytes);
1249 error_report("Error while reading offset %" PRId64 " of %s: %s",
1250 offset, filename, strerror(-ret));
1253 idx = find_nonzero(buffer, bytes);
1255 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1264 * Compares two images. Exit codes:
1266 * 0 - Images are identical
1268 * >1 - Error occurred
1270 static int img_compare(int argc, char **argv)
1272 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1273 BlockBackend *blk1, *blk2;
1274 BlockDriverState *bs1, *bs2;
1275 int64_t total_size1, total_size2;
1276 uint8_t *buf1 = NULL, *buf2 = NULL;
1277 int64_t pnum1, pnum2;
1278 int allocated1, allocated2;
1279 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1280 bool progress = false, quiet = false, strict = false;
1287 uint64_t progress_base;
1288 bool image_opts = false;
1289 bool force_share = false;
1291 cache = BDRV_DEFAULT_CACHE;
1293 static const struct option long_options[] = {
1294 {"help", no_argument, 0, 'h'},
1295 {"object", required_argument, 0, OPTION_OBJECT},
1296 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1297 {"force-share", no_argument, 0, 'U'},
1300 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1301 long_options, NULL);
1307 missing_argument(argv[optind - 1]);
1310 unrecognized_option(argv[optind - 1]);
1336 case OPTION_OBJECT: {
1338 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1345 case OPTION_IMAGE_OPTS:
1351 /* Progress is not shown in Quiet mode */
1357 if (optind != argc - 2) {
1358 error_exit("Expecting two image file names");
1360 filename1 = argv[optind++];
1361 filename2 = argv[optind++];
1363 if (qemu_opts_foreach(&qemu_object_opts,
1364 user_creatable_add_opts_foreach,
1370 /* Initialize before goto out */
1371 qemu_progress_init(progress, 2.0);
1374 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1376 error_report("Invalid source cache option: %s", cache);
1381 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1388 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1397 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1398 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1399 total_size1 = blk_getlength(blk1);
1400 if (total_size1 < 0) {
1401 error_report("Can't get size of %s: %s",
1402 filename1, strerror(-total_size1));
1406 total_size2 = blk_getlength(blk2);
1407 if (total_size2 < 0) {
1408 error_report("Can't get size of %s: %s",
1409 filename2, strerror(-total_size2));
1413 total_size = MIN(total_size1, total_size2);
1414 progress_base = MAX(total_size1, total_size2);
1416 qemu_progress_print(0, 100);
1418 if (strict && total_size1 != total_size2) {
1420 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1424 while (offset < total_size) {
1425 int status1, status2;
1427 status1 = bdrv_block_status_above(bs1, NULL, offset,
1428 total_size1 - offset, &pnum1, NULL,
1432 error_report("Sector allocation test failed for %s", filename1);
1435 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1437 status2 = bdrv_block_status_above(bs2, NULL, offset,
1438 total_size2 - offset, &pnum2, NULL,
1442 error_report("Sector allocation test failed for %s", filename2);
1445 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1447 assert(pnum1 && pnum2);
1448 chunk = MIN(pnum1, pnum2);
1451 if (status1 != status2) {
1453 qprintf(quiet, "Strict mode: Offset %" PRId64
1454 " block status mismatch!\n", offset);
1458 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1460 } else if (allocated1 == allocated2) {
1464 chunk = MIN(chunk, IO_BUF_SIZE);
1465 ret = blk_pread(blk1, offset, buf1, chunk);
1467 error_report("Error while reading offset %" PRId64
1469 offset, filename1, strerror(-ret));
1473 ret = blk_pread(blk2, offset, buf2, chunk);
1475 error_report("Error while reading offset %" PRId64
1477 offset, filename2, strerror(-ret));
1481 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1482 if (ret || pnum != chunk) {
1483 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1484 offset + (ret ? 0 : pnum));
1490 chunk = MIN(chunk, IO_BUF_SIZE);
1492 ret = check_empty_sectors(blk1, offset, chunk,
1493 filename1, buf1, quiet);
1495 ret = check_empty_sectors(blk2, offset, chunk,
1496 filename2, buf1, quiet);
1503 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1506 if (total_size1 != total_size2) {
1507 BlockBackend *blk_over;
1508 const char *filename_over;
1510 qprintf(quiet, "Warning: Image size mismatch!\n");
1511 if (total_size1 > total_size2) {
1513 filename_over = filename1;
1516 filename_over = filename2;
1519 while (offset < progress_base) {
1520 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1521 progress_base - offset, &chunk,
1525 error_report("Sector allocation test failed for %s",
1530 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1531 chunk = MIN(chunk, IO_BUF_SIZE);
1532 ret = check_empty_sectors(blk_over, offset, chunk,
1533 filename_over, buf1, quiet);
1539 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1543 qprintf(quiet, "Images are identical.\n");
1553 qemu_progress_end();
1558 enum ImgConvertBlockStatus {
1564 #define MAX_COROUTINES 16
1566 typedef struct ImgConvertState {
1568 int64_t *src_sectors;
1570 int64_t total_sectors;
1571 int64_t allocated_sectors;
1572 int64_t allocated_done;
1575 enum ImgConvertBlockStatus status;
1576 int64_t sector_next_status;
1577 BlockBackend *target;
1580 bool unallocated_blocks_are_zero;
1581 bool target_has_backing;
1582 int64_t target_backing_sectors; /* negative if unknown */
1587 size_t cluster_sectors;
1589 long num_coroutines;
1590 int running_coroutines;
1591 Coroutine *co[MAX_COROUTINES];
1592 int64_t wait_sector_num[MAX_COROUTINES];
1597 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1598 int *src_cur, int64_t *src_cur_offset)
1601 *src_cur_offset = 0;
1602 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1603 *src_cur_offset += s->src_sectors[*src_cur];
1605 assert(*src_cur < s->src_num);
1609 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1611 int64_t src_cur_offset;
1612 int ret, n, src_cur;
1613 bool post_backing_zero = false;
1615 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1617 assert(s->total_sectors > sector_num);
1618 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1620 if (s->target_backing_sectors >= 0) {
1621 if (sector_num >= s->target_backing_sectors) {
1622 post_backing_zero = s->unallocated_blocks_are_zero;
1623 } else if (sector_num + n > s->target_backing_sectors) {
1624 /* Split requests around target_backing_sectors (because
1625 * starting from there, zeros are handled differently) */
1626 n = s->target_backing_sectors - sector_num;
1630 if (s->sector_next_status <= sector_num) {
1631 int64_t count = n * BDRV_SECTOR_SIZE;
1633 if (s->target_has_backing) {
1635 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1636 (sector_num - src_cur_offset) *
1638 count, &count, NULL, NULL);
1640 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1641 (sector_num - src_cur_offset) *
1643 count, &count, NULL, NULL);
1648 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1650 if (ret & BDRV_BLOCK_ZERO) {
1651 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
1652 } else if (ret & BDRV_BLOCK_DATA) {
1653 s->status = BLK_DATA;
1655 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1658 s->sector_next_status = sector_num + n;
1661 n = MIN(n, s->sector_next_status - sector_num);
1662 if (s->status == BLK_DATA) {
1663 n = MIN(n, s->buf_sectors);
1666 /* We need to write complete clusters for compressed images, so if an
1667 * unallocated area is shorter than that, we must consider the whole
1668 * cluster allocated. */
1669 if (s->compressed) {
1670 if (n < s->cluster_sectors) {
1671 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1672 s->status = BLK_DATA;
1674 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1681 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1682 int nb_sectors, uint8_t *buf)
1688 assert(nb_sectors <= s->buf_sectors);
1689 while (nb_sectors > 0) {
1692 int64_t bs_sectors, src_cur_offset;
1694 /* In the case of compression with multiple source files, we can get a
1695 * nb_sectors that spreads into the next part. So we must be able to
1696 * read across multiple BDSes for one convert_read() call. */
1697 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1698 blk = s->src[src_cur];
1699 bs_sectors = s->src_sectors[src_cur];
1701 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1703 iov.iov_len = n << BDRV_SECTOR_BITS;
1704 qemu_iovec_init_external(&qiov, &iov, 1);
1706 ret = blk_co_preadv(
1707 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1708 n << BDRV_SECTOR_BITS, &qiov, 0);
1715 buf += n * BDRV_SECTOR_SIZE;
1722 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1723 int nb_sectors, uint8_t *buf,
1724 enum ImgConvertBlockStatus status)
1730 while (nb_sectors > 0) {
1732 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1735 case BLK_BACKING_FILE:
1736 /* If we have a backing file, leave clusters unallocated that are
1737 * unallocated in the source image, so that the backing file is
1738 * visible at the respective offset. */
1739 assert(s->target_has_backing);
1743 /* If we're told to keep the target fully allocated (-S 0) or there
1744 * is real non-zero data, we must write it. Otherwise we can treat
1745 * it as zero sectors.
1746 * Compressed clusters need to be written as a whole, so in that
1747 * case we can only save the write if the buffer is completely
1749 if (!s->min_sparse ||
1751 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1752 sector_num, s->alignment)) ||
1754 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1757 iov.iov_len = n << BDRV_SECTOR_BITS;
1758 qemu_iovec_init_external(&qiov, &iov, 1);
1760 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
1761 n << BDRV_SECTOR_BITS, &qiov, flags);
1770 if (s->has_zero_init) {
1771 assert(!s->target_has_backing);
1774 ret = blk_co_pwrite_zeroes(s->target,
1775 sector_num << BDRV_SECTOR_BITS,
1776 n << BDRV_SECTOR_BITS, 0);
1785 buf += n * BDRV_SECTOR_SIZE;
1791 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1796 while (nb_sectors > 0) {
1799 int64_t bs_sectors, src_cur_offset;
1802 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1803 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1804 blk = s->src[src_cur];
1805 bs_sectors = s->src_sectors[src_cur];
1807 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1809 ret = blk_co_copy_range(blk, offset, s->target,
1810 sector_num << BDRV_SECTOR_BITS,
1811 n << BDRV_SECTOR_BITS, 0, 0);
1822 static void coroutine_fn convert_co_do_copy(void *opaque)
1824 ImgConvertState *s = opaque;
1825 uint8_t *buf = NULL;
1829 for (i = 0; i < s->num_coroutines; i++) {
1830 if (s->co[i] == qemu_coroutine_self()) {
1837 s->running_coroutines++;
1838 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1843 enum ImgConvertBlockStatus status;
1846 qemu_co_mutex_lock(&s->lock);
1847 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1848 qemu_co_mutex_unlock(&s->lock);
1851 n = convert_iteration_sectors(s, s->sector_num);
1853 qemu_co_mutex_unlock(&s->lock);
1857 /* save current sector and allocation status to local variables */
1858 sector_num = s->sector_num;
1860 if (!s->min_sparse && s->status == BLK_ZERO) {
1861 n = MIN(n, s->buf_sectors);
1863 /* increment global sector counter so that other coroutines can
1864 * already continue reading beyond this request */
1866 qemu_co_mutex_unlock(&s->lock);
1868 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1869 s->allocated_done += n;
1870 qemu_progress_print(100.0 * s->allocated_done /
1871 s->allocated_sectors, 0);
1875 copy_range = s->copy_range && s->status == BLK_DATA;
1876 if (status == BLK_DATA && !copy_range) {
1877 ret = convert_co_read(s, sector_num, n, buf);
1879 error_report("error while reading sector %" PRId64
1880 ": %s", sector_num, strerror(-ret));
1883 } else if (!s->min_sparse && status == BLK_ZERO) {
1885 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1888 if (s->wr_in_order) {
1889 /* keep writes in order */
1890 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
1891 s->wait_sector_num[index] = sector_num;
1892 qemu_coroutine_yield();
1894 s->wait_sector_num[index] = -1;
1897 if (s->ret == -EINPROGRESS) {
1899 ret = convert_co_copy_range(s, sector_num, n);
1901 s->copy_range = false;
1905 ret = convert_co_write(s, sector_num, n, buf, status);
1908 error_report("error while writing sector %" PRId64
1909 ": %s", sector_num, strerror(-ret));
1914 if (s->wr_in_order) {
1915 /* reenter the coroutine that might have waited
1916 * for this write to complete */
1917 s->wr_offs = sector_num + n;
1918 for (i = 0; i < s->num_coroutines; i++) {
1919 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1921 * A -> B -> A cannot occur because A has
1922 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1923 * B will never enter A during this time window.
1925 qemu_coroutine_enter(s->co[i]);
1933 s->co[index] = NULL;
1934 s->running_coroutines--;
1935 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1936 /* the convert job finished successfully */
1941 static int convert_do_copy(ImgConvertState *s)
1944 int64_t sector_num = 0;
1946 /* Check whether we have zero initialisation or can get it efficiently */
1947 s->has_zero_init = s->min_sparse && !s->target_has_backing
1948 ? bdrv_has_zero_init(blk_bs(s->target))
1951 if (!s->has_zero_init && !s->target_has_backing &&
1952 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1954 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
1956 s->has_zero_init = true;
1960 /* Allocate buffer for copied data. For compressed images, only one cluster
1961 * can be copied at a time. */
1962 if (s->compressed) {
1963 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1964 error_report("invalid cluster size");
1967 s->buf_sectors = s->cluster_sectors;
1970 while (sector_num < s->total_sectors) {
1971 n = convert_iteration_sectors(s, sector_num);
1975 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1977 s->allocated_sectors += n;
1983 s->sector_next_status = 0;
1984 s->ret = -EINPROGRESS;
1986 qemu_co_mutex_init(&s->lock);
1987 for (i = 0; i < s->num_coroutines; i++) {
1988 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1989 s->wait_sector_num[i] = -1;
1990 qemu_coroutine_enter(s->co[i]);
1993 while (s->running_coroutines) {
1994 main_loop_wait(false);
1997 if (s->compressed && !s->ret) {
1998 /* signal EOF to align */
1999 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
2008 static int img_convert(int argc, char **argv)
2010 int c, bs_i, flags, src_flags = 0;
2011 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
2012 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2013 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
2014 BlockDriver *drv = NULL, *proto_drv = NULL;
2015 BlockDriverInfo bdi;
2016 BlockDriverState *out_bs;
2017 QemuOpts *opts = NULL, *sn_opts = NULL;
2018 QemuOptsList *create_opts = NULL;
2019 char *options = NULL;
2020 Error *local_err = NULL;
2021 bool writethrough, src_writethrough, quiet = false, image_opts = false,
2022 skip_create = false, progress = false, tgt_image_opts = false;
2023 int64_t ret = -EINVAL;
2024 bool force_share = false;
2026 ImgConvertState s = (ImgConvertState) {
2027 /* Need at least 4k of zeros for sparse detection */
2030 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2031 .wr_in_order = true,
2032 .num_coroutines = 8,
2036 static const struct option long_options[] = {
2037 {"help", no_argument, 0, 'h'},
2038 {"object", required_argument, 0, OPTION_OBJECT},
2039 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2040 {"force-share", no_argument, 0, 'U'},
2041 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
2044 c = getopt_long(argc, argv, ":hf:O:B:co:l:S:pt:T:qnm:WU",
2045 long_options, NULL);
2051 missing_argument(argv[optind - 1]);
2054 unrecognized_option(argv[optind - 1]);
2066 out_baseimg = optarg;
2069 s.compressed = true;
2070 s.copy_range = false;
2073 if (!is_valid_option_list(optarg)) {
2074 error_report("Invalid option list: %s", optarg);
2078 options = g_strdup(optarg);
2080 char *old_options = options;
2081 options = g_strdup_printf("%s,%s", options, optarg);
2082 g_free(old_options);
2086 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2087 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2090 error_report("Failed in parsing snapshot param '%s'",
2095 snapshot_name = optarg;
2102 sval = cvtnum(optarg);
2104 error_report("Invalid minimum zero buffer size for sparse output specified");
2108 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2109 s.copy_range = false;
2128 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2129 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2130 error_report("Invalid number of coroutines. Allowed number of"
2131 " coroutines is between 1 and %d", MAX_COROUTINES);
2136 s.wr_in_order = false;
2141 case OPTION_OBJECT: {
2142 QemuOpts *object_opts;
2143 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2150 case OPTION_IMAGE_OPTS:
2153 case OPTION_TARGET_IMAGE_OPTS:
2154 tgt_image_opts = true;
2159 if (!out_fmt && !tgt_image_opts) {
2163 if (qemu_opts_foreach(&qemu_object_opts,
2164 user_creatable_add_opts_foreach,
2169 if (tgt_image_opts && !skip_create) {
2170 error_report("--target-image-opts requires use of -n flag");
2174 s.src_num = argc - optind - 1;
2175 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2177 if (options && has_help_option(options)) {
2179 ret = print_block_option_help(out_filename, out_fmt);
2182 error_report("Option help requires a format be specified");
2187 if (s.src_num < 1) {
2188 error_report("Must specify image file name");
2193 /* ret is still -EINVAL until here */
2194 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2196 error_report("Invalid source cache option: %s", src_cache);
2200 /* Initialize before goto out */
2204 qemu_progress_init(progress, 1.0);
2205 qemu_progress_print(0, 100);
2207 s.src = g_new0(BlockBackend *, s.src_num);
2208 s.src_sectors = g_new(int64_t, s.src_num);
2210 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2211 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2212 fmt, src_flags, src_writethrough, quiet,
2218 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2219 if (s.src_sectors[bs_i] < 0) {
2220 error_report("Could not get size of %s: %s",
2221 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2225 s.total_sectors += s.src_sectors[bs_i];
2229 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2230 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2231 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2233 } else if (snapshot_name != NULL) {
2234 if (s.src_num > 1) {
2235 error_report("No support for concatenating multiple snapshot");
2240 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2244 error_reportf_err(local_err, "Failed to load snapshot: ");
2250 /* Find driver and parse its options */
2251 drv = bdrv_find_format(out_fmt);
2253 error_report("Unknown file format '%s'", out_fmt);
2258 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2260 error_report_err(local_err);
2265 if (!drv->create_opts) {
2266 error_report("Format driver '%s' does not support image creation",
2272 if (!proto_drv->create_opts) {
2273 error_report("Protocol driver '%s' does not support image creation",
2274 proto_drv->format_name);
2279 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2280 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2282 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2284 qemu_opts_do_parse(opts, options, NULL, &local_err);
2286 error_report_err(local_err);
2292 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2294 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2300 /* Get backing file name if -o backing_file was used */
2301 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2302 if (out_baseimg_param) {
2303 out_baseimg = out_baseimg_param;
2305 s.target_has_backing = (bool) out_baseimg;
2307 if (s.src_num > 1 && out_baseimg) {
2308 error_report("Having a backing file for the target makes no sense when "
2309 "concatenating multiple input images");
2314 /* Check if compression is supported */
2317 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2318 const char *encryptfmt =
2319 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2320 const char *preallocation =
2321 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2323 if (drv && !drv->bdrv_co_pwritev_compressed) {
2324 error_report("Compression not supported for this file format");
2329 if (encryption || encryptfmt) {
2330 error_report("Compression and encryption not supported at "
2337 && strcmp(preallocation, "off"))
2339 error_report("Compression and preallocation not supported at "
2347 /* Create the new image */
2348 ret = bdrv_create(drv, out_filename, opts, &local_err);
2350 error_reportf_err(local_err, "%s: error while converting %s: ",
2351 out_filename, out_fmt);
2356 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2357 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2359 error_report("Invalid cache option: %s", cache);
2364 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2365 flags, writethrough, quiet, false);
2367 /* TODO ultimately we should allow --target-image-opts
2368 * to be used even when -n is not given.
2369 * That has to wait for bdrv_create to be improved
2370 * to allow filenames in option syntax
2372 s.target = img_open_new_file(out_filename, opts, out_fmt,
2373 flags, writethrough, quiet, false);
2379 out_bs = blk_bs(s.target);
2381 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2382 error_report("Compression not supported for this file format");
2387 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2388 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2390 s.buf_sectors = MIN(32768,
2392 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2393 out_bs->bl.pdiscard_alignment >>
2394 BDRV_SECTOR_BITS)));
2396 /* try to align the write requests to the destination to avoid unnecessary
2398 s.alignment = MAX(pow2floor(s.min_sparse),
2399 DIV_ROUND_UP(out_bs->bl.request_alignment,
2401 assert(is_power_of_2(s.alignment));
2404 int64_t output_sectors = blk_nb_sectors(s.target);
2405 if (output_sectors < 0) {
2406 error_report("unable to get output image length: %s",
2407 strerror(-output_sectors));
2410 } else if (output_sectors < s.total_sectors) {
2411 error_report("output file is smaller than input file");
2417 if (s.target_has_backing) {
2418 /* Errors are treated as "backing length unknown" (which means
2419 * s.target_backing_sectors has to be negative, which it will
2420 * be automatically). The backing file length is used only
2421 * for optimizations, so such a case is not fatal. */
2422 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2424 s.target_backing_sectors = -1;
2427 ret = bdrv_get_info(out_bs, &bdi);
2430 error_report("could not get block driver info");
2434 s.compressed = s.compressed || bdi.needs_compressed_writes;
2435 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2436 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
2439 ret = convert_do_copy(&s);
2442 qemu_progress_print(100, 0);
2444 qemu_progress_end();
2445 qemu_opts_del(opts);
2446 qemu_opts_free(create_opts);
2447 qemu_opts_del(sn_opts);
2448 blk_unref(s.target);
2450 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2451 blk_unref(s.src[bs_i]);
2455 g_free(s.src_sectors);
2463 static void dump_snapshots(BlockDriverState *bs)
2465 QEMUSnapshotInfo *sn_tab, *sn;
2468 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2471 printf("Snapshot list:\n");
2472 bdrv_snapshot_dump(fprintf, stdout, NULL);
2474 for(i = 0; i < nb_sns; i++) {
2476 bdrv_snapshot_dump(fprintf, stdout, sn);
2482 static void dump_json_image_info_list(ImageInfoList *list)
2486 Visitor *v = qobject_output_visitor_new(&obj);
2488 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2489 visit_complete(v, &obj);
2490 str = qobject_to_json_pretty(obj);
2491 assert(str != NULL);
2492 printf("%s\n", qstring_get_str(str));
2498 static void dump_json_image_info(ImageInfo *info)
2502 Visitor *v = qobject_output_visitor_new(&obj);
2504 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2505 visit_complete(v, &obj);
2506 str = qobject_to_json_pretty(obj);
2507 assert(str != NULL);
2508 printf("%s\n", qstring_get_str(str));
2514 static void dump_human_image_info_list(ImageInfoList *list)
2516 ImageInfoList *elem;
2519 for (elem = list; elem; elem = elem->next) {
2525 bdrv_image_info_dump(fprintf, stdout, elem->value);
2529 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2531 return strcmp(a, b) == 0;
2535 * Open an image file chain and return an ImageInfoList
2537 * @filename: topmost image filename
2538 * @fmt: topmost image format (may be NULL to autodetect)
2539 * @chain: true - enumerate entire backing file chain
2540 * false - only topmost image file
2542 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2543 * image file. If there was an error a message will have been printed to
2546 static ImageInfoList *collect_image_info_list(bool image_opts,
2547 const char *filename,
2549 bool chain, bool force_share)
2551 ImageInfoList *head = NULL;
2552 ImageInfoList **last = &head;
2553 GHashTable *filenames;
2556 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2560 BlockDriverState *bs;
2562 ImageInfoList *elem;
2564 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2565 error_report("Backing file '%s' creates an infinite loop.",
2569 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2571 blk = img_open(image_opts, filename, fmt,
2572 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2579 bdrv_query_image_info(bs, &info, &err);
2581 error_report_err(err);
2586 elem = g_new0(ImageInfoList, 1);
2593 filename = fmt = NULL;
2595 if (info->has_full_backing_filename) {
2596 filename = info->full_backing_filename;
2597 } else if (info->has_backing_filename) {
2598 error_report("Could not determine absolute backing filename,"
2599 " but backing filename '%s' present",
2600 info->backing_filename);
2603 if (info->has_backing_filename_format) {
2604 fmt = info->backing_filename_format;
2608 g_hash_table_destroy(filenames);
2612 qapi_free_ImageInfoList(head);
2613 g_hash_table_destroy(filenames);
2617 static int img_info(int argc, char **argv)
2620 OutputFormat output_format = OFORMAT_HUMAN;
2622 const char *filename, *fmt, *output;
2623 ImageInfoList *list;
2624 bool image_opts = false;
2625 bool force_share = false;
2630 int option_index = 0;
2631 static const struct option long_options[] = {
2632 {"help", no_argument, 0, 'h'},
2633 {"format", required_argument, 0, 'f'},
2634 {"output", required_argument, 0, OPTION_OUTPUT},
2635 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2636 {"object", required_argument, 0, OPTION_OBJECT},
2637 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2638 {"force-share", no_argument, 0, 'U'},
2641 c = getopt_long(argc, argv, ":f:hU",
2642 long_options, &option_index);
2648 missing_argument(argv[optind - 1]);
2651 unrecognized_option(argv[optind - 1]);
2665 case OPTION_BACKING_CHAIN:
2668 case OPTION_OBJECT: {
2670 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2676 case OPTION_IMAGE_OPTS:
2681 if (optind != argc - 1) {
2682 error_exit("Expecting one image file name");
2684 filename = argv[optind++];
2686 if (output && !strcmp(output, "json")) {
2687 output_format = OFORMAT_JSON;
2688 } else if (output && !strcmp(output, "human")) {
2689 output_format = OFORMAT_HUMAN;
2690 } else if (output) {
2691 error_report("--output must be used with human or json as argument.");
2695 if (qemu_opts_foreach(&qemu_object_opts,
2696 user_creatable_add_opts_foreach,
2701 list = collect_image_info_list(image_opts, filename, fmt, chain,
2707 switch (output_format) {
2709 dump_human_image_info_list(list);
2713 dump_json_image_info_list(list);
2715 dump_json_image_info(list->value);
2720 qapi_free_ImageInfoList(list);
2724 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2727 switch (output_format) {
2729 if (e->data && !e->has_offset) {
2730 error_report("File contains external, encrypted or compressed clusters.");
2733 if (e->data && !e->zero) {
2734 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2735 e->start, e->length,
2736 e->has_offset ? e->offset : 0,
2737 e->has_filename ? e->filename : "");
2739 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2740 * Modify the flags here to allow more coalescing.
2742 if (next && (!next->data || next->zero)) {
2748 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2749 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2750 (e->start == 0 ? "[" : ",\n"),
2751 e->start, e->length, e->depth,
2752 e->zero ? "true" : "false",
2753 e->data ? "true" : "false");
2754 if (e->has_offset) {
2755 printf(", \"offset\": %"PRId64"", e->offset);
2766 static int get_block_status(BlockDriverState *bs, int64_t offset,
2767 int64_t bytes, MapEntry *e)
2771 BlockDriverState *file;
2775 /* As an optimization, we could cache the current range of unallocated
2776 * clusters in each file of the chain, and avoid querying the same
2782 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
2787 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2790 bs = backing_bs(bs);
2799 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2804 .data = !!(ret & BDRV_BLOCK_DATA),
2805 .zero = !!(ret & BDRV_BLOCK_ZERO),
2807 .has_offset = has_offset,
2809 .has_filename = file && has_offset,
2810 .filename = file && has_offset ? file->filename : NULL,
2816 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2818 if (curr->length == 0) {
2821 if (curr->zero != next->zero ||
2822 curr->data != next->data ||
2823 curr->depth != next->depth ||
2824 curr->has_filename != next->has_filename ||
2825 curr->has_offset != next->has_offset) {
2828 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2831 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2837 static int img_map(int argc, char **argv)
2840 OutputFormat output_format = OFORMAT_HUMAN;
2842 BlockDriverState *bs;
2843 const char *filename, *fmt, *output;
2845 MapEntry curr = { .length = 0 }, next;
2847 bool image_opts = false;
2848 bool force_share = false;
2853 int option_index = 0;
2854 static const struct option long_options[] = {
2855 {"help", no_argument, 0, 'h'},
2856 {"format", required_argument, 0, 'f'},
2857 {"output", required_argument, 0, OPTION_OUTPUT},
2858 {"object", required_argument, 0, OPTION_OBJECT},
2859 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2860 {"force-share", no_argument, 0, 'U'},
2863 c = getopt_long(argc, argv, ":f:hU",
2864 long_options, &option_index);
2870 missing_argument(argv[optind - 1]);
2873 unrecognized_option(argv[optind - 1]);
2887 case OPTION_OBJECT: {
2889 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2895 case OPTION_IMAGE_OPTS:
2900 if (optind != argc - 1) {
2901 error_exit("Expecting one image file name");
2903 filename = argv[optind];
2905 if (output && !strcmp(output, "json")) {
2906 output_format = OFORMAT_JSON;
2907 } else if (output && !strcmp(output, "human")) {
2908 output_format = OFORMAT_HUMAN;
2909 } else if (output) {
2910 error_report("--output must be used with human or json as argument.");
2914 if (qemu_opts_foreach(&qemu_object_opts,
2915 user_creatable_add_opts_foreach,
2920 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
2926 if (output_format == OFORMAT_HUMAN) {
2927 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2930 length = blk_getlength(blk);
2931 while (curr.start + curr.length < length) {
2932 int64_t offset = curr.start + curr.length;
2935 /* Probe up to 1 GiB at a time. */
2936 n = MIN(1 << 30, length - offset);
2937 ret = get_block_status(bs, offset, n, &next);
2940 error_report("Could not read file metadata: %s", strerror(-ret));
2944 if (entry_mergeable(&curr, &next)) {
2945 curr.length += next.length;
2949 if (curr.length > 0) {
2950 dump_map_entry(output_format, &curr, &next);
2955 dump_map_entry(output_format, &curr, NULL);
2962 #define SNAPSHOT_LIST 1
2963 #define SNAPSHOT_CREATE 2
2964 #define SNAPSHOT_APPLY 3
2965 #define SNAPSHOT_DELETE 4
2967 static int img_snapshot(int argc, char **argv)
2970 BlockDriverState *bs;
2971 QEMUSnapshotInfo sn;
2972 char *filename, *snapshot_name = NULL;
2973 int c, ret = 0, bdrv_oflags;
2978 bool image_opts = false;
2979 bool force_share = false;
2981 bdrv_oflags = BDRV_O_RDWR;
2982 /* Parse commandline parameters */
2984 static const struct option long_options[] = {
2985 {"help", no_argument, 0, 'h'},
2986 {"object", required_argument, 0, OPTION_OBJECT},
2987 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2988 {"force-share", no_argument, 0, 'U'},
2991 c = getopt_long(argc, argv, ":la:c:d:hqU",
2992 long_options, NULL);
2998 missing_argument(argv[optind - 1]);
3001 unrecognized_option(argv[optind - 1]);
3008 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3011 action = SNAPSHOT_LIST;
3012 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
3016 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3019 action = SNAPSHOT_APPLY;
3020 snapshot_name = optarg;
3024 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3027 action = SNAPSHOT_CREATE;
3028 snapshot_name = optarg;
3032 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3035 action = SNAPSHOT_DELETE;
3036 snapshot_name = optarg;
3044 case OPTION_OBJECT: {
3046 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3052 case OPTION_IMAGE_OPTS:
3058 if (optind != argc - 1) {
3059 error_exit("Expecting one image file name");
3061 filename = argv[optind++];
3063 if (qemu_opts_foreach(&qemu_object_opts,
3064 user_creatable_add_opts_foreach,
3069 /* Open the image */
3070 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3077 /* Perform the requested action */
3083 case SNAPSHOT_CREATE:
3084 memset(&sn, 0, sizeof(sn));
3085 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3087 qemu_gettimeofday(&tv);
3088 sn.date_sec = tv.tv_sec;
3089 sn.date_nsec = tv.tv_usec * 1000;
3091 ret = bdrv_snapshot_create(bs, &sn);
3093 error_report("Could not create snapshot '%s': %d (%s)",
3094 snapshot_name, ret, strerror(-ret));
3098 case SNAPSHOT_APPLY:
3099 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3101 error_reportf_err(err, "Could not apply snapshot '%s': ",
3106 case SNAPSHOT_DELETE:
3107 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
3109 error_reportf_err(err, "Could not delete snapshot '%s': ",
3124 static int img_rebase(int argc, char **argv)
3126 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3127 uint8_t *buf_old = NULL;
3128 uint8_t *buf_new = NULL;
3129 BlockDriverState *bs = NULL;
3131 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3132 int c, flags, src_flags, ret;
3133 bool writethrough, src_writethrough;
3135 bool force_share = false;
3138 Error *local_err = NULL;
3139 bool image_opts = false;
3141 /* Parse commandline parameters */
3143 cache = BDRV_DEFAULT_CACHE;
3144 src_cache = BDRV_DEFAULT_CACHE;
3148 static const struct option long_options[] = {
3149 {"help", no_argument, 0, 'h'},
3150 {"object", required_argument, 0, OPTION_OBJECT},
3151 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3152 {"force-share", no_argument, 0, 'U'},
3155 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3156 long_options, NULL);
3162 missing_argument(argv[optind - 1]);
3165 unrecognized_option(argv[optind - 1]);
3174 out_basefmt = optarg;
3177 out_baseimg = optarg;
3194 case OPTION_OBJECT: {
3196 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3202 case OPTION_IMAGE_OPTS:
3215 if (optind != argc - 1) {
3216 error_exit("Expecting one image file name");
3218 if (!unsafe && !out_baseimg) {
3219 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3221 filename = argv[optind++];
3223 if (qemu_opts_foreach(&qemu_object_opts,
3224 user_creatable_add_opts_foreach,
3229 qemu_progress_init(progress, 2.0);
3230 qemu_progress_print(0, 100);
3232 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3233 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3235 error_report("Invalid cache option: %s", cache);
3240 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3242 error_report("Invalid source cache option: %s", src_cache);
3246 /* The source files are opened read-only, don't care about WCE */
3247 assert((src_flags & BDRV_O_RDWR) == 0);
3248 (void) src_writethrough;
3253 * Ignore the old backing file for unsafe rebase in case we want to correct
3254 * the reference to a renamed or moved backing file.
3256 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3264 if (out_basefmt != NULL) {
3265 if (bdrv_find_format(out_basefmt) == NULL) {
3266 error_report("Invalid format name: '%s'", out_basefmt);
3272 /* For safe rebasing we need to compare old and new backing file */
3274 char backing_name[PATH_MAX];
3275 QDict *options = NULL;
3277 if (bs->backing_format[0] != '\0') {
3278 options = qdict_new();
3279 qdict_put_str(options, "driver", bs->backing_format);
3284 options = qdict_new();
3286 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3288 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3289 blk_old_backing = blk_new_open(backing_name, NULL,
3290 options, src_flags, &local_err);
3291 if (!blk_old_backing) {
3292 error_reportf_err(local_err,
3293 "Could not open old backing file '%s': ",
3299 if (out_baseimg[0]) {
3300 const char *overlay_filename;
3301 char *out_real_path;
3303 options = qdict_new();
3305 qdict_put_str(options, "driver", out_basefmt);
3308 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3311 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3313 out_real_path = g_malloc(PATH_MAX);
3315 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3321 error_reportf_err(local_err,
3322 "Could not resolve backing filename: ");
3324 g_free(out_real_path);
3328 blk_new_backing = blk_new_open(out_real_path, NULL,
3329 options, src_flags, &local_err);
3330 g_free(out_real_path);
3331 if (!blk_new_backing) {
3332 error_reportf_err(local_err,
3333 "Could not open new backing file '%s': ",
3342 * Check each unallocated cluster in the COW file. If it is unallocated,
3343 * accesses go to the backing file. We must therefore compare this cluster
3344 * in the old and new backing file, and if they differ we need to copy it
3345 * from the old backing file into the COW file.
3347 * If qemu-img crashes during this step, no harm is done. The content of
3348 * the image is the same as the original one at any time.
3352 int64_t old_backing_size;
3353 int64_t new_backing_size = 0;
3356 float local_progress = 0;
3358 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3359 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3361 size = blk_getlength(blk);
3363 error_report("Could not get size of '%s': %s",
3364 filename, strerror(-size));
3368 old_backing_size = blk_getlength(blk_old_backing);
3369 if (old_backing_size < 0) {
3370 char backing_name[PATH_MAX];
3372 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3373 error_report("Could not get size of '%s': %s",
3374 backing_name, strerror(-old_backing_size));
3378 if (blk_new_backing) {
3379 new_backing_size = blk_getlength(blk_new_backing);
3380 if (new_backing_size < 0) {
3381 error_report("Could not get size of '%s': %s",
3382 out_baseimg, strerror(-new_backing_size));
3389 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3392 for (offset = 0; offset < size; offset += n) {
3393 /* How many bytes can we handle with the next read? */
3394 n = MIN(IO_BUF_SIZE, size - offset);
3396 /* If the cluster is allocated, we don't need to take action */
3397 ret = bdrv_is_allocated(bs, offset, n, &n);
3399 error_report("error while reading image metadata: %s",
3408 * Read old and new backing file and take into consideration that
3409 * backing files may be smaller than the COW image.
3411 if (offset >= old_backing_size) {
3412 memset(buf_old, 0, n);
3414 if (offset + n > old_backing_size) {
3415 n = old_backing_size - offset;
3418 ret = blk_pread(blk_old_backing, offset, buf_old, n);
3420 error_report("error while reading from old backing file");
3425 if (offset >= new_backing_size || !blk_new_backing) {
3426 memset(buf_new, 0, n);
3428 if (offset + n > new_backing_size) {
3429 n = new_backing_size - offset;
3432 ret = blk_pread(blk_new_backing, offset, buf_new, n);
3434 error_report("error while reading from new backing file");
3439 /* If they differ, we need to write to the COW file */
3440 uint64_t written = 0;
3442 while (written < n) {
3445 if (compare_buffers(buf_old + written, buf_new + written,
3446 n - written, &pnum))
3448 ret = blk_pwrite(blk, offset + written,
3449 buf_old + written, pnum, 0);
3451 error_report("Error while writing to COW image: %s",
3459 qemu_progress_print(local_progress, 100);
3464 * Change the backing file. All clusters that are different from the old
3465 * backing file are overwritten in the COW file now, so the visible content
3466 * doesn't change when we switch the backing file.
3468 if (out_baseimg && *out_baseimg) {
3469 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3471 ret = bdrv_change_backing_file(bs, NULL, NULL);
3474 if (ret == -ENOSPC) {
3475 error_report("Could not change the backing file to '%s': No "
3476 "space left in the file header", out_baseimg);
3477 } else if (ret < 0) {
3478 error_report("Could not change the backing file to '%s': %s",
3479 out_baseimg, strerror(-ret));
3482 qemu_progress_print(100, 0);
3484 * TODO At this point it is possible to check if any clusters that are
3485 * allocated in the COW file are the same in the backing file. If so, they
3486 * could be dropped from the COW file. Don't do this before switching the
3487 * backing file, in case of a crash this would lead to corruption.
3490 qemu_progress_end();
3493 blk_unref(blk_old_backing);
3494 blk_unref(blk_new_backing);
3496 qemu_vfree(buf_old);
3497 qemu_vfree(buf_new);
3506 static int img_resize(int argc, char **argv)
3509 int c, ret, relative;
3510 const char *filename, *fmt, *size;
3511 int64_t n, total_size, current_size, new_size;
3513 BlockBackend *blk = NULL;
3514 PreallocMode prealloc = PREALLOC_MODE_OFF;
3517 static QemuOptsList resize_options = {
3518 .name = "resize_options",
3519 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3522 .name = BLOCK_OPT_SIZE,
3523 .type = QEMU_OPT_SIZE,
3524 .help = "Virtual disk size"
3530 bool image_opts = false;
3531 bool shrink = false;
3533 /* Remove size from argv manually so that negative numbers are not treated
3534 * as options by getopt. */
3536 error_exit("Not enough arguments");
3540 size = argv[--argc];
3542 /* Parse getopt arguments */
3545 static const struct option long_options[] = {
3546 {"help", no_argument, 0, 'h'},
3547 {"object", required_argument, 0, OPTION_OBJECT},
3548 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3549 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3550 {"shrink", no_argument, 0, OPTION_SHRINK},
3553 c = getopt_long(argc, argv, ":f:hq",
3554 long_options, NULL);
3560 missing_argument(argv[optind - 1]);
3563 unrecognized_option(argv[optind - 1]);
3574 case OPTION_OBJECT: {
3576 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3582 case OPTION_IMAGE_OPTS:
3585 case OPTION_PREALLOCATION:
3586 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3587 PREALLOC_MODE__MAX, NULL);
3588 if (prealloc == PREALLOC_MODE__MAX) {
3589 error_report("Invalid preallocation mode '%s'", optarg);
3598 if (optind != argc - 1) {
3599 error_exit("Expecting image file name and size");
3601 filename = argv[optind++];
3603 if (qemu_opts_foreach(&qemu_object_opts,
3604 user_creatable_add_opts_foreach,
3609 /* Choose grow, shrink, or absolute resize mode */
3625 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3626 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3628 error_report_err(err);
3630 qemu_opts_del(param);
3633 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3634 qemu_opts_del(param);
3636 blk = img_open(image_opts, filename, fmt,
3637 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3644 current_size = blk_getlength(blk);
3645 if (current_size < 0) {
3646 error_report("Failed to inquire current image length: %s",
3647 strerror(-current_size));
3653 total_size = current_size + n * relative;
3657 if (total_size <= 0) {
3658 error_report("New image size must be positive");
3663 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3664 error_report("Preallocation can only be used for growing images");
3669 if (total_size < current_size && !shrink) {
3670 warn_report("Shrinking an image will delete all data beyond the "
3671 "shrunken image's end. Before performing such an "
3672 "operation, make sure there is no important data there.");
3674 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3676 "Use the --shrink option to perform a shrink operation.");
3680 warn_report("Using the --shrink option will suppress this message. "
3681 "Note that future versions of qemu-img may refuse to "
3682 "shrink images without this option.");
3686 ret = blk_truncate(blk, total_size, prealloc, &err);
3688 error_report_err(err);
3692 new_size = blk_getlength(blk);
3694 error_report("Failed to verify truncated image length: %s",
3695 strerror(-new_size));
3700 /* Some block drivers implement a truncation method, but only so
3701 * the user can cause qemu to refresh the image's size from disk.
3702 * The idea is that the user resizes the image outside of qemu and
3703 * then invokes block_resize to inform qemu about it.
3704 * (This includes iscsi and file-posix for device files.)
3705 * Of course, that is not the behavior someone invoking
3706 * qemu-img resize would find useful, so we catch that behavior
3707 * here and tell the user. */
3708 if (new_size != total_size && new_size == current_size) {
3709 error_report("Image was not resized; resizing may not be supported "
3715 if (new_size != total_size) {
3716 warn_report("Image should have been resized to %" PRIi64
3717 " bytes, but was resized to %" PRIi64 " bytes",
3718 total_size, new_size);
3721 qprintf(quiet, "Image resized.\n");
3731 static void amend_status_cb(BlockDriverState *bs,
3732 int64_t offset, int64_t total_work_size,
3735 qemu_progress_print(100.f * offset / total_work_size, 0);
3738 static int print_amend_option_help(const char *format)
3742 /* Find driver and parse its options */
3743 drv = bdrv_find_format(format);
3745 error_report("Unknown file format '%s'", format);
3749 if (!drv->bdrv_amend_options) {
3750 error_report("Format driver '%s' does not support option amendment",
3755 /* Every driver supporting amendment must have create_opts */
3756 assert(drv->create_opts);
3758 printf("Creation options for '%s':\n", format);
3759 qemu_opts_print_help(drv->create_opts);
3760 printf("\nNote that not all of these options may be amendable.\n");
3764 static int img_amend(int argc, char **argv)
3768 char *options = NULL;
3769 QemuOptsList *create_opts = NULL;
3770 QemuOpts *opts = NULL;
3771 const char *fmt = NULL, *filename, *cache;
3774 bool quiet = false, progress = false;
3775 BlockBackend *blk = NULL;
3776 BlockDriverState *bs = NULL;
3777 bool image_opts = false;
3779 cache = BDRV_DEFAULT_CACHE;
3781 static const struct option long_options[] = {
3782 {"help", no_argument, 0, 'h'},
3783 {"object", required_argument, 0, OPTION_OBJECT},
3784 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3787 c = getopt_long(argc, argv, ":ho:f:t:pq",
3788 long_options, NULL);
3795 missing_argument(argv[optind - 1]);
3798 unrecognized_option(argv[optind - 1]);
3804 if (!is_valid_option_list(optarg)) {
3805 error_report("Invalid option list: %s", optarg);
3807 goto out_no_progress;
3810 options = g_strdup(optarg);
3812 char *old_options = options;
3813 options = g_strdup_printf("%s,%s", options, optarg);
3814 g_free(old_options);
3830 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3834 goto out_no_progress;
3837 case OPTION_IMAGE_OPTS:
3844 error_exit("Must specify options (-o)");
3847 if (qemu_opts_foreach(&qemu_object_opts,
3848 user_creatable_add_opts_foreach,
3851 goto out_no_progress;
3857 qemu_progress_init(progress, 1.0);
3859 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3860 if (fmt && has_help_option(options)) {
3861 /* If a format is explicitly specified (and possibly no filename is
3862 * given), print option help here */
3863 ret = print_amend_option_help(fmt);
3867 if (optind != argc - 1) {
3868 error_report("Expecting one image file name");
3873 flags = BDRV_O_RDWR;
3874 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3876 error_report("Invalid cache option: %s", cache);
3880 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3888 fmt = bs->drv->format_name;
3890 if (has_help_option(options)) {
3891 /* If the format was auto-detected, print option help here */
3892 ret = print_amend_option_help(fmt);
3896 if (!bs->drv->bdrv_amend_options) {
3897 error_report("Format driver '%s' does not support option amendment",
3903 /* Every driver supporting amendment must have create_opts */
3904 assert(bs->drv->create_opts);
3906 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
3907 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3908 qemu_opts_do_parse(opts, options, NULL, &err);
3910 error_report_err(err);
3915 /* In case the driver does not call amend_status_cb() */
3916 qemu_progress_print(0.f, 0);
3917 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
3918 qemu_progress_print(100.f, 0);
3920 error_report_err(err);
3925 qemu_progress_end();
3929 qemu_opts_del(opts);
3930 qemu_opts_free(create_opts);
3939 typedef struct BenchData {
3941 uint64_t image_size;
3948 bool drain_on_flush;
3957 static void bench_undrained_flush_cb(void *opaque, int ret)
3960 error_report("Failed flush request: %s", strerror(-ret));
3965 static void bench_cb(void *opaque, int ret)
3967 BenchData *b = opaque;
3971 error_report("Failed request: %s", strerror(-ret));
3976 /* Just finished a flush with drained queue: Start next requests */
3977 assert(b->in_flight == 0);
3978 b->in_flush = false;
3979 } else if (b->in_flight > 0) {
3980 int remaining = b->n - b->in_flight;
3985 /* Time for flush? Drain queue if requested, then flush */
3986 if (b->flush_interval && remaining % b->flush_interval == 0) {
3987 if (!b->in_flight || !b->drain_on_flush) {
3988 BlockCompletionFunc *cb;
3990 if (b->drain_on_flush) {
3994 cb = bench_undrained_flush_cb;
3997 acb = blk_aio_flush(b->blk, cb, b);
3999 error_report("Failed to issue flush request");
4003 if (b->drain_on_flush) {
4009 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4010 int64_t offset = b->offset;
4011 /* blk_aio_* might look for completed I/Os and kick bench_cb
4012 * again, so make sure this operation is counted by in_flight
4013 * and b->offset is ready for the next submission.
4016 b->offset += b->step;
4017 b->offset %= b->image_size;
4019 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
4021 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
4024 error_report("Failed to issue request");
4030 static int img_bench(int argc, char **argv)
4033 const char *fmt = NULL, *filename;
4035 bool image_opts = false;
4036 bool is_write = false;
4040 size_t bufsize = 4096;
4043 int flush_interval = 0;
4044 bool drain_on_flush = true;
4046 BlockBackend *blk = NULL;
4047 BenchData data = {};
4049 bool writethrough = false;
4050 struct timeval t1, t2;
4052 bool force_share = false;
4056 static const struct option long_options[] = {
4057 {"help", no_argument, 0, 'h'},
4058 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
4059 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4060 {"pattern", required_argument, 0, OPTION_PATTERN},
4061 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
4062 {"force-share", no_argument, 0, 'U'},
4065 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
4072 missing_argument(argv[optind - 1]);
4075 unrecognized_option(argv[optind - 1]);
4084 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4085 error_report("Invalid request count specified");
4095 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4096 error_report("Invalid queue depth specified");
4106 flags |= BDRV_O_NATIVE_AIO;
4110 offset = cvtnum(optarg);
4112 error_report("Invalid offset specified");
4125 sval = cvtnum(optarg);
4126 if (sval < 0 || sval > INT_MAX) {
4127 error_report("Invalid buffer size specified");
4138 sval = cvtnum(optarg);
4139 if (sval < 0 || sval > INT_MAX) {
4140 error_report("Invalid step size specified");
4148 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4150 error_report("Invalid cache mode");
4156 flags |= BDRV_O_RDWR;
4162 case OPTION_PATTERN:
4166 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4167 error_report("Invalid pattern byte specified");
4173 case OPTION_FLUSH_INTERVAL:
4177 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4178 error_report("Invalid flush interval specified");
4181 flush_interval = res;
4184 case OPTION_NO_DRAIN:
4185 drain_on_flush = false;
4187 case OPTION_IMAGE_OPTS:
4193 if (optind != argc - 1) {
4194 error_exit("Expecting one image file name");
4196 filename = argv[argc - 1];
4198 if (!is_write && flush_interval) {
4199 error_report("--flush-interval is only available in write tests");
4203 if (flush_interval && flush_interval < depth) {
4204 error_report("Flush interval can't be smaller than depth");
4209 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4216 image_size = blk_getlength(blk);
4217 if (image_size < 0) {
4222 data = (BenchData) {
4224 .image_size = image_size,
4226 .step = step ?: bufsize,
4231 .flush_interval = flush_interval,
4232 .drain_on_flush = drain_on_flush,
4234 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4235 "(starting at offset %" PRId64 ", step size %d)\n",
4236 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4237 data.offset, data.step);
4238 if (flush_interval) {
4239 printf("Sending flush every %d requests\n", flush_interval);
4242 buf_size = data.nrreq * data.bufsize;
4243 data.buf = blk_blockalign(blk, buf_size);
4244 memset(data.buf, pattern, data.nrreq * data.bufsize);
4246 blk_register_buf(blk, data.buf, buf_size);
4248 data.qiov = g_new(QEMUIOVector, data.nrreq);
4249 for (i = 0; i < data.nrreq; i++) {
4250 qemu_iovec_init(&data.qiov[i], 1);
4251 qemu_iovec_add(&data.qiov[i],
4252 data.buf + i * data.bufsize, data.bufsize);
4255 gettimeofday(&t1, NULL);
4258 while (data.n > 0) {
4259 main_loop_wait(false);
4261 gettimeofday(&t2, NULL);
4263 printf("Run completed in %3.3f seconds.\n",
4264 (t2.tv_sec - t1.tv_sec)
4265 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4269 blk_unregister_buf(blk, data.buf);
4271 qemu_vfree(data.buf);
4292 int bsz; /* Block size */
4300 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4304 static int img_dd_bs(const char *arg,
4305 struct DdIo *in, struct DdIo *out,
4312 if (res <= 0 || res > INT_MAX) {
4313 error_report("invalid number: '%s'", arg);
4316 in->bsz = out->bsz = res;
4321 static int img_dd_count(const char *arg,
4322 struct DdIo *in, struct DdIo *out,
4325 dd->count = cvtnum(arg);
4327 if (dd->count < 0) {
4328 error_report("invalid number: '%s'", arg);
4335 static int img_dd_if(const char *arg,
4336 struct DdIo *in, struct DdIo *out,
4339 in->filename = g_strdup(arg);
4344 static int img_dd_of(const char *arg,
4345 struct DdIo *in, struct DdIo *out,
4348 out->filename = g_strdup(arg);
4353 static int img_dd_skip(const char *arg,
4354 struct DdIo *in, struct DdIo *out,
4357 in->offset = cvtnum(arg);
4359 if (in->offset < 0) {
4360 error_report("invalid number: '%s'", arg);
4367 static int img_dd(int argc, char **argv)
4372 BlockDriver *drv = NULL, *proto_drv = NULL;
4373 BlockBackend *blk1 = NULL, *blk2 = NULL;
4374 QemuOpts *opts = NULL;
4375 QemuOptsList *create_opts = NULL;
4376 Error *local_err = NULL;
4377 bool image_opts = false;
4379 const char *out_fmt = "raw";
4380 const char *fmt = NULL;
4382 int64_t block_count = 0, out_pos, in_pos;
4383 bool force_share = false;
4384 struct DdInfo dd = {
4389 .bsz = 512, /* Block size is by default 512 bytes */
4401 const struct DdOpts options[] = {
4402 { "bs", img_dd_bs, C_BS },
4403 { "count", img_dd_count, C_COUNT },
4404 { "if", img_dd_if, C_IF },
4405 { "of", img_dd_of, C_OF },
4406 { "skip", img_dd_skip, C_SKIP },
4409 const struct option long_options[] = {
4410 { "help", no_argument, 0, 'h'},
4411 { "object", required_argument, 0, OPTION_OBJECT},
4412 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4413 { "force-share", no_argument, 0, 'U'},
4417 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4429 missing_argument(argv[optind - 1]);
4432 unrecognized_option(argv[optind - 1]);
4441 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4446 case OPTION_IMAGE_OPTS:
4452 for (i = optind; i < argc; i++) {
4454 arg = g_strdup(argv[i]);
4456 tmp = strchr(arg, '=');
4458 error_report("unrecognized operand %s", arg);
4465 for (j = 0; options[j].name != NULL; j++) {
4466 if (!strcmp(arg, options[j].name)) {
4470 if (options[j].name == NULL) {
4471 error_report("unrecognized operand %s", arg);
4476 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4480 dd.flags |= options[j].flag;
4485 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4486 error_report("Must specify both input and output files");
4491 if (qemu_opts_foreach(&qemu_object_opts,
4492 user_creatable_add_opts_foreach,
4498 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4506 drv = bdrv_find_format(out_fmt);
4508 error_report("Unknown file format");
4512 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4515 error_report_err(local_err);
4519 if (!drv->create_opts) {
4520 error_report("Format driver '%s' does not support image creation",
4525 if (!proto_drv->create_opts) {
4526 error_report("Protocol driver '%s' does not support image creation",
4527 proto_drv->format_name);
4531 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4532 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4534 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4536 size = blk_getlength(blk1);
4538 error_report("Failed to get size for '%s'", in.filename);
4543 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4544 dd.count * in.bsz < size) {
4545 size = dd.count * in.bsz;
4548 /* Overflow means the specified offset is beyond input image's size */
4549 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4550 size < in.bsz * in.offset)) {
4551 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4553 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4554 size - in.bsz * in.offset, &error_abort);
4557 ret = bdrv_create(drv, out.filename, opts, &local_err);
4559 error_reportf_err(local_err,
4560 "%s: error while creating output image: ",
4566 /* TODO, we can't honour --image-opts for the target,
4567 * since it needs to be given in a format compatible
4568 * with the bdrv_create() call above which does not
4569 * support image-opts style.
4571 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
4572 false, false, false);
4579 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4580 size < in.offset * in.bsz)) {
4581 /* We give a warning if the skip option is bigger than the input
4582 * size and create an empty output disk image (i.e. like dd(1)).
4584 error_report("%s: cannot skip to specified offset", in.filename);
4587 in_pos = in.offset * in.bsz;
4590 in.buf = g_new(uint8_t, in.bsz);
4592 for (out_pos = 0; in_pos < size; block_count++) {
4593 int in_ret, out_ret;
4595 if (in_pos + in.bsz > size) {
4596 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4598 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4601 error_report("error while reading from input image file: %s",
4608 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4611 error_report("error while writing to output image file: %s",
4612 strerror(-out_ret));
4621 qemu_opts_del(opts);
4622 qemu_opts_free(create_opts);
4625 g_free(in.filename);
4626 g_free(out.filename);
4636 static void dump_json_block_measure_info(BlockMeasureInfo *info)
4640 Visitor *v = qobject_output_visitor_new(&obj);
4642 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4643 visit_complete(v, &obj);
4644 str = qobject_to_json_pretty(obj);
4645 assert(str != NULL);
4646 printf("%s\n", qstring_get_str(str));
4652 static int img_measure(int argc, char **argv)
4654 static const struct option long_options[] = {
4655 {"help", no_argument, 0, 'h'},
4656 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4657 {"object", required_argument, 0, OPTION_OBJECT},
4658 {"output", required_argument, 0, OPTION_OUTPUT},
4659 {"size", required_argument, 0, OPTION_SIZE},
4660 {"force-share", no_argument, 0, 'U'},
4663 OutputFormat output_format = OFORMAT_HUMAN;
4664 BlockBackend *in_blk = NULL;
4666 const char *filename = NULL;
4667 const char *fmt = NULL;
4668 const char *out_fmt = "raw";
4669 char *options = NULL;
4670 char *snapshot_name = NULL;
4671 bool force_share = false;
4672 QemuOpts *opts = NULL;
4673 QemuOpts *object_opts = NULL;
4674 QemuOpts *sn_opts = NULL;
4675 QemuOptsList *create_opts = NULL;
4676 bool image_opts = false;
4677 uint64_t img_size = UINT64_MAX;
4678 BlockMeasureInfo *info = NULL;
4679 Error *local_err = NULL;
4683 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4684 long_options, NULL)) != -1) {
4697 if (!is_valid_option_list(optarg)) {
4698 error_report("Invalid option list: %s", optarg);
4702 options = g_strdup(optarg);
4704 char *old_options = options;
4705 options = g_strdup_printf("%s,%s", options, optarg);
4706 g_free(old_options);
4710 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4711 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4714 error_report("Failed in parsing snapshot param '%s'",
4719 snapshot_name = optarg;
4726 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4732 case OPTION_IMAGE_OPTS:
4736 if (!strcmp(optarg, "json")) {
4737 output_format = OFORMAT_JSON;
4738 } else if (!strcmp(optarg, "human")) {
4739 output_format = OFORMAT_HUMAN;
4741 error_report("--output must be used with human or json "
4750 sval = cvtnum(optarg);
4752 if (sval == -ERANGE) {
4753 error_report("Image size must be less than 8 EiB!");
4755 error_report("Invalid image size specified! You may use "
4756 "k, M, G, T, P or E suffixes for ");
4757 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4758 "petabytes and exabytes.");
4762 img_size = (uint64_t)sval;
4768 if (qemu_opts_foreach(&qemu_object_opts,
4769 user_creatable_add_opts_foreach,
4774 if (argc - optind > 1) {
4775 error_report("At most one filename argument is allowed.");
4777 } else if (argc - optind == 1) {
4778 filename = argv[optind];
4782 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4783 error_report("--object, --image-opts, -f, and -l "
4784 "require a filename argument.");
4787 if (filename && img_size != UINT64_MAX) {
4788 error_report("--size N cannot be used together with a filename.");
4791 if (!filename && img_size == UINT64_MAX) {
4792 error_report("Either --size N or one filename must be specified.");
4797 in_blk = img_open(image_opts, filename, fmt, 0,
4798 false, false, force_share);
4804 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4805 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4806 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4808 } else if (snapshot_name != NULL) {
4809 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4810 snapshot_name, &local_err);
4813 error_reportf_err(local_err, "Failed to load snapshot: ");
4818 drv = bdrv_find_format(out_fmt);
4820 error_report("Unknown file format '%s'", out_fmt);
4823 if (!drv->create_opts) {
4824 error_report("Format driver '%s' does not support image creation",
4829 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4830 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4831 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4833 qemu_opts_do_parse(opts, options, NULL, &local_err);
4835 error_report_err(local_err);
4836 error_report("Invalid options for file format '%s'", out_fmt);
4840 if (img_size != UINT64_MAX) {
4841 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4844 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4846 error_report_err(local_err);
4850 if (output_format == OFORMAT_HUMAN) {
4851 printf("required size: %" PRIu64 "\n", info->required);
4852 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4854 dump_json_block_measure_info(info);
4860 qapi_free_BlockMeasureInfo(info);
4861 qemu_opts_del(object_opts);
4862 qemu_opts_del(opts);
4863 qemu_opts_del(sn_opts);
4864 qemu_opts_free(create_opts);
4870 static const img_cmd_t img_cmds[] = {
4871 #define DEF(option, callback, arg_string) \
4872 { option, callback },
4873 #include "qemu-img-cmds.h"
4878 int main(int argc, char **argv)
4880 const img_cmd_t *cmd;
4881 const char *cmdname;
4882 Error *local_error = NULL;
4883 char *trace_file = NULL;
4885 static const struct option long_options[] = {
4886 {"help", no_argument, 0, 'h'},
4887 {"version", no_argument, 0, 'V'},
4888 {"trace", required_argument, NULL, 'T'},
4893 signal(SIGPIPE, SIG_IGN);
4896 module_call_init(MODULE_INIT_TRACE);
4897 error_set_progname(argv[0]);
4898 qemu_init_exec_dir(argv[0]);
4900 if (qemu_init_main_loop(&local_error)) {
4901 error_report_err(local_error);
4905 qcrypto_init(&error_fatal);
4907 module_call_init(MODULE_INIT_QOM);
4910 error_exit("Not enough arguments");
4913 qemu_add_opts(&qemu_object_opts);
4914 qemu_add_opts(&qemu_source_opts);
4915 qemu_add_opts(&qemu_trace_opts);
4917 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
4920 missing_argument(argv[optind - 1]);
4923 unrecognized_option(argv[optind - 1]);
4929 printf(QEMU_IMG_VERSION);
4933 trace_file = trace_opt_parse(optarg);
4938 cmdname = argv[optind];
4940 /* reset getopt_long scanning */
4948 if (!trace_init_backends()) {
4951 trace_init_file(trace_file);
4952 qemu_set_log(LOG_TRACE);
4954 /* find the command */
4955 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4956 if (!strcmp(cmdname, cmd->name)) {
4957 return cmd->handler(argc, argv);
4962 error_exit("Command not found: %s", cmdname);