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
24 #include "qemu/osdep.h"
25 #include "qemu-version.h"
26 #include "qapi/error.h"
27 #include "qapi/util.h"
28 #include "qapi-visit.h"
29 #include "qapi/qobject-output-visitor.h"
30 #include "qapi/qmp/qerror.h"
31 #include "qapi/qmp/qjson.h"
32 #include "qapi/qmp/qbool.h"
33 #include "qemu/cutils.h"
34 #include "qemu/config-file.h"
35 #include "qemu/option.h"
36 #include "qemu/error-report.h"
38 #include "qom/object_interfaces.h"
39 #include "sysemu/sysemu.h"
40 #include "sysemu/block-backend.h"
41 #include "block/block_int.h"
42 #include "block/blockjob.h"
43 #include "block/qapi.h"
44 #include "crypto/init.h"
45 #include "trace/control.h"
48 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
49 "\n" QEMU_COPYRIGHT "\n"
51 typedef struct img_cmd_t {
53 int (*handler)(int argc, char **argv);
58 OPTION_BACKING_CHAIN = 257,
60 OPTION_IMAGE_OPTS = 259,
62 OPTION_FLUSH_INTERVAL = 261,
63 OPTION_NO_DRAIN = 262,
64 OPTION_TARGET_IMAGE_OPTS = 263,
66 OPTION_PREALLOCATION = 265,
69 typedef enum OutputFormat {
74 /* Default to cache=writeback as data integrity is not important for qemu-img */
75 #define BDRV_DEFAULT_CACHE "writeback"
77 static void format_print(void *opaque, const char *name)
82 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
86 error_printf("qemu-img: ");
89 error_vprintf(fmt, ap);
92 error_printf("\nTry 'qemu-img --help' for more information\n");
96 static void QEMU_NORETURN missing_argument(const char *option)
98 error_exit("missing argument for option '%s'", option);
101 static void QEMU_NORETURN unrecognized_option(const char *option)
103 error_exit("unrecognized option '%s'", option);
106 /* Please keep in synch with qemu-img.texi */
107 static void QEMU_NORETURN help(void)
109 const char *help_msg =
111 "usage: qemu-img [standard options] command [command options]\n"
112 "QEMU disk image utility\n"
114 " '-h', '--help' display this help and exit\n"
115 " '-V', '--version' output version information and exit\n"
116 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
117 " specify tracing options\n"
120 #define DEF(option, callback, arg_string) \
122 #include "qemu-img-cmds.h"
126 "Command parameters:\n"
127 " 'filename' is a disk image filename\n"
128 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
129 " manual page for a description of the object properties. The most common\n"
130 " object type is a 'secret', which is used to supply passwords and/or\n"
131 " encryption keys.\n"
132 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
133 " 'cache' is the cache mode used to write the output disk image, the valid\n"
134 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
135 " 'directsync' and 'unsafe' (default for convert)\n"
136 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
137 " options are the same as for the 'cache' option\n"
138 " 'size' is the disk image size in bytes. Optional suffixes\n"
139 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
140 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
141 " supported. 'b' is ignored.\n"
142 " 'output_filename' is the destination disk image filename\n"
143 " 'output_fmt' is the destination format\n"
144 " 'options' is a comma separated list of format specific options in a\n"
145 " name=value format. Use -o ? for an overview of the options supported by the\n"
147 " 'snapshot_param' is param used for internal snapshot, format\n"
148 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
150 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
152 " '-c' indicates that target image must be compressed (qcow format only)\n"
153 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
154 " match exactly. The image doesn't need a working backing file before\n"
155 " rebasing in this case (useful for renaming the backing file)\n"
156 " '-h' with or without a command shows this help and lists the supported formats\n"
157 " '-p' show progress of command (only certain commands)\n"
158 " '-q' use Quiet mode - do not print any output (except errors)\n"
159 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
160 " contain only zeros for qemu-img to create a sparse image during\n"
161 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
162 " unallocated or zero sectors, and the destination image will always be\n"
164 " '--output' takes the format in which the output must be done (human or json)\n"
165 " '-n' skips the target volume creation (useful if the volume is created\n"
166 " prior to running qemu-img)\n"
168 "Parameters to check subcommand:\n"
169 " '-r' tries to repair any inconsistencies that are found during the check.\n"
170 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
171 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
172 " hiding corruption that has already occurred.\n"
174 "Parameters to convert subcommand:\n"
175 " '-m' specifies how many coroutines work in parallel during the convert\n"
176 " process (defaults to 8)\n"
177 " '-W' allow to write to the target out of order rather than sequential\n"
179 "Parameters to snapshot subcommand:\n"
180 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
181 " '-a' applies a snapshot (revert disk to saved state)\n"
182 " '-c' creates a snapshot\n"
183 " '-d' deletes a snapshot\n"
184 " '-l' lists all snapshots in the given image\n"
186 "Parameters to compare subcommand:\n"
187 " '-f' first image format\n"
188 " '-F' second image format\n"
189 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
191 "Parameters to dd subcommand:\n"
192 " 'bs=BYTES' read and write up to BYTES bytes at a time "
194 " 'count=N' copy only N input blocks\n"
195 " 'if=FILE' read from FILE\n"
196 " 'of=FILE' write to FILE\n"
197 " 'skip=N' skip N bs-sized blocks at the start of input\n";
199 printf("%s\nSupported formats:", help_msg);
200 bdrv_iterate_format(format_print, NULL);
205 static QemuOptsList qemu_object_opts = {
207 .implied_opt_name = "qom-type",
208 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
214 static QemuOptsList qemu_source_opts = {
216 .implied_opt_name = "file",
217 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
223 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
229 ret = vprintf(fmt, args);
236 static int print_block_option_help(const char *filename, const char *fmt)
238 BlockDriver *drv, *proto_drv;
239 QemuOptsList *create_opts = NULL;
240 Error *local_err = NULL;
242 /* Find driver and parse its options */
243 drv = bdrv_find_format(fmt);
245 error_report("Unknown file format '%s'", fmt);
249 create_opts = qemu_opts_append(create_opts, drv->create_opts);
251 proto_drv = bdrv_find_protocol(filename, true, &local_err);
253 error_report_err(local_err);
254 qemu_opts_free(create_opts);
257 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
260 qemu_opts_print_help(create_opts);
261 qemu_opts_free(create_opts);
266 static BlockBackend *img_open_opts(const char *optstr,
267 QemuOpts *opts, int flags, bool writethrough,
268 bool quiet, bool force_share)
271 Error *local_err = NULL;
273 options = qemu_opts_to_qdict(opts, NULL);
275 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
276 && !qdict_get_bool(options, BDRV_OPT_FORCE_SHARE)) {
277 error_report("--force-share/-U conflicts with image options");
281 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
283 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
285 error_reportf_err(local_err, "Could not open '%s': ", optstr);
288 blk_set_enable_write_cache(blk, !writethrough);
293 static BlockBackend *img_open_file(const char *filename,
295 const char *fmt, int flags,
296 bool writethrough, bool quiet,
300 Error *local_err = NULL;
303 options = qdict_new();
306 qdict_put_str(options, "driver", fmt);
310 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
312 blk = blk_new_open(filename, NULL, options, flags, &local_err);
314 error_reportf_err(local_err, "Could not open '%s': ", filename);
317 blk_set_enable_write_cache(blk, !writethrough);
323 static int img_add_key_secrets(void *opaque,
324 const char *name, const char *value,
327 QDict *options = opaque;
329 if (g_str_has_suffix(name, "key-secret")) {
330 qdict_put_str(options, name, value);
336 static BlockBackend *img_open_new_file(const char *filename,
337 QemuOpts *create_opts,
338 const char *fmt, int flags,
339 bool writethrough, bool quiet,
342 QDict *options = NULL;
344 options = qdict_new();
345 qemu_opt_foreach(create_opts, img_add_key_secrets, options, &error_abort);
347 return img_open_file(filename, options, fmt, flags, writethrough, quiet,
352 static BlockBackend *img_open(bool image_opts,
353 const char *filename,
354 const char *fmt, int flags, bool writethrough,
355 bool quiet, bool force_share)
361 error_report("--image-opts and --format are mutually exclusive");
364 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
369 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
372 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
379 static int add_old_style_options(const char *fmt, QemuOpts *opts,
380 const char *base_filename,
381 const char *base_fmt)
386 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
388 error_report("Backing file not supported for file format '%s'",
395 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
397 error_report("Backing file format not supported for file "
406 static int64_t cvtnum(const char *s)
411 err = qemu_strtosz(s, NULL, &value);
415 if (value > INT64_MAX) {
421 static int img_create(int argc, char **argv)
424 uint64_t img_size = -1;
425 const char *fmt = "raw";
426 const char *base_fmt = NULL;
427 const char *filename;
428 const char *base_filename = NULL;
429 char *options = NULL;
430 Error *local_err = NULL;
434 static const struct option long_options[] = {
435 {"help", no_argument, 0, 'h'},
436 {"object", required_argument, 0, OPTION_OBJECT},
439 c = getopt_long(argc, argv, ":F:b:f:ho:q",
446 missing_argument(argv[optind - 1]);
449 unrecognized_option(argv[optind - 1]);
458 base_filename = optarg;
464 if (!is_valid_option_list(optarg)) {
465 error_report("Invalid option list: %s", optarg);
469 options = g_strdup(optarg);
471 char *old_options = options;
472 options = g_strdup_printf("%s,%s", options, optarg);
479 case OPTION_OBJECT: {
481 opts = qemu_opts_parse_noisily(&qemu_object_opts,
490 /* Get the filename */
491 filename = (optind < argc) ? argv[optind] : NULL;
492 if (options && has_help_option(options)) {
494 return print_block_option_help(filename, fmt);
497 if (optind >= argc) {
498 error_exit("Expecting image file name");
502 if (qemu_opts_foreach(&qemu_object_opts,
503 user_creatable_add_opts_foreach,
508 /* Get image size, if specified */
512 sval = cvtnum(argv[optind++]);
514 if (sval == -ERANGE) {
515 error_report("Image size must be less than 8 EiB!");
517 error_report("Invalid image size specified! You may use k, M, "
518 "G, T, P or E suffixes for ");
519 error_report("kilobytes, megabytes, gigabytes, terabytes, "
520 "petabytes and exabytes.");
524 img_size = (uint64_t)sval;
526 if (optind != argc) {
527 error_exit("Unexpected argument: %s", argv[optind]);
530 bdrv_img_create(filename, fmt, base_filename, base_fmt,
531 options, img_size, 0, quiet, &local_err);
533 error_reportf_err(local_err, "%s: ", filename);
545 static void dump_json_image_check(ImageCheck *check, bool quiet)
549 Visitor *v = qobject_output_visitor_new(&obj);
551 visit_type_ImageCheck(v, NULL, &check, &error_abort);
552 visit_complete(v, &obj);
553 str = qobject_to_json_pretty(obj);
555 qprintf(quiet, "%s\n", qstring_get_str(str));
561 static void dump_human_image_check(ImageCheck *check, bool quiet)
563 if (!(check->corruptions || check->leaks || check->check_errors)) {
564 qprintf(quiet, "No errors were found on the image.\n");
566 if (check->corruptions) {
567 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
568 "Data may be corrupted, or further writes to the image "
575 "\n%" PRId64 " leaked clusters were found on the image.\n"
576 "This means waste of disk space, but no harm to data.\n",
580 if (check->check_errors) {
583 " internal errors have occurred during the check.\n",
584 check->check_errors);
588 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
589 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
590 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
591 check->allocated_clusters, check->total_clusters,
592 check->allocated_clusters * 100.0 / check->total_clusters,
593 check->fragmented_clusters * 100.0 / check->allocated_clusters,
594 check->compressed_clusters * 100.0 /
595 check->allocated_clusters);
598 if (check->image_end_offset) {
600 "Image end offset: %" PRId64 "\n", check->image_end_offset);
604 static int collect_image_check(BlockDriverState *bs,
606 const char *filename,
611 BdrvCheckResult result;
613 ret = bdrv_check(bs, &result, fix);
618 check->filename = g_strdup(filename);
619 check->format = g_strdup(bdrv_get_format_name(bs));
620 check->check_errors = result.check_errors;
621 check->corruptions = result.corruptions;
622 check->has_corruptions = result.corruptions != 0;
623 check->leaks = result.leaks;
624 check->has_leaks = result.leaks != 0;
625 check->corruptions_fixed = result.corruptions_fixed;
626 check->has_corruptions_fixed = result.corruptions != 0;
627 check->leaks_fixed = result.leaks_fixed;
628 check->has_leaks_fixed = result.leaks != 0;
629 check->image_end_offset = result.image_end_offset;
630 check->has_image_end_offset = result.image_end_offset != 0;
631 check->total_clusters = result.bfi.total_clusters;
632 check->has_total_clusters = result.bfi.total_clusters != 0;
633 check->allocated_clusters = result.bfi.allocated_clusters;
634 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
635 check->fragmented_clusters = result.bfi.fragmented_clusters;
636 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
637 check->compressed_clusters = result.bfi.compressed_clusters;
638 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
644 * Checks an image for consistency. Exit codes:
646 * 0 - Check completed, image is good
647 * 1 - Check not completed because of internal errors
648 * 2 - Check completed, image is corrupted
649 * 3 - Check completed, image has leaked clusters, but is good otherwise
650 * 63 - Checks are not supported by the image format
652 static int img_check(int argc, char **argv)
655 OutputFormat output_format = OFORMAT_HUMAN;
656 const char *filename, *fmt, *output, *cache;
658 BlockDriverState *bs;
660 int flags = BDRV_O_CHECK;
664 bool image_opts = false;
665 bool force_share = false;
669 cache = BDRV_DEFAULT_CACHE;
672 int option_index = 0;
673 static const struct option long_options[] = {
674 {"help", no_argument, 0, 'h'},
675 {"format", required_argument, 0, 'f'},
676 {"repair", required_argument, 0, 'r'},
677 {"output", required_argument, 0, OPTION_OUTPUT},
678 {"object", required_argument, 0, OPTION_OBJECT},
679 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
680 {"force-share", no_argument, 0, 'U'},
683 c = getopt_long(argc, argv, ":hf:r:T:qU",
684 long_options, &option_index);
690 missing_argument(argv[optind - 1]);
693 unrecognized_option(argv[optind - 1]);
702 flags |= BDRV_O_RDWR;
704 if (!strcmp(optarg, "leaks")) {
705 fix = BDRV_FIX_LEAKS;
706 } else if (!strcmp(optarg, "all")) {
707 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
709 error_exit("Unknown option value for -r "
710 "(expecting 'leaks' or 'all'): %s", optarg);
725 case OPTION_OBJECT: {
727 opts = qemu_opts_parse_noisily(&qemu_object_opts,
733 case OPTION_IMAGE_OPTS:
738 if (optind != argc - 1) {
739 error_exit("Expecting one image file name");
741 filename = argv[optind++];
743 if (output && !strcmp(output, "json")) {
744 output_format = OFORMAT_JSON;
745 } else if (output && !strcmp(output, "human")) {
746 output_format = OFORMAT_HUMAN;
748 error_report("--output must be used with human or json as argument.");
752 if (qemu_opts_foreach(&qemu_object_opts,
753 user_creatable_add_opts_foreach,
758 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
760 error_report("Invalid source cache option: %s", cache);
764 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
771 check = g_new0(ImageCheck, 1);
772 ret = collect_image_check(bs, check, filename, fmt, fix);
774 if (ret == -ENOTSUP) {
775 error_report("This image format does not support checks");
780 if (check->corruptions_fixed || check->leaks_fixed) {
781 int corruptions_fixed, leaks_fixed;
783 leaks_fixed = check->leaks_fixed;
784 corruptions_fixed = check->corruptions_fixed;
786 if (output_format == OFORMAT_HUMAN) {
788 "The following inconsistencies were found and repaired:\n\n"
789 " %" PRId64 " leaked clusters\n"
790 " %" PRId64 " corruptions\n\n"
791 "Double checking the fixed image now...\n",
793 check->corruptions_fixed);
796 ret = collect_image_check(bs, check, filename, fmt, 0);
798 check->leaks_fixed = leaks_fixed;
799 check->corruptions_fixed = corruptions_fixed;
803 switch (output_format) {
805 dump_human_image_check(check, quiet);
808 dump_json_image_check(check, quiet);
813 if (ret || check->check_errors) {
815 error_report("Check failed: %s", strerror(-ret));
817 error_report("Check failed");
823 if (check->corruptions) {
825 } else if (check->leaks) {
832 qapi_free_ImageCheck(check);
837 typedef struct CommonBlockJobCBInfo {
838 BlockDriverState *bs;
840 } CommonBlockJobCBInfo;
842 static void common_block_job_cb(void *opaque, int ret)
844 CommonBlockJobCBInfo *cbi = opaque;
847 error_setg_errno(cbi->errp, -ret, "Block job failed");
851 static void run_block_job(BlockJob *job, Error **errp)
853 AioContext *aio_context = blk_get_aio_context(job->blk);
856 aio_context_acquire(aio_context);
859 aio_poll(aio_context, true);
860 qemu_progress_print(job->len ?
861 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
862 } while (!job->ready && !job->completed);
864 if (!job->completed) {
865 ret = block_job_complete_sync(job, errp);
869 block_job_unref(job);
870 aio_context_release(aio_context);
872 /* publish completion progress only when success */
874 qemu_progress_print(100.f, 0);
878 static int img_commit(int argc, char **argv)
881 const char *filename, *fmt, *cache, *base;
883 BlockDriverState *bs, *base_bs;
885 bool progress = false, quiet = false, drop = false;
887 Error *local_err = NULL;
888 CommonBlockJobCBInfo cbi;
889 bool image_opts = false;
890 AioContext *aio_context;
893 cache = BDRV_DEFAULT_CACHE;
896 static const struct option long_options[] = {
897 {"help", no_argument, 0, 'h'},
898 {"object", required_argument, 0, OPTION_OBJECT},
899 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
902 c = getopt_long(argc, argv, ":f:ht:b:dpq",
909 missing_argument(argv[optind - 1]);
912 unrecognized_option(argv[optind - 1]);
937 case OPTION_OBJECT: {
939 opts = qemu_opts_parse_noisily(&qemu_object_opts,
945 case OPTION_IMAGE_OPTS:
951 /* Progress is not shown in Quiet mode */
956 if (optind != argc - 1) {
957 error_exit("Expecting one image file name");
959 filename = argv[optind++];
961 if (qemu_opts_foreach(&qemu_object_opts,
962 user_creatable_add_opts_foreach,
967 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
968 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
970 error_report("Invalid cache option: %s", cache);
974 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
981 qemu_progress_init(progress, 1.f);
982 qemu_progress_print(0.f, 100);
985 base_bs = bdrv_find_backing_image(bs, base);
987 error_setg(&local_err,
988 "Did not find '%s' in the backing chain of '%s'",
993 /* This is different from QMP, which by default uses the deepest file in
994 * the backing chain (i.e., the very base); however, the traditional
995 * behavior of qemu-img commit is using the immediate backing file. */
996 base_bs = backing_bs(bs);
998 error_setg(&local_err, "Image does not have a backing file");
1003 cbi = (CommonBlockJobCBInfo){
1008 aio_context = bdrv_get_aio_context(bs);
1009 aio_context_acquire(aio_context);
1010 commit_active_start("commit", bs, base_bs, BLOCK_JOB_DEFAULT, 0,
1011 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1012 &cbi, false, &local_err);
1013 aio_context_release(aio_context);
1018 /* When the block job completes, the BlockBackend reference will point to
1019 * the old backing file. In order to avoid that the top image is already
1020 * deleted, so we can still empty it afterwards, increment the reference
1021 * counter here preemptively. */
1026 job = block_job_get("commit");
1027 run_block_job(job, &local_err);
1032 if (!drop && bs->drv->bdrv_make_empty) {
1033 ret = bs->drv->bdrv_make_empty(bs);
1035 error_setg_errno(&local_err, -ret, "Could not empty %s",
1047 qemu_progress_end();
1052 error_report_err(local_err);
1056 qprintf(quiet, "Image committed.\n");
1061 * Returns true iff the first sector pointed to by 'buf' contains at least
1064 * 'pnum' is set to the number of sectors (including and immediately following
1065 * the first one) that are known to be in the same allocated/unallocated state.
1067 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
1076 is_zero = buffer_is_zero(buf, 512);
1077 for(i = 1; i < n; i++) {
1079 if (is_zero != buffer_is_zero(buf, 512)) {
1088 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1089 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1090 * breaking up write requests for only small sparse areas.
1092 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1096 int num_checked, num_used;
1102 ret = is_allocated_sectors(buf, n, pnum);
1108 buf += BDRV_SECTOR_SIZE * *pnum;
1110 num_checked = num_used;
1113 ret = is_allocated_sectors(buf, n, pnum);
1115 buf += BDRV_SECTOR_SIZE * *pnum;
1117 num_checked += *pnum;
1119 num_used = num_checked;
1120 } else if (*pnum >= min) {
1130 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1131 * buffers matches, non-zero otherwise.
1133 * pnum is set to the number of sectors (including and immediately following
1134 * the first one) that are known to have the same comparison result
1136 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1147 res = !!memcmp(buf1, buf2, 512);
1148 for(i = 1; i < n; i++) {
1152 if (!!memcmp(buf1, buf2, 512) != res) {
1161 #define IO_BUF_SIZE (2 * 1024 * 1024)
1163 static int64_t sectors_to_bytes(int64_t sectors)
1165 return sectors << BDRV_SECTOR_BITS;
1168 static int64_t sectors_to_process(int64_t total, int64_t from)
1170 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1174 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1176 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1177 * data and negative value on error.
1179 * @param blk: BlockBackend for the image
1180 * @param sect_num: Number of first sector to check
1181 * @param sect_count: Number of sectors to check
1182 * @param filename: Name of disk file we are checking (logging purpose)
1183 * @param buffer: Allocated buffer for storing read data
1184 * @param quiet: Flag for quiet mode
1186 static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
1187 int sect_count, const char *filename,
1188 uint8_t *buffer, bool quiet)
1191 ret = blk_pread(blk, sect_num << BDRV_SECTOR_BITS, buffer,
1192 sect_count << BDRV_SECTOR_BITS);
1194 error_report("Error while reading offset %" PRId64 " of %s: %s",
1195 sectors_to_bytes(sect_num), filename, strerror(-ret));
1198 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1199 if (ret || pnum != sect_count) {
1200 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1201 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1209 * Compares two images. Exit codes:
1211 * 0 - Images are identical
1213 * >1 - Error occurred
1215 static int img_compare(int argc, char **argv)
1217 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1218 BlockBackend *blk1, *blk2;
1219 BlockDriverState *bs1, *bs2;
1220 int64_t total_sectors1, total_sectors2;
1221 uint8_t *buf1 = NULL, *buf2 = NULL;
1223 int allocated1, allocated2;
1224 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1225 bool progress = false, quiet = false, strict = false;
1228 int64_t total_sectors;
1229 int64_t sector_num = 0;
1232 uint64_t progress_base;
1233 bool image_opts = false;
1234 bool force_share = false;
1236 cache = BDRV_DEFAULT_CACHE;
1238 static const struct option long_options[] = {
1239 {"help", no_argument, 0, 'h'},
1240 {"object", required_argument, 0, OPTION_OBJECT},
1241 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1242 {"force-share", no_argument, 0, 'U'},
1245 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1246 long_options, NULL);
1252 missing_argument(argv[optind - 1]);
1255 unrecognized_option(argv[optind - 1]);
1281 case OPTION_OBJECT: {
1283 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1290 case OPTION_IMAGE_OPTS:
1296 /* Progress is not shown in Quiet mode */
1302 if (optind != argc - 2) {
1303 error_exit("Expecting two image file names");
1305 filename1 = argv[optind++];
1306 filename2 = argv[optind++];
1308 if (qemu_opts_foreach(&qemu_object_opts,
1309 user_creatable_add_opts_foreach,
1315 /* Initialize before goto out */
1316 qemu_progress_init(progress, 2.0);
1319 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1321 error_report("Invalid source cache option: %s", cache);
1326 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1333 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1342 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1343 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1344 total_sectors1 = blk_nb_sectors(blk1);
1345 if (total_sectors1 < 0) {
1346 error_report("Can't get size of %s: %s",
1347 filename1, strerror(-total_sectors1));
1351 total_sectors2 = blk_nb_sectors(blk2);
1352 if (total_sectors2 < 0) {
1353 error_report("Can't get size of %s: %s",
1354 filename2, strerror(-total_sectors2));
1358 total_sectors = MIN(total_sectors1, total_sectors2);
1359 progress_base = MAX(total_sectors1, total_sectors2);
1361 qemu_progress_print(0, 100);
1363 if (strict && total_sectors1 != total_sectors2) {
1365 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1370 int64_t status1, status2;
1371 BlockDriverState *file;
1373 nb_sectors = sectors_to_process(total_sectors, sector_num);
1374 if (nb_sectors <= 0) {
1377 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1378 total_sectors1 - sector_num,
1382 error_report("Sector allocation test failed for %s", filename1);
1385 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1387 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1388 total_sectors2 - sector_num,
1392 error_report("Sector allocation test failed for %s", filename2);
1395 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1397 nb_sectors = MIN(nb_sectors, pnum1);
1400 nb_sectors = MIN(nb_sectors, pnum2);
1404 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1405 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1407 qprintf(quiet, "Strict mode: Offset %" PRId64
1408 " block status mismatch!\n",
1409 sectors_to_bytes(sector_num));
1413 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1414 nb_sectors = MIN(pnum1, pnum2);
1415 } else if (allocated1 == allocated2) {
1417 ret = blk_pread(blk1, sector_num << BDRV_SECTOR_BITS, buf1,
1418 nb_sectors << BDRV_SECTOR_BITS);
1420 error_report("Error while reading offset %" PRId64 " of %s:"
1421 " %s", sectors_to_bytes(sector_num), filename1,
1426 ret = blk_pread(blk2, sector_num << BDRV_SECTOR_BITS, buf2,
1427 nb_sectors << BDRV_SECTOR_BITS);
1429 error_report("Error while reading offset %" PRId64
1430 " of %s: %s", sectors_to_bytes(sector_num),
1431 filename2, strerror(-ret));
1435 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1436 if (ret || pnum != nb_sectors) {
1437 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1439 ret ? sector_num : sector_num + pnum));
1447 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
1448 filename1, buf1, quiet);
1450 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
1451 filename2, buf1, quiet);
1455 error_report("Error while reading offset %" PRId64 ": %s",
1456 sectors_to_bytes(sector_num), strerror(-ret));
1462 sector_num += nb_sectors;
1463 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1466 if (total_sectors1 != total_sectors2) {
1467 BlockBackend *blk_over;
1468 int64_t total_sectors_over;
1469 const char *filename_over;
1471 qprintf(quiet, "Warning: Image size mismatch!\n");
1472 if (total_sectors1 > total_sectors2) {
1473 total_sectors_over = total_sectors1;
1475 filename_over = filename1;
1477 total_sectors_over = total_sectors2;
1479 filename_over = filename2;
1485 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1486 if (nb_sectors <= 0) {
1489 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL,
1490 sector_num * BDRV_SECTOR_SIZE,
1491 nb_sectors * BDRV_SECTOR_SIZE,
1495 error_report("Sector allocation test failed for %s",
1500 /* TODO relax this once bdrv_is_allocated_above does not enforce
1501 * sector alignment */
1502 assert(QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE));
1503 nb_sectors = count >> BDRV_SECTOR_BITS;
1505 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
1506 filename_over, buf1, quiet);
1509 error_report("Error while reading offset %" PRId64
1510 " of %s: %s", sectors_to_bytes(sector_num),
1511 filename_over, strerror(-ret));
1517 sector_num += nb_sectors;
1518 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1522 qprintf(quiet, "Images are identical.\n");
1532 qemu_progress_end();
1537 enum ImgConvertBlockStatus {
1543 #define MAX_COROUTINES 16
1545 typedef struct ImgConvertState {
1547 int64_t *src_sectors;
1549 int64_t total_sectors;
1550 int64_t allocated_sectors;
1551 int64_t allocated_done;
1554 enum ImgConvertBlockStatus status;
1555 int64_t sector_next_status;
1556 BlockBackend *target;
1559 bool target_has_backing;
1562 size_t cluster_sectors;
1564 long num_coroutines;
1565 int running_coroutines;
1566 Coroutine *co[MAX_COROUTINES];
1567 int64_t wait_sector_num[MAX_COROUTINES];
1572 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1573 int *src_cur, int64_t *src_cur_offset)
1576 *src_cur_offset = 0;
1577 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1578 *src_cur_offset += s->src_sectors[*src_cur];
1580 assert(*src_cur < s->src_num);
1584 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1586 int64_t ret, src_cur_offset;
1589 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1591 assert(s->total_sectors > sector_num);
1592 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1594 if (s->sector_next_status <= sector_num) {
1595 BlockDriverState *file;
1596 if (s->target_has_backing) {
1597 ret = bdrv_get_block_status(blk_bs(s->src[src_cur]),
1598 sector_num - src_cur_offset,
1601 ret = bdrv_get_block_status_above(blk_bs(s->src[src_cur]), NULL,
1602 sector_num - src_cur_offset,
1609 if (ret & BDRV_BLOCK_ZERO) {
1610 s->status = BLK_ZERO;
1611 } else if (ret & BDRV_BLOCK_DATA) {
1612 s->status = BLK_DATA;
1614 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1617 s->sector_next_status = sector_num + n;
1620 n = MIN(n, s->sector_next_status - sector_num);
1621 if (s->status == BLK_DATA) {
1622 n = MIN(n, s->buf_sectors);
1625 /* We need to write complete clusters for compressed images, so if an
1626 * unallocated area is shorter than that, we must consider the whole
1627 * cluster allocated. */
1628 if (s->compressed) {
1629 if (n < s->cluster_sectors) {
1630 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1631 s->status = BLK_DATA;
1633 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1640 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1641 int nb_sectors, uint8_t *buf)
1647 assert(nb_sectors <= s->buf_sectors);
1648 while (nb_sectors > 0) {
1651 int64_t bs_sectors, src_cur_offset;
1653 /* In the case of compression with multiple source files, we can get a
1654 * nb_sectors that spreads into the next part. So we must be able to
1655 * read across multiple BDSes for one convert_read() call. */
1656 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1657 blk = s->src[src_cur];
1658 bs_sectors = s->src_sectors[src_cur];
1660 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1662 iov.iov_len = n << BDRV_SECTOR_BITS;
1663 qemu_iovec_init_external(&qiov, &iov, 1);
1665 ret = blk_co_preadv(
1666 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1667 n << BDRV_SECTOR_BITS, &qiov, 0);
1674 buf += n * BDRV_SECTOR_SIZE;
1681 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1682 int nb_sectors, uint8_t *buf,
1683 enum ImgConvertBlockStatus status)
1689 while (nb_sectors > 0) {
1691 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1694 case BLK_BACKING_FILE:
1695 /* If we have a backing file, leave clusters unallocated that are
1696 * unallocated in the source image, so that the backing file is
1697 * visible at the respective offset. */
1698 assert(s->target_has_backing);
1702 /* If we're told to keep the target fully allocated (-S 0) or there
1703 * is real non-zero data, we must write it. Otherwise we can treat
1704 * it as zero sectors.
1705 * Compressed clusters need to be written as a whole, so in that
1706 * case we can only save the write if the buffer is completely
1708 if (!s->min_sparse ||
1710 is_allocated_sectors_min(buf, n, &n, s->min_sparse)) ||
1712 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1715 iov.iov_len = n << BDRV_SECTOR_BITS;
1716 qemu_iovec_init_external(&qiov, &iov, 1);
1718 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
1719 n << BDRV_SECTOR_BITS, &qiov, flags);
1728 if (s->has_zero_init) {
1729 assert(!s->target_has_backing);
1732 ret = blk_co_pwrite_zeroes(s->target,
1733 sector_num << BDRV_SECTOR_BITS,
1734 n << BDRV_SECTOR_BITS, 0);
1743 buf += n * BDRV_SECTOR_SIZE;
1749 static void coroutine_fn convert_co_do_copy(void *opaque)
1751 ImgConvertState *s = opaque;
1752 uint8_t *buf = NULL;
1756 for (i = 0; i < s->num_coroutines; i++) {
1757 if (s->co[i] == qemu_coroutine_self()) {
1764 s->running_coroutines++;
1765 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1770 enum ImgConvertBlockStatus status;
1772 qemu_co_mutex_lock(&s->lock);
1773 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1774 qemu_co_mutex_unlock(&s->lock);
1777 n = convert_iteration_sectors(s, s->sector_num);
1779 qemu_co_mutex_unlock(&s->lock);
1783 /* save current sector and allocation status to local variables */
1784 sector_num = s->sector_num;
1786 if (!s->min_sparse && s->status == BLK_ZERO) {
1787 n = MIN(n, s->buf_sectors);
1789 /* increment global sector counter so that other coroutines can
1790 * already continue reading beyond this request */
1792 qemu_co_mutex_unlock(&s->lock);
1794 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1795 s->allocated_done += n;
1796 qemu_progress_print(100.0 * s->allocated_done /
1797 s->allocated_sectors, 0);
1800 if (status == BLK_DATA) {
1801 ret = convert_co_read(s, sector_num, n, buf);
1803 error_report("error while reading sector %" PRId64
1804 ": %s", sector_num, strerror(-ret));
1807 } else if (!s->min_sparse && status == BLK_ZERO) {
1809 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1812 if (s->wr_in_order) {
1813 /* keep writes in order */
1814 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
1815 s->wait_sector_num[index] = sector_num;
1816 qemu_coroutine_yield();
1818 s->wait_sector_num[index] = -1;
1821 if (s->ret == -EINPROGRESS) {
1822 ret = convert_co_write(s, sector_num, n, buf, status);
1824 error_report("error while writing sector %" PRId64
1825 ": %s", sector_num, strerror(-ret));
1830 if (s->wr_in_order) {
1831 /* reenter the coroutine that might have waited
1832 * for this write to complete */
1833 s->wr_offs = sector_num + n;
1834 for (i = 0; i < s->num_coroutines; i++) {
1835 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1837 * A -> B -> A cannot occur because A has
1838 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1839 * B will never enter A during this time window.
1841 qemu_coroutine_enter(s->co[i]);
1849 s->co[index] = NULL;
1850 s->running_coroutines--;
1851 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1852 /* the convert job finished successfully */
1857 static int convert_do_copy(ImgConvertState *s)
1860 int64_t sector_num = 0;
1862 /* Check whether we have zero initialisation or can get it efficiently */
1863 s->has_zero_init = s->min_sparse && !s->target_has_backing
1864 ? bdrv_has_zero_init(blk_bs(s->target))
1867 if (!s->has_zero_init && !s->target_has_backing &&
1868 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1870 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
1872 s->has_zero_init = true;
1876 /* Allocate buffer for copied data. For compressed images, only one cluster
1877 * can be copied at a time. */
1878 if (s->compressed) {
1879 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1880 error_report("invalid cluster size");
1883 s->buf_sectors = s->cluster_sectors;
1886 while (sector_num < s->total_sectors) {
1887 n = convert_iteration_sectors(s, sector_num);
1891 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1893 s->allocated_sectors += n;
1899 s->sector_next_status = 0;
1900 s->ret = -EINPROGRESS;
1902 qemu_co_mutex_init(&s->lock);
1903 for (i = 0; i < s->num_coroutines; i++) {
1904 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1905 s->wait_sector_num[i] = -1;
1906 qemu_coroutine_enter(s->co[i]);
1909 while (s->running_coroutines) {
1910 main_loop_wait(false);
1913 if (s->compressed && !s->ret) {
1914 /* signal EOF to align */
1915 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
1924 static int img_convert(int argc, char **argv)
1926 int c, bs_i, flags, src_flags = 0;
1927 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
1928 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
1929 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
1930 BlockDriver *drv = NULL, *proto_drv = NULL;
1931 BlockDriverInfo bdi;
1932 BlockDriverState *out_bs;
1933 QemuOpts *opts = NULL, *sn_opts = NULL;
1934 QemuOptsList *create_opts = NULL;
1935 char *options = NULL;
1936 Error *local_err = NULL;
1937 bool writethrough, src_writethrough, quiet = false, image_opts = false,
1938 skip_create = false, progress = false, tgt_image_opts = false;
1939 int64_t ret = -EINVAL;
1940 bool force_share = false;
1942 ImgConvertState s = (ImgConvertState) {
1943 /* Need at least 4k of zeros for sparse detection */
1945 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
1946 .wr_in_order = true,
1947 .num_coroutines = 8,
1951 static const struct option long_options[] = {
1952 {"help", no_argument, 0, 'h'},
1953 {"object", required_argument, 0, OPTION_OBJECT},
1954 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1955 {"force-share", no_argument, 0, 'U'},
1956 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
1959 c = getopt_long(argc, argv, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
1960 long_options, NULL);
1966 missing_argument(argv[optind - 1]);
1969 unrecognized_option(argv[optind - 1]);
1981 out_baseimg = optarg;
1984 s.compressed = true;
1987 if (!is_valid_option_list(optarg)) {
1988 error_report("Invalid option list: %s", optarg);
1992 options = g_strdup(optarg);
1994 char *old_options = options;
1995 options = g_strdup_printf("%s,%s", options, optarg);
1996 g_free(old_options);
2000 snapshot_name = optarg;
2003 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2004 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2007 error_report("Failed in parsing snapshot param '%s'",
2012 snapshot_name = optarg;
2019 sval = cvtnum(optarg);
2021 error_report("Invalid minimum zero buffer size for sparse output specified");
2025 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2044 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2045 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2046 error_report("Invalid number of coroutines. Allowed number of"
2047 " coroutines is between 1 and %d", MAX_COROUTINES);
2052 s.wr_in_order = false;
2057 case OPTION_OBJECT: {
2058 QemuOpts *object_opts;
2059 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2066 case OPTION_IMAGE_OPTS:
2069 case OPTION_TARGET_IMAGE_OPTS:
2070 tgt_image_opts = true;
2075 if (!out_fmt && !tgt_image_opts) {
2079 if (qemu_opts_foreach(&qemu_object_opts,
2080 user_creatable_add_opts_foreach,
2085 if (!s.wr_in_order && s.compressed) {
2086 error_report("Out of order write and compress are mutually exclusive");
2090 if (tgt_image_opts && !skip_create) {
2091 error_report("--target-image-opts requires use of -n flag");
2095 s.src_num = argc - optind - 1;
2096 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2098 if (options && has_help_option(options)) {
2100 ret = print_block_option_help(out_filename, out_fmt);
2103 error_report("Option help requires a format be specified");
2108 if (s.src_num < 1) {
2109 error_report("Must specify image file name");
2114 /* ret is still -EINVAL until here */
2115 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2117 error_report("Invalid source cache option: %s", src_cache);
2121 /* Initialize before goto out */
2125 qemu_progress_init(progress, 1.0);
2126 qemu_progress_print(0, 100);
2128 s.src = g_new0(BlockBackend *, s.src_num);
2129 s.src_sectors = g_new(int64_t, s.src_num);
2131 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2132 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2133 fmt, src_flags, src_writethrough, quiet,
2139 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2140 if (s.src_sectors[bs_i] < 0) {
2141 error_report("Could not get size of %s: %s",
2142 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2146 s.total_sectors += s.src_sectors[bs_i];
2150 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2151 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2152 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2154 } else if (snapshot_name != NULL) {
2155 if (s.src_num > 1) {
2156 error_report("No support for concatenating multiple snapshot");
2161 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2165 error_reportf_err(local_err, "Failed to load snapshot: ");
2171 /* Find driver and parse its options */
2172 drv = bdrv_find_format(out_fmt);
2174 error_report("Unknown file format '%s'", out_fmt);
2179 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2181 error_report_err(local_err);
2186 if (!drv->create_opts) {
2187 error_report("Format driver '%s' does not support image creation",
2193 if (!proto_drv->create_opts) {
2194 error_report("Protocol driver '%s' does not support image creation",
2195 proto_drv->format_name);
2200 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2201 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2203 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2205 qemu_opts_do_parse(opts, options, NULL, &local_err);
2207 error_report_err(local_err);
2213 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2215 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2221 /* Get backing file name if -o backing_file was used */
2222 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2223 if (out_baseimg_param) {
2224 out_baseimg = out_baseimg_param;
2226 s.target_has_backing = (bool) out_baseimg;
2228 if (s.src_num > 1 && out_baseimg) {
2229 error_report("Having a backing file for the target makes no sense when "
2230 "concatenating multiple input images");
2235 /* Check if compression is supported */
2238 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2239 const char *encryptfmt =
2240 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2241 const char *preallocation =
2242 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2244 if (drv && !drv->bdrv_co_pwritev_compressed) {
2245 error_report("Compression not supported for this file format");
2250 if (encryption || encryptfmt) {
2251 error_report("Compression and encryption not supported at "
2258 && strcmp(preallocation, "off"))
2260 error_report("Compression and preallocation not supported at "
2268 /* Create the new image */
2269 ret = bdrv_create(drv, out_filename, opts, &local_err);
2271 error_reportf_err(local_err, "%s: error while converting %s: ",
2272 out_filename, out_fmt);
2277 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2278 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2280 error_report("Invalid cache option: %s", cache);
2285 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2286 flags, writethrough, quiet, false);
2288 /* TODO ultimately we should allow --target-image-opts
2289 * to be used even when -n is not given.
2290 * That has to wait for bdrv_create to be improved
2291 * to allow filenames in option syntax
2293 s.target = img_open_new_file(out_filename, opts, out_fmt,
2294 flags, writethrough, quiet, false);
2300 out_bs = blk_bs(s.target);
2302 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2303 error_report("Compression not supported for this file format");
2308 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2309 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2311 s.buf_sectors = MIN(32768,
2313 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2314 out_bs->bl.pdiscard_alignment >>
2315 BDRV_SECTOR_BITS)));
2318 int64_t output_sectors = blk_nb_sectors(s.target);
2319 if (output_sectors < 0) {
2320 error_report("unable to get output image length: %s",
2321 strerror(-output_sectors));
2324 } else if (output_sectors < s.total_sectors) {
2325 error_report("output file is smaller than input file");
2331 ret = bdrv_get_info(out_bs, &bdi);
2334 error_report("could not get block driver info");
2338 s.compressed = s.compressed || bdi.needs_compressed_writes;
2339 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2342 ret = convert_do_copy(&s);
2345 qemu_progress_print(100, 0);
2347 qemu_progress_end();
2348 qemu_opts_del(opts);
2349 qemu_opts_free(create_opts);
2350 qemu_opts_del(sn_opts);
2351 blk_unref(s.target);
2353 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2354 blk_unref(s.src[bs_i]);
2358 g_free(s.src_sectors);
2366 static void dump_snapshots(BlockDriverState *bs)
2368 QEMUSnapshotInfo *sn_tab, *sn;
2371 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2374 printf("Snapshot list:\n");
2375 bdrv_snapshot_dump(fprintf, stdout, NULL);
2377 for(i = 0; i < nb_sns; i++) {
2379 bdrv_snapshot_dump(fprintf, stdout, sn);
2385 static void dump_json_image_info_list(ImageInfoList *list)
2389 Visitor *v = qobject_output_visitor_new(&obj);
2391 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2392 visit_complete(v, &obj);
2393 str = qobject_to_json_pretty(obj);
2394 assert(str != NULL);
2395 printf("%s\n", qstring_get_str(str));
2396 qobject_decref(obj);
2401 static void dump_json_image_info(ImageInfo *info)
2405 Visitor *v = qobject_output_visitor_new(&obj);
2407 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2408 visit_complete(v, &obj);
2409 str = qobject_to_json_pretty(obj);
2410 assert(str != NULL);
2411 printf("%s\n", qstring_get_str(str));
2412 qobject_decref(obj);
2417 static void dump_human_image_info_list(ImageInfoList *list)
2419 ImageInfoList *elem;
2422 for (elem = list; elem; elem = elem->next) {
2428 bdrv_image_info_dump(fprintf, stdout, elem->value);
2432 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2434 return strcmp(a, b) == 0;
2438 * Open an image file chain and return an ImageInfoList
2440 * @filename: topmost image filename
2441 * @fmt: topmost image format (may be NULL to autodetect)
2442 * @chain: true - enumerate entire backing file chain
2443 * false - only topmost image file
2445 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2446 * image file. If there was an error a message will have been printed to
2449 static ImageInfoList *collect_image_info_list(bool image_opts,
2450 const char *filename,
2452 bool chain, bool force_share)
2454 ImageInfoList *head = NULL;
2455 ImageInfoList **last = &head;
2456 GHashTable *filenames;
2459 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2463 BlockDriverState *bs;
2465 ImageInfoList *elem;
2467 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2468 error_report("Backing file '%s' creates an infinite loop.",
2472 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2474 blk = img_open(image_opts, filename, fmt,
2475 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2482 bdrv_query_image_info(bs, &info, &err);
2484 error_report_err(err);
2489 elem = g_new0(ImageInfoList, 1);
2496 filename = fmt = NULL;
2498 if (info->has_full_backing_filename) {
2499 filename = info->full_backing_filename;
2500 } else if (info->has_backing_filename) {
2501 error_report("Could not determine absolute backing filename,"
2502 " but backing filename '%s' present",
2503 info->backing_filename);
2506 if (info->has_backing_filename_format) {
2507 fmt = info->backing_filename_format;
2511 g_hash_table_destroy(filenames);
2515 qapi_free_ImageInfoList(head);
2516 g_hash_table_destroy(filenames);
2520 static int img_info(int argc, char **argv)
2523 OutputFormat output_format = OFORMAT_HUMAN;
2525 const char *filename, *fmt, *output;
2526 ImageInfoList *list;
2527 bool image_opts = false;
2528 bool force_share = false;
2533 int option_index = 0;
2534 static const struct option long_options[] = {
2535 {"help", no_argument, 0, 'h'},
2536 {"format", required_argument, 0, 'f'},
2537 {"output", required_argument, 0, OPTION_OUTPUT},
2538 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2539 {"object", required_argument, 0, OPTION_OBJECT},
2540 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2541 {"force-share", no_argument, 0, 'U'},
2544 c = getopt_long(argc, argv, ":f:hU",
2545 long_options, &option_index);
2551 missing_argument(argv[optind - 1]);
2554 unrecognized_option(argv[optind - 1]);
2568 case OPTION_BACKING_CHAIN:
2571 case OPTION_OBJECT: {
2573 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2579 case OPTION_IMAGE_OPTS:
2584 if (optind != argc - 1) {
2585 error_exit("Expecting one image file name");
2587 filename = argv[optind++];
2589 if (output && !strcmp(output, "json")) {
2590 output_format = OFORMAT_JSON;
2591 } else if (output && !strcmp(output, "human")) {
2592 output_format = OFORMAT_HUMAN;
2593 } else if (output) {
2594 error_report("--output must be used with human or json as argument.");
2598 if (qemu_opts_foreach(&qemu_object_opts,
2599 user_creatable_add_opts_foreach,
2604 list = collect_image_info_list(image_opts, filename, fmt, chain,
2610 switch (output_format) {
2612 dump_human_image_info_list(list);
2616 dump_json_image_info_list(list);
2618 dump_json_image_info(list->value);
2623 qapi_free_ImageInfoList(list);
2627 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2630 switch (output_format) {
2632 if (e->data && !e->has_offset) {
2633 error_report("File contains external, encrypted or compressed clusters.");
2636 if (e->data && !e->zero) {
2637 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2638 e->start, e->length,
2639 e->has_offset ? e->offset : 0,
2640 e->has_filename ? e->filename : "");
2642 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2643 * Modify the flags here to allow more coalescing.
2645 if (next && (!next->data || next->zero)) {
2651 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2652 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2653 (e->start == 0 ? "[" : ",\n"),
2654 e->start, e->length, e->depth,
2655 e->zero ? "true" : "false",
2656 e->data ? "true" : "false");
2657 if (e->has_offset) {
2658 printf(", \"offset\": %"PRId64"", e->offset);
2669 static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2670 int nb_sectors, MapEntry *e)
2674 BlockDriverState *file;
2677 /* As an optimization, we could cache the current range of unallocated
2678 * clusters in each file of the chain, and avoid querying the same
2684 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2690 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2693 bs = backing_bs(bs);
2702 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2705 .start = sector_num * BDRV_SECTOR_SIZE,
2706 .length = nb_sectors * BDRV_SECTOR_SIZE,
2707 .data = !!(ret & BDRV_BLOCK_DATA),
2708 .zero = !!(ret & BDRV_BLOCK_ZERO),
2709 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2710 .has_offset = has_offset,
2712 .has_filename = file && has_offset,
2713 .filename = file && has_offset ? file->filename : NULL,
2719 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2721 if (curr->length == 0) {
2724 if (curr->zero != next->zero ||
2725 curr->data != next->data ||
2726 curr->depth != next->depth ||
2727 curr->has_filename != next->has_filename ||
2728 curr->has_offset != next->has_offset) {
2731 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2734 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2740 static int img_map(int argc, char **argv)
2743 OutputFormat output_format = OFORMAT_HUMAN;
2745 BlockDriverState *bs;
2746 const char *filename, *fmt, *output;
2748 MapEntry curr = { .length = 0 }, next;
2750 bool image_opts = false;
2751 bool force_share = false;
2756 int option_index = 0;
2757 static const struct option long_options[] = {
2758 {"help", no_argument, 0, 'h'},
2759 {"format", required_argument, 0, 'f'},
2760 {"output", required_argument, 0, OPTION_OUTPUT},
2761 {"object", required_argument, 0, OPTION_OBJECT},
2762 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2763 {"force-share", no_argument, 0, 'U'},
2766 c = getopt_long(argc, argv, ":f:hU",
2767 long_options, &option_index);
2773 missing_argument(argv[optind - 1]);
2776 unrecognized_option(argv[optind - 1]);
2790 case OPTION_OBJECT: {
2792 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2798 case OPTION_IMAGE_OPTS:
2803 if (optind != argc - 1) {
2804 error_exit("Expecting one image file name");
2806 filename = argv[optind];
2808 if (output && !strcmp(output, "json")) {
2809 output_format = OFORMAT_JSON;
2810 } else if (output && !strcmp(output, "human")) {
2811 output_format = OFORMAT_HUMAN;
2812 } else if (output) {
2813 error_report("--output must be used with human or json as argument.");
2817 if (qemu_opts_foreach(&qemu_object_opts,
2818 user_creatable_add_opts_foreach,
2823 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
2829 if (output_format == OFORMAT_HUMAN) {
2830 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2833 length = blk_getlength(blk);
2834 while (curr.start + curr.length < length) {
2835 int64_t nsectors_left;
2839 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2841 /* Probe up to 1 GiB at a time. */
2842 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2843 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2844 ret = get_block_status(bs, sector_num, n, &next);
2847 error_report("Could not read file metadata: %s", strerror(-ret));
2851 if (entry_mergeable(&curr, &next)) {
2852 curr.length += next.length;
2856 if (curr.length > 0) {
2857 dump_map_entry(output_format, &curr, &next);
2862 dump_map_entry(output_format, &curr, NULL);
2869 #define SNAPSHOT_LIST 1
2870 #define SNAPSHOT_CREATE 2
2871 #define SNAPSHOT_APPLY 3
2872 #define SNAPSHOT_DELETE 4
2874 static int img_snapshot(int argc, char **argv)
2877 BlockDriverState *bs;
2878 QEMUSnapshotInfo sn;
2879 char *filename, *snapshot_name = NULL;
2880 int c, ret = 0, bdrv_oflags;
2885 bool image_opts = false;
2886 bool force_share = false;
2888 bdrv_oflags = BDRV_O_RDWR;
2889 /* Parse commandline parameters */
2891 static const struct option long_options[] = {
2892 {"help", no_argument, 0, 'h'},
2893 {"object", required_argument, 0, OPTION_OBJECT},
2894 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2895 {"force-share", no_argument, 0, 'U'},
2898 c = getopt_long(argc, argv, ":la:c:d:hqU",
2899 long_options, NULL);
2905 missing_argument(argv[optind - 1]);
2908 unrecognized_option(argv[optind - 1]);
2915 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2918 action = SNAPSHOT_LIST;
2919 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
2923 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2926 action = SNAPSHOT_APPLY;
2927 snapshot_name = optarg;
2931 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2934 action = SNAPSHOT_CREATE;
2935 snapshot_name = optarg;
2939 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2942 action = SNAPSHOT_DELETE;
2943 snapshot_name = optarg;
2951 case OPTION_OBJECT: {
2953 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2959 case OPTION_IMAGE_OPTS:
2965 if (optind != argc - 1) {
2966 error_exit("Expecting one image file name");
2968 filename = argv[optind++];
2970 if (qemu_opts_foreach(&qemu_object_opts,
2971 user_creatable_add_opts_foreach,
2976 /* Open the image */
2977 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
2984 /* Perform the requested action */
2990 case SNAPSHOT_CREATE:
2991 memset(&sn, 0, sizeof(sn));
2992 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2994 qemu_gettimeofday(&tv);
2995 sn.date_sec = tv.tv_sec;
2996 sn.date_nsec = tv.tv_usec * 1000;
2998 ret = bdrv_snapshot_create(bs, &sn);
3000 error_report("Could not create snapshot '%s': %d (%s)",
3001 snapshot_name, ret, strerror(-ret));
3005 case SNAPSHOT_APPLY:
3006 ret = bdrv_snapshot_goto(bs, snapshot_name);
3008 error_report("Could not apply snapshot '%s': %d (%s)",
3009 snapshot_name, ret, strerror(-ret));
3013 case SNAPSHOT_DELETE:
3014 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
3016 error_reportf_err(err, "Could not delete snapshot '%s': ",
3031 static int img_rebase(int argc, char **argv)
3033 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3034 uint8_t *buf_old = NULL;
3035 uint8_t *buf_new = NULL;
3036 BlockDriverState *bs = NULL;
3038 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3039 int c, flags, src_flags, ret;
3040 bool writethrough, src_writethrough;
3042 bool force_share = false;
3045 Error *local_err = NULL;
3046 bool image_opts = false;
3048 /* Parse commandline parameters */
3050 cache = BDRV_DEFAULT_CACHE;
3051 src_cache = BDRV_DEFAULT_CACHE;
3055 static const struct option long_options[] = {
3056 {"help", no_argument, 0, 'h'},
3057 {"object", required_argument, 0, OPTION_OBJECT},
3058 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3059 {"force-share", no_argument, 0, 'U'},
3062 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3063 long_options, NULL);
3069 missing_argument(argv[optind - 1]);
3072 unrecognized_option(argv[optind - 1]);
3081 out_basefmt = optarg;
3084 out_baseimg = optarg;
3101 case OPTION_OBJECT: {
3103 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3109 case OPTION_IMAGE_OPTS:
3122 if (optind != argc - 1) {
3123 error_exit("Expecting one image file name");
3125 if (!unsafe && !out_baseimg) {
3126 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3128 filename = argv[optind++];
3130 if (qemu_opts_foreach(&qemu_object_opts,
3131 user_creatable_add_opts_foreach,
3136 qemu_progress_init(progress, 2.0);
3137 qemu_progress_print(0, 100);
3139 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3140 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3142 error_report("Invalid cache option: %s", cache);
3147 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3149 error_report("Invalid source cache option: %s", src_cache);
3153 /* The source files are opened read-only, don't care about WCE */
3154 assert((src_flags & BDRV_O_RDWR) == 0);
3155 (void) src_writethrough;
3160 * Ignore the old backing file for unsafe rebase in case we want to correct
3161 * the reference to a renamed or moved backing file.
3163 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3171 if (out_basefmt != NULL) {
3172 if (bdrv_find_format(out_basefmt) == NULL) {
3173 error_report("Invalid format name: '%s'", out_basefmt);
3179 /* For safe rebasing we need to compare old and new backing file */
3181 char backing_name[PATH_MAX];
3182 QDict *options = NULL;
3184 if (bs->backing_format[0] != '\0') {
3185 options = qdict_new();
3186 qdict_put_str(options, "driver", bs->backing_format);
3191 options = qdict_new();
3193 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3195 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3196 blk_old_backing = blk_new_open(backing_name, NULL,
3197 options, src_flags, &local_err);
3198 if (!blk_old_backing) {
3199 error_reportf_err(local_err,
3200 "Could not open old backing file '%s': ",
3206 if (out_baseimg[0]) {
3207 options = qdict_new();
3209 qdict_put_str(options, "driver", out_basefmt);
3212 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3215 blk_new_backing = blk_new_open(out_baseimg, NULL,
3216 options, src_flags, &local_err);
3217 if (!blk_new_backing) {
3218 error_reportf_err(local_err,
3219 "Could not open new backing file '%s': ",
3228 * Check each unallocated cluster in the COW file. If it is unallocated,
3229 * accesses go to the backing file. We must therefore compare this cluster
3230 * in the old and new backing file, and if they differ we need to copy it
3231 * from the old backing file into the COW file.
3233 * If qemu-img crashes during this step, no harm is done. The content of
3234 * the image is the same as the original one at any time.
3237 int64_t num_sectors;
3238 int64_t old_backing_num_sectors;
3239 int64_t new_backing_num_sectors = 0;
3243 float local_progress = 0;
3245 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3246 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3248 num_sectors = blk_nb_sectors(blk);
3249 if (num_sectors < 0) {
3250 error_report("Could not get size of '%s': %s",
3251 filename, strerror(-num_sectors));
3255 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
3256 if (old_backing_num_sectors < 0) {
3257 char backing_name[PATH_MAX];
3259 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3260 error_report("Could not get size of '%s': %s",
3261 backing_name, strerror(-old_backing_num_sectors));
3265 if (blk_new_backing) {
3266 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
3267 if (new_backing_num_sectors < 0) {
3268 error_report("Could not get size of '%s': %s",
3269 out_baseimg, strerror(-new_backing_num_sectors));
3275 if (num_sectors != 0) {
3276 local_progress = (float)100 /
3277 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3280 for (sector = 0; sector < num_sectors; sector += n) {
3282 /* How many sectors can we handle with the next read? */
3283 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3284 n = (IO_BUF_SIZE / 512);
3286 n = num_sectors - sector;
3289 /* If the cluster is allocated, we don't need to take action */
3290 ret = bdrv_is_allocated(bs, sector << BDRV_SECTOR_BITS,
3291 n << BDRV_SECTOR_BITS, &count);
3293 error_report("error while reading image metadata: %s",
3297 /* TODO relax this once bdrv_is_allocated does not enforce
3298 * sector alignment */
3299 assert(QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE));
3300 n = count >> BDRV_SECTOR_BITS;
3306 * Read old and new backing file and take into consideration that
3307 * backing files may be smaller than the COW image.
3309 if (sector >= old_backing_num_sectors) {
3310 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3312 if (sector + n > old_backing_num_sectors) {
3313 n = old_backing_num_sectors - sector;
3316 ret = blk_pread(blk_old_backing, sector << BDRV_SECTOR_BITS,
3317 buf_old, n << BDRV_SECTOR_BITS);
3319 error_report("error while reading from old backing file");
3324 if (sector >= new_backing_num_sectors || !blk_new_backing) {
3325 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3327 if (sector + n > new_backing_num_sectors) {
3328 n = new_backing_num_sectors - sector;
3331 ret = blk_pread(blk_new_backing, sector << BDRV_SECTOR_BITS,
3332 buf_new, n << BDRV_SECTOR_BITS);
3334 error_report("error while reading from new backing file");
3339 /* If they differ, we need to write to the COW file */
3340 uint64_t written = 0;
3342 while (written < n) {
3345 if (compare_sectors(buf_old + written * 512,
3346 buf_new + written * 512, n - written, &pnum))
3348 ret = blk_pwrite(blk,
3349 (sector + written) << BDRV_SECTOR_BITS,
3350 buf_old + written * 512,
3351 pnum << BDRV_SECTOR_BITS, 0);
3353 error_report("Error while writing to COW image: %s",
3361 qemu_progress_print(local_progress, 100);
3366 * Change the backing file. All clusters that are different from the old
3367 * backing file are overwritten in the COW file now, so the visible content
3368 * doesn't change when we switch the backing file.
3370 if (out_baseimg && *out_baseimg) {
3371 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3373 ret = bdrv_change_backing_file(bs, NULL, NULL);
3376 if (ret == -ENOSPC) {
3377 error_report("Could not change the backing file to '%s': No "
3378 "space left in the file header", out_baseimg);
3379 } else if (ret < 0) {
3380 error_report("Could not change the backing file to '%s': %s",
3381 out_baseimg, strerror(-ret));
3384 qemu_progress_print(100, 0);
3386 * TODO At this point it is possible to check if any clusters that are
3387 * allocated in the COW file are the same in the backing file. If so, they
3388 * could be dropped from the COW file. Don't do this before switching the
3389 * backing file, in case of a crash this would lead to corruption.
3392 qemu_progress_end();
3395 blk_unref(blk_old_backing);
3396 blk_unref(blk_new_backing);
3398 qemu_vfree(buf_old);
3399 qemu_vfree(buf_new);
3408 static int img_resize(int argc, char **argv)
3411 int c, ret, relative;
3412 const char *filename, *fmt, *size;
3413 int64_t n, total_size, current_size;
3415 BlockBackend *blk = NULL;
3416 PreallocMode prealloc = PREALLOC_MODE_OFF;
3419 static QemuOptsList resize_options = {
3420 .name = "resize_options",
3421 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3424 .name = BLOCK_OPT_SIZE,
3425 .type = QEMU_OPT_SIZE,
3426 .help = "Virtual disk size"
3432 bool image_opts = false;
3434 /* Remove size from argv manually so that negative numbers are not treated
3435 * as options by getopt. */
3437 error_exit("Not enough arguments");
3441 size = argv[--argc];
3443 /* Parse getopt arguments */
3446 static const struct option long_options[] = {
3447 {"help", no_argument, 0, 'h'},
3448 {"object", required_argument, 0, OPTION_OBJECT},
3449 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3450 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3453 c = getopt_long(argc, argv, ":f:hq",
3454 long_options, NULL);
3460 missing_argument(argv[optind - 1]);
3463 unrecognized_option(argv[optind - 1]);
3474 case OPTION_OBJECT: {
3476 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3482 case OPTION_IMAGE_OPTS:
3485 case OPTION_PREALLOCATION:
3486 prealloc = qapi_enum_parse(PreallocMode_lookup, optarg,
3487 PREALLOC_MODE__MAX, PREALLOC_MODE__MAX,
3489 if (prealloc == PREALLOC_MODE__MAX) {
3490 error_report("Invalid preallocation mode '%s'", optarg);
3496 if (optind != argc - 1) {
3497 error_exit("Expecting one image file name");
3499 filename = argv[optind++];
3501 if (qemu_opts_foreach(&qemu_object_opts,
3502 user_creatable_add_opts_foreach,
3507 /* Choose grow, shrink, or absolute resize mode */
3523 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3524 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3526 error_report_err(err);
3528 qemu_opts_del(param);
3531 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3532 qemu_opts_del(param);
3534 blk = img_open(image_opts, filename, fmt,
3535 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3542 current_size = blk_getlength(blk);
3543 if (current_size < 0) {
3544 error_report("Failed to inquire current image length: %s",
3545 strerror(-current_size));
3551 total_size = current_size + n * relative;
3555 if (total_size <= 0) {
3556 error_report("New image size must be positive");
3561 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3562 error_report("Preallocation can only be used for growing images");
3567 ret = blk_truncate(blk, total_size, prealloc, &err);
3569 qprintf(quiet, "Image resized.\n");
3571 error_report_err(err);
3581 static void amend_status_cb(BlockDriverState *bs,
3582 int64_t offset, int64_t total_work_size,
3585 qemu_progress_print(100.f * offset / total_work_size, 0);
3588 static int img_amend(int argc, char **argv)
3592 char *options = NULL;
3593 QemuOptsList *create_opts = NULL;
3594 QemuOpts *opts = NULL;
3595 const char *fmt = NULL, *filename, *cache;
3598 bool quiet = false, progress = false;
3599 BlockBackend *blk = NULL;
3600 BlockDriverState *bs = NULL;
3601 bool image_opts = false;
3603 cache = BDRV_DEFAULT_CACHE;
3605 static const struct option long_options[] = {
3606 {"help", no_argument, 0, 'h'},
3607 {"object", required_argument, 0, OPTION_OBJECT},
3608 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3611 c = getopt_long(argc, argv, ":ho:f:t:pq",
3612 long_options, NULL);
3619 missing_argument(argv[optind - 1]);
3622 unrecognized_option(argv[optind - 1]);
3628 if (!is_valid_option_list(optarg)) {
3629 error_report("Invalid option list: %s", optarg);
3631 goto out_no_progress;
3634 options = g_strdup(optarg);
3636 char *old_options = options;
3637 options = g_strdup_printf("%s,%s", options, optarg);
3638 g_free(old_options);
3654 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3658 goto out_no_progress;
3661 case OPTION_IMAGE_OPTS:
3668 error_exit("Must specify options (-o)");
3671 if (qemu_opts_foreach(&qemu_object_opts,
3672 user_creatable_add_opts_foreach,
3675 goto out_no_progress;
3681 qemu_progress_init(progress, 1.0);
3683 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3684 if (fmt && has_help_option(options)) {
3685 /* If a format is explicitly specified (and possibly no filename is
3686 * given), print option help here */
3687 ret = print_block_option_help(filename, fmt);
3691 if (optind != argc - 1) {
3692 error_report("Expecting one image file name");
3697 flags = BDRV_O_RDWR;
3698 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3700 error_report("Invalid cache option: %s", cache);
3704 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3712 fmt = bs->drv->format_name;
3714 if (has_help_option(options)) {
3715 /* If the format was auto-detected, print option help here */
3716 ret = print_block_option_help(filename, fmt);
3720 if (!bs->drv->create_opts) {
3721 error_report("Format driver '%s' does not support any options to amend",
3727 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
3728 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3729 qemu_opts_do_parse(opts, options, NULL, &err);
3731 error_report_err(err);
3736 /* In case the driver does not call amend_status_cb() */
3737 qemu_progress_print(0.f, 0);
3738 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
3739 qemu_progress_print(100.f, 0);
3741 error_report("Error while amending options: %s", strerror(-ret));
3746 qemu_progress_end();
3750 qemu_opts_del(opts);
3751 qemu_opts_free(create_opts);
3760 typedef struct BenchData {
3762 uint64_t image_size;
3769 bool drain_on_flush;
3778 static void bench_undrained_flush_cb(void *opaque, int ret)
3781 error_report("Failed flush request: %s", strerror(-ret));
3786 static void bench_cb(void *opaque, int ret)
3788 BenchData *b = opaque;
3792 error_report("Failed request: %s", strerror(-ret));
3797 /* Just finished a flush with drained queue: Start next requests */
3798 assert(b->in_flight == 0);
3799 b->in_flush = false;
3800 } else if (b->in_flight > 0) {
3801 int remaining = b->n - b->in_flight;
3806 /* Time for flush? Drain queue if requested, then flush */
3807 if (b->flush_interval && remaining % b->flush_interval == 0) {
3808 if (!b->in_flight || !b->drain_on_flush) {
3809 BlockCompletionFunc *cb;
3811 if (b->drain_on_flush) {
3815 cb = bench_undrained_flush_cb;
3818 acb = blk_aio_flush(b->blk, cb, b);
3820 error_report("Failed to issue flush request");
3824 if (b->drain_on_flush) {
3830 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
3831 int64_t offset = b->offset;
3832 /* blk_aio_* might look for completed I/Os and kick bench_cb
3833 * again, so make sure this operation is counted by in_flight
3834 * and b->offset is ready for the next submission.
3837 b->offset += b->step;
3838 b->offset %= b->image_size;
3840 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
3842 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
3845 error_report("Failed to issue request");
3851 static int img_bench(int argc, char **argv)
3854 const char *fmt = NULL, *filename;
3856 bool image_opts = false;
3857 bool is_write = false;
3861 size_t bufsize = 4096;
3864 int flush_interval = 0;
3865 bool drain_on_flush = true;
3867 BlockBackend *blk = NULL;
3868 BenchData data = {};
3870 bool writethrough = false;
3871 struct timeval t1, t2;
3873 bool force_share = false;
3876 static const struct option long_options[] = {
3877 {"help", no_argument, 0, 'h'},
3878 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
3879 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3880 {"pattern", required_argument, 0, OPTION_PATTERN},
3881 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
3882 {"force-share", no_argument, 0, 'U'},
3885 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
3892 missing_argument(argv[optind - 1]);
3895 unrecognized_option(argv[optind - 1]);
3904 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
3905 error_report("Invalid request count specified");
3915 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
3916 error_report("Invalid queue depth specified");
3926 flags |= BDRV_O_NATIVE_AIO;
3930 offset = cvtnum(optarg);
3932 error_report("Invalid offset specified");
3945 sval = cvtnum(optarg);
3946 if (sval < 0 || sval > INT_MAX) {
3947 error_report("Invalid buffer size specified");
3958 sval = cvtnum(optarg);
3959 if (sval < 0 || sval > INT_MAX) {
3960 error_report("Invalid step size specified");
3968 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
3970 error_report("Invalid cache mode");
3976 flags |= BDRV_O_RDWR;
3982 case OPTION_PATTERN:
3986 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
3987 error_report("Invalid pattern byte specified");
3993 case OPTION_FLUSH_INTERVAL:
3997 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
3998 error_report("Invalid flush interval specified");
4001 flush_interval = res;
4004 case OPTION_NO_DRAIN:
4005 drain_on_flush = false;
4007 case OPTION_IMAGE_OPTS:
4013 if (optind != argc - 1) {
4014 error_exit("Expecting one image file name");
4016 filename = argv[argc - 1];
4018 if (!is_write && flush_interval) {
4019 error_report("--flush-interval is only available in write tests");
4023 if (flush_interval && flush_interval < depth) {
4024 error_report("Flush interval can't be smaller than depth");
4029 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4036 image_size = blk_getlength(blk);
4037 if (image_size < 0) {
4042 data = (BenchData) {
4044 .image_size = image_size,
4046 .step = step ?: bufsize,
4051 .flush_interval = flush_interval,
4052 .drain_on_flush = drain_on_flush,
4054 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4055 "(starting at offset %" PRId64 ", step size %d)\n",
4056 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4057 data.offset, data.step);
4058 if (flush_interval) {
4059 printf("Sending flush every %d requests\n", flush_interval);
4062 data.buf = blk_blockalign(blk, data.nrreq * data.bufsize);
4063 memset(data.buf, pattern, data.nrreq * data.bufsize);
4065 data.qiov = g_new(QEMUIOVector, data.nrreq);
4066 for (i = 0; i < data.nrreq; i++) {
4067 qemu_iovec_init(&data.qiov[i], 1);
4068 qemu_iovec_add(&data.qiov[i],
4069 data.buf + i * data.bufsize, data.bufsize);
4072 gettimeofday(&t1, NULL);
4075 while (data.n > 0) {
4076 main_loop_wait(false);
4078 gettimeofday(&t2, NULL);
4080 printf("Run completed in %3.3f seconds.\n",
4081 (t2.tv_sec - t1.tv_sec)
4082 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4085 qemu_vfree(data.buf);
4106 int bsz; /* Block size */
4114 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4118 static int img_dd_bs(const char *arg,
4119 struct DdIo *in, struct DdIo *out,
4126 if (res <= 0 || res > INT_MAX) {
4127 error_report("invalid number: '%s'", arg);
4130 in->bsz = out->bsz = res;
4135 static int img_dd_count(const char *arg,
4136 struct DdIo *in, struct DdIo *out,
4139 dd->count = cvtnum(arg);
4141 if (dd->count < 0) {
4142 error_report("invalid number: '%s'", arg);
4149 static int img_dd_if(const char *arg,
4150 struct DdIo *in, struct DdIo *out,
4153 in->filename = g_strdup(arg);
4158 static int img_dd_of(const char *arg,
4159 struct DdIo *in, struct DdIo *out,
4162 out->filename = g_strdup(arg);
4167 static int img_dd_skip(const char *arg,
4168 struct DdIo *in, struct DdIo *out,
4171 in->offset = cvtnum(arg);
4173 if (in->offset < 0) {
4174 error_report("invalid number: '%s'", arg);
4181 static int img_dd(int argc, char **argv)
4186 BlockDriver *drv = NULL, *proto_drv = NULL;
4187 BlockBackend *blk1 = NULL, *blk2 = NULL;
4188 QemuOpts *opts = NULL;
4189 QemuOptsList *create_opts = NULL;
4190 Error *local_err = NULL;
4191 bool image_opts = false;
4193 const char *out_fmt = "raw";
4194 const char *fmt = NULL;
4196 int64_t block_count = 0, out_pos, in_pos;
4197 bool force_share = false;
4198 struct DdInfo dd = {
4203 .bsz = 512, /* Block size is by default 512 bytes */
4215 const struct DdOpts options[] = {
4216 { "bs", img_dd_bs, C_BS },
4217 { "count", img_dd_count, C_COUNT },
4218 { "if", img_dd_if, C_IF },
4219 { "of", img_dd_of, C_OF },
4220 { "skip", img_dd_skip, C_SKIP },
4223 const struct option long_options[] = {
4224 { "help", no_argument, 0, 'h'},
4225 { "object", required_argument, 0, OPTION_OBJECT},
4226 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4227 { "force-share", no_argument, 0, 'U'},
4231 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4243 missing_argument(argv[optind - 1]);
4246 unrecognized_option(argv[optind - 1]);
4255 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4260 case OPTION_IMAGE_OPTS:
4266 for (i = optind; i < argc; i++) {
4268 arg = g_strdup(argv[i]);
4270 tmp = strchr(arg, '=');
4272 error_report("unrecognized operand %s", arg);
4279 for (j = 0; options[j].name != NULL; j++) {
4280 if (!strcmp(arg, options[j].name)) {
4284 if (options[j].name == NULL) {
4285 error_report("unrecognized operand %s", arg);
4290 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4294 dd.flags |= options[j].flag;
4299 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4300 error_report("Must specify both input and output files");
4305 if (qemu_opts_foreach(&qemu_object_opts,
4306 user_creatable_add_opts_foreach,
4312 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4320 drv = bdrv_find_format(out_fmt);
4322 error_report("Unknown file format");
4326 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4329 error_report_err(local_err);
4333 if (!drv->create_opts) {
4334 error_report("Format driver '%s' does not support image creation",
4339 if (!proto_drv->create_opts) {
4340 error_report("Protocol driver '%s' does not support image creation",
4341 proto_drv->format_name);
4345 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4346 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4348 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4350 size = blk_getlength(blk1);
4352 error_report("Failed to get size for '%s'", in.filename);
4357 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4358 dd.count * in.bsz < size) {
4359 size = dd.count * in.bsz;
4362 /* Overflow means the specified offset is beyond input image's size */
4363 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4364 size < in.bsz * in.offset)) {
4365 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4367 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4368 size - in.bsz * in.offset, &error_abort);
4371 ret = bdrv_create(drv, out.filename, opts, &local_err);
4373 error_reportf_err(local_err,
4374 "%s: error while creating output image: ",
4380 /* TODO, we can't honour --image-opts for the target,
4381 * since it needs to be given in a format compatible
4382 * with the bdrv_create() call above which does not
4383 * support image-opts style.
4385 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
4386 false, false, false);
4393 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4394 size < in.offset * in.bsz)) {
4395 /* We give a warning if the skip option is bigger than the input
4396 * size and create an empty output disk image (i.e. like dd(1)).
4398 error_report("%s: cannot skip to specified offset", in.filename);
4401 in_pos = in.offset * in.bsz;
4404 in.buf = g_new(uint8_t, in.bsz);
4406 for (out_pos = 0; in_pos < size; block_count++) {
4407 int in_ret, out_ret;
4409 if (in_pos + in.bsz > size) {
4410 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4412 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4415 error_report("error while reading from input image file: %s",
4422 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4425 error_report("error while writing to output image file: %s",
4426 strerror(-out_ret));
4435 qemu_opts_del(opts);
4436 qemu_opts_free(create_opts);
4439 g_free(in.filename);
4440 g_free(out.filename);
4450 static void dump_json_block_measure_info(BlockMeasureInfo *info)
4454 Visitor *v = qobject_output_visitor_new(&obj);
4456 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4457 visit_complete(v, &obj);
4458 str = qobject_to_json_pretty(obj);
4459 assert(str != NULL);
4460 printf("%s\n", qstring_get_str(str));
4461 qobject_decref(obj);
4466 static int img_measure(int argc, char **argv)
4468 static const struct option long_options[] = {
4469 {"help", no_argument, 0, 'h'},
4470 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4471 {"object", required_argument, 0, OPTION_OBJECT},
4472 {"output", required_argument, 0, OPTION_OUTPUT},
4473 {"size", required_argument, 0, OPTION_SIZE},
4474 {"force-share", no_argument, 0, 'U'},
4477 OutputFormat output_format = OFORMAT_HUMAN;
4478 BlockBackend *in_blk = NULL;
4480 const char *filename = NULL;
4481 const char *fmt = NULL;
4482 const char *out_fmt = "raw";
4483 char *options = NULL;
4484 char *snapshot_name = NULL;
4485 bool force_share = false;
4486 QemuOpts *opts = NULL;
4487 QemuOpts *object_opts = NULL;
4488 QemuOpts *sn_opts = NULL;
4489 QemuOptsList *create_opts = NULL;
4490 bool image_opts = false;
4491 uint64_t img_size = UINT64_MAX;
4492 BlockMeasureInfo *info = NULL;
4493 Error *local_err = NULL;
4497 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4498 long_options, NULL)) != -1) {
4511 if (!is_valid_option_list(optarg)) {
4512 error_report("Invalid option list: %s", optarg);
4516 options = g_strdup(optarg);
4518 char *old_options = options;
4519 options = g_strdup_printf("%s,%s", options, optarg);
4520 g_free(old_options);
4524 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4525 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4528 error_report("Failed in parsing snapshot param '%s'",
4533 snapshot_name = optarg;
4540 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4546 case OPTION_IMAGE_OPTS:
4550 if (!strcmp(optarg, "json")) {
4551 output_format = OFORMAT_JSON;
4552 } else if (!strcmp(optarg, "human")) {
4553 output_format = OFORMAT_HUMAN;
4555 error_report("--output must be used with human or json "
4564 sval = cvtnum(optarg);
4566 if (sval == -ERANGE) {
4567 error_report("Image size must be less than 8 EiB!");
4569 error_report("Invalid image size specified! You may use "
4570 "k, M, G, T, P or E suffixes for ");
4571 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4572 "petabytes and exabytes.");
4576 img_size = (uint64_t)sval;
4582 if (qemu_opts_foreach(&qemu_object_opts,
4583 user_creatable_add_opts_foreach,
4588 if (argc - optind > 1) {
4589 error_report("At most one filename argument is allowed.");
4591 } else if (argc - optind == 1) {
4592 filename = argv[optind];
4596 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4597 error_report("--object, --image-opts, -f, and -l "
4598 "require a filename argument.");
4601 if (filename && img_size != UINT64_MAX) {
4602 error_report("--size N cannot be used together with a filename.");
4605 if (!filename && img_size == UINT64_MAX) {
4606 error_report("Either --size N or one filename must be specified.");
4611 in_blk = img_open(image_opts, filename, fmt, 0,
4612 false, false, force_share);
4618 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4619 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4620 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4622 } else if (snapshot_name != NULL) {
4623 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4624 snapshot_name, &local_err);
4627 error_reportf_err(local_err, "Failed to load snapshot: ");
4632 drv = bdrv_find_format(out_fmt);
4634 error_report("Unknown file format '%s'", out_fmt);
4637 if (!drv->create_opts) {
4638 error_report("Format driver '%s' does not support image creation",
4643 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4644 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4645 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4647 qemu_opts_do_parse(opts, options, NULL, &local_err);
4649 error_report_err(local_err);
4650 error_report("Invalid options for file format '%s'", out_fmt);
4654 if (img_size != UINT64_MAX) {
4655 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4658 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4660 error_report_err(local_err);
4664 if (output_format == OFORMAT_HUMAN) {
4665 printf("required size: %" PRIu64 "\n", info->required);
4666 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4668 dump_json_block_measure_info(info);
4674 qapi_free_BlockMeasureInfo(info);
4675 qemu_opts_del(object_opts);
4676 qemu_opts_del(opts);
4677 qemu_opts_del(sn_opts);
4678 qemu_opts_free(create_opts);
4684 static const img_cmd_t img_cmds[] = {
4685 #define DEF(option, callback, arg_string) \
4686 { option, callback },
4687 #include "qemu-img-cmds.h"
4693 int main(int argc, char **argv)
4695 const img_cmd_t *cmd;
4696 const char *cmdname;
4697 Error *local_error = NULL;
4698 char *trace_file = NULL;
4700 static const struct option long_options[] = {
4701 {"help", no_argument, 0, 'h'},
4702 {"version", no_argument, 0, 'V'},
4703 {"trace", required_argument, NULL, 'T'},
4708 signal(SIGPIPE, SIG_IGN);
4711 module_call_init(MODULE_INIT_TRACE);
4712 error_set_progname(argv[0]);
4713 qemu_init_exec_dir(argv[0]);
4715 if (qemu_init_main_loop(&local_error)) {
4716 error_report_err(local_error);
4720 qcrypto_init(&error_fatal);
4722 module_call_init(MODULE_INIT_QOM);
4725 error_exit("Not enough arguments");
4728 qemu_add_opts(&qemu_object_opts);
4729 qemu_add_opts(&qemu_source_opts);
4730 qemu_add_opts(&qemu_trace_opts);
4732 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
4735 missing_argument(argv[optind - 1]);
4738 unrecognized_option(argv[optind - 1]);
4744 printf(QEMU_IMG_VERSION);
4748 trace_file = trace_opt_parse(optarg);
4753 cmdname = argv[optind];
4755 /* reset getopt_long scanning */
4763 if (!trace_init_backends()) {
4766 trace_init_file(trace_file);
4767 qemu_set_log(LOG_TRACE);
4769 /* find the command */
4770 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4771 if (!strcmp(cmdname, cmd->name)) {
4772 return cmd->handler(argc, argv);
4777 error_exit("Command not found: %s", cmdname);