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.
1109 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
1118 is_zero = buffer_is_zero(buf, 512);
1119 for(i = 1; i < n; i++) {
1121 if (is_zero != buffer_is_zero(buf, 512)) {
1130 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1131 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1132 * breaking up write requests for only small sparse areas.
1134 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1138 int num_checked, num_used;
1144 ret = is_allocated_sectors(buf, n, pnum);
1150 buf += BDRV_SECTOR_SIZE * *pnum;
1152 num_checked = num_used;
1155 ret = is_allocated_sectors(buf, n, pnum);
1157 buf += BDRV_SECTOR_SIZE * *pnum;
1159 num_checked += *pnum;
1161 num_used = num_checked;
1162 } else if (*pnum >= min) {
1172 * Compares two buffers sector by sector. Returns 0 if the first
1173 * sector of each buffer matches, non-zero otherwise.
1175 * pnum is set to the sector-aligned size of the buffer prefix that
1176 * has the same matching status as the first sector.
1178 static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1179 int64_t bytes, int64_t *pnum)
1182 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
1186 res = !!memcmp(buf1, buf2, i);
1188 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
1190 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
1200 #define IO_BUF_SIZE (2 * 1024 * 1024)
1203 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1205 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1206 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1207 * failure), and 4 on error (the exit status for read errors), after emitting
1210 * @param blk: BlockBackend for the image
1211 * @param offset: Starting offset to check
1212 * @param bytes: Number of bytes to check
1213 * @param filename: Name of disk file we are checking (logging purpose)
1214 * @param buffer: Allocated buffer for storing read data
1215 * @param quiet: Flag for quiet mode
1217 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1218 int64_t bytes, const char *filename,
1219 uint8_t *buffer, bool quiet)
1224 ret = blk_pread(blk, offset, buffer, bytes);
1226 error_report("Error while reading offset %" PRId64 " of %s: %s",
1227 offset, filename, strerror(-ret));
1230 idx = find_nonzero(buffer, bytes);
1232 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1241 * Compares two images. Exit codes:
1243 * 0 - Images are identical
1245 * >1 - Error occurred
1247 static int img_compare(int argc, char **argv)
1249 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1250 BlockBackend *blk1, *blk2;
1251 BlockDriverState *bs1, *bs2;
1252 int64_t total_size1, total_size2;
1253 uint8_t *buf1 = NULL, *buf2 = NULL;
1254 int64_t pnum1, pnum2;
1255 int allocated1, allocated2;
1256 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1257 bool progress = false, quiet = false, strict = false;
1264 uint64_t progress_base;
1265 bool image_opts = false;
1266 bool force_share = false;
1268 cache = BDRV_DEFAULT_CACHE;
1270 static const struct option long_options[] = {
1271 {"help", no_argument, 0, 'h'},
1272 {"object", required_argument, 0, OPTION_OBJECT},
1273 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1274 {"force-share", no_argument, 0, 'U'},
1277 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1278 long_options, NULL);
1284 missing_argument(argv[optind - 1]);
1287 unrecognized_option(argv[optind - 1]);
1313 case OPTION_OBJECT: {
1315 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1322 case OPTION_IMAGE_OPTS:
1328 /* Progress is not shown in Quiet mode */
1334 if (optind != argc - 2) {
1335 error_exit("Expecting two image file names");
1337 filename1 = argv[optind++];
1338 filename2 = argv[optind++];
1340 if (qemu_opts_foreach(&qemu_object_opts,
1341 user_creatable_add_opts_foreach,
1347 /* Initialize before goto out */
1348 qemu_progress_init(progress, 2.0);
1351 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1353 error_report("Invalid source cache option: %s", cache);
1358 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1365 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1374 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1375 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1376 total_size1 = blk_getlength(blk1);
1377 if (total_size1 < 0) {
1378 error_report("Can't get size of %s: %s",
1379 filename1, strerror(-total_size1));
1383 total_size2 = blk_getlength(blk2);
1384 if (total_size2 < 0) {
1385 error_report("Can't get size of %s: %s",
1386 filename2, strerror(-total_size2));
1390 total_size = MIN(total_size1, total_size2);
1391 progress_base = MAX(total_size1, total_size2);
1393 qemu_progress_print(0, 100);
1395 if (strict && total_size1 != total_size2) {
1397 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1401 while (offset < total_size) {
1402 int status1, status2;
1404 status1 = bdrv_block_status_above(bs1, NULL, offset,
1405 total_size1 - offset, &pnum1, NULL,
1409 error_report("Sector allocation test failed for %s", filename1);
1412 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1414 status2 = bdrv_block_status_above(bs2, NULL, offset,
1415 total_size2 - offset, &pnum2, NULL,
1419 error_report("Sector allocation test failed for %s", filename2);
1422 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1424 assert(pnum1 && pnum2);
1425 chunk = MIN(pnum1, pnum2);
1428 if (status1 != status2) {
1430 qprintf(quiet, "Strict mode: Offset %" PRId64
1431 " block status mismatch!\n", offset);
1435 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1437 } else if (allocated1 == allocated2) {
1441 chunk = MIN(chunk, IO_BUF_SIZE);
1442 ret = blk_pread(blk1, offset, buf1, chunk);
1444 error_report("Error while reading offset %" PRId64
1446 offset, filename1, strerror(-ret));
1450 ret = blk_pread(blk2, offset, buf2, chunk);
1452 error_report("Error while reading offset %" PRId64
1454 offset, filename2, strerror(-ret));
1458 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1459 if (ret || pnum != chunk) {
1460 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1461 offset + (ret ? 0 : pnum));
1467 chunk = MIN(chunk, IO_BUF_SIZE);
1469 ret = check_empty_sectors(blk1, offset, chunk,
1470 filename1, buf1, quiet);
1472 ret = check_empty_sectors(blk2, offset, chunk,
1473 filename2, buf1, quiet);
1480 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1483 if (total_size1 != total_size2) {
1484 BlockBackend *blk_over;
1485 const char *filename_over;
1487 qprintf(quiet, "Warning: Image size mismatch!\n");
1488 if (total_size1 > total_size2) {
1490 filename_over = filename1;
1493 filename_over = filename2;
1496 while (offset < progress_base) {
1497 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1498 progress_base - offset, &chunk,
1502 error_report("Sector allocation test failed for %s",
1507 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1508 chunk = MIN(chunk, IO_BUF_SIZE);
1509 ret = check_empty_sectors(blk_over, offset, chunk,
1510 filename_over, buf1, quiet);
1516 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1520 qprintf(quiet, "Images are identical.\n");
1530 qemu_progress_end();
1535 enum ImgConvertBlockStatus {
1541 #define MAX_COROUTINES 16
1543 typedef struct ImgConvertState {
1545 int64_t *src_sectors;
1547 int64_t total_sectors;
1548 int64_t allocated_sectors;
1549 int64_t allocated_done;
1552 enum ImgConvertBlockStatus status;
1553 int64_t sector_next_status;
1554 BlockBackend *target;
1557 bool unallocated_blocks_are_zero;
1558 bool target_has_backing;
1559 int64_t target_backing_sectors; /* negative if unknown */
1563 size_t cluster_sectors;
1565 long num_coroutines;
1566 int running_coroutines;
1567 Coroutine *co[MAX_COROUTINES];
1568 int64_t wait_sector_num[MAX_COROUTINES];
1573 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1574 int *src_cur, int64_t *src_cur_offset)
1577 *src_cur_offset = 0;
1578 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1579 *src_cur_offset += s->src_sectors[*src_cur];
1581 assert(*src_cur < s->src_num);
1585 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1587 int64_t src_cur_offset;
1588 int ret, n, src_cur;
1589 bool post_backing_zero = false;
1591 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1593 assert(s->total_sectors > sector_num);
1594 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1596 if (s->target_backing_sectors >= 0) {
1597 if (sector_num >= s->target_backing_sectors) {
1598 post_backing_zero = s->unallocated_blocks_are_zero;
1599 } else if (sector_num + n > s->target_backing_sectors) {
1600 /* Split requests around target_backing_sectors (because
1601 * starting from there, zeros are handled differently) */
1602 n = s->target_backing_sectors - sector_num;
1606 if (s->sector_next_status <= sector_num) {
1607 int64_t count = n * BDRV_SECTOR_SIZE;
1609 if (s->target_has_backing) {
1611 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1612 (sector_num - src_cur_offset) *
1614 count, &count, NULL, NULL);
1616 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1617 (sector_num - src_cur_offset) *
1619 count, &count, NULL, NULL);
1624 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1626 if (ret & BDRV_BLOCK_ZERO) {
1627 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
1628 } else if (ret & BDRV_BLOCK_DATA) {
1629 s->status = BLK_DATA;
1631 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1634 s->sector_next_status = sector_num + n;
1637 n = MIN(n, s->sector_next_status - sector_num);
1638 if (s->status == BLK_DATA) {
1639 n = MIN(n, s->buf_sectors);
1642 /* We need to write complete clusters for compressed images, so if an
1643 * unallocated area is shorter than that, we must consider the whole
1644 * cluster allocated. */
1645 if (s->compressed) {
1646 if (n < s->cluster_sectors) {
1647 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1648 s->status = BLK_DATA;
1650 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1657 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1658 int nb_sectors, uint8_t *buf)
1664 assert(nb_sectors <= s->buf_sectors);
1665 while (nb_sectors > 0) {
1668 int64_t bs_sectors, src_cur_offset;
1670 /* In the case of compression with multiple source files, we can get a
1671 * nb_sectors that spreads into the next part. So we must be able to
1672 * read across multiple BDSes for one convert_read() call. */
1673 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1674 blk = s->src[src_cur];
1675 bs_sectors = s->src_sectors[src_cur];
1677 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1679 iov.iov_len = n << BDRV_SECTOR_BITS;
1680 qemu_iovec_init_external(&qiov, &iov, 1);
1682 ret = blk_co_preadv(
1683 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1684 n << BDRV_SECTOR_BITS, &qiov, 0);
1691 buf += n * BDRV_SECTOR_SIZE;
1698 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1699 int nb_sectors, uint8_t *buf,
1700 enum ImgConvertBlockStatus status)
1706 while (nb_sectors > 0) {
1708 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1711 case BLK_BACKING_FILE:
1712 /* If we have a backing file, leave clusters unallocated that are
1713 * unallocated in the source image, so that the backing file is
1714 * visible at the respective offset. */
1715 assert(s->target_has_backing);
1719 /* If we're told to keep the target fully allocated (-S 0) or there
1720 * is real non-zero data, we must write it. Otherwise we can treat
1721 * it as zero sectors.
1722 * Compressed clusters need to be written as a whole, so in that
1723 * case we can only save the write if the buffer is completely
1725 if (!s->min_sparse ||
1727 is_allocated_sectors_min(buf, n, &n, s->min_sparse)) ||
1729 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1732 iov.iov_len = n << BDRV_SECTOR_BITS;
1733 qemu_iovec_init_external(&qiov, &iov, 1);
1735 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
1736 n << BDRV_SECTOR_BITS, &qiov, flags);
1745 if (s->has_zero_init) {
1746 assert(!s->target_has_backing);
1749 ret = blk_co_pwrite_zeroes(s->target,
1750 sector_num << BDRV_SECTOR_BITS,
1751 n << BDRV_SECTOR_BITS, 0);
1760 buf += n * BDRV_SECTOR_SIZE;
1766 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1771 while (nb_sectors > 0) {
1774 int64_t bs_sectors, src_cur_offset;
1777 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1778 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1779 blk = s->src[src_cur];
1780 bs_sectors = s->src_sectors[src_cur];
1782 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1784 ret = blk_co_copy_range(blk, offset, s->target,
1785 sector_num << BDRV_SECTOR_BITS,
1786 n << BDRV_SECTOR_BITS, 0);
1797 static void coroutine_fn convert_co_do_copy(void *opaque)
1799 ImgConvertState *s = opaque;
1800 uint8_t *buf = NULL;
1804 for (i = 0; i < s->num_coroutines; i++) {
1805 if (s->co[i] == qemu_coroutine_self()) {
1812 s->running_coroutines++;
1813 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1818 enum ImgConvertBlockStatus status;
1821 qemu_co_mutex_lock(&s->lock);
1822 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1823 qemu_co_mutex_unlock(&s->lock);
1826 n = convert_iteration_sectors(s, s->sector_num);
1828 qemu_co_mutex_unlock(&s->lock);
1832 /* save current sector and allocation status to local variables */
1833 sector_num = s->sector_num;
1835 if (!s->min_sparse && s->status == BLK_ZERO) {
1836 n = MIN(n, s->buf_sectors);
1838 /* increment global sector counter so that other coroutines can
1839 * already continue reading beyond this request */
1841 qemu_co_mutex_unlock(&s->lock);
1843 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1844 s->allocated_done += n;
1845 qemu_progress_print(100.0 * s->allocated_done /
1846 s->allocated_sectors, 0);
1850 copy_range = s->copy_range && s->status == BLK_DATA;
1851 if (status == BLK_DATA && !copy_range) {
1852 ret = convert_co_read(s, sector_num, n, buf);
1854 error_report("error while reading sector %" PRId64
1855 ": %s", sector_num, strerror(-ret));
1858 } else if (!s->min_sparse && status == BLK_ZERO) {
1860 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1863 if (s->wr_in_order) {
1864 /* keep writes in order */
1865 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
1866 s->wait_sector_num[index] = sector_num;
1867 qemu_coroutine_yield();
1869 s->wait_sector_num[index] = -1;
1872 if (s->ret == -EINPROGRESS) {
1874 ret = convert_co_copy_range(s, sector_num, n);
1876 s->copy_range = false;
1880 ret = convert_co_write(s, sector_num, n, buf, status);
1883 error_report("error while writing sector %" PRId64
1884 ": %s", sector_num, strerror(-ret));
1889 if (s->wr_in_order) {
1890 /* reenter the coroutine that might have waited
1891 * for this write to complete */
1892 s->wr_offs = sector_num + n;
1893 for (i = 0; i < s->num_coroutines; i++) {
1894 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1896 * A -> B -> A cannot occur because A has
1897 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1898 * B will never enter A during this time window.
1900 qemu_coroutine_enter(s->co[i]);
1908 s->co[index] = NULL;
1909 s->running_coroutines--;
1910 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1911 /* the convert job finished successfully */
1916 static int convert_do_copy(ImgConvertState *s)
1919 int64_t sector_num = 0;
1921 /* Check whether we have zero initialisation or can get it efficiently */
1922 s->has_zero_init = s->min_sparse && !s->target_has_backing
1923 ? bdrv_has_zero_init(blk_bs(s->target))
1926 if (!s->has_zero_init && !s->target_has_backing &&
1927 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1929 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
1931 s->has_zero_init = true;
1935 /* Allocate buffer for copied data. For compressed images, only one cluster
1936 * can be copied at a time. */
1937 if (s->compressed) {
1938 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1939 error_report("invalid cluster size");
1942 s->buf_sectors = s->cluster_sectors;
1945 while (sector_num < s->total_sectors) {
1946 n = convert_iteration_sectors(s, sector_num);
1950 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1952 s->allocated_sectors += n;
1958 s->sector_next_status = 0;
1959 s->ret = -EINPROGRESS;
1961 qemu_co_mutex_init(&s->lock);
1962 for (i = 0; i < s->num_coroutines; i++) {
1963 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1964 s->wait_sector_num[i] = -1;
1965 qemu_coroutine_enter(s->co[i]);
1968 while (s->running_coroutines) {
1969 main_loop_wait(false);
1972 if (s->compressed && !s->ret) {
1973 /* signal EOF to align */
1974 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
1983 static int img_convert(int argc, char **argv)
1985 int c, bs_i, flags, src_flags = 0;
1986 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
1987 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
1988 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
1989 BlockDriver *drv = NULL, *proto_drv = NULL;
1990 BlockDriverInfo bdi;
1991 BlockDriverState *out_bs;
1992 QemuOpts *opts = NULL, *sn_opts = NULL;
1993 QemuOptsList *create_opts = NULL;
1994 char *options = NULL;
1995 Error *local_err = NULL;
1996 bool writethrough, src_writethrough, quiet = false, image_opts = false,
1997 skip_create = false, progress = false, tgt_image_opts = false;
1998 int64_t ret = -EINVAL;
1999 bool force_share = false;
2001 ImgConvertState s = (ImgConvertState) {
2002 /* Need at least 4k of zeros for sparse detection */
2005 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2006 .wr_in_order = true,
2007 .num_coroutines = 8,
2011 static const struct option long_options[] = {
2012 {"help", no_argument, 0, 'h'},
2013 {"object", required_argument, 0, OPTION_OBJECT},
2014 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2015 {"force-share", no_argument, 0, 'U'},
2016 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
2019 c = getopt_long(argc, argv, ":hf:O:B:co:l:S:pt:T:qnm:WU",
2020 long_options, NULL);
2026 missing_argument(argv[optind - 1]);
2029 unrecognized_option(argv[optind - 1]);
2041 out_baseimg = optarg;
2044 s.compressed = true;
2045 s.copy_range = false;
2048 if (!is_valid_option_list(optarg)) {
2049 error_report("Invalid option list: %s", optarg);
2053 options = g_strdup(optarg);
2055 char *old_options = options;
2056 options = g_strdup_printf("%s,%s", options, optarg);
2057 g_free(old_options);
2061 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2062 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2065 error_report("Failed in parsing snapshot param '%s'",
2070 snapshot_name = optarg;
2077 sval = cvtnum(optarg);
2079 error_report("Invalid minimum zero buffer size for sparse output specified");
2083 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2084 s.copy_range = false;
2103 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2104 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2105 error_report("Invalid number of coroutines. Allowed number of"
2106 " coroutines is between 1 and %d", MAX_COROUTINES);
2111 s.wr_in_order = false;
2116 case OPTION_OBJECT: {
2117 QemuOpts *object_opts;
2118 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2125 case OPTION_IMAGE_OPTS:
2128 case OPTION_TARGET_IMAGE_OPTS:
2129 tgt_image_opts = true;
2134 if (!out_fmt && !tgt_image_opts) {
2138 if (qemu_opts_foreach(&qemu_object_opts,
2139 user_creatable_add_opts_foreach,
2144 if (tgt_image_opts && !skip_create) {
2145 error_report("--target-image-opts requires use of -n flag");
2149 s.src_num = argc - optind - 1;
2150 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2152 if (options && has_help_option(options)) {
2154 ret = print_block_option_help(out_filename, out_fmt);
2157 error_report("Option help requires a format be specified");
2162 if (s.src_num < 1) {
2163 error_report("Must specify image file name");
2168 /* ret is still -EINVAL until here */
2169 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2171 error_report("Invalid source cache option: %s", src_cache);
2175 /* Initialize before goto out */
2179 qemu_progress_init(progress, 1.0);
2180 qemu_progress_print(0, 100);
2182 s.src = g_new0(BlockBackend *, s.src_num);
2183 s.src_sectors = g_new(int64_t, s.src_num);
2185 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2186 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2187 fmt, src_flags, src_writethrough, quiet,
2193 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2194 if (s.src_sectors[bs_i] < 0) {
2195 error_report("Could not get size of %s: %s",
2196 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2200 s.total_sectors += s.src_sectors[bs_i];
2204 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2205 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2206 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2208 } else if (snapshot_name != NULL) {
2209 if (s.src_num > 1) {
2210 error_report("No support for concatenating multiple snapshot");
2215 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2219 error_reportf_err(local_err, "Failed to load snapshot: ");
2225 /* Find driver and parse its options */
2226 drv = bdrv_find_format(out_fmt);
2228 error_report("Unknown file format '%s'", out_fmt);
2233 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2235 error_report_err(local_err);
2240 if (!drv->create_opts) {
2241 error_report("Format driver '%s' does not support image creation",
2247 if (!proto_drv->create_opts) {
2248 error_report("Protocol driver '%s' does not support image creation",
2249 proto_drv->format_name);
2254 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2255 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2257 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2259 qemu_opts_do_parse(opts, options, NULL, &local_err);
2261 error_report_err(local_err);
2267 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2269 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2275 /* Get backing file name if -o backing_file was used */
2276 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2277 if (out_baseimg_param) {
2278 out_baseimg = out_baseimg_param;
2280 s.target_has_backing = (bool) out_baseimg;
2282 if (s.src_num > 1 && out_baseimg) {
2283 error_report("Having a backing file for the target makes no sense when "
2284 "concatenating multiple input images");
2289 /* Check if compression is supported */
2292 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2293 const char *encryptfmt =
2294 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2295 const char *preallocation =
2296 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2298 if (drv && !drv->bdrv_co_pwritev_compressed) {
2299 error_report("Compression not supported for this file format");
2304 if (encryption || encryptfmt) {
2305 error_report("Compression and encryption not supported at "
2312 && strcmp(preallocation, "off"))
2314 error_report("Compression and preallocation not supported at "
2322 /* Create the new image */
2323 ret = bdrv_create(drv, out_filename, opts, &local_err);
2325 error_reportf_err(local_err, "%s: error while converting %s: ",
2326 out_filename, out_fmt);
2331 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2332 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2334 error_report("Invalid cache option: %s", cache);
2339 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2340 flags, writethrough, quiet, false);
2342 /* TODO ultimately we should allow --target-image-opts
2343 * to be used even when -n is not given.
2344 * That has to wait for bdrv_create to be improved
2345 * to allow filenames in option syntax
2347 s.target = img_open_new_file(out_filename, opts, out_fmt,
2348 flags, writethrough, quiet, false);
2354 out_bs = blk_bs(s.target);
2356 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2357 error_report("Compression not supported for this file format");
2362 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2363 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2365 s.buf_sectors = MIN(32768,
2367 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2368 out_bs->bl.pdiscard_alignment >>
2369 BDRV_SECTOR_BITS)));
2372 int64_t output_sectors = blk_nb_sectors(s.target);
2373 if (output_sectors < 0) {
2374 error_report("unable to get output image length: %s",
2375 strerror(-output_sectors));
2378 } else if (output_sectors < s.total_sectors) {
2379 error_report("output file is smaller than input file");
2385 if (s.target_has_backing) {
2386 /* Errors are treated as "backing length unknown" (which means
2387 * s.target_backing_sectors has to be negative, which it will
2388 * be automatically). The backing file length is used only
2389 * for optimizations, so such a case is not fatal. */
2390 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2392 s.target_backing_sectors = -1;
2395 ret = bdrv_get_info(out_bs, &bdi);
2398 error_report("could not get block driver info");
2402 s.compressed = s.compressed || bdi.needs_compressed_writes;
2403 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2404 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
2407 ret = convert_do_copy(&s);
2410 qemu_progress_print(100, 0);
2412 qemu_progress_end();
2413 qemu_opts_del(opts);
2414 qemu_opts_free(create_opts);
2415 qemu_opts_del(sn_opts);
2416 blk_unref(s.target);
2418 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2419 blk_unref(s.src[bs_i]);
2423 g_free(s.src_sectors);
2431 static void dump_snapshots(BlockDriverState *bs)
2433 QEMUSnapshotInfo *sn_tab, *sn;
2436 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2439 printf("Snapshot list:\n");
2440 bdrv_snapshot_dump(fprintf, stdout, NULL);
2442 for(i = 0; i < nb_sns; i++) {
2444 bdrv_snapshot_dump(fprintf, stdout, sn);
2450 static void dump_json_image_info_list(ImageInfoList *list)
2454 Visitor *v = qobject_output_visitor_new(&obj);
2456 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2457 visit_complete(v, &obj);
2458 str = qobject_to_json_pretty(obj);
2459 assert(str != NULL);
2460 printf("%s\n", qstring_get_str(str));
2466 static void dump_json_image_info(ImageInfo *info)
2470 Visitor *v = qobject_output_visitor_new(&obj);
2472 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2473 visit_complete(v, &obj);
2474 str = qobject_to_json_pretty(obj);
2475 assert(str != NULL);
2476 printf("%s\n", qstring_get_str(str));
2482 static void dump_human_image_info_list(ImageInfoList *list)
2484 ImageInfoList *elem;
2487 for (elem = list; elem; elem = elem->next) {
2493 bdrv_image_info_dump(fprintf, stdout, elem->value);
2497 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2499 return strcmp(a, b) == 0;
2503 * Open an image file chain and return an ImageInfoList
2505 * @filename: topmost image filename
2506 * @fmt: topmost image format (may be NULL to autodetect)
2507 * @chain: true - enumerate entire backing file chain
2508 * false - only topmost image file
2510 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2511 * image file. If there was an error a message will have been printed to
2514 static ImageInfoList *collect_image_info_list(bool image_opts,
2515 const char *filename,
2517 bool chain, bool force_share)
2519 ImageInfoList *head = NULL;
2520 ImageInfoList **last = &head;
2521 GHashTable *filenames;
2524 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2528 BlockDriverState *bs;
2530 ImageInfoList *elem;
2532 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2533 error_report("Backing file '%s' creates an infinite loop.",
2537 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2539 blk = img_open(image_opts, filename, fmt,
2540 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2547 bdrv_query_image_info(bs, &info, &err);
2549 error_report_err(err);
2554 elem = g_new0(ImageInfoList, 1);
2561 filename = fmt = NULL;
2563 if (info->has_full_backing_filename) {
2564 filename = info->full_backing_filename;
2565 } else if (info->has_backing_filename) {
2566 error_report("Could not determine absolute backing filename,"
2567 " but backing filename '%s' present",
2568 info->backing_filename);
2571 if (info->has_backing_filename_format) {
2572 fmt = info->backing_filename_format;
2576 g_hash_table_destroy(filenames);
2580 qapi_free_ImageInfoList(head);
2581 g_hash_table_destroy(filenames);
2585 static int img_info(int argc, char **argv)
2588 OutputFormat output_format = OFORMAT_HUMAN;
2590 const char *filename, *fmt, *output;
2591 ImageInfoList *list;
2592 bool image_opts = false;
2593 bool force_share = false;
2598 int option_index = 0;
2599 static const struct option long_options[] = {
2600 {"help", no_argument, 0, 'h'},
2601 {"format", required_argument, 0, 'f'},
2602 {"output", required_argument, 0, OPTION_OUTPUT},
2603 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2604 {"object", required_argument, 0, OPTION_OBJECT},
2605 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2606 {"force-share", no_argument, 0, 'U'},
2609 c = getopt_long(argc, argv, ":f:hU",
2610 long_options, &option_index);
2616 missing_argument(argv[optind - 1]);
2619 unrecognized_option(argv[optind - 1]);
2633 case OPTION_BACKING_CHAIN:
2636 case OPTION_OBJECT: {
2638 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2644 case OPTION_IMAGE_OPTS:
2649 if (optind != argc - 1) {
2650 error_exit("Expecting one image file name");
2652 filename = argv[optind++];
2654 if (output && !strcmp(output, "json")) {
2655 output_format = OFORMAT_JSON;
2656 } else if (output && !strcmp(output, "human")) {
2657 output_format = OFORMAT_HUMAN;
2658 } else if (output) {
2659 error_report("--output must be used with human or json as argument.");
2663 if (qemu_opts_foreach(&qemu_object_opts,
2664 user_creatable_add_opts_foreach,
2669 list = collect_image_info_list(image_opts, filename, fmt, chain,
2675 switch (output_format) {
2677 dump_human_image_info_list(list);
2681 dump_json_image_info_list(list);
2683 dump_json_image_info(list->value);
2688 qapi_free_ImageInfoList(list);
2692 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2695 switch (output_format) {
2697 if (e->data && !e->has_offset) {
2698 error_report("File contains external, encrypted or compressed clusters.");
2701 if (e->data && !e->zero) {
2702 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2703 e->start, e->length,
2704 e->has_offset ? e->offset : 0,
2705 e->has_filename ? e->filename : "");
2707 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2708 * Modify the flags here to allow more coalescing.
2710 if (next && (!next->data || next->zero)) {
2716 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2717 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2718 (e->start == 0 ? "[" : ",\n"),
2719 e->start, e->length, e->depth,
2720 e->zero ? "true" : "false",
2721 e->data ? "true" : "false");
2722 if (e->has_offset) {
2723 printf(", \"offset\": %"PRId64"", e->offset);
2734 static int get_block_status(BlockDriverState *bs, int64_t offset,
2735 int64_t bytes, MapEntry *e)
2739 BlockDriverState *file;
2743 /* As an optimization, we could cache the current range of unallocated
2744 * clusters in each file of the chain, and avoid querying the same
2750 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
2755 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2758 bs = backing_bs(bs);
2767 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2772 .data = !!(ret & BDRV_BLOCK_DATA),
2773 .zero = !!(ret & BDRV_BLOCK_ZERO),
2775 .has_offset = has_offset,
2777 .has_filename = file && has_offset,
2778 .filename = file && has_offset ? file->filename : NULL,
2784 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2786 if (curr->length == 0) {
2789 if (curr->zero != next->zero ||
2790 curr->data != next->data ||
2791 curr->depth != next->depth ||
2792 curr->has_filename != next->has_filename ||
2793 curr->has_offset != next->has_offset) {
2796 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2799 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2805 static int img_map(int argc, char **argv)
2808 OutputFormat output_format = OFORMAT_HUMAN;
2810 BlockDriverState *bs;
2811 const char *filename, *fmt, *output;
2813 MapEntry curr = { .length = 0 }, next;
2815 bool image_opts = false;
2816 bool force_share = false;
2821 int option_index = 0;
2822 static const struct option long_options[] = {
2823 {"help", no_argument, 0, 'h'},
2824 {"format", required_argument, 0, 'f'},
2825 {"output", required_argument, 0, OPTION_OUTPUT},
2826 {"object", required_argument, 0, OPTION_OBJECT},
2827 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2828 {"force-share", no_argument, 0, 'U'},
2831 c = getopt_long(argc, argv, ":f:hU",
2832 long_options, &option_index);
2838 missing_argument(argv[optind - 1]);
2841 unrecognized_option(argv[optind - 1]);
2855 case OPTION_OBJECT: {
2857 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2863 case OPTION_IMAGE_OPTS:
2868 if (optind != argc - 1) {
2869 error_exit("Expecting one image file name");
2871 filename = argv[optind];
2873 if (output && !strcmp(output, "json")) {
2874 output_format = OFORMAT_JSON;
2875 } else if (output && !strcmp(output, "human")) {
2876 output_format = OFORMAT_HUMAN;
2877 } else if (output) {
2878 error_report("--output must be used with human or json as argument.");
2882 if (qemu_opts_foreach(&qemu_object_opts,
2883 user_creatable_add_opts_foreach,
2888 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
2894 if (output_format == OFORMAT_HUMAN) {
2895 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2898 length = blk_getlength(blk);
2899 while (curr.start + curr.length < length) {
2900 int64_t offset = curr.start + curr.length;
2903 /* Probe up to 1 GiB at a time. */
2904 n = MIN(1 << 30, length - offset);
2905 ret = get_block_status(bs, offset, n, &next);
2908 error_report("Could not read file metadata: %s", strerror(-ret));
2912 if (entry_mergeable(&curr, &next)) {
2913 curr.length += next.length;
2917 if (curr.length > 0) {
2918 dump_map_entry(output_format, &curr, &next);
2923 dump_map_entry(output_format, &curr, NULL);
2930 #define SNAPSHOT_LIST 1
2931 #define SNAPSHOT_CREATE 2
2932 #define SNAPSHOT_APPLY 3
2933 #define SNAPSHOT_DELETE 4
2935 static int img_snapshot(int argc, char **argv)
2938 BlockDriverState *bs;
2939 QEMUSnapshotInfo sn;
2940 char *filename, *snapshot_name = NULL;
2941 int c, ret = 0, bdrv_oflags;
2946 bool image_opts = false;
2947 bool force_share = false;
2949 bdrv_oflags = BDRV_O_RDWR;
2950 /* Parse commandline parameters */
2952 static const struct option long_options[] = {
2953 {"help", no_argument, 0, 'h'},
2954 {"object", required_argument, 0, OPTION_OBJECT},
2955 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2956 {"force-share", no_argument, 0, 'U'},
2959 c = getopt_long(argc, argv, ":la:c:d:hqU",
2960 long_options, NULL);
2966 missing_argument(argv[optind - 1]);
2969 unrecognized_option(argv[optind - 1]);
2976 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2979 action = SNAPSHOT_LIST;
2980 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
2984 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2987 action = SNAPSHOT_APPLY;
2988 snapshot_name = optarg;
2992 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2995 action = SNAPSHOT_CREATE;
2996 snapshot_name = optarg;
3000 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3003 action = SNAPSHOT_DELETE;
3004 snapshot_name = optarg;
3012 case OPTION_OBJECT: {
3014 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3020 case OPTION_IMAGE_OPTS:
3026 if (optind != argc - 1) {
3027 error_exit("Expecting one image file name");
3029 filename = argv[optind++];
3031 if (qemu_opts_foreach(&qemu_object_opts,
3032 user_creatable_add_opts_foreach,
3037 /* Open the image */
3038 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3045 /* Perform the requested action */
3051 case SNAPSHOT_CREATE:
3052 memset(&sn, 0, sizeof(sn));
3053 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3055 qemu_gettimeofday(&tv);
3056 sn.date_sec = tv.tv_sec;
3057 sn.date_nsec = tv.tv_usec * 1000;
3059 ret = bdrv_snapshot_create(bs, &sn);
3061 error_report("Could not create snapshot '%s': %d (%s)",
3062 snapshot_name, ret, strerror(-ret));
3066 case SNAPSHOT_APPLY:
3067 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3069 error_reportf_err(err, "Could not apply snapshot '%s': ",
3074 case SNAPSHOT_DELETE:
3075 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
3077 error_reportf_err(err, "Could not delete snapshot '%s': ",
3092 static int img_rebase(int argc, char **argv)
3094 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3095 uint8_t *buf_old = NULL;
3096 uint8_t *buf_new = NULL;
3097 BlockDriverState *bs = NULL;
3099 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3100 int c, flags, src_flags, ret;
3101 bool writethrough, src_writethrough;
3103 bool force_share = false;
3106 Error *local_err = NULL;
3107 bool image_opts = false;
3109 /* Parse commandline parameters */
3111 cache = BDRV_DEFAULT_CACHE;
3112 src_cache = BDRV_DEFAULT_CACHE;
3116 static const struct option long_options[] = {
3117 {"help", no_argument, 0, 'h'},
3118 {"object", required_argument, 0, OPTION_OBJECT},
3119 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3120 {"force-share", no_argument, 0, 'U'},
3123 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3124 long_options, NULL);
3130 missing_argument(argv[optind - 1]);
3133 unrecognized_option(argv[optind - 1]);
3142 out_basefmt = optarg;
3145 out_baseimg = optarg;
3162 case OPTION_OBJECT: {
3164 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3170 case OPTION_IMAGE_OPTS:
3183 if (optind != argc - 1) {
3184 error_exit("Expecting one image file name");
3186 if (!unsafe && !out_baseimg) {
3187 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3189 filename = argv[optind++];
3191 if (qemu_opts_foreach(&qemu_object_opts,
3192 user_creatable_add_opts_foreach,
3197 qemu_progress_init(progress, 2.0);
3198 qemu_progress_print(0, 100);
3200 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3201 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3203 error_report("Invalid cache option: %s", cache);
3208 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3210 error_report("Invalid source cache option: %s", src_cache);
3214 /* The source files are opened read-only, don't care about WCE */
3215 assert((src_flags & BDRV_O_RDWR) == 0);
3216 (void) src_writethrough;
3221 * Ignore the old backing file for unsafe rebase in case we want to correct
3222 * the reference to a renamed or moved backing file.
3224 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3232 if (out_basefmt != NULL) {
3233 if (bdrv_find_format(out_basefmt) == NULL) {
3234 error_report("Invalid format name: '%s'", out_basefmt);
3240 /* For safe rebasing we need to compare old and new backing file */
3242 char backing_name[PATH_MAX];
3243 QDict *options = NULL;
3245 if (bs->backing_format[0] != '\0') {
3246 options = qdict_new();
3247 qdict_put_str(options, "driver", bs->backing_format);
3252 options = qdict_new();
3254 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3256 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3257 blk_old_backing = blk_new_open(backing_name, NULL,
3258 options, src_flags, &local_err);
3259 if (!blk_old_backing) {
3260 error_reportf_err(local_err,
3261 "Could not open old backing file '%s': ",
3267 if (out_baseimg[0]) {
3268 const char *overlay_filename;
3269 char *out_real_path;
3271 options = qdict_new();
3273 qdict_put_str(options, "driver", out_basefmt);
3276 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3279 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3281 out_real_path = g_malloc(PATH_MAX);
3283 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3289 error_reportf_err(local_err,
3290 "Could not resolve backing filename: ");
3292 g_free(out_real_path);
3296 blk_new_backing = blk_new_open(out_real_path, NULL,
3297 options, src_flags, &local_err);
3298 g_free(out_real_path);
3299 if (!blk_new_backing) {
3300 error_reportf_err(local_err,
3301 "Could not open new backing file '%s': ",
3310 * Check each unallocated cluster in the COW file. If it is unallocated,
3311 * accesses go to the backing file. We must therefore compare this cluster
3312 * in the old and new backing file, and if they differ we need to copy it
3313 * from the old backing file into the COW file.
3315 * If qemu-img crashes during this step, no harm is done. The content of
3316 * the image is the same as the original one at any time.
3320 int64_t old_backing_size;
3321 int64_t new_backing_size = 0;
3324 float local_progress = 0;
3326 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3327 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3329 size = blk_getlength(blk);
3331 error_report("Could not get size of '%s': %s",
3332 filename, strerror(-size));
3336 old_backing_size = blk_getlength(blk_old_backing);
3337 if (old_backing_size < 0) {
3338 char backing_name[PATH_MAX];
3340 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3341 error_report("Could not get size of '%s': %s",
3342 backing_name, strerror(-old_backing_size));
3346 if (blk_new_backing) {
3347 new_backing_size = blk_getlength(blk_new_backing);
3348 if (new_backing_size < 0) {
3349 error_report("Could not get size of '%s': %s",
3350 out_baseimg, strerror(-new_backing_size));
3357 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3360 for (offset = 0; offset < size; offset += n) {
3361 /* How many bytes can we handle with the next read? */
3362 n = MIN(IO_BUF_SIZE, size - offset);
3364 /* If the cluster is allocated, we don't need to take action */
3365 ret = bdrv_is_allocated(bs, offset, n, &n);
3367 error_report("error while reading image metadata: %s",
3376 * Read old and new backing file and take into consideration that
3377 * backing files may be smaller than the COW image.
3379 if (offset >= old_backing_size) {
3380 memset(buf_old, 0, n);
3382 if (offset + n > old_backing_size) {
3383 n = old_backing_size - offset;
3386 ret = blk_pread(blk_old_backing, offset, buf_old, n);
3388 error_report("error while reading from old backing file");
3393 if (offset >= new_backing_size || !blk_new_backing) {
3394 memset(buf_new, 0, n);
3396 if (offset + n > new_backing_size) {
3397 n = new_backing_size - offset;
3400 ret = blk_pread(blk_new_backing, offset, buf_new, n);
3402 error_report("error while reading from new backing file");
3407 /* If they differ, we need to write to the COW file */
3408 uint64_t written = 0;
3410 while (written < n) {
3413 if (compare_buffers(buf_old + written, buf_new + written,
3414 n - written, &pnum))
3416 ret = blk_pwrite(blk, offset + written,
3417 buf_old + written, pnum, 0);
3419 error_report("Error while writing to COW image: %s",
3427 qemu_progress_print(local_progress, 100);
3432 * Change the backing file. All clusters that are different from the old
3433 * backing file are overwritten in the COW file now, so the visible content
3434 * doesn't change when we switch the backing file.
3436 if (out_baseimg && *out_baseimg) {
3437 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3439 ret = bdrv_change_backing_file(bs, NULL, NULL);
3442 if (ret == -ENOSPC) {
3443 error_report("Could not change the backing file to '%s': No "
3444 "space left in the file header", out_baseimg);
3445 } else if (ret < 0) {
3446 error_report("Could not change the backing file to '%s': %s",
3447 out_baseimg, strerror(-ret));
3450 qemu_progress_print(100, 0);
3452 * TODO At this point it is possible to check if any clusters that are
3453 * allocated in the COW file are the same in the backing file. If so, they
3454 * could be dropped from the COW file. Don't do this before switching the
3455 * backing file, in case of a crash this would lead to corruption.
3458 qemu_progress_end();
3461 blk_unref(blk_old_backing);
3462 blk_unref(blk_new_backing);
3464 qemu_vfree(buf_old);
3465 qemu_vfree(buf_new);
3474 static int img_resize(int argc, char **argv)
3477 int c, ret, relative;
3478 const char *filename, *fmt, *size;
3479 int64_t n, total_size, current_size, new_size;
3481 BlockBackend *blk = NULL;
3482 PreallocMode prealloc = PREALLOC_MODE_OFF;
3485 static QemuOptsList resize_options = {
3486 .name = "resize_options",
3487 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3490 .name = BLOCK_OPT_SIZE,
3491 .type = QEMU_OPT_SIZE,
3492 .help = "Virtual disk size"
3498 bool image_opts = false;
3499 bool shrink = false;
3501 /* Remove size from argv manually so that negative numbers are not treated
3502 * as options by getopt. */
3504 error_exit("Not enough arguments");
3508 size = argv[--argc];
3510 /* Parse getopt arguments */
3513 static const struct option long_options[] = {
3514 {"help", no_argument, 0, 'h'},
3515 {"object", required_argument, 0, OPTION_OBJECT},
3516 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3517 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3518 {"shrink", no_argument, 0, OPTION_SHRINK},
3521 c = getopt_long(argc, argv, ":f:hq",
3522 long_options, NULL);
3528 missing_argument(argv[optind - 1]);
3531 unrecognized_option(argv[optind - 1]);
3542 case OPTION_OBJECT: {
3544 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3550 case OPTION_IMAGE_OPTS:
3553 case OPTION_PREALLOCATION:
3554 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3555 PREALLOC_MODE__MAX, NULL);
3556 if (prealloc == PREALLOC_MODE__MAX) {
3557 error_report("Invalid preallocation mode '%s'", optarg);
3566 if (optind != argc - 1) {
3567 error_exit("Expecting image file name and size");
3569 filename = argv[optind++];
3571 if (qemu_opts_foreach(&qemu_object_opts,
3572 user_creatable_add_opts_foreach,
3577 /* Choose grow, shrink, or absolute resize mode */
3593 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3594 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3596 error_report_err(err);
3598 qemu_opts_del(param);
3601 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3602 qemu_opts_del(param);
3604 blk = img_open(image_opts, filename, fmt,
3605 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3612 current_size = blk_getlength(blk);
3613 if (current_size < 0) {
3614 error_report("Failed to inquire current image length: %s",
3615 strerror(-current_size));
3621 total_size = current_size + n * relative;
3625 if (total_size <= 0) {
3626 error_report("New image size must be positive");
3631 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3632 error_report("Preallocation can only be used for growing images");
3637 if (total_size < current_size && !shrink) {
3638 warn_report("Shrinking an image will delete all data beyond the "
3639 "shrunken image's end. Before performing such an "
3640 "operation, make sure there is no important data there.");
3642 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3644 "Use the --shrink option to perform a shrink operation.");
3648 warn_report("Using the --shrink option will suppress this message. "
3649 "Note that future versions of qemu-img may refuse to "
3650 "shrink images without this option.");
3654 ret = blk_truncate(blk, total_size, prealloc, &err);
3656 error_report_err(err);
3660 new_size = blk_getlength(blk);
3662 error_report("Failed to verify truncated image length: %s",
3663 strerror(-new_size));
3668 /* Some block drivers implement a truncation method, but only so
3669 * the user can cause qemu to refresh the image's size from disk.
3670 * The idea is that the user resizes the image outside of qemu and
3671 * then invokes block_resize to inform qemu about it.
3672 * (This includes iscsi and file-posix for device files.)
3673 * Of course, that is not the behavior someone invoking
3674 * qemu-img resize would find useful, so we catch that behavior
3675 * here and tell the user. */
3676 if (new_size != total_size && new_size == current_size) {
3677 error_report("Image was not resized; resizing may not be supported "
3683 if (new_size != total_size) {
3684 warn_report("Image should have been resized to %" PRIi64
3685 " bytes, but was resized to %" PRIi64 " bytes",
3686 total_size, new_size);
3689 qprintf(quiet, "Image resized.\n");
3699 static void amend_status_cb(BlockDriverState *bs,
3700 int64_t offset, int64_t total_work_size,
3703 qemu_progress_print(100.f * offset / total_work_size, 0);
3706 static int print_amend_option_help(const char *format)
3710 /* Find driver and parse its options */
3711 drv = bdrv_find_format(format);
3713 error_report("Unknown file format '%s'", format);
3717 if (!drv->bdrv_amend_options) {
3718 error_report("Format driver '%s' does not support option amendment",
3723 /* Every driver supporting amendment must have create_opts */
3724 assert(drv->create_opts);
3726 printf("Creation options for '%s':\n", format);
3727 qemu_opts_print_help(drv->create_opts);
3728 printf("\nNote that not all of these options may be amendable.\n");
3732 static int img_amend(int argc, char **argv)
3736 char *options = NULL;
3737 QemuOptsList *create_opts = NULL;
3738 QemuOpts *opts = NULL;
3739 const char *fmt = NULL, *filename, *cache;
3742 bool quiet = false, progress = false;
3743 BlockBackend *blk = NULL;
3744 BlockDriverState *bs = NULL;
3745 bool image_opts = false;
3747 cache = BDRV_DEFAULT_CACHE;
3749 static const struct option long_options[] = {
3750 {"help", no_argument, 0, 'h'},
3751 {"object", required_argument, 0, OPTION_OBJECT},
3752 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3755 c = getopt_long(argc, argv, ":ho:f:t:pq",
3756 long_options, NULL);
3763 missing_argument(argv[optind - 1]);
3766 unrecognized_option(argv[optind - 1]);
3772 if (!is_valid_option_list(optarg)) {
3773 error_report("Invalid option list: %s", optarg);
3775 goto out_no_progress;
3778 options = g_strdup(optarg);
3780 char *old_options = options;
3781 options = g_strdup_printf("%s,%s", options, optarg);
3782 g_free(old_options);
3798 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3802 goto out_no_progress;
3805 case OPTION_IMAGE_OPTS:
3812 error_exit("Must specify options (-o)");
3815 if (qemu_opts_foreach(&qemu_object_opts,
3816 user_creatable_add_opts_foreach,
3819 goto out_no_progress;
3825 qemu_progress_init(progress, 1.0);
3827 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3828 if (fmt && has_help_option(options)) {
3829 /* If a format is explicitly specified (and possibly no filename is
3830 * given), print option help here */
3831 ret = print_amend_option_help(fmt);
3835 if (optind != argc - 1) {
3836 error_report("Expecting one image file name");
3841 flags = BDRV_O_RDWR;
3842 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3844 error_report("Invalid cache option: %s", cache);
3848 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3856 fmt = bs->drv->format_name;
3858 if (has_help_option(options)) {
3859 /* If the format was auto-detected, print option help here */
3860 ret = print_amend_option_help(fmt);
3864 if (!bs->drv->bdrv_amend_options) {
3865 error_report("Format driver '%s' does not support option amendment",
3871 /* Every driver supporting amendment must have create_opts */
3872 assert(bs->drv->create_opts);
3874 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
3875 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3876 qemu_opts_do_parse(opts, options, NULL, &err);
3878 error_report_err(err);
3883 /* In case the driver does not call amend_status_cb() */
3884 qemu_progress_print(0.f, 0);
3885 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
3886 qemu_progress_print(100.f, 0);
3888 error_report_err(err);
3893 qemu_progress_end();
3897 qemu_opts_del(opts);
3898 qemu_opts_free(create_opts);
3907 typedef struct BenchData {
3909 uint64_t image_size;
3916 bool drain_on_flush;
3925 static void bench_undrained_flush_cb(void *opaque, int ret)
3928 error_report("Failed flush request: %s", strerror(-ret));
3933 static void bench_cb(void *opaque, int ret)
3935 BenchData *b = opaque;
3939 error_report("Failed request: %s", strerror(-ret));
3944 /* Just finished a flush with drained queue: Start next requests */
3945 assert(b->in_flight == 0);
3946 b->in_flush = false;
3947 } else if (b->in_flight > 0) {
3948 int remaining = b->n - b->in_flight;
3953 /* Time for flush? Drain queue if requested, then flush */
3954 if (b->flush_interval && remaining % b->flush_interval == 0) {
3955 if (!b->in_flight || !b->drain_on_flush) {
3956 BlockCompletionFunc *cb;
3958 if (b->drain_on_flush) {
3962 cb = bench_undrained_flush_cb;
3965 acb = blk_aio_flush(b->blk, cb, b);
3967 error_report("Failed to issue flush request");
3971 if (b->drain_on_flush) {
3977 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
3978 int64_t offset = b->offset;
3979 /* blk_aio_* might look for completed I/Os and kick bench_cb
3980 * again, so make sure this operation is counted by in_flight
3981 * and b->offset is ready for the next submission.
3984 b->offset += b->step;
3985 b->offset %= b->image_size;
3987 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
3989 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
3992 error_report("Failed to issue request");
3998 static int img_bench(int argc, char **argv)
4001 const char *fmt = NULL, *filename;
4003 bool image_opts = false;
4004 bool is_write = false;
4008 size_t bufsize = 4096;
4011 int flush_interval = 0;
4012 bool drain_on_flush = true;
4014 BlockBackend *blk = NULL;
4015 BenchData data = {};
4017 bool writethrough = false;
4018 struct timeval t1, t2;
4020 bool force_share = false;
4024 static const struct option long_options[] = {
4025 {"help", no_argument, 0, 'h'},
4026 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
4027 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4028 {"pattern", required_argument, 0, OPTION_PATTERN},
4029 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
4030 {"force-share", no_argument, 0, 'U'},
4033 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
4040 missing_argument(argv[optind - 1]);
4043 unrecognized_option(argv[optind - 1]);
4052 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4053 error_report("Invalid request count specified");
4063 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4064 error_report("Invalid queue depth specified");
4074 flags |= BDRV_O_NATIVE_AIO;
4078 offset = cvtnum(optarg);
4080 error_report("Invalid offset specified");
4093 sval = cvtnum(optarg);
4094 if (sval < 0 || sval > INT_MAX) {
4095 error_report("Invalid buffer size specified");
4106 sval = cvtnum(optarg);
4107 if (sval < 0 || sval > INT_MAX) {
4108 error_report("Invalid step size specified");
4116 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4118 error_report("Invalid cache mode");
4124 flags |= BDRV_O_RDWR;
4130 case OPTION_PATTERN:
4134 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4135 error_report("Invalid pattern byte specified");
4141 case OPTION_FLUSH_INTERVAL:
4145 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4146 error_report("Invalid flush interval specified");
4149 flush_interval = res;
4152 case OPTION_NO_DRAIN:
4153 drain_on_flush = false;
4155 case OPTION_IMAGE_OPTS:
4161 if (optind != argc - 1) {
4162 error_exit("Expecting one image file name");
4164 filename = argv[argc - 1];
4166 if (!is_write && flush_interval) {
4167 error_report("--flush-interval is only available in write tests");
4171 if (flush_interval && flush_interval < depth) {
4172 error_report("Flush interval can't be smaller than depth");
4177 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4184 image_size = blk_getlength(blk);
4185 if (image_size < 0) {
4190 data = (BenchData) {
4192 .image_size = image_size,
4194 .step = step ?: bufsize,
4199 .flush_interval = flush_interval,
4200 .drain_on_flush = drain_on_flush,
4202 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4203 "(starting at offset %" PRId64 ", step size %d)\n",
4204 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4205 data.offset, data.step);
4206 if (flush_interval) {
4207 printf("Sending flush every %d requests\n", flush_interval);
4210 buf_size = data.nrreq * data.bufsize;
4211 data.buf = blk_blockalign(blk, buf_size);
4212 memset(data.buf, pattern, data.nrreq * data.bufsize);
4214 blk_register_buf(blk, data.buf, buf_size);
4216 data.qiov = g_new(QEMUIOVector, data.nrreq);
4217 for (i = 0; i < data.nrreq; i++) {
4218 qemu_iovec_init(&data.qiov[i], 1);
4219 qemu_iovec_add(&data.qiov[i],
4220 data.buf + i * data.bufsize, data.bufsize);
4223 gettimeofday(&t1, NULL);
4226 while (data.n > 0) {
4227 main_loop_wait(false);
4229 gettimeofday(&t2, NULL);
4231 printf("Run completed in %3.3f seconds.\n",
4232 (t2.tv_sec - t1.tv_sec)
4233 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4237 blk_unregister_buf(blk, data.buf);
4239 qemu_vfree(data.buf);
4260 int bsz; /* Block size */
4268 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4272 static int img_dd_bs(const char *arg,
4273 struct DdIo *in, struct DdIo *out,
4280 if (res <= 0 || res > INT_MAX) {
4281 error_report("invalid number: '%s'", arg);
4284 in->bsz = out->bsz = res;
4289 static int img_dd_count(const char *arg,
4290 struct DdIo *in, struct DdIo *out,
4293 dd->count = cvtnum(arg);
4295 if (dd->count < 0) {
4296 error_report("invalid number: '%s'", arg);
4303 static int img_dd_if(const char *arg,
4304 struct DdIo *in, struct DdIo *out,
4307 in->filename = g_strdup(arg);
4312 static int img_dd_of(const char *arg,
4313 struct DdIo *in, struct DdIo *out,
4316 out->filename = g_strdup(arg);
4321 static int img_dd_skip(const char *arg,
4322 struct DdIo *in, struct DdIo *out,
4325 in->offset = cvtnum(arg);
4327 if (in->offset < 0) {
4328 error_report("invalid number: '%s'", arg);
4335 static int img_dd(int argc, char **argv)
4340 BlockDriver *drv = NULL, *proto_drv = NULL;
4341 BlockBackend *blk1 = NULL, *blk2 = NULL;
4342 QemuOpts *opts = NULL;
4343 QemuOptsList *create_opts = NULL;
4344 Error *local_err = NULL;
4345 bool image_opts = false;
4347 const char *out_fmt = "raw";
4348 const char *fmt = NULL;
4350 int64_t block_count = 0, out_pos, in_pos;
4351 bool force_share = false;
4352 struct DdInfo dd = {
4357 .bsz = 512, /* Block size is by default 512 bytes */
4369 const struct DdOpts options[] = {
4370 { "bs", img_dd_bs, C_BS },
4371 { "count", img_dd_count, C_COUNT },
4372 { "if", img_dd_if, C_IF },
4373 { "of", img_dd_of, C_OF },
4374 { "skip", img_dd_skip, C_SKIP },
4377 const struct option long_options[] = {
4378 { "help", no_argument, 0, 'h'},
4379 { "object", required_argument, 0, OPTION_OBJECT},
4380 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4381 { "force-share", no_argument, 0, 'U'},
4385 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4397 missing_argument(argv[optind - 1]);
4400 unrecognized_option(argv[optind - 1]);
4409 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4414 case OPTION_IMAGE_OPTS:
4420 for (i = optind; i < argc; i++) {
4422 arg = g_strdup(argv[i]);
4424 tmp = strchr(arg, '=');
4426 error_report("unrecognized operand %s", arg);
4433 for (j = 0; options[j].name != NULL; j++) {
4434 if (!strcmp(arg, options[j].name)) {
4438 if (options[j].name == NULL) {
4439 error_report("unrecognized operand %s", arg);
4444 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4448 dd.flags |= options[j].flag;
4453 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4454 error_report("Must specify both input and output files");
4459 if (qemu_opts_foreach(&qemu_object_opts,
4460 user_creatable_add_opts_foreach,
4466 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4474 drv = bdrv_find_format(out_fmt);
4476 error_report("Unknown file format");
4480 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4483 error_report_err(local_err);
4487 if (!drv->create_opts) {
4488 error_report("Format driver '%s' does not support image creation",
4493 if (!proto_drv->create_opts) {
4494 error_report("Protocol driver '%s' does not support image creation",
4495 proto_drv->format_name);
4499 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4500 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4502 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4504 size = blk_getlength(blk1);
4506 error_report("Failed to get size for '%s'", in.filename);
4511 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4512 dd.count * in.bsz < size) {
4513 size = dd.count * in.bsz;
4516 /* Overflow means the specified offset is beyond input image's size */
4517 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4518 size < in.bsz * in.offset)) {
4519 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4521 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4522 size - in.bsz * in.offset, &error_abort);
4525 ret = bdrv_create(drv, out.filename, opts, &local_err);
4527 error_reportf_err(local_err,
4528 "%s: error while creating output image: ",
4534 /* TODO, we can't honour --image-opts for the target,
4535 * since it needs to be given in a format compatible
4536 * with the bdrv_create() call above which does not
4537 * support image-opts style.
4539 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
4540 false, false, false);
4547 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4548 size < in.offset * in.bsz)) {
4549 /* We give a warning if the skip option is bigger than the input
4550 * size and create an empty output disk image (i.e. like dd(1)).
4552 error_report("%s: cannot skip to specified offset", in.filename);
4555 in_pos = in.offset * in.bsz;
4558 in.buf = g_new(uint8_t, in.bsz);
4560 for (out_pos = 0; in_pos < size; block_count++) {
4561 int in_ret, out_ret;
4563 if (in_pos + in.bsz > size) {
4564 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4566 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4569 error_report("error while reading from input image file: %s",
4576 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4579 error_report("error while writing to output image file: %s",
4580 strerror(-out_ret));
4589 qemu_opts_del(opts);
4590 qemu_opts_free(create_opts);
4593 g_free(in.filename);
4594 g_free(out.filename);
4604 static void dump_json_block_measure_info(BlockMeasureInfo *info)
4608 Visitor *v = qobject_output_visitor_new(&obj);
4610 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4611 visit_complete(v, &obj);
4612 str = qobject_to_json_pretty(obj);
4613 assert(str != NULL);
4614 printf("%s\n", qstring_get_str(str));
4620 static int img_measure(int argc, char **argv)
4622 static const struct option long_options[] = {
4623 {"help", no_argument, 0, 'h'},
4624 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4625 {"object", required_argument, 0, OPTION_OBJECT},
4626 {"output", required_argument, 0, OPTION_OUTPUT},
4627 {"size", required_argument, 0, OPTION_SIZE},
4628 {"force-share", no_argument, 0, 'U'},
4631 OutputFormat output_format = OFORMAT_HUMAN;
4632 BlockBackend *in_blk = NULL;
4634 const char *filename = NULL;
4635 const char *fmt = NULL;
4636 const char *out_fmt = "raw";
4637 char *options = NULL;
4638 char *snapshot_name = NULL;
4639 bool force_share = false;
4640 QemuOpts *opts = NULL;
4641 QemuOpts *object_opts = NULL;
4642 QemuOpts *sn_opts = NULL;
4643 QemuOptsList *create_opts = NULL;
4644 bool image_opts = false;
4645 uint64_t img_size = UINT64_MAX;
4646 BlockMeasureInfo *info = NULL;
4647 Error *local_err = NULL;
4651 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4652 long_options, NULL)) != -1) {
4665 if (!is_valid_option_list(optarg)) {
4666 error_report("Invalid option list: %s", optarg);
4670 options = g_strdup(optarg);
4672 char *old_options = options;
4673 options = g_strdup_printf("%s,%s", options, optarg);
4674 g_free(old_options);
4678 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4679 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4682 error_report("Failed in parsing snapshot param '%s'",
4687 snapshot_name = optarg;
4694 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4700 case OPTION_IMAGE_OPTS:
4704 if (!strcmp(optarg, "json")) {
4705 output_format = OFORMAT_JSON;
4706 } else if (!strcmp(optarg, "human")) {
4707 output_format = OFORMAT_HUMAN;
4709 error_report("--output must be used with human or json "
4718 sval = cvtnum(optarg);
4720 if (sval == -ERANGE) {
4721 error_report("Image size must be less than 8 EiB!");
4723 error_report("Invalid image size specified! You may use "
4724 "k, M, G, T, P or E suffixes for ");
4725 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4726 "petabytes and exabytes.");
4730 img_size = (uint64_t)sval;
4736 if (qemu_opts_foreach(&qemu_object_opts,
4737 user_creatable_add_opts_foreach,
4742 if (argc - optind > 1) {
4743 error_report("At most one filename argument is allowed.");
4745 } else if (argc - optind == 1) {
4746 filename = argv[optind];
4750 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4751 error_report("--object, --image-opts, -f, and -l "
4752 "require a filename argument.");
4755 if (filename && img_size != UINT64_MAX) {
4756 error_report("--size N cannot be used together with a filename.");
4759 if (!filename && img_size == UINT64_MAX) {
4760 error_report("Either --size N or one filename must be specified.");
4765 in_blk = img_open(image_opts, filename, fmt, 0,
4766 false, false, force_share);
4772 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4773 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4774 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4776 } else if (snapshot_name != NULL) {
4777 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4778 snapshot_name, &local_err);
4781 error_reportf_err(local_err, "Failed to load snapshot: ");
4786 drv = bdrv_find_format(out_fmt);
4788 error_report("Unknown file format '%s'", out_fmt);
4791 if (!drv->create_opts) {
4792 error_report("Format driver '%s' does not support image creation",
4797 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4798 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4799 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4801 qemu_opts_do_parse(opts, options, NULL, &local_err);
4803 error_report_err(local_err);
4804 error_report("Invalid options for file format '%s'", out_fmt);
4808 if (img_size != UINT64_MAX) {
4809 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4812 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4814 error_report_err(local_err);
4818 if (output_format == OFORMAT_HUMAN) {
4819 printf("required size: %" PRIu64 "\n", info->required);
4820 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4822 dump_json_block_measure_info(info);
4828 qapi_free_BlockMeasureInfo(info);
4829 qemu_opts_del(object_opts);
4830 qemu_opts_del(opts);
4831 qemu_opts_del(sn_opts);
4832 qemu_opts_free(create_opts);
4838 static const img_cmd_t img_cmds[] = {
4839 #define DEF(option, callback, arg_string) \
4840 { option, callback },
4841 #include "qemu-img-cmds.h"
4846 int main(int argc, char **argv)
4848 const img_cmd_t *cmd;
4849 const char *cmdname;
4850 Error *local_error = NULL;
4851 char *trace_file = NULL;
4853 static const struct option long_options[] = {
4854 {"help", no_argument, 0, 'h'},
4855 {"version", no_argument, 0, 'V'},
4856 {"trace", required_argument, NULL, 'T'},
4861 signal(SIGPIPE, SIG_IGN);
4864 module_call_init(MODULE_INIT_TRACE);
4865 error_set_progname(argv[0]);
4866 qemu_init_exec_dir(argv[0]);
4868 if (qemu_init_main_loop(&local_error)) {
4869 error_report_err(local_error);
4873 qcrypto_init(&error_fatal);
4875 module_call_init(MODULE_INIT_QOM);
4878 error_exit("Not enough arguments");
4881 qemu_add_opts(&qemu_object_opts);
4882 qemu_add_opts(&qemu_source_opts);
4883 qemu_add_opts(&qemu_trace_opts);
4885 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
4888 missing_argument(argv[optind - 1]);
4891 unrecognized_option(argv[optind - 1]);
4897 printf(QEMU_IMG_VERSION);
4901 trace_file = trace_opt_parse(optarg);
4906 cmdname = argv[optind];
4908 /* reset getopt_long scanning */
4916 if (!trace_init_backends()) {
4919 trace_init_file(trace_file);
4920 qemu_set_log(LOG_TRACE);
4922 /* find the command */
4923 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4924 if (!strcmp(cmdname, cmd->name)) {
4925 return cmd->handler(argc, argv);
4930 error_exit("Command not found: %s", cmdname);