2 * QEMU disk image utility
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "qemu/osdep.h"
28 #include "qemu-common.h"
29 #include "qemu-version.h"
30 #include "qapi/error.h"
31 #include "qapi/qapi-visit-block-core.h"
32 #include "qapi/qobject-output-visitor.h"
33 #include "qapi/qmp/qjson.h"
34 #include "qapi/qmp/qdict.h"
35 #include "qapi/qmp/qstring.h"
36 #include "qemu/cutils.h"
37 #include "qemu/config-file.h"
38 #include "qemu/option.h"
39 #include "qemu/error-report.h"
41 #include "qemu/module.h"
42 #include "qemu/units.h"
43 #include "qom/object_interfaces.h"
44 #include "sysemu/sysemu.h"
45 #include "sysemu/block-backend.h"
46 #include "block/block_int.h"
47 #include "block/blockjob.h"
48 #include "block/qapi.h"
49 #include "crypto/init.h"
50 #include "trace/control.h"
52 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
53 "\n" QEMU_COPYRIGHT "\n"
55 typedef struct img_cmd_t {
57 int (*handler)(int argc, char **argv);
62 OPTION_BACKING_CHAIN = 257,
64 OPTION_IMAGE_OPTS = 259,
66 OPTION_FLUSH_INTERVAL = 261,
67 OPTION_NO_DRAIN = 262,
68 OPTION_TARGET_IMAGE_OPTS = 263,
70 OPTION_PREALLOCATION = 265,
75 typedef enum OutputFormat {
80 /* Default to cache=writeback as data integrity is not important for qemu-img */
81 #define BDRV_DEFAULT_CACHE "writeback"
83 static void format_print(void *opaque, const char *name)
88 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
93 error_vreport(fmt, ap);
96 error_printf("Try 'qemu-img --help' for more information\n");
100 static void QEMU_NORETURN missing_argument(const char *option)
102 error_exit("missing argument for option '%s'", option);
105 static void QEMU_NORETURN unrecognized_option(const char *option)
107 error_exit("unrecognized option '%s'", option);
110 /* Please keep in synch with qemu-img.texi */
111 static void QEMU_NORETURN help(void)
113 const char *help_msg =
115 "usage: qemu-img [standard options] command [command options]\n"
116 "QEMU disk image utility\n"
118 " '-h', '--help' display this help and exit\n"
119 " '-V', '--version' output version information and exit\n"
120 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
121 " specify tracing options\n"
124 #define DEF(option, callback, arg_string) \
126 #include "qemu-img-cmds.h"
129 "Command parameters:\n"
130 " 'filename' is a disk image filename\n"
131 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
132 " manual page for a description of the object properties. The most common\n"
133 " object type is a 'secret', which is used to supply passwords and/or\n"
134 " encryption keys.\n"
135 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
136 " 'cache' is the cache mode used to write the output disk image, the valid\n"
137 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
138 " 'directsync' and 'unsafe' (default for convert)\n"
139 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
140 " options are the same as for the 'cache' option\n"
141 " 'size' is the disk image size in bytes. Optional suffixes\n"
142 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
143 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
144 " supported. 'b' is ignored.\n"
145 " 'output_filename' is the destination disk image filename\n"
146 " 'output_fmt' is the destination format\n"
147 " 'options' is a comma separated list of format specific options in a\n"
148 " name=value format. Use -o ? for an overview of the options supported by the\n"
150 " 'snapshot_param' is param used for internal snapshot, format\n"
151 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\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, false);
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 if (!drv->create_opts) {
253 error_report("Format driver '%s' does not support image creation", fmt);
257 create_opts = qemu_opts_append(create_opts, drv->create_opts);
259 proto_drv = bdrv_find_protocol(filename, true, &local_err);
261 error_report_err(local_err);
262 qemu_opts_free(create_opts);
265 if (!proto_drv->create_opts) {
266 error_report("Protocol driver '%s' does not support image creation",
267 proto_drv->format_name);
268 qemu_opts_free(create_opts);
271 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
275 printf("Supported options:\n");
277 printf("Supported %s options:\n", fmt);
279 qemu_opts_print_help(create_opts, false);
280 qemu_opts_free(create_opts);
284 "The protocol level may support further options.\n"
285 "Specify the target filename to include those options.\n");
292 static BlockBackend *img_open_opts(const char *optstr,
293 QemuOpts *opts, int flags, bool writethrough,
294 bool quiet, bool force_share)
297 Error *local_err = NULL;
299 options = qemu_opts_to_qdict(opts, NULL);
301 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
302 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
303 error_report("--force-share/-U conflicts with image options");
304 qobject_unref(options);
307 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
309 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
311 error_reportf_err(local_err, "Could not open '%s': ", optstr);
314 blk_set_enable_write_cache(blk, !writethrough);
319 static BlockBackend *img_open_file(const char *filename,
321 const char *fmt, int flags,
322 bool writethrough, bool quiet,
326 Error *local_err = NULL;
329 options = qdict_new();
332 qdict_put_str(options, "driver", fmt);
336 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
338 blk = blk_new_open(filename, NULL, options, flags, &local_err);
340 error_reportf_err(local_err, "Could not open '%s': ", filename);
343 blk_set_enable_write_cache(blk, !writethrough);
349 static int img_add_key_secrets(void *opaque,
350 const char *name, const char *value,
353 QDict *options = opaque;
355 if (g_str_has_suffix(name, "key-secret")) {
356 qdict_put_str(options, name, value);
363 static BlockBackend *img_open(bool image_opts,
364 const char *filename,
365 const char *fmt, int flags, bool writethrough,
366 bool quiet, bool force_share)
372 error_report("--image-opts and --format are mutually exclusive");
375 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
380 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
383 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
390 static int add_old_style_options(const char *fmt, QemuOpts *opts,
391 const char *base_filename,
392 const char *base_fmt)
397 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
399 error_report("Backing file not supported for file format '%s'",
406 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
408 error_report("Backing file format not supported for file "
417 static int64_t cvtnum(const char *s)
422 err = qemu_strtosz(s, NULL, &value);
426 if (value > INT64_MAX) {
432 static int img_create(int argc, char **argv)
435 uint64_t img_size = -1;
436 const char *fmt = "raw";
437 const char *base_fmt = NULL;
438 const char *filename;
439 const char *base_filename = NULL;
440 char *options = NULL;
441 Error *local_err = NULL;
446 static const struct option long_options[] = {
447 {"help", no_argument, 0, 'h'},
448 {"object", required_argument, 0, OPTION_OBJECT},
451 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
458 missing_argument(argv[optind - 1]);
461 unrecognized_option(argv[optind - 1]);
470 base_filename = optarg;
476 if (!is_valid_option_list(optarg)) {
477 error_report("Invalid option list: %s", optarg);
481 options = g_strdup(optarg);
483 char *old_options = options;
484 options = g_strdup_printf("%s,%s", options, optarg);
492 flags |= BDRV_O_NO_BACKING;
494 case OPTION_OBJECT: {
496 opts = qemu_opts_parse_noisily(&qemu_object_opts,
505 /* Get the filename */
506 filename = (optind < argc) ? argv[optind] : NULL;
507 if (options && has_help_option(options)) {
509 return print_block_option_help(filename, fmt);
512 if (optind >= argc) {
513 error_exit("Expecting image file name");
517 if (qemu_opts_foreach(&qemu_object_opts,
518 user_creatable_add_opts_foreach,
519 NULL, &error_fatal)) {
523 /* Get image size, if specified */
527 sval = cvtnum(argv[optind++]);
529 if (sval == -ERANGE) {
530 error_report("Image size must be less than 8 EiB!");
532 error_report("Invalid image size specified! You may use k, M, "
533 "G, T, P or E suffixes for ");
534 error_report("kilobytes, megabytes, gigabytes, terabytes, "
535 "petabytes and exabytes.");
539 img_size = (uint64_t)sval;
541 if (optind != argc) {
542 error_exit("Unexpected argument: %s", argv[optind]);
545 bdrv_img_create(filename, fmt, base_filename, base_fmt,
546 options, img_size, flags, quiet, &local_err);
548 error_reportf_err(local_err, "%s: ", filename);
560 static void dump_json_image_check(ImageCheck *check, bool quiet)
564 Visitor *v = qobject_output_visitor_new(&obj);
566 visit_type_ImageCheck(v, NULL, &check, &error_abort);
567 visit_complete(v, &obj);
568 str = qobject_to_json_pretty(obj);
570 qprintf(quiet, "%s\n", qstring_get_str(str));
576 static void dump_human_image_check(ImageCheck *check, bool quiet)
578 if (!(check->corruptions || check->leaks || check->check_errors)) {
579 qprintf(quiet, "No errors were found on the image.\n");
581 if (check->corruptions) {
582 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
583 "Data may be corrupted, or further writes to the image "
590 "\n%" PRId64 " leaked clusters were found on the image.\n"
591 "This means waste of disk space, but no harm to data.\n",
595 if (check->check_errors) {
598 " internal errors have occurred during the check.\n",
599 check->check_errors);
603 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
604 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
605 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
606 check->allocated_clusters, check->total_clusters,
607 check->allocated_clusters * 100.0 / check->total_clusters,
608 check->fragmented_clusters * 100.0 / check->allocated_clusters,
609 check->compressed_clusters * 100.0 /
610 check->allocated_clusters);
613 if (check->image_end_offset) {
615 "Image end offset: %" PRId64 "\n", check->image_end_offset);
619 static int collect_image_check(BlockDriverState *bs,
621 const char *filename,
626 BdrvCheckResult result;
628 ret = bdrv_check(bs, &result, fix);
633 check->filename = g_strdup(filename);
634 check->format = g_strdup(bdrv_get_format_name(bs));
635 check->check_errors = result.check_errors;
636 check->corruptions = result.corruptions;
637 check->has_corruptions = result.corruptions != 0;
638 check->leaks = result.leaks;
639 check->has_leaks = result.leaks != 0;
640 check->corruptions_fixed = result.corruptions_fixed;
641 check->has_corruptions_fixed = result.corruptions != 0;
642 check->leaks_fixed = result.leaks_fixed;
643 check->has_leaks_fixed = result.leaks != 0;
644 check->image_end_offset = result.image_end_offset;
645 check->has_image_end_offset = result.image_end_offset != 0;
646 check->total_clusters = result.bfi.total_clusters;
647 check->has_total_clusters = result.bfi.total_clusters != 0;
648 check->allocated_clusters = result.bfi.allocated_clusters;
649 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
650 check->fragmented_clusters = result.bfi.fragmented_clusters;
651 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
652 check->compressed_clusters = result.bfi.compressed_clusters;
653 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
659 * Checks an image for consistency. Exit codes:
661 * 0 - Check completed, image is good
662 * 1 - Check not completed because of internal errors
663 * 2 - Check completed, image is corrupted
664 * 3 - Check completed, image has leaked clusters, but is good otherwise
665 * 63 - Checks are not supported by the image format
667 static int img_check(int argc, char **argv)
670 OutputFormat output_format = OFORMAT_HUMAN;
671 const char *filename, *fmt, *output, *cache;
673 BlockDriverState *bs;
675 int flags = BDRV_O_CHECK;
679 bool image_opts = false;
680 bool force_share = false;
684 cache = BDRV_DEFAULT_CACHE;
687 int option_index = 0;
688 static const struct option long_options[] = {
689 {"help", no_argument, 0, 'h'},
690 {"format", required_argument, 0, 'f'},
691 {"repair", required_argument, 0, 'r'},
692 {"output", required_argument, 0, OPTION_OUTPUT},
693 {"object", required_argument, 0, OPTION_OBJECT},
694 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
695 {"force-share", no_argument, 0, 'U'},
698 c = getopt_long(argc, argv, ":hf:r:T:qU",
699 long_options, &option_index);
705 missing_argument(argv[optind - 1]);
708 unrecognized_option(argv[optind - 1]);
717 flags |= BDRV_O_RDWR;
719 if (!strcmp(optarg, "leaks")) {
720 fix = BDRV_FIX_LEAKS;
721 } else if (!strcmp(optarg, "all")) {
722 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
724 error_exit("Unknown option value for -r "
725 "(expecting 'leaks' or 'all'): %s", optarg);
740 case OPTION_OBJECT: {
742 opts = qemu_opts_parse_noisily(&qemu_object_opts,
748 case OPTION_IMAGE_OPTS:
753 if (optind != argc - 1) {
754 error_exit("Expecting one image file name");
756 filename = argv[optind++];
758 if (output && !strcmp(output, "json")) {
759 output_format = OFORMAT_JSON;
760 } else if (output && !strcmp(output, "human")) {
761 output_format = OFORMAT_HUMAN;
763 error_report("--output must be used with human or json as argument.");
767 if (qemu_opts_foreach(&qemu_object_opts,
768 user_creatable_add_opts_foreach,
769 NULL, &error_fatal)) {
773 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
775 error_report("Invalid source cache option: %s", cache);
779 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
786 check = g_new0(ImageCheck, 1);
787 ret = collect_image_check(bs, check, filename, fmt, fix);
789 if (ret == -ENOTSUP) {
790 error_report("This image format does not support checks");
795 if (check->corruptions_fixed || check->leaks_fixed) {
796 int corruptions_fixed, leaks_fixed;
798 leaks_fixed = check->leaks_fixed;
799 corruptions_fixed = check->corruptions_fixed;
801 if (output_format == OFORMAT_HUMAN) {
803 "The following inconsistencies were found and repaired:\n\n"
804 " %" PRId64 " leaked clusters\n"
805 " %" PRId64 " corruptions\n\n"
806 "Double checking the fixed image now...\n",
808 check->corruptions_fixed);
811 ret = collect_image_check(bs, check, filename, fmt, 0);
813 check->leaks_fixed = leaks_fixed;
814 check->corruptions_fixed = corruptions_fixed;
818 switch (output_format) {
820 dump_human_image_check(check, quiet);
823 dump_json_image_check(check, quiet);
828 if (ret || check->check_errors) {
830 error_report("Check failed: %s", strerror(-ret));
832 error_report("Check failed");
838 if (check->corruptions) {
840 } else if (check->leaks) {
847 qapi_free_ImageCheck(check);
852 typedef struct CommonBlockJobCBInfo {
853 BlockDriverState *bs;
855 } CommonBlockJobCBInfo;
857 static void common_block_job_cb(void *opaque, int ret)
859 CommonBlockJobCBInfo *cbi = opaque;
862 error_setg_errno(cbi->errp, -ret, "Block job failed");
866 static void run_block_job(BlockJob *job, Error **errp)
868 AioContext *aio_context = blk_get_aio_context(job->blk);
871 aio_context_acquire(aio_context);
874 float progress = 0.0f;
875 aio_poll(aio_context, true);
876 if (job->job.progress_total) {
877 progress = (float)job->job.progress_current /
878 job->job.progress_total * 100.f;
880 qemu_progress_print(progress, 0);
881 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
883 if (!job_is_completed(&job->job)) {
884 ret = job_complete_sync(&job->job, errp);
888 job_unref(&job->job);
889 aio_context_release(aio_context);
891 /* publish completion progress only when success */
893 qemu_progress_print(100.f, 0);
897 static int img_commit(int argc, char **argv)
900 const char *filename, *fmt, *cache, *base;
902 BlockDriverState *bs, *base_bs;
904 bool progress = false, quiet = false, drop = false;
906 Error *local_err = NULL;
907 CommonBlockJobCBInfo cbi;
908 bool image_opts = false;
909 AioContext *aio_context;
912 cache = BDRV_DEFAULT_CACHE;
915 static const struct option long_options[] = {
916 {"help", no_argument, 0, 'h'},
917 {"object", required_argument, 0, OPTION_OBJECT},
918 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
921 c = getopt_long(argc, argv, ":f:ht:b:dpq",
928 missing_argument(argv[optind - 1]);
931 unrecognized_option(argv[optind - 1]);
956 case OPTION_OBJECT: {
958 opts = qemu_opts_parse_noisily(&qemu_object_opts,
964 case OPTION_IMAGE_OPTS:
970 /* Progress is not shown in Quiet mode */
975 if (optind != argc - 1) {
976 error_exit("Expecting one image file name");
978 filename = argv[optind++];
980 if (qemu_opts_foreach(&qemu_object_opts,
981 user_creatable_add_opts_foreach,
982 NULL, &error_fatal)) {
986 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
987 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
989 error_report("Invalid cache option: %s", cache);
993 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1000 qemu_progress_init(progress, 1.f);
1001 qemu_progress_print(0.f, 100);
1004 base_bs = bdrv_find_backing_image(bs, base);
1006 error_setg(&local_err,
1007 "Did not find '%s' in the backing chain of '%s'",
1012 /* This is different from QMP, which by default uses the deepest file in
1013 * the backing chain (i.e., the very base); however, the traditional
1014 * behavior of qemu-img commit is using the immediate backing file. */
1015 base_bs = backing_bs(bs);
1017 error_setg(&local_err, "Image does not have a backing file");
1022 cbi = (CommonBlockJobCBInfo){
1027 aio_context = bdrv_get_aio_context(bs);
1028 aio_context_acquire(aio_context);
1029 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
1030 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1031 &cbi, false, &local_err);
1032 aio_context_release(aio_context);
1037 /* When the block job completes, the BlockBackend reference will point to
1038 * the old backing file. In order to avoid that the top image is already
1039 * deleted, so we can still empty it afterwards, increment the reference
1040 * counter here preemptively. */
1045 job = block_job_get("commit");
1047 run_block_job(job, &local_err);
1052 if (!drop && bs->drv->bdrv_make_empty) {
1053 ret = bs->drv->bdrv_make_empty(bs);
1055 error_setg_errno(&local_err, -ret, "Could not empty %s",
1067 qemu_progress_end();
1072 error_report_err(local_err);
1076 qprintf(quiet, "Image committed.\n");
1081 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1082 * of the first sector boundary within buf where the sector contains a
1083 * non-zero byte. This function is robust to a buffer that is not
1086 static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1089 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1091 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1092 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1096 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1103 * Returns true iff the first sector pointed to by 'buf' contains at least
1106 * 'pnum' is set to the number of sectors (including and immediately following
1107 * the first one) that are known to be in the same allocated/unallocated state.
1108 * The function will try to align the end offset to alignment boundaries so
1109 * that the request will at least end aligned and consequtive requests will
1110 * also start at an aligned offset.
1112 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1113 int64_t sector_num, int alignment)
1122 is_zero = buffer_is_zero(buf, 512);
1123 for(i = 1; i < n; i++) {
1125 if (is_zero != buffer_is_zero(buf, 512)) {
1130 tail = (sector_num + i) & (alignment - 1);
1132 if (is_zero && i <= tail) {
1133 /* treat unallocated areas which only consist
1134 * of a small tail as allocated. */
1138 /* align up end offset of allocated areas. */
1139 i += alignment - tail;
1142 /* align down end offset of zero areas. */
1151 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1152 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1153 * breaking up write requests for only small sparse areas.
1155 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1156 int min, int64_t sector_num, int alignment)
1159 int num_checked, num_used;
1165 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1171 buf += BDRV_SECTOR_SIZE * *pnum;
1173 sector_num += *pnum;
1174 num_checked = num_used;
1177 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1179 buf += BDRV_SECTOR_SIZE * *pnum;
1181 sector_num += *pnum;
1182 num_checked += *pnum;
1184 num_used = num_checked;
1185 } else if (*pnum >= min) {
1195 * Compares two buffers sector by sector. Returns 0 if the first
1196 * sector of each buffer matches, non-zero otherwise.
1198 * pnum is set to the sector-aligned size of the buffer prefix that
1199 * has the same matching status as the first sector.
1201 static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1202 int64_t bytes, int64_t *pnum)
1205 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
1209 res = !!memcmp(buf1, buf2, i);
1211 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
1213 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
1223 #define IO_BUF_SIZE (2 * MiB)
1226 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1228 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1229 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1230 * failure), and 4 on error (the exit status for read errors), after emitting
1233 * @param blk: BlockBackend for the image
1234 * @param offset: Starting offset to check
1235 * @param bytes: Number of bytes to check
1236 * @param filename: Name of disk file we are checking (logging purpose)
1237 * @param buffer: Allocated buffer for storing read data
1238 * @param quiet: Flag for quiet mode
1240 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1241 int64_t bytes, const char *filename,
1242 uint8_t *buffer, bool quiet)
1247 ret = blk_pread(blk, offset, buffer, bytes);
1249 error_report("Error while reading offset %" PRId64 " of %s: %s",
1250 offset, filename, strerror(-ret));
1253 idx = find_nonzero(buffer, bytes);
1255 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1264 * Compares two images. Exit codes:
1266 * 0 - Images are identical
1268 * >1 - Error occurred
1270 static int img_compare(int argc, char **argv)
1272 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1273 BlockBackend *blk1, *blk2;
1274 BlockDriverState *bs1, *bs2;
1275 int64_t total_size1, total_size2;
1276 uint8_t *buf1 = NULL, *buf2 = NULL;
1277 int64_t pnum1, pnum2;
1278 int allocated1, allocated2;
1279 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1280 bool progress = false, quiet = false, strict = false;
1287 uint64_t progress_base;
1288 bool image_opts = false;
1289 bool force_share = false;
1291 cache = BDRV_DEFAULT_CACHE;
1293 static const struct option long_options[] = {
1294 {"help", no_argument, 0, 'h'},
1295 {"object", required_argument, 0, OPTION_OBJECT},
1296 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1297 {"force-share", no_argument, 0, 'U'},
1300 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1301 long_options, NULL);
1307 missing_argument(argv[optind - 1]);
1310 unrecognized_option(argv[optind - 1]);
1336 case OPTION_OBJECT: {
1338 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1345 case OPTION_IMAGE_OPTS:
1351 /* Progress is not shown in Quiet mode */
1357 if (optind != argc - 2) {
1358 error_exit("Expecting two image file names");
1360 filename1 = argv[optind++];
1361 filename2 = argv[optind++];
1363 if (qemu_opts_foreach(&qemu_object_opts,
1364 user_creatable_add_opts_foreach,
1365 NULL, &error_fatal)) {
1370 /* Initialize before goto out */
1371 qemu_progress_init(progress, 2.0);
1374 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1376 error_report("Invalid source cache option: %s", cache);
1381 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1388 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1397 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1398 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1399 total_size1 = blk_getlength(blk1);
1400 if (total_size1 < 0) {
1401 error_report("Can't get size of %s: %s",
1402 filename1, strerror(-total_size1));
1406 total_size2 = blk_getlength(blk2);
1407 if (total_size2 < 0) {
1408 error_report("Can't get size of %s: %s",
1409 filename2, strerror(-total_size2));
1413 total_size = MIN(total_size1, total_size2);
1414 progress_base = MAX(total_size1, total_size2);
1416 qemu_progress_print(0, 100);
1418 if (strict && total_size1 != total_size2) {
1420 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1424 while (offset < total_size) {
1425 int status1, status2;
1427 status1 = bdrv_block_status_above(bs1, NULL, offset,
1428 total_size1 - offset, &pnum1, NULL,
1432 error_report("Sector allocation test failed for %s", filename1);
1435 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1437 status2 = bdrv_block_status_above(bs2, NULL, offset,
1438 total_size2 - offset, &pnum2, NULL,
1442 error_report("Sector allocation test failed for %s", filename2);
1445 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1447 assert(pnum1 && pnum2);
1448 chunk = MIN(pnum1, pnum2);
1451 if (status1 != status2) {
1453 qprintf(quiet, "Strict mode: Offset %" PRId64
1454 " block status mismatch!\n", offset);
1458 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1460 } else if (allocated1 == allocated2) {
1464 chunk = MIN(chunk, IO_BUF_SIZE);
1465 ret = blk_pread(blk1, offset, buf1, chunk);
1467 error_report("Error while reading offset %" PRId64
1469 offset, filename1, strerror(-ret));
1473 ret = blk_pread(blk2, offset, buf2, chunk);
1475 error_report("Error while reading offset %" PRId64
1477 offset, filename2, strerror(-ret));
1481 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1482 if (ret || pnum != chunk) {
1483 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1484 offset + (ret ? 0 : pnum));
1490 chunk = MIN(chunk, IO_BUF_SIZE);
1492 ret = check_empty_sectors(blk1, offset, chunk,
1493 filename1, buf1, quiet);
1495 ret = check_empty_sectors(blk2, offset, chunk,
1496 filename2, buf1, quiet);
1503 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1506 if (total_size1 != total_size2) {
1507 BlockBackend *blk_over;
1508 const char *filename_over;
1510 qprintf(quiet, "Warning: Image size mismatch!\n");
1511 if (total_size1 > total_size2) {
1513 filename_over = filename1;
1516 filename_over = filename2;
1519 while (offset < progress_base) {
1520 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1521 progress_base - offset, &chunk,
1525 error_report("Sector allocation test failed for %s",
1530 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1531 chunk = MIN(chunk, IO_BUF_SIZE);
1532 ret = check_empty_sectors(blk_over, offset, chunk,
1533 filename_over, buf1, quiet);
1539 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1543 qprintf(quiet, "Images are identical.\n");
1553 qemu_progress_end();
1558 enum ImgConvertBlockStatus {
1564 #define MAX_COROUTINES 16
1566 typedef struct ImgConvertState {
1568 int64_t *src_sectors;
1570 int64_t total_sectors;
1571 int64_t allocated_sectors;
1572 int64_t allocated_done;
1575 enum ImgConvertBlockStatus status;
1576 int64_t sector_next_status;
1577 BlockBackend *target;
1580 bool unallocated_blocks_are_zero;
1581 bool target_has_backing;
1582 int64_t target_backing_sectors; /* negative if unknown */
1589 size_t cluster_sectors;
1591 long num_coroutines;
1592 int running_coroutines;
1593 Coroutine *co[MAX_COROUTINES];
1594 int64_t wait_sector_num[MAX_COROUTINES];
1599 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1600 int *src_cur, int64_t *src_cur_offset)
1603 *src_cur_offset = 0;
1604 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1605 *src_cur_offset += s->src_sectors[*src_cur];
1607 assert(*src_cur < s->src_num);
1611 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1613 int64_t src_cur_offset;
1614 int ret, n, src_cur;
1615 bool post_backing_zero = false;
1617 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1619 assert(s->total_sectors > sector_num);
1620 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1622 if (s->target_backing_sectors >= 0) {
1623 if (sector_num >= s->target_backing_sectors) {
1624 post_backing_zero = s->unallocated_blocks_are_zero;
1625 } else if (sector_num + n > s->target_backing_sectors) {
1626 /* Split requests around target_backing_sectors (because
1627 * starting from there, zeros are handled differently) */
1628 n = s->target_backing_sectors - sector_num;
1632 if (s->sector_next_status <= sector_num) {
1633 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1637 count = n * BDRV_SECTOR_SIZE;
1639 if (s->target_has_backing) {
1640 ret = bdrv_block_status(blk_bs(s->src[src_cur]), offset,
1641 count, &count, NULL, NULL);
1643 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1644 offset, count, &count, NULL,
1652 warn_report("error while reading block status at "
1653 "offset %" PRIu64 ": %s", offset,
1656 /* Just try to read the data, then */
1657 ret = BDRV_BLOCK_DATA;
1658 count = BDRV_SECTOR_SIZE;
1660 /* Retry on a shorter range */
1661 n = DIV_ROUND_UP(n, 4);
1664 error_report("error while reading block status at offset "
1665 "%" PRIu64 ": %s", offset, strerror(-ret));
1671 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1673 if (ret & BDRV_BLOCK_ZERO) {
1674 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
1675 } else if (ret & BDRV_BLOCK_DATA) {
1676 s->status = BLK_DATA;
1678 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1681 s->sector_next_status = sector_num + n;
1684 n = MIN(n, s->sector_next_status - sector_num);
1685 if (s->status == BLK_DATA) {
1686 n = MIN(n, s->buf_sectors);
1689 /* We need to write complete clusters for compressed images, so if an
1690 * unallocated area is shorter than that, we must consider the whole
1691 * cluster allocated. */
1692 if (s->compressed) {
1693 if (n < s->cluster_sectors) {
1694 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1695 s->status = BLK_DATA;
1697 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1704 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1705 int nb_sectors, uint8_t *buf)
1707 uint64_t single_read_until = 0;
1710 assert(nb_sectors <= s->buf_sectors);
1711 while (nb_sectors > 0) {
1714 int64_t bs_sectors, src_cur_offset;
1717 /* In the case of compression with multiple source files, we can get a
1718 * nb_sectors that spreads into the next part. So we must be able to
1719 * read across multiple BDSes for one convert_read() call. */
1720 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1721 blk = s->src[src_cur];
1722 bs_sectors = s->src_sectors[src_cur];
1724 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1726 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1727 if (single_read_until > offset) {
1731 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
1735 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1739 warn_report("error while reading offset %" PRIu64
1740 ": %s", offset, strerror(-ret));
1742 memset(buf, 0, BDRV_SECTOR_SIZE);
1751 buf += n * BDRV_SECTOR_SIZE;
1758 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1759 int nb_sectors, uint8_t *buf,
1760 enum ImgConvertBlockStatus status)
1764 while (nb_sectors > 0) {
1766 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1769 case BLK_BACKING_FILE:
1770 /* If we have a backing file, leave clusters unallocated that are
1771 * unallocated in the source image, so that the backing file is
1772 * visible at the respective offset. */
1773 assert(s->target_has_backing);
1777 /* If we're told to keep the target fully allocated (-S 0) or there
1778 * is real non-zero data, we must write it. Otherwise we can treat
1779 * it as zero sectors.
1780 * Compressed clusters need to be written as a whole, so in that
1781 * case we can only save the write if the buffer is completely
1783 if (!s->min_sparse ||
1785 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1786 sector_num, s->alignment)) ||
1788 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1790 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1791 n << BDRV_SECTOR_BITS, buf, flags);
1800 if (s->has_zero_init) {
1801 assert(!s->target_has_backing);
1804 ret = blk_co_pwrite_zeroes(s->target,
1805 sector_num << BDRV_SECTOR_BITS,
1806 n << BDRV_SECTOR_BITS,
1807 BDRV_REQ_MAY_UNMAP);
1816 buf += n * BDRV_SECTOR_SIZE;
1822 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1827 while (nb_sectors > 0) {
1830 int64_t bs_sectors, src_cur_offset;
1833 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1834 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1835 blk = s->src[src_cur];
1836 bs_sectors = s->src_sectors[src_cur];
1838 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1840 ret = blk_co_copy_range(blk, offset, s->target,
1841 sector_num << BDRV_SECTOR_BITS,
1842 n << BDRV_SECTOR_BITS, 0, 0);
1853 static void coroutine_fn convert_co_do_copy(void *opaque)
1855 ImgConvertState *s = opaque;
1856 uint8_t *buf = NULL;
1860 for (i = 0; i < s->num_coroutines; i++) {
1861 if (s->co[i] == qemu_coroutine_self()) {
1868 s->running_coroutines++;
1869 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1874 enum ImgConvertBlockStatus status;
1877 qemu_co_mutex_lock(&s->lock);
1878 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1879 qemu_co_mutex_unlock(&s->lock);
1882 n = convert_iteration_sectors(s, s->sector_num);
1884 qemu_co_mutex_unlock(&s->lock);
1888 /* save current sector and allocation status to local variables */
1889 sector_num = s->sector_num;
1891 if (!s->min_sparse && s->status == BLK_ZERO) {
1892 n = MIN(n, s->buf_sectors);
1894 /* increment global sector counter so that other coroutines can
1895 * already continue reading beyond this request */
1897 qemu_co_mutex_unlock(&s->lock);
1899 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1900 s->allocated_done += n;
1901 qemu_progress_print(100.0 * s->allocated_done /
1902 s->allocated_sectors, 0);
1906 copy_range = s->copy_range && s->status == BLK_DATA;
1907 if (status == BLK_DATA && !copy_range) {
1908 ret = convert_co_read(s, sector_num, n, buf);
1910 error_report("error while reading sector %" PRId64
1911 ": %s", sector_num, strerror(-ret));
1914 } else if (!s->min_sparse && status == BLK_ZERO) {
1916 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1919 if (s->wr_in_order) {
1920 /* keep writes in order */
1921 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
1922 s->wait_sector_num[index] = sector_num;
1923 qemu_coroutine_yield();
1925 s->wait_sector_num[index] = -1;
1928 if (s->ret == -EINPROGRESS) {
1930 ret = convert_co_copy_range(s, sector_num, n);
1932 s->copy_range = false;
1936 ret = convert_co_write(s, sector_num, n, buf, status);
1939 error_report("error while writing sector %" PRId64
1940 ": %s", sector_num, strerror(-ret));
1945 if (s->wr_in_order) {
1946 /* reenter the coroutine that might have waited
1947 * for this write to complete */
1948 s->wr_offs = sector_num + n;
1949 for (i = 0; i < s->num_coroutines; i++) {
1950 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1952 * A -> B -> A cannot occur because A has
1953 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1954 * B will never enter A during this time window.
1956 qemu_coroutine_enter(s->co[i]);
1964 s->co[index] = NULL;
1965 s->running_coroutines--;
1966 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1967 /* the convert job finished successfully */
1972 static int convert_do_copy(ImgConvertState *s)
1975 int64_t sector_num = 0;
1977 /* Check whether we have zero initialisation or can get it efficiently */
1978 s->has_zero_init = s->min_sparse && !s->target_has_backing
1979 ? bdrv_has_zero_init(blk_bs(s->target))
1982 if (!s->has_zero_init && !s->target_has_backing &&
1983 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1985 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
1987 s->has_zero_init = true;
1991 /* Allocate buffer for copied data. For compressed images, only one cluster
1992 * can be copied at a time. */
1993 if (s->compressed) {
1994 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1995 error_report("invalid cluster size");
1998 s->buf_sectors = s->cluster_sectors;
2001 while (sector_num < s->total_sectors) {
2002 n = convert_iteration_sectors(s, sector_num);
2006 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2008 s->allocated_sectors += n;
2014 s->sector_next_status = 0;
2015 s->ret = -EINPROGRESS;
2017 qemu_co_mutex_init(&s->lock);
2018 for (i = 0; i < s->num_coroutines; i++) {
2019 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2020 s->wait_sector_num[i] = -1;
2021 qemu_coroutine_enter(s->co[i]);
2024 while (s->running_coroutines) {
2025 main_loop_wait(false);
2028 if (s->compressed && !s->ret) {
2029 /* signal EOF to align */
2030 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
2039 #define MAX_BUF_SECTORS 32768
2041 static int img_convert(int argc, char **argv)
2043 int c, bs_i, flags, src_flags = 0;
2044 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
2045 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2046 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
2047 BlockDriver *drv = NULL, *proto_drv = NULL;
2048 BlockDriverInfo bdi;
2049 BlockDriverState *out_bs;
2050 QemuOpts *opts = NULL, *sn_opts = NULL;
2051 QemuOptsList *create_opts = NULL;
2052 QDict *open_opts = NULL;
2053 char *options = NULL;
2054 Error *local_err = NULL;
2055 bool writethrough, src_writethrough, image_opts = false,
2056 skip_create = false, progress = false, tgt_image_opts = false;
2057 int64_t ret = -EINVAL;
2058 bool force_share = false;
2059 bool explict_min_sparse = false;
2061 ImgConvertState s = (ImgConvertState) {
2062 /* Need at least 4k of zeros for sparse detection */
2064 .copy_range = false,
2065 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2066 .wr_in_order = true,
2067 .num_coroutines = 8,
2071 static const struct option long_options[] = {
2072 {"help", no_argument, 0, 'h'},
2073 {"object", required_argument, 0, OPTION_OBJECT},
2074 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2075 {"force-share", no_argument, 0, 'U'},
2076 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
2077 {"salvage", no_argument, 0, OPTION_SALVAGE},
2080 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2081 long_options, NULL);
2087 missing_argument(argv[optind - 1]);
2090 unrecognized_option(argv[optind - 1]);
2102 out_baseimg = optarg;
2105 s.copy_range = true;
2108 s.compressed = true;
2111 if (!is_valid_option_list(optarg)) {
2112 error_report("Invalid option list: %s", optarg);
2116 options = g_strdup(optarg);
2118 char *old_options = options;
2119 options = g_strdup_printf("%s,%s", options, optarg);
2120 g_free(old_options);
2124 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2125 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2128 error_report("Failed in parsing snapshot param '%s'",
2133 snapshot_name = optarg;
2140 sval = cvtnum(optarg);
2141 if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
2142 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2143 error_report("Invalid buffer size for sparse output specified. "
2144 "Valid sizes are multiples of %llu up to %llu. Select "
2145 "0 to disable sparse detection (fully allocates output).",
2146 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
2150 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2151 explict_min_sparse = true;
2170 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2171 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2172 error_report("Invalid number of coroutines. Allowed number of"
2173 " coroutines is between 1 and %d", MAX_COROUTINES);
2178 s.wr_in_order = false;
2183 case OPTION_OBJECT: {
2184 QemuOpts *object_opts;
2185 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2192 case OPTION_IMAGE_OPTS:
2195 case OPTION_SALVAGE:
2198 case OPTION_TARGET_IMAGE_OPTS:
2199 tgt_image_opts = true;
2204 if (!out_fmt && !tgt_image_opts) {
2208 if (qemu_opts_foreach(&qemu_object_opts,
2209 user_creatable_add_opts_foreach,
2210 NULL, &error_fatal)) {
2214 if (s.compressed && s.copy_range) {
2215 error_report("Cannot enable copy offloading when -c is used");
2219 if (explict_min_sparse && s.copy_range) {
2220 error_report("Cannot enable copy offloading when -S is used");
2224 if (s.copy_range && s.salvage) {
2225 error_report("Cannot use copy offloading in salvaging mode");
2229 if (tgt_image_opts && !skip_create) {
2230 error_report("--target-image-opts requires use of -n flag");
2234 s.src_num = argc - optind - 1;
2235 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2237 if (options && has_help_option(options)) {
2239 ret = print_block_option_help(out_filename, out_fmt);
2242 error_report("Option help requires a format be specified");
2247 if (s.src_num < 1) {
2248 error_report("Must specify image file name");
2253 /* ret is still -EINVAL until here */
2254 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2256 error_report("Invalid source cache option: %s", src_cache);
2260 /* Initialize before goto out */
2264 qemu_progress_init(progress, 1.0);
2265 qemu_progress_print(0, 100);
2267 s.src = g_new0(BlockBackend *, s.src_num);
2268 s.src_sectors = g_new(int64_t, s.src_num);
2270 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2271 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2272 fmt, src_flags, src_writethrough, s.quiet,
2278 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2279 if (s.src_sectors[bs_i] < 0) {
2280 error_report("Could not get size of %s: %s",
2281 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2285 s.total_sectors += s.src_sectors[bs_i];
2289 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2290 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2291 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2293 } else if (snapshot_name != NULL) {
2294 if (s.src_num > 1) {
2295 error_report("No support for concatenating multiple snapshot");
2300 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2304 error_reportf_err(local_err, "Failed to load snapshot: ");
2310 /* Find driver and parse its options */
2311 drv = bdrv_find_format(out_fmt);
2313 error_report("Unknown file format '%s'", out_fmt);
2318 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2320 error_report_err(local_err);
2325 if (!drv->create_opts) {
2326 error_report("Format driver '%s' does not support image creation",
2332 if (!proto_drv->create_opts) {
2333 error_report("Protocol driver '%s' does not support image creation",
2334 proto_drv->format_name);
2339 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2340 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2342 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2344 qemu_opts_do_parse(opts, options, NULL, &local_err);
2346 error_report_err(local_err);
2352 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2354 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2360 /* Get backing file name if -o backing_file was used */
2361 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2362 if (out_baseimg_param) {
2363 out_baseimg = out_baseimg_param;
2365 s.target_has_backing = (bool) out_baseimg;
2367 if (s.src_num > 1 && out_baseimg) {
2368 error_report("Having a backing file for the target makes no sense when "
2369 "concatenating multiple input images");
2374 /* Check if compression is supported */
2377 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2378 const char *encryptfmt =
2379 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2380 const char *preallocation =
2381 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2383 if (drv && !drv->bdrv_co_pwritev_compressed) {
2384 error_report("Compression not supported for this file format");
2389 if (encryption || encryptfmt) {
2390 error_report("Compression and encryption not supported at "
2397 && strcmp(preallocation, "off"))
2399 error_report("Compression and preallocation not supported at "
2407 * The later open call will need any decryption secrets, and
2408 * bdrv_create() will purge "opts", so extract them now before
2412 open_opts = qdict_new();
2413 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2417 /* Create the new image */
2418 ret = bdrv_create(drv, out_filename, opts, &local_err);
2420 error_reportf_err(local_err, "%s: error while converting %s: ",
2421 out_filename, out_fmt);
2426 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2427 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2429 error_report("Invalid cache option: %s", cache);
2434 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2435 flags, writethrough, s.quiet, false);
2437 /* TODO ultimately we should allow --target-image-opts
2438 * to be used even when -n is not given.
2439 * That has to wait for bdrv_create to be improved
2440 * to allow filenames in option syntax
2442 s.target = img_open_file(out_filename, open_opts, out_fmt,
2443 flags, writethrough, s.quiet, false);
2444 open_opts = NULL; /* blk_new_open will have freed it */
2450 out_bs = blk_bs(s.target);
2452 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2453 error_report("Compression not supported for this file format");
2458 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2459 * or discard_alignment of the out_bs is greater. Limit to
2460 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2461 s.buf_sectors = MIN(MAX_BUF_SECTORS,
2463 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2464 out_bs->bl.pdiscard_alignment >>
2465 BDRV_SECTOR_BITS)));
2467 /* try to align the write requests to the destination to avoid unnecessary
2469 s.alignment = MAX(pow2floor(s.min_sparse),
2470 DIV_ROUND_UP(out_bs->bl.request_alignment,
2472 assert(is_power_of_2(s.alignment));
2475 int64_t output_sectors = blk_nb_sectors(s.target);
2476 if (output_sectors < 0) {
2477 error_report("unable to get output image length: %s",
2478 strerror(-output_sectors));
2481 } else if (output_sectors < s.total_sectors) {
2482 error_report("output file is smaller than input file");
2488 if (s.target_has_backing) {
2489 /* Errors are treated as "backing length unknown" (which means
2490 * s.target_backing_sectors has to be negative, which it will
2491 * be automatically). The backing file length is used only
2492 * for optimizations, so such a case is not fatal. */
2493 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2495 s.target_backing_sectors = -1;
2498 ret = bdrv_get_info(out_bs, &bdi);
2501 error_report("could not get block driver info");
2505 s.compressed = s.compressed || bdi.needs_compressed_writes;
2506 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2507 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
2510 ret = convert_do_copy(&s);
2513 qemu_progress_print(100, 0);
2515 qemu_progress_end();
2516 qemu_opts_del(opts);
2517 qemu_opts_free(create_opts);
2518 qemu_opts_del(sn_opts);
2519 qobject_unref(open_opts);
2520 blk_unref(s.target);
2522 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2523 blk_unref(s.src[bs_i]);
2527 g_free(s.src_sectors);
2535 static void dump_snapshots(BlockDriverState *bs)
2537 QEMUSnapshotInfo *sn_tab, *sn;
2540 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2543 printf("Snapshot list:\n");
2544 bdrv_snapshot_dump(NULL);
2546 for(i = 0; i < nb_sns; i++) {
2548 bdrv_snapshot_dump(sn);
2554 static void dump_json_image_info_list(ImageInfoList *list)
2558 Visitor *v = qobject_output_visitor_new(&obj);
2560 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2561 visit_complete(v, &obj);
2562 str = qobject_to_json_pretty(obj);
2563 assert(str != NULL);
2564 printf("%s\n", qstring_get_str(str));
2570 static void dump_json_image_info(ImageInfo *info)
2574 Visitor *v = qobject_output_visitor_new(&obj);
2576 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2577 visit_complete(v, &obj);
2578 str = qobject_to_json_pretty(obj);
2579 assert(str != NULL);
2580 printf("%s\n", qstring_get_str(str));
2586 static void dump_human_image_info_list(ImageInfoList *list)
2588 ImageInfoList *elem;
2591 for (elem = list; elem; elem = elem->next) {
2597 bdrv_image_info_dump(elem->value);
2601 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2603 return strcmp(a, b) == 0;
2607 * Open an image file chain and return an ImageInfoList
2609 * @filename: topmost image filename
2610 * @fmt: topmost image format (may be NULL to autodetect)
2611 * @chain: true - enumerate entire backing file chain
2612 * false - only topmost image file
2614 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2615 * image file. If there was an error a message will have been printed to
2618 static ImageInfoList *collect_image_info_list(bool image_opts,
2619 const char *filename,
2621 bool chain, bool force_share)
2623 ImageInfoList *head = NULL;
2624 ImageInfoList **last = &head;
2625 GHashTable *filenames;
2628 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2632 BlockDriverState *bs;
2634 ImageInfoList *elem;
2636 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2637 error_report("Backing file '%s' creates an infinite loop.",
2641 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2643 blk = img_open(image_opts, filename, fmt,
2644 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2651 bdrv_query_image_info(bs, &info, &err);
2653 error_report_err(err);
2658 elem = g_new0(ImageInfoList, 1);
2665 filename = fmt = NULL;
2667 if (info->has_full_backing_filename) {
2668 filename = info->full_backing_filename;
2669 } else if (info->has_backing_filename) {
2670 error_report("Could not determine absolute backing filename,"
2671 " but backing filename '%s' present",
2672 info->backing_filename);
2675 if (info->has_backing_filename_format) {
2676 fmt = info->backing_filename_format;
2680 g_hash_table_destroy(filenames);
2684 qapi_free_ImageInfoList(head);
2685 g_hash_table_destroy(filenames);
2689 static int img_info(int argc, char **argv)
2692 OutputFormat output_format = OFORMAT_HUMAN;
2694 const char *filename, *fmt, *output;
2695 ImageInfoList *list;
2696 bool image_opts = false;
2697 bool force_share = false;
2702 int option_index = 0;
2703 static const struct option long_options[] = {
2704 {"help", no_argument, 0, 'h'},
2705 {"format", required_argument, 0, 'f'},
2706 {"output", required_argument, 0, OPTION_OUTPUT},
2707 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2708 {"object", required_argument, 0, OPTION_OBJECT},
2709 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2710 {"force-share", no_argument, 0, 'U'},
2713 c = getopt_long(argc, argv, ":f:hU",
2714 long_options, &option_index);
2720 missing_argument(argv[optind - 1]);
2723 unrecognized_option(argv[optind - 1]);
2737 case OPTION_BACKING_CHAIN:
2740 case OPTION_OBJECT: {
2742 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2748 case OPTION_IMAGE_OPTS:
2753 if (optind != argc - 1) {
2754 error_exit("Expecting one image file name");
2756 filename = argv[optind++];
2758 if (output && !strcmp(output, "json")) {
2759 output_format = OFORMAT_JSON;
2760 } else if (output && !strcmp(output, "human")) {
2761 output_format = OFORMAT_HUMAN;
2762 } else if (output) {
2763 error_report("--output must be used with human or json as argument.");
2767 if (qemu_opts_foreach(&qemu_object_opts,
2768 user_creatable_add_opts_foreach,
2769 NULL, &error_fatal)) {
2773 list = collect_image_info_list(image_opts, filename, fmt, chain,
2779 switch (output_format) {
2781 dump_human_image_info_list(list);
2785 dump_json_image_info_list(list);
2787 dump_json_image_info(list->value);
2792 qapi_free_ImageInfoList(list);
2796 static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2799 switch (output_format) {
2801 if (e->data && !e->has_offset) {
2802 error_report("File contains external, encrypted or compressed clusters.");
2805 if (e->data && !e->zero) {
2806 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2807 e->start, e->length,
2808 e->has_offset ? e->offset : 0,
2809 e->has_filename ? e->filename : "");
2811 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2812 * Modify the flags here to allow more coalescing.
2814 if (next && (!next->data || next->zero)) {
2820 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2821 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2822 (e->start == 0 ? "[" : ",\n"),
2823 e->start, e->length, e->depth,
2824 e->zero ? "true" : "false",
2825 e->data ? "true" : "false");
2826 if (e->has_offset) {
2827 printf(", \"offset\": %"PRId64"", e->offset);
2839 static int get_block_status(BlockDriverState *bs, int64_t offset,
2840 int64_t bytes, MapEntry *e)
2844 BlockDriverState *file;
2847 char *filename = NULL;
2849 /* As an optimization, we could cache the current range of unallocated
2850 * clusters in each file of the chain, and avoid querying the same
2856 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
2861 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2864 bs = backing_bs(bs);
2873 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2875 if (file && has_offset) {
2876 bdrv_refresh_filename(file);
2877 filename = file->filename;
2883 .data = !!(ret & BDRV_BLOCK_DATA),
2884 .zero = !!(ret & BDRV_BLOCK_ZERO),
2886 .has_offset = has_offset,
2888 .has_filename = filename,
2889 .filename = filename,
2895 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2897 if (curr->length == 0) {
2900 if (curr->zero != next->zero ||
2901 curr->data != next->data ||
2902 curr->depth != next->depth ||
2903 curr->has_filename != next->has_filename ||
2904 curr->has_offset != next->has_offset) {
2907 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2910 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2916 static int img_map(int argc, char **argv)
2919 OutputFormat output_format = OFORMAT_HUMAN;
2921 BlockDriverState *bs;
2922 const char *filename, *fmt, *output;
2924 MapEntry curr = { .length = 0 }, next;
2926 bool image_opts = false;
2927 bool force_share = false;
2932 int option_index = 0;
2933 static const struct option long_options[] = {
2934 {"help", no_argument, 0, 'h'},
2935 {"format", required_argument, 0, 'f'},
2936 {"output", required_argument, 0, OPTION_OUTPUT},
2937 {"object", required_argument, 0, OPTION_OBJECT},
2938 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2939 {"force-share", no_argument, 0, 'U'},
2942 c = getopt_long(argc, argv, ":f:hU",
2943 long_options, &option_index);
2949 missing_argument(argv[optind - 1]);
2952 unrecognized_option(argv[optind - 1]);
2966 case OPTION_OBJECT: {
2968 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2974 case OPTION_IMAGE_OPTS:
2979 if (optind != argc - 1) {
2980 error_exit("Expecting one image file name");
2982 filename = argv[optind];
2984 if (output && !strcmp(output, "json")) {
2985 output_format = OFORMAT_JSON;
2986 } else if (output && !strcmp(output, "human")) {
2987 output_format = OFORMAT_HUMAN;
2988 } else if (output) {
2989 error_report("--output must be used with human or json as argument.");
2993 if (qemu_opts_foreach(&qemu_object_opts,
2994 user_creatable_add_opts_foreach,
2995 NULL, &error_fatal)) {
2999 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
3005 if (output_format == OFORMAT_HUMAN) {
3006 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3009 length = blk_getlength(blk);
3010 while (curr.start + curr.length < length) {
3011 int64_t offset = curr.start + curr.length;
3014 /* Probe up to 1 GiB at a time. */
3015 n = MIN(1 * GiB, length - offset);
3016 ret = get_block_status(bs, offset, n, &next);
3019 error_report("Could not read file metadata: %s", strerror(-ret));
3023 if (entry_mergeable(&curr, &next)) {
3024 curr.length += next.length;
3028 if (curr.length > 0) {
3029 ret = dump_map_entry(output_format, &curr, &next);
3037 ret = dump_map_entry(output_format, &curr, NULL);
3044 #define SNAPSHOT_LIST 1
3045 #define SNAPSHOT_CREATE 2
3046 #define SNAPSHOT_APPLY 3
3047 #define SNAPSHOT_DELETE 4
3049 static int img_snapshot(int argc, char **argv)
3052 BlockDriverState *bs;
3053 QEMUSnapshotInfo sn;
3054 char *filename, *snapshot_name = NULL;
3055 int c, ret = 0, bdrv_oflags;
3060 bool image_opts = false;
3061 bool force_share = false;
3063 bdrv_oflags = BDRV_O_RDWR;
3064 /* Parse commandline parameters */
3066 static const struct option long_options[] = {
3067 {"help", no_argument, 0, 'h'},
3068 {"object", required_argument, 0, OPTION_OBJECT},
3069 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3070 {"force-share", no_argument, 0, 'U'},
3073 c = getopt_long(argc, argv, ":la:c:d:hqU",
3074 long_options, NULL);
3080 missing_argument(argv[optind - 1]);
3083 unrecognized_option(argv[optind - 1]);
3090 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3093 action = SNAPSHOT_LIST;
3094 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
3098 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3101 action = SNAPSHOT_APPLY;
3102 snapshot_name = optarg;
3106 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3109 action = SNAPSHOT_CREATE;
3110 snapshot_name = optarg;
3114 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3117 action = SNAPSHOT_DELETE;
3118 snapshot_name = optarg;
3126 case OPTION_OBJECT: {
3128 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3134 case OPTION_IMAGE_OPTS:
3140 if (optind != argc - 1) {
3141 error_exit("Expecting one image file name");
3143 filename = argv[optind++];
3145 if (qemu_opts_foreach(&qemu_object_opts,
3146 user_creatable_add_opts_foreach,
3147 NULL, &error_fatal)) {
3151 /* Open the image */
3152 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3159 /* Perform the requested action */
3165 case SNAPSHOT_CREATE:
3166 memset(&sn, 0, sizeof(sn));
3167 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3169 qemu_gettimeofday(&tv);
3170 sn.date_sec = tv.tv_sec;
3171 sn.date_nsec = tv.tv_usec * 1000;
3173 ret = bdrv_snapshot_create(bs, &sn);
3175 error_report("Could not create snapshot '%s': %d (%s)",
3176 snapshot_name, ret, strerror(-ret));
3180 case SNAPSHOT_APPLY:
3181 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3183 error_reportf_err(err, "Could not apply snapshot '%s': ",
3188 case SNAPSHOT_DELETE:
3189 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3191 error_report("Could not delete snapshot '%s': snapshot not "
3192 "found", snapshot_name);
3195 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3197 error_reportf_err(err, "Could not delete snapshot '%s': ",
3213 static int img_rebase(int argc, char **argv)
3215 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3216 uint8_t *buf_old = NULL;
3217 uint8_t *buf_new = NULL;
3218 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
3220 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3221 int c, flags, src_flags, ret;
3222 bool writethrough, src_writethrough;
3224 bool force_share = false;
3227 Error *local_err = NULL;
3228 bool image_opts = false;
3230 /* Parse commandline parameters */
3232 cache = BDRV_DEFAULT_CACHE;
3233 src_cache = BDRV_DEFAULT_CACHE;
3237 static const struct option long_options[] = {
3238 {"help", no_argument, 0, 'h'},
3239 {"object", required_argument, 0, OPTION_OBJECT},
3240 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3241 {"force-share", no_argument, 0, 'U'},
3244 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3245 long_options, NULL);
3251 missing_argument(argv[optind - 1]);
3254 unrecognized_option(argv[optind - 1]);
3263 out_basefmt = optarg;
3266 out_baseimg = optarg;
3283 case OPTION_OBJECT: {
3285 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3291 case OPTION_IMAGE_OPTS:
3304 if (optind != argc - 1) {
3305 error_exit("Expecting one image file name");
3307 if (!unsafe && !out_baseimg) {
3308 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3310 filename = argv[optind++];
3312 if (qemu_opts_foreach(&qemu_object_opts,
3313 user_creatable_add_opts_foreach,
3314 NULL, &error_fatal)) {
3318 qemu_progress_init(progress, 2.0);
3319 qemu_progress_print(0, 100);
3321 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3322 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3324 error_report("Invalid cache option: %s", cache);
3329 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3331 error_report("Invalid source cache option: %s", src_cache);
3335 /* The source files are opened read-only, don't care about WCE */
3336 assert((src_flags & BDRV_O_RDWR) == 0);
3337 (void) src_writethrough;
3342 * Ignore the old backing file for unsafe rebase in case we want to correct
3343 * the reference to a renamed or moved backing file.
3345 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3353 if (out_basefmt != NULL) {
3354 if (bdrv_find_format(out_basefmt) == NULL) {
3355 error_report("Invalid format name: '%s'", out_basefmt);
3361 /* For safe rebasing we need to compare old and new backing file */
3363 QDict *options = NULL;
3364 BlockDriverState *base_bs = backing_bs(bs);
3367 blk_old_backing = blk_new(qemu_get_aio_context(),
3368 BLK_PERM_CONSISTENT_READ,
3370 ret = blk_insert_bs(blk_old_backing, base_bs,
3373 error_reportf_err(local_err,
3374 "Could not reuse old backing file '%s': ",
3379 blk_old_backing = NULL;
3382 if (out_baseimg[0]) {
3383 const char *overlay_filename;
3384 char *out_real_path;
3386 options = qdict_new();
3388 qdict_put_str(options, "driver", out_basefmt);
3391 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3394 bdrv_refresh_filename(bs);
3395 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3398 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3402 qobject_unref(options);
3403 error_reportf_err(local_err,
3404 "Could not resolve backing filename: ");
3410 * Find out whether we rebase an image on top of a previous image
3413 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
3414 if (prefix_chain_bs) {
3415 qobject_unref(options);
3416 g_free(out_real_path);
3418 blk_new_backing = blk_new(qemu_get_aio_context(),
3419 BLK_PERM_CONSISTENT_READ,
3421 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3424 error_reportf_err(local_err,
3425 "Could not reuse backing file '%s': ",
3430 blk_new_backing = blk_new_open(out_real_path, NULL,
3431 options, src_flags, &local_err);
3432 g_free(out_real_path);
3433 if (!blk_new_backing) {
3434 error_reportf_err(local_err,
3435 "Could not open new backing file '%s': ",
3445 * Check each unallocated cluster in the COW file. If it is unallocated,
3446 * accesses go to the backing file. We must therefore compare this cluster
3447 * in the old and new backing file, and if they differ we need to copy it
3448 * from the old backing file into the COW file.
3450 * If qemu-img crashes during this step, no harm is done. The content of
3451 * the image is the same as the original one at any time.
3455 int64_t old_backing_size = 0;
3456 int64_t new_backing_size = 0;
3459 float local_progress = 0;
3461 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3462 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3464 size = blk_getlength(blk);
3466 error_report("Could not get size of '%s': %s",
3467 filename, strerror(-size));
3471 if (blk_old_backing) {
3472 old_backing_size = blk_getlength(blk_old_backing);
3473 if (old_backing_size < 0) {
3474 char backing_name[PATH_MAX];
3476 bdrv_get_backing_filename(bs, backing_name,
3477 sizeof(backing_name));
3478 error_report("Could not get size of '%s': %s",
3479 backing_name, strerror(-old_backing_size));
3484 if (blk_new_backing) {
3485 new_backing_size = blk_getlength(blk_new_backing);
3486 if (new_backing_size < 0) {
3487 error_report("Could not get size of '%s': %s",
3488 out_baseimg, strerror(-new_backing_size));
3495 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3498 for (offset = 0; offset < size; offset += n) {
3499 bool buf_old_is_zero = false;
3501 /* How many bytes can we handle with the next read? */
3502 n = MIN(IO_BUF_SIZE, size - offset);
3504 /* If the cluster is allocated, we don't need to take action */
3505 ret = bdrv_is_allocated(bs, offset, n, &n);
3507 error_report("error while reading image metadata: %s",
3515 if (prefix_chain_bs) {
3517 * If cluster wasn't changed since prefix_chain, we don't need
3520 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
3523 error_report("error while reading image metadata: %s",
3533 * Read old and new backing file and take into consideration that
3534 * backing files may be smaller than the COW image.
3536 if (offset >= old_backing_size) {
3537 memset(buf_old, 0, n);
3538 buf_old_is_zero = true;
3540 if (offset + n > old_backing_size) {
3541 n = old_backing_size - offset;
3544 ret = blk_pread(blk_old_backing, offset, buf_old, n);
3546 error_report("error while reading from old backing file");
3551 if (offset >= new_backing_size || !blk_new_backing) {
3552 memset(buf_new, 0, n);
3554 if (offset + n > new_backing_size) {
3555 n = new_backing_size - offset;
3558 ret = blk_pread(blk_new_backing, offset, buf_new, n);
3560 error_report("error while reading from new backing file");
3565 /* If they differ, we need to write to the COW file */
3566 uint64_t written = 0;
3568 while (written < n) {
3571 if (compare_buffers(buf_old + written, buf_new + written,
3572 n - written, &pnum))
3574 if (buf_old_is_zero) {
3575 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3577 ret = blk_pwrite(blk, offset + written,
3578 buf_old + written, pnum, 0);
3581 error_report("Error while writing to COW image: %s",
3589 qemu_progress_print(local_progress, 100);
3594 * Change the backing file. All clusters that are different from the old
3595 * backing file are overwritten in the COW file now, so the visible content
3596 * doesn't change when we switch the backing file.
3598 if (out_baseimg && *out_baseimg) {
3599 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3601 ret = bdrv_change_backing_file(bs, NULL, NULL);
3604 if (ret == -ENOSPC) {
3605 error_report("Could not change the backing file to '%s': No "
3606 "space left in the file header", out_baseimg);
3607 } else if (ret < 0) {
3608 error_report("Could not change the backing file to '%s': %s",
3609 out_baseimg, strerror(-ret));
3612 qemu_progress_print(100, 0);
3614 * TODO At this point it is possible to check if any clusters that are
3615 * allocated in the COW file are the same in the backing file. If so, they
3616 * could be dropped from the COW file. Don't do this before switching the
3617 * backing file, in case of a crash this would lead to corruption.
3620 qemu_progress_end();
3623 blk_unref(blk_old_backing);
3624 blk_unref(blk_new_backing);
3626 qemu_vfree(buf_old);
3627 qemu_vfree(buf_new);
3636 static int img_resize(int argc, char **argv)
3639 int c, ret, relative;
3640 const char *filename, *fmt, *size;
3641 int64_t n, total_size, current_size, new_size;
3643 BlockBackend *blk = NULL;
3644 PreallocMode prealloc = PREALLOC_MODE_OFF;
3647 static QemuOptsList resize_options = {
3648 .name = "resize_options",
3649 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3652 .name = BLOCK_OPT_SIZE,
3653 .type = QEMU_OPT_SIZE,
3654 .help = "Virtual disk size"
3660 bool image_opts = false;
3661 bool shrink = false;
3663 /* Remove size from argv manually so that negative numbers are not treated
3664 * as options by getopt. */
3666 error_exit("Not enough arguments");
3670 size = argv[--argc];
3672 /* Parse getopt arguments */
3675 static const struct option long_options[] = {
3676 {"help", no_argument, 0, 'h'},
3677 {"object", required_argument, 0, OPTION_OBJECT},
3678 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3679 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3680 {"shrink", no_argument, 0, OPTION_SHRINK},
3683 c = getopt_long(argc, argv, ":f:hq",
3684 long_options, NULL);
3690 missing_argument(argv[optind - 1]);
3693 unrecognized_option(argv[optind - 1]);
3704 case OPTION_OBJECT: {
3706 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3712 case OPTION_IMAGE_OPTS:
3715 case OPTION_PREALLOCATION:
3716 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3717 PREALLOC_MODE__MAX, NULL);
3718 if (prealloc == PREALLOC_MODE__MAX) {
3719 error_report("Invalid preallocation mode '%s'", optarg);
3728 if (optind != argc - 1) {
3729 error_exit("Expecting image file name and size");
3731 filename = argv[optind++];
3733 if (qemu_opts_foreach(&qemu_object_opts,
3734 user_creatable_add_opts_foreach,
3735 NULL, &error_fatal)) {
3739 /* Choose grow, shrink, or absolute resize mode */
3755 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3756 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3758 error_report_err(err);
3760 qemu_opts_del(param);
3763 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3764 qemu_opts_del(param);
3766 blk = img_open(image_opts, filename, fmt,
3767 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3774 current_size = blk_getlength(blk);
3775 if (current_size < 0) {
3776 error_report("Failed to inquire current image length: %s",
3777 strerror(-current_size));
3783 total_size = current_size + n * relative;
3787 if (total_size <= 0) {
3788 error_report("New image size must be positive");
3793 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3794 error_report("Preallocation can only be used for growing images");
3799 if (total_size < current_size && !shrink) {
3800 warn_report("Shrinking an image will delete all data beyond the "
3801 "shrunken image's end. Before performing such an "
3802 "operation, make sure there is no important data there.");
3804 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3806 "Use the --shrink option to perform a shrink operation.");
3810 warn_report("Using the --shrink option will suppress this message. "
3811 "Note that future versions of qemu-img may refuse to "
3812 "shrink images without this option.");
3816 ret = blk_truncate(blk, total_size, prealloc, &err);
3818 error_report_err(err);
3822 new_size = blk_getlength(blk);
3824 error_report("Failed to verify truncated image length: %s",
3825 strerror(-new_size));
3830 /* Some block drivers implement a truncation method, but only so
3831 * the user can cause qemu to refresh the image's size from disk.
3832 * The idea is that the user resizes the image outside of qemu and
3833 * then invokes block_resize to inform qemu about it.
3834 * (This includes iscsi and file-posix for device files.)
3835 * Of course, that is not the behavior someone invoking
3836 * qemu-img resize would find useful, so we catch that behavior
3837 * here and tell the user. */
3838 if (new_size != total_size && new_size == current_size) {
3839 error_report("Image was not resized; resizing may not be supported "
3845 if (new_size != total_size) {
3846 warn_report("Image should have been resized to %" PRIi64
3847 " bytes, but was resized to %" PRIi64 " bytes",
3848 total_size, new_size);
3851 qprintf(quiet, "Image resized.\n");
3861 static void amend_status_cb(BlockDriverState *bs,
3862 int64_t offset, int64_t total_work_size,
3865 qemu_progress_print(100.f * offset / total_work_size, 0);
3868 static int print_amend_option_help(const char *format)
3872 /* Find driver and parse its options */
3873 drv = bdrv_find_format(format);
3875 error_report("Unknown file format '%s'", format);
3879 if (!drv->bdrv_amend_options) {
3880 error_report("Format driver '%s' does not support option amendment",
3885 /* Every driver supporting amendment must have create_opts */
3886 assert(drv->create_opts);
3888 printf("Creation options for '%s':\n", format);
3889 qemu_opts_print_help(drv->create_opts, false);
3890 printf("\nNote that not all of these options may be amendable.\n");
3894 static int img_amend(int argc, char **argv)
3898 char *options = NULL;
3899 QemuOptsList *create_opts = NULL;
3900 QemuOpts *opts = NULL;
3901 const char *fmt = NULL, *filename, *cache;
3904 bool quiet = false, progress = false;
3905 BlockBackend *blk = NULL;
3906 BlockDriverState *bs = NULL;
3907 bool image_opts = false;
3909 cache = BDRV_DEFAULT_CACHE;
3911 static const struct option long_options[] = {
3912 {"help", no_argument, 0, 'h'},
3913 {"object", required_argument, 0, OPTION_OBJECT},
3914 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3917 c = getopt_long(argc, argv, ":ho:f:t:pq",
3918 long_options, NULL);
3925 missing_argument(argv[optind - 1]);
3928 unrecognized_option(argv[optind - 1]);
3934 if (!is_valid_option_list(optarg)) {
3935 error_report("Invalid option list: %s", optarg);
3937 goto out_no_progress;
3940 options = g_strdup(optarg);
3942 char *old_options = options;
3943 options = g_strdup_printf("%s,%s", options, optarg);
3944 g_free(old_options);
3960 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3964 goto out_no_progress;
3967 case OPTION_IMAGE_OPTS:
3974 error_exit("Must specify options (-o)");
3977 if (qemu_opts_foreach(&qemu_object_opts,
3978 user_creatable_add_opts_foreach,
3979 NULL, &error_fatal)) {
3981 goto out_no_progress;
3987 qemu_progress_init(progress, 1.0);
3989 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3990 if (fmt && has_help_option(options)) {
3991 /* If a format is explicitly specified (and possibly no filename is
3992 * given), print option help here */
3993 ret = print_amend_option_help(fmt);
3997 if (optind != argc - 1) {
3998 error_report("Expecting one image file name");
4003 flags = BDRV_O_RDWR;
4004 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
4006 error_report("Invalid cache option: %s", cache);
4010 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4018 fmt = bs->drv->format_name;
4020 if (has_help_option(options)) {
4021 /* If the format was auto-detected, print option help here */
4022 ret = print_amend_option_help(fmt);
4026 if (!bs->drv->bdrv_amend_options) {
4027 error_report("Format driver '%s' does not support option amendment",
4033 /* Every driver supporting amendment must have create_opts */
4034 assert(bs->drv->create_opts);
4036 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
4037 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4038 qemu_opts_do_parse(opts, options, NULL, &err);
4040 error_report_err(err);
4045 /* In case the driver does not call amend_status_cb() */
4046 qemu_progress_print(0.f, 0);
4047 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
4048 qemu_progress_print(100.f, 0);
4050 error_report_err(err);
4055 qemu_progress_end();
4059 qemu_opts_del(opts);
4060 qemu_opts_free(create_opts);
4069 typedef struct BenchData {
4071 uint64_t image_size;
4078 bool drain_on_flush;
4087 static void bench_undrained_flush_cb(void *opaque, int ret)
4090 error_report("Failed flush request: %s", strerror(-ret));
4095 static void bench_cb(void *opaque, int ret)
4097 BenchData *b = opaque;
4101 error_report("Failed request: %s", strerror(-ret));
4106 /* Just finished a flush with drained queue: Start next requests */
4107 assert(b->in_flight == 0);
4108 b->in_flush = false;
4109 } else if (b->in_flight > 0) {
4110 int remaining = b->n - b->in_flight;
4115 /* Time for flush? Drain queue if requested, then flush */
4116 if (b->flush_interval && remaining % b->flush_interval == 0) {
4117 if (!b->in_flight || !b->drain_on_flush) {
4118 BlockCompletionFunc *cb;
4120 if (b->drain_on_flush) {
4124 cb = bench_undrained_flush_cb;
4127 acb = blk_aio_flush(b->blk, cb, b);
4129 error_report("Failed to issue flush request");
4133 if (b->drain_on_flush) {
4139 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4140 int64_t offset = b->offset;
4141 /* blk_aio_* might look for completed I/Os and kick bench_cb
4142 * again, so make sure this operation is counted by in_flight
4143 * and b->offset is ready for the next submission.
4146 b->offset += b->step;
4147 b->offset %= b->image_size;
4149 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
4151 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
4154 error_report("Failed to issue request");
4160 static int img_bench(int argc, char **argv)
4163 const char *fmt = NULL, *filename;
4165 bool image_opts = false;
4166 bool is_write = false;
4170 size_t bufsize = 4096;
4173 int flush_interval = 0;
4174 bool drain_on_flush = true;
4176 BlockBackend *blk = NULL;
4177 BenchData data = {};
4179 bool writethrough = false;
4180 struct timeval t1, t2;
4182 bool force_share = false;
4186 static const struct option long_options[] = {
4187 {"help", no_argument, 0, 'h'},
4188 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
4189 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4190 {"pattern", required_argument, 0, OPTION_PATTERN},
4191 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
4192 {"force-share", no_argument, 0, 'U'},
4195 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
4202 missing_argument(argv[optind - 1]);
4205 unrecognized_option(argv[optind - 1]);
4214 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4215 error_report("Invalid request count specified");
4225 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4226 error_report("Invalid queue depth specified");
4236 flags |= BDRV_O_NATIVE_AIO;
4240 offset = cvtnum(optarg);
4242 error_report("Invalid offset specified");
4255 sval = cvtnum(optarg);
4256 if (sval < 0 || sval > INT_MAX) {
4257 error_report("Invalid buffer size specified");
4268 sval = cvtnum(optarg);
4269 if (sval < 0 || sval > INT_MAX) {
4270 error_report("Invalid step size specified");
4278 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4280 error_report("Invalid cache mode");
4286 flags |= BDRV_O_RDWR;
4292 case OPTION_PATTERN:
4296 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4297 error_report("Invalid pattern byte specified");
4303 case OPTION_FLUSH_INTERVAL:
4307 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4308 error_report("Invalid flush interval specified");
4311 flush_interval = res;
4314 case OPTION_NO_DRAIN:
4315 drain_on_flush = false;
4317 case OPTION_IMAGE_OPTS:
4323 if (optind != argc - 1) {
4324 error_exit("Expecting one image file name");
4326 filename = argv[argc - 1];
4328 if (!is_write && flush_interval) {
4329 error_report("--flush-interval is only available in write tests");
4333 if (flush_interval && flush_interval < depth) {
4334 error_report("Flush interval can't be smaller than depth");
4339 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4346 image_size = blk_getlength(blk);
4347 if (image_size < 0) {
4352 data = (BenchData) {
4354 .image_size = image_size,
4356 .step = step ?: bufsize,
4361 .flush_interval = flush_interval,
4362 .drain_on_flush = drain_on_flush,
4364 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4365 "(starting at offset %" PRId64 ", step size %d)\n",
4366 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4367 data.offset, data.step);
4368 if (flush_interval) {
4369 printf("Sending flush every %d requests\n", flush_interval);
4372 buf_size = data.nrreq * data.bufsize;
4373 data.buf = blk_blockalign(blk, buf_size);
4374 memset(data.buf, pattern, data.nrreq * data.bufsize);
4376 blk_register_buf(blk, data.buf, buf_size);
4378 data.qiov = g_new(QEMUIOVector, data.nrreq);
4379 for (i = 0; i < data.nrreq; i++) {
4380 qemu_iovec_init(&data.qiov[i], 1);
4381 qemu_iovec_add(&data.qiov[i],
4382 data.buf + i * data.bufsize, data.bufsize);
4385 gettimeofday(&t1, NULL);
4388 while (data.n > 0) {
4389 main_loop_wait(false);
4391 gettimeofday(&t2, NULL);
4393 printf("Run completed in %3.3f seconds.\n",
4394 (t2.tv_sec - t1.tv_sec)
4395 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4399 blk_unregister_buf(blk, data.buf);
4401 qemu_vfree(data.buf);
4422 int bsz; /* Block size */
4430 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4434 static int img_dd_bs(const char *arg,
4435 struct DdIo *in, struct DdIo *out,
4442 if (res <= 0 || res > INT_MAX) {
4443 error_report("invalid number: '%s'", arg);
4446 in->bsz = out->bsz = res;
4451 static int img_dd_count(const char *arg,
4452 struct DdIo *in, struct DdIo *out,
4455 dd->count = cvtnum(arg);
4457 if (dd->count < 0) {
4458 error_report("invalid number: '%s'", arg);
4465 static int img_dd_if(const char *arg,
4466 struct DdIo *in, struct DdIo *out,
4469 in->filename = g_strdup(arg);
4474 static int img_dd_of(const char *arg,
4475 struct DdIo *in, struct DdIo *out,
4478 out->filename = g_strdup(arg);
4483 static int img_dd_skip(const char *arg,
4484 struct DdIo *in, struct DdIo *out,
4487 in->offset = cvtnum(arg);
4489 if (in->offset < 0) {
4490 error_report("invalid number: '%s'", arg);
4497 static int img_dd(int argc, char **argv)
4502 BlockDriver *drv = NULL, *proto_drv = NULL;
4503 BlockBackend *blk1 = NULL, *blk2 = NULL;
4504 QemuOpts *opts = NULL;
4505 QemuOptsList *create_opts = NULL;
4506 Error *local_err = NULL;
4507 bool image_opts = false;
4509 const char *out_fmt = "raw";
4510 const char *fmt = NULL;
4512 int64_t block_count = 0, out_pos, in_pos;
4513 bool force_share = false;
4514 struct DdInfo dd = {
4519 .bsz = 512, /* Block size is by default 512 bytes */
4531 const struct DdOpts options[] = {
4532 { "bs", img_dd_bs, C_BS },
4533 { "count", img_dd_count, C_COUNT },
4534 { "if", img_dd_if, C_IF },
4535 { "of", img_dd_of, C_OF },
4536 { "skip", img_dd_skip, C_SKIP },
4539 const struct option long_options[] = {
4540 { "help", no_argument, 0, 'h'},
4541 { "object", required_argument, 0, OPTION_OBJECT},
4542 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4543 { "force-share", no_argument, 0, 'U'},
4547 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4559 missing_argument(argv[optind - 1]);
4562 unrecognized_option(argv[optind - 1]);
4571 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4576 case OPTION_IMAGE_OPTS:
4582 for (i = optind; i < argc; i++) {
4584 arg = g_strdup(argv[i]);
4586 tmp = strchr(arg, '=');
4588 error_report("unrecognized operand %s", arg);
4595 for (j = 0; options[j].name != NULL; j++) {
4596 if (!strcmp(arg, options[j].name)) {
4600 if (options[j].name == NULL) {
4601 error_report("unrecognized operand %s", arg);
4606 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4610 dd.flags |= options[j].flag;
4615 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4616 error_report("Must specify both input and output files");
4621 if (qemu_opts_foreach(&qemu_object_opts,
4622 user_creatable_add_opts_foreach,
4623 NULL, &error_fatal)) {
4628 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4636 drv = bdrv_find_format(out_fmt);
4638 error_report("Unknown file format");
4642 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4645 error_report_err(local_err);
4649 if (!drv->create_opts) {
4650 error_report("Format driver '%s' does not support image creation",
4655 if (!proto_drv->create_opts) {
4656 error_report("Protocol driver '%s' does not support image creation",
4657 proto_drv->format_name);
4661 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4662 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4664 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4666 size = blk_getlength(blk1);
4668 error_report("Failed to get size for '%s'", in.filename);
4673 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4674 dd.count * in.bsz < size) {
4675 size = dd.count * in.bsz;
4678 /* Overflow means the specified offset is beyond input image's size */
4679 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4680 size < in.bsz * in.offset)) {
4681 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4683 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4684 size - in.bsz * in.offset, &error_abort);
4687 ret = bdrv_create(drv, out.filename, opts, &local_err);
4689 error_reportf_err(local_err,
4690 "%s: error while creating output image: ",
4696 /* TODO, we can't honour --image-opts for the target,
4697 * since it needs to be given in a format compatible
4698 * with the bdrv_create() call above which does not
4699 * support image-opts style.
4701 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
4702 false, false, false);
4709 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4710 size < in.offset * in.bsz)) {
4711 /* We give a warning if the skip option is bigger than the input
4712 * size and create an empty output disk image (i.e. like dd(1)).
4714 error_report("%s: cannot skip to specified offset", in.filename);
4717 in_pos = in.offset * in.bsz;
4720 in.buf = g_new(uint8_t, in.bsz);
4722 for (out_pos = 0; in_pos < size; block_count++) {
4723 int in_ret, out_ret;
4725 if (in_pos + in.bsz > size) {
4726 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4728 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4731 error_report("error while reading from input image file: %s",
4738 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4741 error_report("error while writing to output image file: %s",
4742 strerror(-out_ret));
4751 qemu_opts_del(opts);
4752 qemu_opts_free(create_opts);
4755 g_free(in.filename);
4756 g_free(out.filename);
4766 static void dump_json_block_measure_info(BlockMeasureInfo *info)
4770 Visitor *v = qobject_output_visitor_new(&obj);
4772 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4773 visit_complete(v, &obj);
4774 str = qobject_to_json_pretty(obj);
4775 assert(str != NULL);
4776 printf("%s\n", qstring_get_str(str));
4782 static int img_measure(int argc, char **argv)
4784 static const struct option long_options[] = {
4785 {"help", no_argument, 0, 'h'},
4786 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4787 {"object", required_argument, 0, OPTION_OBJECT},
4788 {"output", required_argument, 0, OPTION_OUTPUT},
4789 {"size", required_argument, 0, OPTION_SIZE},
4790 {"force-share", no_argument, 0, 'U'},
4793 OutputFormat output_format = OFORMAT_HUMAN;
4794 BlockBackend *in_blk = NULL;
4796 const char *filename = NULL;
4797 const char *fmt = NULL;
4798 const char *out_fmt = "raw";
4799 char *options = NULL;
4800 char *snapshot_name = NULL;
4801 bool force_share = false;
4802 QemuOpts *opts = NULL;
4803 QemuOpts *object_opts = NULL;
4804 QemuOpts *sn_opts = NULL;
4805 QemuOptsList *create_opts = NULL;
4806 bool image_opts = false;
4807 uint64_t img_size = UINT64_MAX;
4808 BlockMeasureInfo *info = NULL;
4809 Error *local_err = NULL;
4813 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4814 long_options, NULL)) != -1) {
4827 if (!is_valid_option_list(optarg)) {
4828 error_report("Invalid option list: %s", optarg);
4832 options = g_strdup(optarg);
4834 char *old_options = options;
4835 options = g_strdup_printf("%s,%s", options, optarg);
4836 g_free(old_options);
4840 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4841 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4844 error_report("Failed in parsing snapshot param '%s'",
4849 snapshot_name = optarg;
4856 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4862 case OPTION_IMAGE_OPTS:
4866 if (!strcmp(optarg, "json")) {
4867 output_format = OFORMAT_JSON;
4868 } else if (!strcmp(optarg, "human")) {
4869 output_format = OFORMAT_HUMAN;
4871 error_report("--output must be used with human or json "
4880 sval = cvtnum(optarg);
4882 if (sval == -ERANGE) {
4883 error_report("Image size must be less than 8 EiB!");
4885 error_report("Invalid image size specified! You may use "
4886 "k, M, G, T, P or E suffixes for ");
4887 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4888 "petabytes and exabytes.");
4892 img_size = (uint64_t)sval;
4898 if (qemu_opts_foreach(&qemu_object_opts,
4899 user_creatable_add_opts_foreach,
4900 NULL, &error_fatal)) {
4904 if (argc - optind > 1) {
4905 error_report("At most one filename argument is allowed.");
4907 } else if (argc - optind == 1) {
4908 filename = argv[optind];
4912 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4913 error_report("--object, --image-opts, -f, and -l "
4914 "require a filename argument.");
4917 if (filename && img_size != UINT64_MAX) {
4918 error_report("--size N cannot be used together with a filename.");
4921 if (!filename && img_size == UINT64_MAX) {
4922 error_report("Either --size N or one filename must be specified.");
4927 in_blk = img_open(image_opts, filename, fmt, 0,
4928 false, false, force_share);
4934 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4935 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4936 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4938 } else if (snapshot_name != NULL) {
4939 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4940 snapshot_name, &local_err);
4943 error_reportf_err(local_err, "Failed to load snapshot: ");
4948 drv = bdrv_find_format(out_fmt);
4950 error_report("Unknown file format '%s'", out_fmt);
4953 if (!drv->create_opts) {
4954 error_report("Format driver '%s' does not support image creation",
4959 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4960 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4961 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4963 qemu_opts_do_parse(opts, options, NULL, &local_err);
4965 error_report_err(local_err);
4966 error_report("Invalid options for file format '%s'", out_fmt);
4970 if (img_size != UINT64_MAX) {
4971 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4974 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4976 error_report_err(local_err);
4980 if (output_format == OFORMAT_HUMAN) {
4981 printf("required size: %" PRIu64 "\n", info->required);
4982 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4984 dump_json_block_measure_info(info);
4990 qapi_free_BlockMeasureInfo(info);
4991 qemu_opts_del(object_opts);
4992 qemu_opts_del(opts);
4993 qemu_opts_del(sn_opts);
4994 qemu_opts_free(create_opts);
5000 static const img_cmd_t img_cmds[] = {
5001 #define DEF(option, callback, arg_string) \
5002 { option, callback },
5003 #include "qemu-img-cmds.h"
5008 int main(int argc, char **argv)
5010 const img_cmd_t *cmd;
5011 const char *cmdname;
5012 Error *local_error = NULL;
5013 char *trace_file = NULL;
5015 static const struct option long_options[] = {
5016 {"help", no_argument, 0, 'h'},
5017 {"version", no_argument, 0, 'V'},
5018 {"trace", required_argument, NULL, 'T'},
5023 signal(SIGPIPE, SIG_IGN);
5026 error_init(argv[0]);
5027 module_call_init(MODULE_INIT_TRACE);
5028 qemu_init_exec_dir(argv[0]);
5030 if (qemu_init_main_loop(&local_error)) {
5031 error_report_err(local_error);
5035 qcrypto_init(&error_fatal);
5037 module_call_init(MODULE_INIT_QOM);
5040 error_exit("Not enough arguments");
5043 qemu_add_opts(&qemu_object_opts);
5044 qemu_add_opts(&qemu_source_opts);
5045 qemu_add_opts(&qemu_trace_opts);
5047 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
5050 missing_argument(argv[optind - 1]);
5053 unrecognized_option(argv[optind - 1]);
5059 printf(QEMU_IMG_VERSION);
5063 trace_file = trace_opt_parse(optarg);
5068 cmdname = argv[optind];
5070 /* reset getopt_long scanning */
5076 qemu_reset_optind();
5078 if (!trace_init_backends()) {
5081 trace_init_file(trace_file);
5082 qemu_set_log(LOG_TRACE);
5084 /* find the command */
5085 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5086 if (!strcmp(cmdname, cmd->name)) {
5087 return cmd->handler(argc, argv);
5092 error_exit("Command not found: %s", cmdname);