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 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
153 " '-c' indicates that target image must be compressed (qcow format only)\n"
154 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
155 " new backing file match exactly. The image doesn't need a working\n"
156 " backing file before rebasing in this case (useful for renaming the\n"
157 " backing file). For image creation, allow creating without attempting\n"
158 " to open the backing file.\n"
159 " '-h' with or without a command shows this help and lists the supported formats\n"
160 " '-p' show progress of command (only certain commands)\n"
161 " '-q' use Quiet mode - do not print any output (except errors)\n"
162 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
163 " contain only zeros for qemu-img to create a sparse image during\n"
164 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
165 " unallocated or zero sectors, and the destination image will always be\n"
167 " '--output' takes the format in which the output must be done (human or json)\n"
168 " '-n' skips the target volume creation (useful if the volume is created\n"
169 " prior to running qemu-img)\n"
171 "Parameters to check subcommand:\n"
172 " '-r' tries to repair any inconsistencies that are found during the check.\n"
173 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
174 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
175 " hiding corruption that has already occurred.\n"
177 "Parameters to convert subcommand:\n"
178 " '-m' specifies how many coroutines work in parallel during the convert\n"
179 " process (defaults to 8)\n"
180 " '-W' allow to write to the target out of order rather than sequential\n"
182 "Parameters to snapshot subcommand:\n"
183 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
184 " '-a' applies a snapshot (revert disk to saved state)\n"
185 " '-c' creates a snapshot\n"
186 " '-d' deletes a snapshot\n"
187 " '-l' lists all snapshots in the given image\n"
189 "Parameters to compare subcommand:\n"
190 " '-f' first image format\n"
191 " '-F' second image format\n"
192 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
194 "Parameters to dd subcommand:\n"
195 " 'bs=BYTES' read and write up to BYTES bytes at a time "
197 " 'count=N' copy only N input blocks\n"
198 " 'if=FILE' read from FILE\n"
199 " 'of=FILE' write to FILE\n"
200 " 'skip=N' skip N bs-sized blocks at the start of input\n";
202 printf("%s\nSupported formats:", help_msg);
203 bdrv_iterate_format(format_print, NULL);
204 printf("\n\n" QEMU_HELP_BOTTOM "\n");
208 static QemuOptsList qemu_object_opts = {
210 .implied_opt_name = "qom-type",
211 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
217 static QemuOptsList qemu_source_opts = {
219 .implied_opt_name = "file",
220 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
226 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
232 ret = vprintf(fmt, args);
239 static int print_block_option_help(const char *filename, const char *fmt)
241 BlockDriver *drv, *proto_drv;
242 QemuOptsList *create_opts = NULL;
243 Error *local_err = NULL;
245 /* Find driver and parse its options */
246 drv = bdrv_find_format(fmt);
248 error_report("Unknown file format '%s'", fmt);
252 create_opts = qemu_opts_append(create_opts, drv->create_opts);
254 proto_drv = bdrv_find_protocol(filename, true, &local_err);
256 error_report_err(local_err);
257 qemu_opts_free(create_opts);
260 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
263 printf("Supported options:\n");
264 qemu_opts_print_help(create_opts);
265 qemu_opts_free(create_opts);
270 static BlockBackend *img_open_opts(const char *optstr,
271 QemuOpts *opts, int flags, bool writethrough,
272 bool quiet, bool force_share)
275 Error *local_err = NULL;
277 options = qemu_opts_to_qdict(opts, NULL);
279 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
280 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
281 error_report("--force-share/-U conflicts with image options");
282 qobject_unref(options);
285 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
287 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
289 error_reportf_err(local_err, "Could not open '%s': ", optstr);
292 blk_set_enable_write_cache(blk, !writethrough);
297 static BlockBackend *img_open_file(const char *filename,
299 const char *fmt, int flags,
300 bool writethrough, bool quiet,
304 Error *local_err = NULL;
307 options = qdict_new();
310 qdict_put_str(options, "driver", fmt);
314 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
316 blk = blk_new_open(filename, NULL, options, flags, &local_err);
318 error_reportf_err(local_err, "Could not open '%s': ", filename);
321 blk_set_enable_write_cache(blk, !writethrough);
327 static int img_add_key_secrets(void *opaque,
328 const char *name, const char *value,
331 QDict *options = opaque;
333 if (g_str_has_suffix(name, "key-secret")) {
334 qdict_put_str(options, name, value);
340 static BlockBackend *img_open_new_file(const char *filename,
341 QemuOpts *create_opts,
342 const char *fmt, int flags,
343 bool writethrough, bool quiet,
346 QDict *options = NULL;
348 options = qdict_new();
349 qemu_opt_foreach(create_opts, img_add_key_secrets, options, &error_abort);
351 return img_open_file(filename, options, fmt, flags, writethrough, quiet,
356 static BlockBackend *img_open(bool image_opts,
357 const char *filename,
358 const char *fmt, int flags, bool writethrough,
359 bool quiet, bool force_share)
365 error_report("--image-opts and --format are mutually exclusive");
368 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
373 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
376 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
383 static int add_old_style_options(const char *fmt, QemuOpts *opts,
384 const char *base_filename,
385 const char *base_fmt)
390 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
392 error_report("Backing file not supported for file format '%s'",
399 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
401 error_report("Backing file format not supported for file "
410 static int64_t cvtnum(const char *s)
415 err = qemu_strtosz(s, NULL, &value);
419 if (value > INT64_MAX) {
425 static int img_create(int argc, char **argv)
428 uint64_t img_size = -1;
429 const char *fmt = "raw";
430 const char *base_fmt = NULL;
431 const char *filename;
432 const char *base_filename = NULL;
433 char *options = NULL;
434 Error *local_err = NULL;
439 static const struct option long_options[] = {
440 {"help", no_argument, 0, 'h'},
441 {"object", required_argument, 0, OPTION_OBJECT},
444 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
451 missing_argument(argv[optind - 1]);
454 unrecognized_option(argv[optind - 1]);
463 base_filename = optarg;
469 if (!is_valid_option_list(optarg)) {
470 error_report("Invalid option list: %s", optarg);
474 options = g_strdup(optarg);
476 char *old_options = options;
477 options = g_strdup_printf("%s,%s", options, optarg);
485 flags |= BDRV_O_NO_BACKING;
487 case OPTION_OBJECT: {
489 opts = qemu_opts_parse_noisily(&qemu_object_opts,
498 /* Get the filename */
499 filename = (optind < argc) ? argv[optind] : NULL;
500 if (options && has_help_option(options)) {
502 return print_block_option_help(filename, fmt);
505 if (optind >= argc) {
506 error_exit("Expecting image file name");
510 if (qemu_opts_foreach(&qemu_object_opts,
511 user_creatable_add_opts_foreach,
516 /* Get image size, if specified */
520 sval = cvtnum(argv[optind++]);
522 if (sval == -ERANGE) {
523 error_report("Image size must be less than 8 EiB!");
525 error_report("Invalid image size specified! You may use k, M, "
526 "G, T, P or E suffixes for ");
527 error_report("kilobytes, megabytes, gigabytes, terabytes, "
528 "petabytes and exabytes.");
532 img_size = (uint64_t)sval;
534 if (optind != argc) {
535 error_exit("Unexpected argument: %s", argv[optind]);
538 bdrv_img_create(filename, fmt, base_filename, base_fmt,
539 options, img_size, flags, quiet, &local_err);
541 error_reportf_err(local_err, "%s: ", filename);
553 static void dump_json_image_check(ImageCheck *check, bool quiet)
557 Visitor *v = qobject_output_visitor_new(&obj);
559 visit_type_ImageCheck(v, NULL, &check, &error_abort);
560 visit_complete(v, &obj);
561 str = qobject_to_json_pretty(obj);
563 qprintf(quiet, "%s\n", qstring_get_str(str));
569 static void dump_human_image_check(ImageCheck *check, bool quiet)
571 if (!(check->corruptions || check->leaks || check->check_errors)) {
572 qprintf(quiet, "No errors were found on the image.\n");
574 if (check->corruptions) {
575 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
576 "Data may be corrupted, or further writes to the image "
583 "\n%" PRId64 " leaked clusters were found on the image.\n"
584 "This means waste of disk space, but no harm to data.\n",
588 if (check->check_errors) {
591 " internal errors have occurred during the check.\n",
592 check->check_errors);
596 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
597 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
598 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
599 check->allocated_clusters, check->total_clusters,
600 check->allocated_clusters * 100.0 / check->total_clusters,
601 check->fragmented_clusters * 100.0 / check->allocated_clusters,
602 check->compressed_clusters * 100.0 /
603 check->allocated_clusters);
606 if (check->image_end_offset) {
608 "Image end offset: %" PRId64 "\n", check->image_end_offset);
612 static int collect_image_check(BlockDriverState *bs,
614 const char *filename,
619 BdrvCheckResult result;
621 ret = bdrv_check(bs, &result, fix);
626 check->filename = g_strdup(filename);
627 check->format = g_strdup(bdrv_get_format_name(bs));
628 check->check_errors = result.check_errors;
629 check->corruptions = result.corruptions;
630 check->has_corruptions = result.corruptions != 0;
631 check->leaks = result.leaks;
632 check->has_leaks = result.leaks != 0;
633 check->corruptions_fixed = result.corruptions_fixed;
634 check->has_corruptions_fixed = result.corruptions != 0;
635 check->leaks_fixed = result.leaks_fixed;
636 check->has_leaks_fixed = result.leaks != 0;
637 check->image_end_offset = result.image_end_offset;
638 check->has_image_end_offset = result.image_end_offset != 0;
639 check->total_clusters = result.bfi.total_clusters;
640 check->has_total_clusters = result.bfi.total_clusters != 0;
641 check->allocated_clusters = result.bfi.allocated_clusters;
642 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
643 check->fragmented_clusters = result.bfi.fragmented_clusters;
644 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
645 check->compressed_clusters = result.bfi.compressed_clusters;
646 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
652 * Checks an image for consistency. Exit codes:
654 * 0 - Check completed, image is good
655 * 1 - Check not completed because of internal errors
656 * 2 - Check completed, image is corrupted
657 * 3 - Check completed, image has leaked clusters, but is good otherwise
658 * 63 - Checks are not supported by the image format
660 static int img_check(int argc, char **argv)
663 OutputFormat output_format = OFORMAT_HUMAN;
664 const char *filename, *fmt, *output, *cache;
666 BlockDriverState *bs;
668 int flags = BDRV_O_CHECK;
672 bool image_opts = false;
673 bool force_share = false;
677 cache = BDRV_DEFAULT_CACHE;
680 int option_index = 0;
681 static const struct option long_options[] = {
682 {"help", no_argument, 0, 'h'},
683 {"format", required_argument, 0, 'f'},
684 {"repair", required_argument, 0, 'r'},
685 {"output", required_argument, 0, OPTION_OUTPUT},
686 {"object", required_argument, 0, OPTION_OBJECT},
687 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
688 {"force-share", no_argument, 0, 'U'},
691 c = getopt_long(argc, argv, ":hf:r:T:qU",
692 long_options, &option_index);
698 missing_argument(argv[optind - 1]);
701 unrecognized_option(argv[optind - 1]);
710 flags |= BDRV_O_RDWR;
712 if (!strcmp(optarg, "leaks")) {
713 fix = BDRV_FIX_LEAKS;
714 } else if (!strcmp(optarg, "all")) {
715 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
717 error_exit("Unknown option value for -r "
718 "(expecting 'leaks' or 'all'): %s", optarg);
733 case OPTION_OBJECT: {
735 opts = qemu_opts_parse_noisily(&qemu_object_opts,
741 case OPTION_IMAGE_OPTS:
746 if (optind != argc - 1) {
747 error_exit("Expecting one image file name");
749 filename = argv[optind++];
751 if (output && !strcmp(output, "json")) {
752 output_format = OFORMAT_JSON;
753 } else if (output && !strcmp(output, "human")) {
754 output_format = OFORMAT_HUMAN;
756 error_report("--output must be used with human or json as argument.");
760 if (qemu_opts_foreach(&qemu_object_opts,
761 user_creatable_add_opts_foreach,
766 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
768 error_report("Invalid source cache option: %s", cache);
772 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
779 check = g_new0(ImageCheck, 1);
780 ret = collect_image_check(bs, check, filename, fmt, fix);
782 if (ret == -ENOTSUP) {
783 error_report("This image format does not support checks");
788 if (check->corruptions_fixed || check->leaks_fixed) {
789 int corruptions_fixed, leaks_fixed;
791 leaks_fixed = check->leaks_fixed;
792 corruptions_fixed = check->corruptions_fixed;
794 if (output_format == OFORMAT_HUMAN) {
796 "The following inconsistencies were found and repaired:\n\n"
797 " %" PRId64 " leaked clusters\n"
798 " %" PRId64 " corruptions\n\n"
799 "Double checking the fixed image now...\n",
801 check->corruptions_fixed);
804 ret = collect_image_check(bs, check, filename, fmt, 0);
806 check->leaks_fixed = leaks_fixed;
807 check->corruptions_fixed = corruptions_fixed;
811 switch (output_format) {
813 dump_human_image_check(check, quiet);
816 dump_json_image_check(check, quiet);
821 if (ret || check->check_errors) {
823 error_report("Check failed: %s", strerror(-ret));
825 error_report("Check failed");
831 if (check->corruptions) {
833 } else if (check->leaks) {
840 qapi_free_ImageCheck(check);
845 typedef struct CommonBlockJobCBInfo {
846 BlockDriverState *bs;
848 } CommonBlockJobCBInfo;
850 static void common_block_job_cb(void *opaque, int ret)
852 CommonBlockJobCBInfo *cbi = opaque;
855 error_setg_errno(cbi->errp, -ret, "Block job failed");
859 static void run_block_job(BlockJob *job, Error **errp)
861 AioContext *aio_context = blk_get_aio_context(job->blk);
864 aio_context_acquire(aio_context);
867 float progress = 0.0f;
868 aio_poll(aio_context, true);
869 if (job->job.progress_total) {
870 progress = (float)job->job.progress_current /
871 job->job.progress_total * 100.f;
873 qemu_progress_print(progress, 0);
874 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
876 if (!job_is_completed(&job->job)) {
877 ret = job_complete_sync(&job->job, errp);
881 job_unref(&job->job);
882 aio_context_release(aio_context);
884 /* publish completion progress only when success */
886 qemu_progress_print(100.f, 0);
890 static int img_commit(int argc, char **argv)
893 const char *filename, *fmt, *cache, *base;
895 BlockDriverState *bs, *base_bs;
897 bool progress = false, quiet = false, drop = false;
899 Error *local_err = NULL;
900 CommonBlockJobCBInfo cbi;
901 bool image_opts = false;
902 AioContext *aio_context;
905 cache = BDRV_DEFAULT_CACHE;
908 static const struct option long_options[] = {
909 {"help", no_argument, 0, 'h'},
910 {"object", required_argument, 0, OPTION_OBJECT},
911 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
914 c = getopt_long(argc, argv, ":f:ht:b:dpq",
921 missing_argument(argv[optind - 1]);
924 unrecognized_option(argv[optind - 1]);
949 case OPTION_OBJECT: {
951 opts = qemu_opts_parse_noisily(&qemu_object_opts,
957 case OPTION_IMAGE_OPTS:
963 /* Progress is not shown in Quiet mode */
968 if (optind != argc - 1) {
969 error_exit("Expecting one image file name");
971 filename = argv[optind++];
973 if (qemu_opts_foreach(&qemu_object_opts,
974 user_creatable_add_opts_foreach,
979 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
980 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
982 error_report("Invalid cache option: %s", cache);
986 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
993 qemu_progress_init(progress, 1.f);
994 qemu_progress_print(0.f, 100);
997 base_bs = bdrv_find_backing_image(bs, base);
999 error_setg(&local_err,
1000 "Did not find '%s' in the backing chain of '%s'",
1005 /* This is different from QMP, which by default uses the deepest file in
1006 * the backing chain (i.e., the very base); however, the traditional
1007 * behavior of qemu-img commit is using the immediate backing file. */
1008 base_bs = backing_bs(bs);
1010 error_setg(&local_err, "Image does not have a backing file");
1015 cbi = (CommonBlockJobCBInfo){
1020 aio_context = bdrv_get_aio_context(bs);
1021 aio_context_acquire(aio_context);
1022 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
1023 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1024 &cbi, false, &local_err);
1025 aio_context_release(aio_context);
1030 /* When the block job completes, the BlockBackend reference will point to
1031 * the old backing file. In order to avoid that the top image is already
1032 * deleted, so we can still empty it afterwards, increment the reference
1033 * counter here preemptively. */
1038 job = block_job_get("commit");
1039 run_block_job(job, &local_err);
1044 if (!drop && bs->drv->bdrv_make_empty) {
1045 ret = bs->drv->bdrv_make_empty(bs);
1047 error_setg_errno(&local_err, -ret, "Could not empty %s",
1059 qemu_progress_end();
1064 error_report_err(local_err);
1068 qprintf(quiet, "Image committed.\n");
1073 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1074 * of the first sector boundary within buf where the sector contains a
1075 * non-zero byte. This function is robust to a buffer that is not
1078 static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1081 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1083 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1084 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1088 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1095 * Returns true iff the first sector pointed to by 'buf' contains at least
1098 * 'pnum' is set to the number of sectors (including and immediately following
1099 * the first one) that are known to be in the same allocated/unallocated state.
1101 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
1110 is_zero = buffer_is_zero(buf, 512);
1111 for(i = 1; i < n; i++) {
1113 if (is_zero != buffer_is_zero(buf, 512)) {
1122 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1123 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1124 * breaking up write requests for only small sparse areas.
1126 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1130 int num_checked, num_used;
1136 ret = is_allocated_sectors(buf, n, pnum);
1142 buf += BDRV_SECTOR_SIZE * *pnum;
1144 num_checked = num_used;
1147 ret = is_allocated_sectors(buf, n, pnum);
1149 buf += BDRV_SECTOR_SIZE * *pnum;
1151 num_checked += *pnum;
1153 num_used = num_checked;
1154 } else if (*pnum >= min) {
1164 * Compares two buffers sector by sector. Returns 0 if the first
1165 * sector of each buffer matches, non-zero otherwise.
1167 * pnum is set to the sector-aligned size of the buffer prefix that
1168 * has the same matching status as the first sector.
1170 static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1171 int64_t bytes, int64_t *pnum)
1174 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
1178 res = !!memcmp(buf1, buf2, i);
1180 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
1182 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
1192 #define IO_BUF_SIZE (2 * 1024 * 1024)
1195 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1197 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1198 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1199 * failure), and 4 on error (the exit status for read errors), after emitting
1202 * @param blk: BlockBackend for the image
1203 * @param offset: Starting offset to check
1204 * @param bytes: Number of bytes to check
1205 * @param filename: Name of disk file we are checking (logging purpose)
1206 * @param buffer: Allocated buffer for storing read data
1207 * @param quiet: Flag for quiet mode
1209 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1210 int64_t bytes, const char *filename,
1211 uint8_t *buffer, bool quiet)
1216 ret = blk_pread(blk, offset, buffer, bytes);
1218 error_report("Error while reading offset %" PRId64 " of %s: %s",
1219 offset, filename, strerror(-ret));
1222 idx = find_nonzero(buffer, bytes);
1224 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1233 * Compares two images. Exit codes:
1235 * 0 - Images are identical
1237 * >1 - Error occurred
1239 static int img_compare(int argc, char **argv)
1241 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1242 BlockBackend *blk1, *blk2;
1243 BlockDriverState *bs1, *bs2;
1244 int64_t total_size1, total_size2;
1245 uint8_t *buf1 = NULL, *buf2 = NULL;
1246 int64_t pnum1, pnum2;
1247 int allocated1, allocated2;
1248 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1249 bool progress = false, quiet = false, strict = false;
1256 uint64_t progress_base;
1257 bool image_opts = false;
1258 bool force_share = false;
1260 cache = BDRV_DEFAULT_CACHE;
1262 static const struct option long_options[] = {
1263 {"help", no_argument, 0, 'h'},
1264 {"object", required_argument, 0, OPTION_OBJECT},
1265 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1266 {"force-share", no_argument, 0, 'U'},
1269 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1270 long_options, NULL);
1276 missing_argument(argv[optind - 1]);
1279 unrecognized_option(argv[optind - 1]);
1305 case OPTION_OBJECT: {
1307 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1314 case OPTION_IMAGE_OPTS:
1320 /* Progress is not shown in Quiet mode */
1326 if (optind != argc - 2) {
1327 error_exit("Expecting two image file names");
1329 filename1 = argv[optind++];
1330 filename2 = argv[optind++];
1332 if (qemu_opts_foreach(&qemu_object_opts,
1333 user_creatable_add_opts_foreach,
1339 /* Initialize before goto out */
1340 qemu_progress_init(progress, 2.0);
1343 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1345 error_report("Invalid source cache option: %s", cache);
1350 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1357 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1366 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1367 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1368 total_size1 = blk_getlength(blk1);
1369 if (total_size1 < 0) {
1370 error_report("Can't get size of %s: %s",
1371 filename1, strerror(-total_size1));
1375 total_size2 = blk_getlength(blk2);
1376 if (total_size2 < 0) {
1377 error_report("Can't get size of %s: %s",
1378 filename2, strerror(-total_size2));
1382 total_size = MIN(total_size1, total_size2);
1383 progress_base = MAX(total_size1, total_size2);
1385 qemu_progress_print(0, 100);
1387 if (strict && total_size1 != total_size2) {
1389 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1393 while (offset < total_size) {
1394 int status1, status2;
1396 status1 = bdrv_block_status_above(bs1, NULL, offset,
1397 total_size1 - offset, &pnum1, NULL,
1401 error_report("Sector allocation test failed for %s", filename1);
1404 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1406 status2 = bdrv_block_status_above(bs2, NULL, offset,
1407 total_size2 - offset, &pnum2, NULL,
1411 error_report("Sector allocation test failed for %s", filename2);
1414 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1416 assert(pnum1 && pnum2);
1417 chunk = MIN(pnum1, pnum2);
1420 if (status1 != status2) {
1422 qprintf(quiet, "Strict mode: Offset %" PRId64
1423 " block status mismatch!\n", offset);
1427 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1429 } else if (allocated1 == allocated2) {
1433 chunk = MIN(chunk, IO_BUF_SIZE);
1434 ret = blk_pread(blk1, offset, buf1, chunk);
1436 error_report("Error while reading offset %" PRId64
1438 offset, filename1, strerror(-ret));
1442 ret = blk_pread(blk2, offset, buf2, chunk);
1444 error_report("Error while reading offset %" PRId64
1446 offset, filename2, strerror(-ret));
1450 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1451 if (ret || pnum != chunk) {
1452 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1453 offset + (ret ? 0 : pnum));
1459 chunk = MIN(chunk, IO_BUF_SIZE);
1461 ret = check_empty_sectors(blk1, offset, chunk,
1462 filename1, buf1, quiet);
1464 ret = check_empty_sectors(blk2, offset, chunk,
1465 filename2, buf1, quiet);
1472 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1475 if (total_size1 != total_size2) {
1476 BlockBackend *blk_over;
1477 const char *filename_over;
1479 qprintf(quiet, "Warning: Image size mismatch!\n");
1480 if (total_size1 > total_size2) {
1482 filename_over = filename1;
1485 filename_over = filename2;
1488 while (offset < progress_base) {
1489 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1490 progress_base - offset, &chunk,
1494 error_report("Sector allocation test failed for %s",
1499 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1500 chunk = MIN(chunk, IO_BUF_SIZE);
1501 ret = check_empty_sectors(blk_over, offset, chunk,
1502 filename_over, buf1, quiet);
1508 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1512 qprintf(quiet, "Images are identical.\n");
1522 qemu_progress_end();
1527 enum ImgConvertBlockStatus {
1533 #define MAX_COROUTINES 16
1535 typedef struct ImgConvertState {
1537 int64_t *src_sectors;
1539 int64_t total_sectors;
1540 int64_t allocated_sectors;
1541 int64_t allocated_done;
1544 enum ImgConvertBlockStatus status;
1545 int64_t sector_next_status;
1546 BlockBackend *target;
1549 bool target_has_backing;
1553 size_t cluster_sectors;
1555 long num_coroutines;
1556 int running_coroutines;
1557 Coroutine *co[MAX_COROUTINES];
1558 int64_t wait_sector_num[MAX_COROUTINES];
1563 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1564 int *src_cur, int64_t *src_cur_offset)
1567 *src_cur_offset = 0;
1568 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1569 *src_cur_offset += s->src_sectors[*src_cur];
1571 assert(*src_cur < s->src_num);
1575 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1577 int64_t src_cur_offset;
1578 int ret, n, src_cur;
1580 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1582 assert(s->total_sectors > sector_num);
1583 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1585 if (s->sector_next_status <= sector_num) {
1586 int64_t count = n * BDRV_SECTOR_SIZE;
1588 if (s->target_has_backing) {
1590 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1591 (sector_num - src_cur_offset) *
1593 count, &count, NULL, NULL);
1595 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1596 (sector_num - src_cur_offset) *
1598 count, &count, NULL, NULL);
1603 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1605 if (ret & BDRV_BLOCK_ZERO) {
1606 s->status = BLK_ZERO;
1607 } else if (ret & BDRV_BLOCK_DATA) {
1608 s->status = BLK_DATA;
1610 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1613 s->sector_next_status = sector_num + n;
1616 n = MIN(n, s->sector_next_status - sector_num);
1617 if (s->status == BLK_DATA) {
1618 n = MIN(n, s->buf_sectors);
1621 /* We need to write complete clusters for compressed images, so if an
1622 * unallocated area is shorter than that, we must consider the whole
1623 * cluster allocated. */
1624 if (s->compressed) {
1625 if (n < s->cluster_sectors) {
1626 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1627 s->status = BLK_DATA;
1629 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1636 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1637 int nb_sectors, uint8_t *buf)
1643 assert(nb_sectors <= s->buf_sectors);
1644 while (nb_sectors > 0) {
1647 int64_t bs_sectors, src_cur_offset;
1649 /* In the case of compression with multiple source files, we can get a
1650 * nb_sectors that spreads into the next part. So we must be able to
1651 * read across multiple BDSes for one convert_read() call. */
1652 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1653 blk = s->src[src_cur];
1654 bs_sectors = s->src_sectors[src_cur];
1656 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1658 iov.iov_len = n << BDRV_SECTOR_BITS;
1659 qemu_iovec_init_external(&qiov, &iov, 1);
1661 ret = blk_co_preadv(
1662 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1663 n << BDRV_SECTOR_BITS, &qiov, 0);
1670 buf += n * BDRV_SECTOR_SIZE;
1677 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1678 int nb_sectors, uint8_t *buf,
1679 enum ImgConvertBlockStatus status)
1685 while (nb_sectors > 0) {
1687 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1690 case BLK_BACKING_FILE:
1691 /* If we have a backing file, leave clusters unallocated that are
1692 * unallocated in the source image, so that the backing file is
1693 * visible at the respective offset. */
1694 assert(s->target_has_backing);
1698 /* If we're told to keep the target fully allocated (-S 0) or there
1699 * is real non-zero data, we must write it. Otherwise we can treat
1700 * it as zero sectors.
1701 * Compressed clusters need to be written as a whole, so in that
1702 * case we can only save the write if the buffer is completely
1704 if (!s->min_sparse ||
1706 is_allocated_sectors_min(buf, n, &n, s->min_sparse)) ||
1708 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1711 iov.iov_len = n << BDRV_SECTOR_BITS;
1712 qemu_iovec_init_external(&qiov, &iov, 1);
1714 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
1715 n << BDRV_SECTOR_BITS, &qiov, flags);
1724 if (s->has_zero_init) {
1725 assert(!s->target_has_backing);
1728 ret = blk_co_pwrite_zeroes(s->target,
1729 sector_num << BDRV_SECTOR_BITS,
1730 n << BDRV_SECTOR_BITS, 0);
1739 buf += n * BDRV_SECTOR_SIZE;
1745 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1750 while (nb_sectors > 0) {
1753 int64_t bs_sectors, src_cur_offset;
1756 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1757 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1758 blk = s->src[src_cur];
1759 bs_sectors = s->src_sectors[src_cur];
1761 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1763 ret = blk_co_copy_range(blk, offset, s->target,
1764 sector_num << BDRV_SECTOR_BITS,
1765 n << BDRV_SECTOR_BITS, 0);
1776 static void coroutine_fn convert_co_do_copy(void *opaque)
1778 ImgConvertState *s = opaque;
1779 uint8_t *buf = NULL;
1783 for (i = 0; i < s->num_coroutines; i++) {
1784 if (s->co[i] == qemu_coroutine_self()) {
1791 s->running_coroutines++;
1792 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1797 enum ImgConvertBlockStatus status;
1800 qemu_co_mutex_lock(&s->lock);
1801 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1802 qemu_co_mutex_unlock(&s->lock);
1805 n = convert_iteration_sectors(s, s->sector_num);
1807 qemu_co_mutex_unlock(&s->lock);
1811 /* save current sector and allocation status to local variables */
1812 sector_num = s->sector_num;
1814 if (!s->min_sparse && s->status == BLK_ZERO) {
1815 n = MIN(n, s->buf_sectors);
1817 /* increment global sector counter so that other coroutines can
1818 * already continue reading beyond this request */
1820 qemu_co_mutex_unlock(&s->lock);
1822 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1823 s->allocated_done += n;
1824 qemu_progress_print(100.0 * s->allocated_done /
1825 s->allocated_sectors, 0);
1829 copy_range = s->copy_range && s->status == BLK_DATA;
1830 if (status == BLK_DATA && !copy_range) {
1831 ret = convert_co_read(s, sector_num, n, buf);
1833 error_report("error while reading sector %" PRId64
1834 ": %s", sector_num, strerror(-ret));
1837 } else if (!s->min_sparse && status == BLK_ZERO) {
1839 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1842 if (s->wr_in_order) {
1843 /* keep writes in order */
1844 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
1845 s->wait_sector_num[index] = sector_num;
1846 qemu_coroutine_yield();
1848 s->wait_sector_num[index] = -1;
1851 if (s->ret == -EINPROGRESS) {
1853 ret = convert_co_copy_range(s, sector_num, n);
1855 s->copy_range = false;
1859 ret = convert_co_write(s, sector_num, n, buf, status);
1862 error_report("error while writing sector %" PRId64
1863 ": %s", sector_num, strerror(-ret));
1868 if (s->wr_in_order) {
1869 /* reenter the coroutine that might have waited
1870 * for this write to complete */
1871 s->wr_offs = sector_num + n;
1872 for (i = 0; i < s->num_coroutines; i++) {
1873 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1875 * A -> B -> A cannot occur because A has
1876 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1877 * B will never enter A during this time window.
1879 qemu_coroutine_enter(s->co[i]);
1887 s->co[index] = NULL;
1888 s->running_coroutines--;
1889 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1890 /* the convert job finished successfully */
1895 static int convert_do_copy(ImgConvertState *s)
1898 int64_t sector_num = 0;
1900 /* Check whether we have zero initialisation or can get it efficiently */
1901 s->has_zero_init = s->min_sparse && !s->target_has_backing
1902 ? bdrv_has_zero_init(blk_bs(s->target))
1905 if (!s->has_zero_init && !s->target_has_backing &&
1906 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1908 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
1910 s->has_zero_init = true;
1914 /* Allocate buffer for copied data. For compressed images, only one cluster
1915 * can be copied at a time. */
1916 if (s->compressed) {
1917 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1918 error_report("invalid cluster size");
1921 s->buf_sectors = s->cluster_sectors;
1924 while (sector_num < s->total_sectors) {
1925 n = convert_iteration_sectors(s, sector_num);
1929 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1931 s->allocated_sectors += n;
1937 s->sector_next_status = 0;
1938 s->ret = -EINPROGRESS;
1940 qemu_co_mutex_init(&s->lock);
1941 for (i = 0; i < s->num_coroutines; i++) {
1942 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1943 s->wait_sector_num[i] = -1;
1944 qemu_coroutine_enter(s->co[i]);
1947 while (s->running_coroutines) {
1948 main_loop_wait(false);
1951 if (s->compressed && !s->ret) {
1952 /* signal EOF to align */
1953 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
1962 static int img_convert(int argc, char **argv)
1964 int c, bs_i, flags, src_flags = 0;
1965 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
1966 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
1967 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
1968 BlockDriver *drv = NULL, *proto_drv = NULL;
1969 BlockDriverInfo bdi;
1970 BlockDriverState *out_bs;
1971 QemuOpts *opts = NULL, *sn_opts = NULL;
1972 QemuOptsList *create_opts = NULL;
1973 char *options = NULL;
1974 Error *local_err = NULL;
1975 bool writethrough, src_writethrough, quiet = false, image_opts = false,
1976 skip_create = false, progress = false, tgt_image_opts = false;
1977 int64_t ret = -EINVAL;
1978 bool force_share = false;
1980 ImgConvertState s = (ImgConvertState) {
1981 /* Need at least 4k of zeros for sparse detection */
1984 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
1985 .wr_in_order = true,
1986 .num_coroutines = 8,
1990 static const struct option long_options[] = {
1991 {"help", no_argument, 0, 'h'},
1992 {"object", required_argument, 0, OPTION_OBJECT},
1993 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1994 {"force-share", no_argument, 0, 'U'},
1995 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
1998 c = getopt_long(argc, argv, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
1999 long_options, NULL);
2005 missing_argument(argv[optind - 1]);
2008 unrecognized_option(argv[optind - 1]);
2020 out_baseimg = optarg;
2023 s.compressed = true;
2024 s.copy_range = false;
2027 if (!is_valid_option_list(optarg)) {
2028 error_report("Invalid option list: %s", optarg);
2032 options = g_strdup(optarg);
2034 char *old_options = options;
2035 options = g_strdup_printf("%s,%s", options, optarg);
2036 g_free(old_options);
2040 snapshot_name = optarg;
2043 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2044 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2047 error_report("Failed in parsing snapshot param '%s'",
2052 snapshot_name = optarg;
2059 sval = cvtnum(optarg);
2061 error_report("Invalid minimum zero buffer size for sparse output specified");
2065 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2066 s.copy_range = false;
2085 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2086 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2087 error_report("Invalid number of coroutines. Allowed number of"
2088 " coroutines is between 1 and %d", MAX_COROUTINES);
2093 s.wr_in_order = false;
2098 case OPTION_OBJECT: {
2099 QemuOpts *object_opts;
2100 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2107 case OPTION_IMAGE_OPTS:
2110 case OPTION_TARGET_IMAGE_OPTS:
2111 tgt_image_opts = true;
2116 if (!out_fmt && !tgt_image_opts) {
2120 if (qemu_opts_foreach(&qemu_object_opts,
2121 user_creatable_add_opts_foreach,
2126 if (!s.wr_in_order && s.compressed) {
2127 error_report("Out of order write and compress are mutually exclusive");
2131 if (tgt_image_opts && !skip_create) {
2132 error_report("--target-image-opts requires use of -n flag");
2136 s.src_num = argc - optind - 1;
2137 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2139 if (options && has_help_option(options)) {
2141 ret = print_block_option_help(out_filename, out_fmt);
2144 error_report("Option help requires a format be specified");
2149 if (s.src_num < 1) {
2150 error_report("Must specify image file name");
2155 /* ret is still -EINVAL until here */
2156 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2158 error_report("Invalid source cache option: %s", src_cache);
2162 /* Initialize before goto out */
2166 qemu_progress_init(progress, 1.0);
2167 qemu_progress_print(0, 100);
2169 s.src = g_new0(BlockBackend *, s.src_num);
2170 s.src_sectors = g_new(int64_t, s.src_num);
2172 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2173 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2174 fmt, src_flags, src_writethrough, quiet,
2180 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2181 if (s.src_sectors[bs_i] < 0) {
2182 error_report("Could not get size of %s: %s",
2183 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2187 s.total_sectors += s.src_sectors[bs_i];
2191 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2192 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2193 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2195 } else if (snapshot_name != NULL) {
2196 if (s.src_num > 1) {
2197 error_report("No support for concatenating multiple snapshot");
2202 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2206 error_reportf_err(local_err, "Failed to load snapshot: ");
2212 /* Find driver and parse its options */
2213 drv = bdrv_find_format(out_fmt);
2215 error_report("Unknown file format '%s'", out_fmt);
2220 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2222 error_report_err(local_err);
2227 if (!drv->create_opts) {
2228 error_report("Format driver '%s' does not support image creation",
2234 if (!proto_drv->create_opts) {
2235 error_report("Protocol driver '%s' does not support image creation",
2236 proto_drv->format_name);
2241 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2242 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2244 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2246 qemu_opts_do_parse(opts, options, NULL, &local_err);
2248 error_report_err(local_err);
2254 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2256 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2262 /* Get backing file name if -o backing_file was used */
2263 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2264 if (out_baseimg_param) {
2265 out_baseimg = out_baseimg_param;
2267 s.target_has_backing = (bool) out_baseimg;
2269 if (s.src_num > 1 && out_baseimg) {
2270 error_report("Having a backing file for the target makes no sense when "
2271 "concatenating multiple input images");
2276 /* Check if compression is supported */
2279 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2280 const char *encryptfmt =
2281 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2282 const char *preallocation =
2283 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2285 if (drv && !drv->bdrv_co_pwritev_compressed) {
2286 error_report("Compression not supported for this file format");
2291 if (encryption || encryptfmt) {
2292 error_report("Compression and encryption not supported at "
2299 && strcmp(preallocation, "off"))
2301 error_report("Compression and preallocation not supported at "
2309 /* Create the new image */
2310 ret = bdrv_create(drv, out_filename, opts, &local_err);
2312 error_reportf_err(local_err, "%s: error while converting %s: ",
2313 out_filename, out_fmt);
2318 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2319 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2321 error_report("Invalid cache option: %s", cache);
2326 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2327 flags, writethrough, quiet, false);
2329 /* TODO ultimately we should allow --target-image-opts
2330 * to be used even when -n is not given.
2331 * That has to wait for bdrv_create to be improved
2332 * to allow filenames in option syntax
2334 s.target = img_open_new_file(out_filename, opts, out_fmt,
2335 flags, writethrough, quiet, false);
2341 out_bs = blk_bs(s.target);
2343 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2344 error_report("Compression not supported for this file format");
2349 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2350 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2352 s.buf_sectors = MIN(32768,
2354 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2355 out_bs->bl.pdiscard_alignment >>
2356 BDRV_SECTOR_BITS)));
2359 int64_t output_sectors = blk_nb_sectors(s.target);
2360 if (output_sectors < 0) {
2361 error_report("unable to get output image length: %s",
2362 strerror(-output_sectors));
2365 } else if (output_sectors < s.total_sectors) {
2366 error_report("output file is smaller than input file");
2372 ret = bdrv_get_info(out_bs, &bdi);
2375 error_report("could not get block driver info");
2379 s.compressed = s.compressed || bdi.needs_compressed_writes;
2380 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2383 ret = convert_do_copy(&s);
2386 qemu_progress_print(100, 0);
2388 qemu_progress_end();
2389 qemu_opts_del(opts);
2390 qemu_opts_free(create_opts);
2391 qemu_opts_del(sn_opts);
2392 blk_unref(s.target);
2394 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2395 blk_unref(s.src[bs_i]);
2399 g_free(s.src_sectors);
2407 static void dump_snapshots(BlockDriverState *bs)
2409 QEMUSnapshotInfo *sn_tab, *sn;
2412 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2415 printf("Snapshot list:\n");
2416 bdrv_snapshot_dump(fprintf, stdout, NULL);
2418 for(i = 0; i < nb_sns; i++) {
2420 bdrv_snapshot_dump(fprintf, stdout, sn);
2426 static void dump_json_image_info_list(ImageInfoList *list)
2430 Visitor *v = qobject_output_visitor_new(&obj);
2432 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2433 visit_complete(v, &obj);
2434 str = qobject_to_json_pretty(obj);
2435 assert(str != NULL);
2436 printf("%s\n", qstring_get_str(str));
2442 static void dump_json_image_info(ImageInfo *info)
2446 Visitor *v = qobject_output_visitor_new(&obj);
2448 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2449 visit_complete(v, &obj);
2450 str = qobject_to_json_pretty(obj);
2451 assert(str != NULL);
2452 printf("%s\n", qstring_get_str(str));
2458 static void dump_human_image_info_list(ImageInfoList *list)
2460 ImageInfoList *elem;
2463 for (elem = list; elem; elem = elem->next) {
2469 bdrv_image_info_dump(fprintf, stdout, elem->value);
2473 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2475 return strcmp(a, b) == 0;
2479 * Open an image file chain and return an ImageInfoList
2481 * @filename: topmost image filename
2482 * @fmt: topmost image format (may be NULL to autodetect)
2483 * @chain: true - enumerate entire backing file chain
2484 * false - only topmost image file
2486 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2487 * image file. If there was an error a message will have been printed to
2490 static ImageInfoList *collect_image_info_list(bool image_opts,
2491 const char *filename,
2493 bool chain, bool force_share)
2495 ImageInfoList *head = NULL;
2496 ImageInfoList **last = &head;
2497 GHashTable *filenames;
2500 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2504 BlockDriverState *bs;
2506 ImageInfoList *elem;
2508 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2509 error_report("Backing file '%s' creates an infinite loop.",
2513 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2515 blk = img_open(image_opts, filename, fmt,
2516 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2523 bdrv_query_image_info(bs, &info, &err);
2525 error_report_err(err);
2530 elem = g_new0(ImageInfoList, 1);
2537 filename = fmt = NULL;
2539 if (info->has_full_backing_filename) {
2540 filename = info->full_backing_filename;
2541 } else if (info->has_backing_filename) {
2542 error_report("Could not determine absolute backing filename,"
2543 " but backing filename '%s' present",
2544 info->backing_filename);
2547 if (info->has_backing_filename_format) {
2548 fmt = info->backing_filename_format;
2552 g_hash_table_destroy(filenames);
2556 qapi_free_ImageInfoList(head);
2557 g_hash_table_destroy(filenames);
2561 static int img_info(int argc, char **argv)
2564 OutputFormat output_format = OFORMAT_HUMAN;
2566 const char *filename, *fmt, *output;
2567 ImageInfoList *list;
2568 bool image_opts = false;
2569 bool force_share = false;
2574 int option_index = 0;
2575 static const struct option long_options[] = {
2576 {"help", no_argument, 0, 'h'},
2577 {"format", required_argument, 0, 'f'},
2578 {"output", required_argument, 0, OPTION_OUTPUT},
2579 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2580 {"object", required_argument, 0, OPTION_OBJECT},
2581 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2582 {"force-share", no_argument, 0, 'U'},
2585 c = getopt_long(argc, argv, ":f:hU",
2586 long_options, &option_index);
2592 missing_argument(argv[optind - 1]);
2595 unrecognized_option(argv[optind - 1]);
2609 case OPTION_BACKING_CHAIN:
2612 case OPTION_OBJECT: {
2614 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2620 case OPTION_IMAGE_OPTS:
2625 if (optind != argc - 1) {
2626 error_exit("Expecting one image file name");
2628 filename = argv[optind++];
2630 if (output && !strcmp(output, "json")) {
2631 output_format = OFORMAT_JSON;
2632 } else if (output && !strcmp(output, "human")) {
2633 output_format = OFORMAT_HUMAN;
2634 } else if (output) {
2635 error_report("--output must be used with human or json as argument.");
2639 if (qemu_opts_foreach(&qemu_object_opts,
2640 user_creatable_add_opts_foreach,
2645 list = collect_image_info_list(image_opts, filename, fmt, chain,
2651 switch (output_format) {
2653 dump_human_image_info_list(list);
2657 dump_json_image_info_list(list);
2659 dump_json_image_info(list->value);
2664 qapi_free_ImageInfoList(list);
2668 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2671 switch (output_format) {
2673 if (e->data && !e->has_offset) {
2674 error_report("File contains external, encrypted or compressed clusters.");
2677 if (e->data && !e->zero) {
2678 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2679 e->start, e->length,
2680 e->has_offset ? e->offset : 0,
2681 e->has_filename ? e->filename : "");
2683 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2684 * Modify the flags here to allow more coalescing.
2686 if (next && (!next->data || next->zero)) {
2692 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2693 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2694 (e->start == 0 ? "[" : ",\n"),
2695 e->start, e->length, e->depth,
2696 e->zero ? "true" : "false",
2697 e->data ? "true" : "false");
2698 if (e->has_offset) {
2699 printf(", \"offset\": %"PRId64"", e->offset);
2710 static int get_block_status(BlockDriverState *bs, int64_t offset,
2711 int64_t bytes, MapEntry *e)
2715 BlockDriverState *file;
2719 /* As an optimization, we could cache the current range of unallocated
2720 * clusters in each file of the chain, and avoid querying the same
2726 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
2731 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2734 bs = backing_bs(bs);
2743 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2748 .data = !!(ret & BDRV_BLOCK_DATA),
2749 .zero = !!(ret & BDRV_BLOCK_ZERO),
2751 .has_offset = has_offset,
2753 .has_filename = file && has_offset,
2754 .filename = file && has_offset ? file->filename : NULL,
2760 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2762 if (curr->length == 0) {
2765 if (curr->zero != next->zero ||
2766 curr->data != next->data ||
2767 curr->depth != next->depth ||
2768 curr->has_filename != next->has_filename ||
2769 curr->has_offset != next->has_offset) {
2772 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2775 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2781 static int img_map(int argc, char **argv)
2784 OutputFormat output_format = OFORMAT_HUMAN;
2786 BlockDriverState *bs;
2787 const char *filename, *fmt, *output;
2789 MapEntry curr = { .length = 0 }, next;
2791 bool image_opts = false;
2792 bool force_share = false;
2797 int option_index = 0;
2798 static const struct option long_options[] = {
2799 {"help", no_argument, 0, 'h'},
2800 {"format", required_argument, 0, 'f'},
2801 {"output", required_argument, 0, OPTION_OUTPUT},
2802 {"object", required_argument, 0, OPTION_OBJECT},
2803 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2804 {"force-share", no_argument, 0, 'U'},
2807 c = getopt_long(argc, argv, ":f:hU",
2808 long_options, &option_index);
2814 missing_argument(argv[optind - 1]);
2817 unrecognized_option(argv[optind - 1]);
2831 case OPTION_OBJECT: {
2833 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2839 case OPTION_IMAGE_OPTS:
2844 if (optind != argc - 1) {
2845 error_exit("Expecting one image file name");
2847 filename = argv[optind];
2849 if (output && !strcmp(output, "json")) {
2850 output_format = OFORMAT_JSON;
2851 } else if (output && !strcmp(output, "human")) {
2852 output_format = OFORMAT_HUMAN;
2853 } else if (output) {
2854 error_report("--output must be used with human or json as argument.");
2858 if (qemu_opts_foreach(&qemu_object_opts,
2859 user_creatable_add_opts_foreach,
2864 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
2870 if (output_format == OFORMAT_HUMAN) {
2871 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2874 length = blk_getlength(blk);
2875 while (curr.start + curr.length < length) {
2876 int64_t offset = curr.start + curr.length;
2879 /* Probe up to 1 GiB at a time. */
2880 n = QEMU_ALIGN_DOWN(MIN(1 << 30, length - offset), BDRV_SECTOR_SIZE);
2881 ret = get_block_status(bs, offset, n, &next);
2884 error_report("Could not read file metadata: %s", strerror(-ret));
2888 if (entry_mergeable(&curr, &next)) {
2889 curr.length += next.length;
2893 if (curr.length > 0) {
2894 dump_map_entry(output_format, &curr, &next);
2899 dump_map_entry(output_format, &curr, NULL);
2906 #define SNAPSHOT_LIST 1
2907 #define SNAPSHOT_CREATE 2
2908 #define SNAPSHOT_APPLY 3
2909 #define SNAPSHOT_DELETE 4
2911 static int img_snapshot(int argc, char **argv)
2914 BlockDriverState *bs;
2915 QEMUSnapshotInfo sn;
2916 char *filename, *snapshot_name = NULL;
2917 int c, ret = 0, bdrv_oflags;
2922 bool image_opts = false;
2923 bool force_share = false;
2925 bdrv_oflags = BDRV_O_RDWR;
2926 /* Parse commandline parameters */
2928 static const struct option long_options[] = {
2929 {"help", no_argument, 0, 'h'},
2930 {"object", required_argument, 0, OPTION_OBJECT},
2931 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2932 {"force-share", no_argument, 0, 'U'},
2935 c = getopt_long(argc, argv, ":la:c:d:hqU",
2936 long_options, NULL);
2942 missing_argument(argv[optind - 1]);
2945 unrecognized_option(argv[optind - 1]);
2952 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2955 action = SNAPSHOT_LIST;
2956 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
2960 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2963 action = SNAPSHOT_APPLY;
2964 snapshot_name = optarg;
2968 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2971 action = SNAPSHOT_CREATE;
2972 snapshot_name = optarg;
2976 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2979 action = SNAPSHOT_DELETE;
2980 snapshot_name = optarg;
2988 case OPTION_OBJECT: {
2990 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2996 case OPTION_IMAGE_OPTS:
3002 if (optind != argc - 1) {
3003 error_exit("Expecting one image file name");
3005 filename = argv[optind++];
3007 if (qemu_opts_foreach(&qemu_object_opts,
3008 user_creatable_add_opts_foreach,
3013 /* Open the image */
3014 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3021 /* Perform the requested action */
3027 case SNAPSHOT_CREATE:
3028 memset(&sn, 0, sizeof(sn));
3029 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3031 qemu_gettimeofday(&tv);
3032 sn.date_sec = tv.tv_sec;
3033 sn.date_nsec = tv.tv_usec * 1000;
3035 ret = bdrv_snapshot_create(bs, &sn);
3037 error_report("Could not create snapshot '%s': %d (%s)",
3038 snapshot_name, ret, strerror(-ret));
3042 case SNAPSHOT_APPLY:
3043 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3045 error_reportf_err(err, "Could not apply snapshot '%s': ",
3050 case SNAPSHOT_DELETE:
3051 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
3053 error_reportf_err(err, "Could not delete snapshot '%s': ",
3068 static int img_rebase(int argc, char **argv)
3070 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3071 uint8_t *buf_old = NULL;
3072 uint8_t *buf_new = NULL;
3073 BlockDriverState *bs = NULL;
3075 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3076 int c, flags, src_flags, ret;
3077 bool writethrough, src_writethrough;
3079 bool force_share = false;
3082 Error *local_err = NULL;
3083 bool image_opts = false;
3085 /* Parse commandline parameters */
3087 cache = BDRV_DEFAULT_CACHE;
3088 src_cache = BDRV_DEFAULT_CACHE;
3092 static const struct option long_options[] = {
3093 {"help", no_argument, 0, 'h'},
3094 {"object", required_argument, 0, OPTION_OBJECT},
3095 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3096 {"force-share", no_argument, 0, 'U'},
3099 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3100 long_options, NULL);
3106 missing_argument(argv[optind - 1]);
3109 unrecognized_option(argv[optind - 1]);
3118 out_basefmt = optarg;
3121 out_baseimg = optarg;
3138 case OPTION_OBJECT: {
3140 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3146 case OPTION_IMAGE_OPTS:
3159 if (optind != argc - 1) {
3160 error_exit("Expecting one image file name");
3162 if (!unsafe && !out_baseimg) {
3163 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3165 filename = argv[optind++];
3167 if (qemu_opts_foreach(&qemu_object_opts,
3168 user_creatable_add_opts_foreach,
3173 qemu_progress_init(progress, 2.0);
3174 qemu_progress_print(0, 100);
3176 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3177 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3179 error_report("Invalid cache option: %s", cache);
3184 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3186 error_report("Invalid source cache option: %s", src_cache);
3190 /* The source files are opened read-only, don't care about WCE */
3191 assert((src_flags & BDRV_O_RDWR) == 0);
3192 (void) src_writethrough;
3197 * Ignore the old backing file for unsafe rebase in case we want to correct
3198 * the reference to a renamed or moved backing file.
3200 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3208 if (out_basefmt != NULL) {
3209 if (bdrv_find_format(out_basefmt) == NULL) {
3210 error_report("Invalid format name: '%s'", out_basefmt);
3216 /* For safe rebasing we need to compare old and new backing file */
3218 char backing_name[PATH_MAX];
3219 QDict *options = NULL;
3221 if (bs->backing_format[0] != '\0') {
3222 options = qdict_new();
3223 qdict_put_str(options, "driver", bs->backing_format);
3228 options = qdict_new();
3230 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3232 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3233 blk_old_backing = blk_new_open(backing_name, NULL,
3234 options, src_flags, &local_err);
3235 if (!blk_old_backing) {
3236 error_reportf_err(local_err,
3237 "Could not open old backing file '%s': ",
3243 if (out_baseimg[0]) {
3244 options = qdict_new();
3246 qdict_put_str(options, "driver", out_basefmt);
3249 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3252 blk_new_backing = blk_new_open(out_baseimg, NULL,
3253 options, src_flags, &local_err);
3254 if (!blk_new_backing) {
3255 error_reportf_err(local_err,
3256 "Could not open new backing file '%s': ",
3265 * Check each unallocated cluster in the COW file. If it is unallocated,
3266 * accesses go to the backing file. We must therefore compare this cluster
3267 * in the old and new backing file, and if they differ we need to copy it
3268 * from the old backing file into the COW file.
3270 * If qemu-img crashes during this step, no harm is done. The content of
3271 * the image is the same as the original one at any time.
3275 int64_t old_backing_size;
3276 int64_t new_backing_size = 0;
3279 float local_progress = 0;
3281 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3282 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3284 size = blk_getlength(blk);
3286 error_report("Could not get size of '%s': %s",
3287 filename, strerror(-size));
3291 old_backing_size = blk_getlength(blk_old_backing);
3292 if (old_backing_size < 0) {
3293 char backing_name[PATH_MAX];
3295 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3296 error_report("Could not get size of '%s': %s",
3297 backing_name, strerror(-old_backing_size));
3301 if (blk_new_backing) {
3302 new_backing_size = blk_getlength(blk_new_backing);
3303 if (new_backing_size < 0) {
3304 error_report("Could not get size of '%s': %s",
3305 out_baseimg, strerror(-new_backing_size));
3312 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3315 for (offset = 0; offset < size; offset += n) {
3316 /* How many bytes can we handle with the next read? */
3317 n = MIN(IO_BUF_SIZE, size - offset);
3319 /* If the cluster is allocated, we don't need to take action */
3320 ret = bdrv_is_allocated(bs, offset, n, &n);
3322 error_report("error while reading image metadata: %s",
3331 * Read old and new backing file and take into consideration that
3332 * backing files may be smaller than the COW image.
3334 if (offset >= old_backing_size) {
3335 memset(buf_old, 0, n);
3337 if (offset + n > old_backing_size) {
3338 n = old_backing_size - offset;
3341 ret = blk_pread(blk_old_backing, offset, buf_old, n);
3343 error_report("error while reading from old backing file");
3348 if (offset >= new_backing_size || !blk_new_backing) {
3349 memset(buf_new, 0, n);
3351 if (offset + n > new_backing_size) {
3352 n = new_backing_size - offset;
3355 ret = blk_pread(blk_new_backing, offset, buf_new, n);
3357 error_report("error while reading from new backing file");
3362 /* If they differ, we need to write to the COW file */
3363 uint64_t written = 0;
3365 while (written < n) {
3368 if (compare_buffers(buf_old + written, buf_new + written,
3369 n - written, &pnum))
3371 ret = blk_pwrite(blk, offset + written,
3372 buf_old + written, pnum, 0);
3374 error_report("Error while writing to COW image: %s",
3382 qemu_progress_print(local_progress, 100);
3387 * Change the backing file. All clusters that are different from the old
3388 * backing file are overwritten in the COW file now, so the visible content
3389 * doesn't change when we switch the backing file.
3391 if (out_baseimg && *out_baseimg) {
3392 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3394 ret = bdrv_change_backing_file(bs, NULL, NULL);
3397 if (ret == -ENOSPC) {
3398 error_report("Could not change the backing file to '%s': No "
3399 "space left in the file header", out_baseimg);
3400 } else if (ret < 0) {
3401 error_report("Could not change the backing file to '%s': %s",
3402 out_baseimg, strerror(-ret));
3405 qemu_progress_print(100, 0);
3407 * TODO At this point it is possible to check if any clusters that are
3408 * allocated in the COW file are the same in the backing file. If so, they
3409 * could be dropped from the COW file. Don't do this before switching the
3410 * backing file, in case of a crash this would lead to corruption.
3413 qemu_progress_end();
3416 blk_unref(blk_old_backing);
3417 blk_unref(blk_new_backing);
3419 qemu_vfree(buf_old);
3420 qemu_vfree(buf_new);
3429 static int img_resize(int argc, char **argv)
3432 int c, ret, relative;
3433 const char *filename, *fmt, *size;
3434 int64_t n, total_size, current_size, new_size;
3436 BlockBackend *blk = NULL;
3437 PreallocMode prealloc = PREALLOC_MODE_OFF;
3440 static QemuOptsList resize_options = {
3441 .name = "resize_options",
3442 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3445 .name = BLOCK_OPT_SIZE,
3446 .type = QEMU_OPT_SIZE,
3447 .help = "Virtual disk size"
3453 bool image_opts = false;
3454 bool shrink = false;
3456 /* Remove size from argv manually so that negative numbers are not treated
3457 * as options by getopt. */
3459 error_exit("Not enough arguments");
3463 size = argv[--argc];
3465 /* Parse getopt arguments */
3468 static const struct option long_options[] = {
3469 {"help", no_argument, 0, 'h'},
3470 {"object", required_argument, 0, OPTION_OBJECT},
3471 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3472 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3473 {"shrink", no_argument, 0, OPTION_SHRINK},
3476 c = getopt_long(argc, argv, ":f:hq",
3477 long_options, NULL);
3483 missing_argument(argv[optind - 1]);
3486 unrecognized_option(argv[optind - 1]);
3497 case OPTION_OBJECT: {
3499 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3505 case OPTION_IMAGE_OPTS:
3508 case OPTION_PREALLOCATION:
3509 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3510 PREALLOC_MODE__MAX, NULL);
3511 if (prealloc == PREALLOC_MODE__MAX) {
3512 error_report("Invalid preallocation mode '%s'", optarg);
3521 if (optind != argc - 1) {
3522 error_exit("Expecting image file name and size");
3524 filename = argv[optind++];
3526 if (qemu_opts_foreach(&qemu_object_opts,
3527 user_creatable_add_opts_foreach,
3532 /* Choose grow, shrink, or absolute resize mode */
3548 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3549 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3551 error_report_err(err);
3553 qemu_opts_del(param);
3556 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3557 qemu_opts_del(param);
3559 blk = img_open(image_opts, filename, fmt,
3560 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3567 current_size = blk_getlength(blk);
3568 if (current_size < 0) {
3569 error_report("Failed to inquire current image length: %s",
3570 strerror(-current_size));
3576 total_size = current_size + n * relative;
3580 if (total_size <= 0) {
3581 error_report("New image size must be positive");
3586 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3587 error_report("Preallocation can only be used for growing images");
3592 if (total_size < current_size && !shrink) {
3593 warn_report("Shrinking an image will delete all data beyond the "
3594 "shrunken image's end. Before performing such an "
3595 "operation, make sure there is no important data there.");
3597 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3599 "Use the --shrink option to perform a shrink operation.");
3603 warn_report("Using the --shrink option will suppress this message. "
3604 "Note that future versions of qemu-img may refuse to "
3605 "shrink images without this option.");
3609 ret = blk_truncate(blk, total_size, prealloc, &err);
3611 error_report_err(err);
3615 new_size = blk_getlength(blk);
3617 error_report("Failed to verify truncated image length: %s",
3618 strerror(-new_size));
3623 /* Some block drivers implement a truncation method, but only so
3624 * the user can cause qemu to refresh the image's size from disk.
3625 * The idea is that the user resizes the image outside of qemu and
3626 * then invokes block_resize to inform qemu about it.
3627 * (This includes iscsi and file-posix for device files.)
3628 * Of course, that is not the behavior someone invoking
3629 * qemu-img resize would find useful, so we catch that behavior
3630 * here and tell the user. */
3631 if (new_size != total_size && new_size == current_size) {
3632 error_report("Image was not resized; resizing may not be supported "
3638 if (new_size != total_size) {
3639 warn_report("Image should have been resized to %" PRIi64
3640 " bytes, but was resized to %" PRIi64 " bytes",
3641 total_size, new_size);
3644 qprintf(quiet, "Image resized.\n");
3654 static void amend_status_cb(BlockDriverState *bs,
3655 int64_t offset, int64_t total_work_size,
3658 qemu_progress_print(100.f * offset / total_work_size, 0);
3661 static int img_amend(int argc, char **argv)
3665 char *options = NULL;
3666 QemuOptsList *create_opts = NULL;
3667 QemuOpts *opts = NULL;
3668 const char *fmt = NULL, *filename, *cache;
3671 bool quiet = false, progress = false;
3672 BlockBackend *blk = NULL;
3673 BlockDriverState *bs = NULL;
3674 bool image_opts = false;
3676 cache = BDRV_DEFAULT_CACHE;
3678 static const struct option long_options[] = {
3679 {"help", no_argument, 0, 'h'},
3680 {"object", required_argument, 0, OPTION_OBJECT},
3681 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3684 c = getopt_long(argc, argv, ":ho:f:t:pq",
3685 long_options, NULL);
3692 missing_argument(argv[optind - 1]);
3695 unrecognized_option(argv[optind - 1]);
3701 if (!is_valid_option_list(optarg)) {
3702 error_report("Invalid option list: %s", optarg);
3704 goto out_no_progress;
3707 options = g_strdup(optarg);
3709 char *old_options = options;
3710 options = g_strdup_printf("%s,%s", options, optarg);
3711 g_free(old_options);
3727 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3731 goto out_no_progress;
3734 case OPTION_IMAGE_OPTS:
3741 error_exit("Must specify options (-o)");
3744 if (qemu_opts_foreach(&qemu_object_opts,
3745 user_creatable_add_opts_foreach,
3748 goto out_no_progress;
3754 qemu_progress_init(progress, 1.0);
3756 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3757 if (fmt && has_help_option(options)) {
3758 /* If a format is explicitly specified (and possibly no filename is
3759 * given), print option help here */
3760 ret = print_block_option_help(filename, fmt);
3764 if (optind != argc - 1) {
3765 error_report("Expecting one image file name");
3770 flags = BDRV_O_RDWR;
3771 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3773 error_report("Invalid cache option: %s", cache);
3777 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3785 fmt = bs->drv->format_name;
3787 if (has_help_option(options)) {
3788 /* If the format was auto-detected, print option help here */
3789 ret = print_block_option_help(filename, fmt);
3793 if (!bs->drv->bdrv_amend_options) {
3794 error_report("Format driver '%s' does not support option amendment",
3800 /* Every driver supporting amendment must have create_opts */
3801 assert(bs->drv->create_opts);
3803 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
3804 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3805 qemu_opts_do_parse(opts, options, NULL, &err);
3807 error_report_err(err);
3812 /* In case the driver does not call amend_status_cb() */
3813 qemu_progress_print(0.f, 0);
3814 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
3815 qemu_progress_print(100.f, 0);
3817 error_report_err(err);
3822 qemu_progress_end();
3826 qemu_opts_del(opts);
3827 qemu_opts_free(create_opts);
3836 typedef struct BenchData {
3838 uint64_t image_size;
3845 bool drain_on_flush;
3854 static void bench_undrained_flush_cb(void *opaque, int ret)
3857 error_report("Failed flush request: %s", strerror(-ret));
3862 static void bench_cb(void *opaque, int ret)
3864 BenchData *b = opaque;
3868 error_report("Failed request: %s", strerror(-ret));
3873 /* Just finished a flush with drained queue: Start next requests */
3874 assert(b->in_flight == 0);
3875 b->in_flush = false;
3876 } else if (b->in_flight > 0) {
3877 int remaining = b->n - b->in_flight;
3882 /* Time for flush? Drain queue if requested, then flush */
3883 if (b->flush_interval && remaining % b->flush_interval == 0) {
3884 if (!b->in_flight || !b->drain_on_flush) {
3885 BlockCompletionFunc *cb;
3887 if (b->drain_on_flush) {
3891 cb = bench_undrained_flush_cb;
3894 acb = blk_aio_flush(b->blk, cb, b);
3896 error_report("Failed to issue flush request");
3900 if (b->drain_on_flush) {
3906 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
3907 int64_t offset = b->offset;
3908 /* blk_aio_* might look for completed I/Os and kick bench_cb
3909 * again, so make sure this operation is counted by in_flight
3910 * and b->offset is ready for the next submission.
3913 b->offset += b->step;
3914 b->offset %= b->image_size;
3916 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
3918 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
3921 error_report("Failed to issue request");
3927 static int img_bench(int argc, char **argv)
3930 const char *fmt = NULL, *filename;
3932 bool image_opts = false;
3933 bool is_write = false;
3937 size_t bufsize = 4096;
3940 int flush_interval = 0;
3941 bool drain_on_flush = true;
3943 BlockBackend *blk = NULL;
3944 BenchData data = {};
3946 bool writethrough = false;
3947 struct timeval t1, t2;
3949 bool force_share = false;
3953 static const struct option long_options[] = {
3954 {"help", no_argument, 0, 'h'},
3955 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
3956 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3957 {"pattern", required_argument, 0, OPTION_PATTERN},
3958 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
3959 {"force-share", no_argument, 0, 'U'},
3962 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
3969 missing_argument(argv[optind - 1]);
3972 unrecognized_option(argv[optind - 1]);
3981 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
3982 error_report("Invalid request count specified");
3992 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
3993 error_report("Invalid queue depth specified");
4003 flags |= BDRV_O_NATIVE_AIO;
4007 offset = cvtnum(optarg);
4009 error_report("Invalid offset specified");
4022 sval = cvtnum(optarg);
4023 if (sval < 0 || sval > INT_MAX) {
4024 error_report("Invalid buffer size specified");
4035 sval = cvtnum(optarg);
4036 if (sval < 0 || sval > INT_MAX) {
4037 error_report("Invalid step size specified");
4045 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4047 error_report("Invalid cache mode");
4053 flags |= BDRV_O_RDWR;
4059 case OPTION_PATTERN:
4063 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4064 error_report("Invalid pattern byte specified");
4070 case OPTION_FLUSH_INTERVAL:
4074 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4075 error_report("Invalid flush interval specified");
4078 flush_interval = res;
4081 case OPTION_NO_DRAIN:
4082 drain_on_flush = false;
4084 case OPTION_IMAGE_OPTS:
4090 if (optind != argc - 1) {
4091 error_exit("Expecting one image file name");
4093 filename = argv[argc - 1];
4095 if (!is_write && flush_interval) {
4096 error_report("--flush-interval is only available in write tests");
4100 if (flush_interval && flush_interval < depth) {
4101 error_report("Flush interval can't be smaller than depth");
4106 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4113 image_size = blk_getlength(blk);
4114 if (image_size < 0) {
4119 data = (BenchData) {
4121 .image_size = image_size,
4123 .step = step ?: bufsize,
4128 .flush_interval = flush_interval,
4129 .drain_on_flush = drain_on_flush,
4131 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4132 "(starting at offset %" PRId64 ", step size %d)\n",
4133 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4134 data.offset, data.step);
4135 if (flush_interval) {
4136 printf("Sending flush every %d requests\n", flush_interval);
4139 buf_size = data.nrreq * data.bufsize;
4140 data.buf = blk_blockalign(blk, buf_size);
4141 memset(data.buf, pattern, data.nrreq * data.bufsize);
4143 blk_register_buf(blk, data.buf, buf_size);
4145 data.qiov = g_new(QEMUIOVector, data.nrreq);
4146 for (i = 0; i < data.nrreq; i++) {
4147 qemu_iovec_init(&data.qiov[i], 1);
4148 qemu_iovec_add(&data.qiov[i],
4149 data.buf + i * data.bufsize, data.bufsize);
4152 gettimeofday(&t1, NULL);
4155 while (data.n > 0) {
4156 main_loop_wait(false);
4158 gettimeofday(&t2, NULL);
4160 printf("Run completed in %3.3f seconds.\n",
4161 (t2.tv_sec - t1.tv_sec)
4162 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4166 blk_unregister_buf(blk, data.buf);
4168 qemu_vfree(data.buf);
4189 int bsz; /* Block size */
4197 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4201 static int img_dd_bs(const char *arg,
4202 struct DdIo *in, struct DdIo *out,
4209 if (res <= 0 || res > INT_MAX) {
4210 error_report("invalid number: '%s'", arg);
4213 in->bsz = out->bsz = res;
4218 static int img_dd_count(const char *arg,
4219 struct DdIo *in, struct DdIo *out,
4222 dd->count = cvtnum(arg);
4224 if (dd->count < 0) {
4225 error_report("invalid number: '%s'", arg);
4232 static int img_dd_if(const char *arg,
4233 struct DdIo *in, struct DdIo *out,
4236 in->filename = g_strdup(arg);
4241 static int img_dd_of(const char *arg,
4242 struct DdIo *in, struct DdIo *out,
4245 out->filename = g_strdup(arg);
4250 static int img_dd_skip(const char *arg,
4251 struct DdIo *in, struct DdIo *out,
4254 in->offset = cvtnum(arg);
4256 if (in->offset < 0) {
4257 error_report("invalid number: '%s'", arg);
4264 static int img_dd(int argc, char **argv)
4269 BlockDriver *drv = NULL, *proto_drv = NULL;
4270 BlockBackend *blk1 = NULL, *blk2 = NULL;
4271 QemuOpts *opts = NULL;
4272 QemuOptsList *create_opts = NULL;
4273 Error *local_err = NULL;
4274 bool image_opts = false;
4276 const char *out_fmt = "raw";
4277 const char *fmt = NULL;
4279 int64_t block_count = 0, out_pos, in_pos;
4280 bool force_share = false;
4281 struct DdInfo dd = {
4286 .bsz = 512, /* Block size is by default 512 bytes */
4298 const struct DdOpts options[] = {
4299 { "bs", img_dd_bs, C_BS },
4300 { "count", img_dd_count, C_COUNT },
4301 { "if", img_dd_if, C_IF },
4302 { "of", img_dd_of, C_OF },
4303 { "skip", img_dd_skip, C_SKIP },
4306 const struct option long_options[] = {
4307 { "help", no_argument, 0, 'h'},
4308 { "object", required_argument, 0, OPTION_OBJECT},
4309 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4310 { "force-share", no_argument, 0, 'U'},
4314 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4326 missing_argument(argv[optind - 1]);
4329 unrecognized_option(argv[optind - 1]);
4338 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4343 case OPTION_IMAGE_OPTS:
4349 for (i = optind; i < argc; i++) {
4351 arg = g_strdup(argv[i]);
4353 tmp = strchr(arg, '=');
4355 error_report("unrecognized operand %s", arg);
4362 for (j = 0; options[j].name != NULL; j++) {
4363 if (!strcmp(arg, options[j].name)) {
4367 if (options[j].name == NULL) {
4368 error_report("unrecognized operand %s", arg);
4373 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4377 dd.flags |= options[j].flag;
4382 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4383 error_report("Must specify both input and output files");
4388 if (qemu_opts_foreach(&qemu_object_opts,
4389 user_creatable_add_opts_foreach,
4395 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4403 drv = bdrv_find_format(out_fmt);
4405 error_report("Unknown file format");
4409 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4412 error_report_err(local_err);
4416 if (!drv->create_opts) {
4417 error_report("Format driver '%s' does not support image creation",
4422 if (!proto_drv->create_opts) {
4423 error_report("Protocol driver '%s' does not support image creation",
4424 proto_drv->format_name);
4428 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4429 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4431 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4433 size = blk_getlength(blk1);
4435 error_report("Failed to get size for '%s'", in.filename);
4440 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4441 dd.count * in.bsz < size) {
4442 size = dd.count * in.bsz;
4445 /* Overflow means the specified offset is beyond input image's size */
4446 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4447 size < in.bsz * in.offset)) {
4448 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4450 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4451 size - in.bsz * in.offset, &error_abort);
4454 ret = bdrv_create(drv, out.filename, opts, &local_err);
4456 error_reportf_err(local_err,
4457 "%s: error while creating output image: ",
4463 /* TODO, we can't honour --image-opts for the target,
4464 * since it needs to be given in a format compatible
4465 * with the bdrv_create() call above which does not
4466 * support image-opts style.
4468 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
4469 false, false, false);
4476 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4477 size < in.offset * in.bsz)) {
4478 /* We give a warning if the skip option is bigger than the input
4479 * size and create an empty output disk image (i.e. like dd(1)).
4481 error_report("%s: cannot skip to specified offset", in.filename);
4484 in_pos = in.offset * in.bsz;
4487 in.buf = g_new(uint8_t, in.bsz);
4489 for (out_pos = 0; in_pos < size; block_count++) {
4490 int in_ret, out_ret;
4492 if (in_pos + in.bsz > size) {
4493 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4495 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4498 error_report("error while reading from input image file: %s",
4505 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4508 error_report("error while writing to output image file: %s",
4509 strerror(-out_ret));
4518 qemu_opts_del(opts);
4519 qemu_opts_free(create_opts);
4522 g_free(in.filename);
4523 g_free(out.filename);
4533 static void dump_json_block_measure_info(BlockMeasureInfo *info)
4537 Visitor *v = qobject_output_visitor_new(&obj);
4539 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4540 visit_complete(v, &obj);
4541 str = qobject_to_json_pretty(obj);
4542 assert(str != NULL);
4543 printf("%s\n", qstring_get_str(str));
4549 static int img_measure(int argc, char **argv)
4551 static const struct option long_options[] = {
4552 {"help", no_argument, 0, 'h'},
4553 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4554 {"object", required_argument, 0, OPTION_OBJECT},
4555 {"output", required_argument, 0, OPTION_OUTPUT},
4556 {"size", required_argument, 0, OPTION_SIZE},
4557 {"force-share", no_argument, 0, 'U'},
4560 OutputFormat output_format = OFORMAT_HUMAN;
4561 BlockBackend *in_blk = NULL;
4563 const char *filename = NULL;
4564 const char *fmt = NULL;
4565 const char *out_fmt = "raw";
4566 char *options = NULL;
4567 char *snapshot_name = NULL;
4568 bool force_share = false;
4569 QemuOpts *opts = NULL;
4570 QemuOpts *object_opts = NULL;
4571 QemuOpts *sn_opts = NULL;
4572 QemuOptsList *create_opts = NULL;
4573 bool image_opts = false;
4574 uint64_t img_size = UINT64_MAX;
4575 BlockMeasureInfo *info = NULL;
4576 Error *local_err = NULL;
4580 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4581 long_options, NULL)) != -1) {
4594 if (!is_valid_option_list(optarg)) {
4595 error_report("Invalid option list: %s", optarg);
4599 options = g_strdup(optarg);
4601 char *old_options = options;
4602 options = g_strdup_printf("%s,%s", options, optarg);
4603 g_free(old_options);
4607 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4608 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4611 error_report("Failed in parsing snapshot param '%s'",
4616 snapshot_name = optarg;
4623 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4629 case OPTION_IMAGE_OPTS:
4633 if (!strcmp(optarg, "json")) {
4634 output_format = OFORMAT_JSON;
4635 } else if (!strcmp(optarg, "human")) {
4636 output_format = OFORMAT_HUMAN;
4638 error_report("--output must be used with human or json "
4647 sval = cvtnum(optarg);
4649 if (sval == -ERANGE) {
4650 error_report("Image size must be less than 8 EiB!");
4652 error_report("Invalid image size specified! You may use "
4653 "k, M, G, T, P or E suffixes for ");
4654 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4655 "petabytes and exabytes.");
4659 img_size = (uint64_t)sval;
4665 if (qemu_opts_foreach(&qemu_object_opts,
4666 user_creatable_add_opts_foreach,
4671 if (argc - optind > 1) {
4672 error_report("At most one filename argument is allowed.");
4674 } else if (argc - optind == 1) {
4675 filename = argv[optind];
4679 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4680 error_report("--object, --image-opts, -f, and -l "
4681 "require a filename argument.");
4684 if (filename && img_size != UINT64_MAX) {
4685 error_report("--size N cannot be used together with a filename.");
4688 if (!filename && img_size == UINT64_MAX) {
4689 error_report("Either --size N or one filename must be specified.");
4694 in_blk = img_open(image_opts, filename, fmt, 0,
4695 false, false, force_share);
4701 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4702 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4703 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4705 } else if (snapshot_name != NULL) {
4706 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4707 snapshot_name, &local_err);
4710 error_reportf_err(local_err, "Failed to load snapshot: ");
4715 drv = bdrv_find_format(out_fmt);
4717 error_report("Unknown file format '%s'", out_fmt);
4720 if (!drv->create_opts) {
4721 error_report("Format driver '%s' does not support image creation",
4726 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4727 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4728 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4730 qemu_opts_do_parse(opts, options, NULL, &local_err);
4732 error_report_err(local_err);
4733 error_report("Invalid options for file format '%s'", out_fmt);
4737 if (img_size != UINT64_MAX) {
4738 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4741 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4743 error_report_err(local_err);
4747 if (output_format == OFORMAT_HUMAN) {
4748 printf("required size: %" PRIu64 "\n", info->required);
4749 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4751 dump_json_block_measure_info(info);
4757 qapi_free_BlockMeasureInfo(info);
4758 qemu_opts_del(object_opts);
4759 qemu_opts_del(opts);
4760 qemu_opts_del(sn_opts);
4761 qemu_opts_free(create_opts);
4767 static const img_cmd_t img_cmds[] = {
4768 #define DEF(option, callback, arg_string) \
4769 { option, callback },
4770 #include "qemu-img-cmds.h"
4775 int main(int argc, char **argv)
4777 const img_cmd_t *cmd;
4778 const char *cmdname;
4779 Error *local_error = NULL;
4780 char *trace_file = NULL;
4782 static const struct option long_options[] = {
4783 {"help", no_argument, 0, 'h'},
4784 {"version", no_argument, 0, 'V'},
4785 {"trace", required_argument, NULL, 'T'},
4790 signal(SIGPIPE, SIG_IGN);
4793 module_call_init(MODULE_INIT_TRACE);
4794 error_set_progname(argv[0]);
4795 qemu_init_exec_dir(argv[0]);
4797 if (qemu_init_main_loop(&local_error)) {
4798 error_report_err(local_error);
4802 qcrypto_init(&error_fatal);
4804 module_call_init(MODULE_INIT_QOM);
4807 error_exit("Not enough arguments");
4810 qemu_add_opts(&qemu_object_opts);
4811 qemu_add_opts(&qemu_source_opts);
4812 qemu_add_opts(&qemu_trace_opts);
4814 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
4817 missing_argument(argv[optind - 1]);
4820 unrecognized_option(argv[optind - 1]);
4826 printf(QEMU_IMG_VERSION);
4830 trace_file = trace_opt_parse(optarg);
4835 cmdname = argv[optind];
4837 /* reset getopt_long scanning */
4845 if (!trace_init_backends()) {
4848 trace_init_file(trace_file);
4849 qemu_set_log(LOG_TRACE);
4851 /* find the command */
4852 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4853 if (!strcmp(cmdname, cmd->name)) {
4854 return cmd->handler(argc, argv);
4859 error_exit("Command not found: %s", cmdname);