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/main-loop.h"
42 #include "qemu/module.h"
43 #include "qemu/units.h"
44 #include "qom/object_interfaces.h"
45 #include "sysemu/sysemu.h"
46 #include "sysemu/block-backend.h"
47 #include "block/block_int.h"
48 #include "block/blockjob.h"
49 #include "block/qapi.h"
50 #include "crypto/init.h"
51 #include "trace/control.h"
53 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
54 "\n" QEMU_COPYRIGHT "\n"
56 typedef struct img_cmd_t {
58 int (*handler)(int argc, char **argv);
63 OPTION_BACKING_CHAIN = 257,
65 OPTION_IMAGE_OPTS = 259,
67 OPTION_FLUSH_INTERVAL = 261,
68 OPTION_NO_DRAIN = 262,
69 OPTION_TARGET_IMAGE_OPTS = 263,
71 OPTION_PREALLOCATION = 265,
76 typedef enum OutputFormat {
81 /* Default to cache=writeback as data integrity is not important for qemu-img */
82 #define BDRV_DEFAULT_CACHE "writeback"
84 static void format_print(void *opaque, const char *name)
89 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
94 error_vreport(fmt, ap);
97 error_printf("Try 'qemu-img --help' for more information\n");
101 static void QEMU_NORETURN missing_argument(const char *option)
103 error_exit("missing argument for option '%s'", option);
106 static void QEMU_NORETURN unrecognized_option(const char *option)
108 error_exit("unrecognized option '%s'", option);
111 /* Please keep in synch with qemu-img.texi */
112 static void QEMU_NORETURN help(void)
114 const char *help_msg =
116 "usage: qemu-img [standard options] command [command options]\n"
117 "QEMU disk image utility\n"
119 " '-h', '--help' display this help and exit\n"
120 " '-V', '--version' output version information and exit\n"
121 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
122 " specify tracing options\n"
125 #define DEF(option, callback, arg_string) \
127 #include "qemu-img-cmds.h"
130 "Command parameters:\n"
131 " 'filename' is a disk image filename\n"
132 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
133 " manual page for a description of the object properties. The most common\n"
134 " object type is a 'secret', which is used to supply passwords and/or\n"
135 " encryption keys.\n"
136 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
137 " 'cache' is the cache mode used to write the output disk image, the valid\n"
138 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
139 " 'directsync' and 'unsafe' (default for convert)\n"
140 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
141 " options are the same as for the 'cache' option\n"
142 " 'size' is the disk image size in bytes. Optional suffixes\n"
143 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
144 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
145 " supported. 'b' is ignored.\n"
146 " 'output_filename' is the destination disk image filename\n"
147 " 'output_fmt' is the destination format\n"
148 " 'options' is a comma separated list of format specific options in a\n"
149 " name=value format. Use -o ? for an overview of the options supported by the\n"
151 " 'snapshot_param' is param used for internal snapshot, format\n"
152 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
154 " '-c' indicates that target image must be compressed (qcow format only)\n"
155 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
156 " new backing file match exactly. The image doesn't need a working\n"
157 " backing file before rebasing in this case (useful for renaming the\n"
158 " backing file). For image creation, allow creating without attempting\n"
159 " to open the backing file.\n"
160 " '-h' with or without a command shows this help and lists the supported formats\n"
161 " '-p' show progress of command (only certain commands)\n"
162 " '-q' use Quiet mode - do not print any output (except errors)\n"
163 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
164 " contain only zeros for qemu-img to create a sparse image during\n"
165 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
166 " unallocated or zero sectors, and the destination image will always be\n"
168 " '--output' takes the format in which the output must be done (human or json)\n"
169 " '-n' skips the target volume creation (useful if the volume is created\n"
170 " prior to running qemu-img)\n"
172 "Parameters to check subcommand:\n"
173 " '-r' tries to repair any inconsistencies that are found during the check.\n"
174 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
175 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
176 " hiding corruption that has already occurred.\n"
178 "Parameters to convert subcommand:\n"
179 " '-m' specifies how many coroutines work in parallel during the convert\n"
180 " process (defaults to 8)\n"
181 " '-W' allow to write to the target out of order rather than sequential\n"
183 "Parameters to snapshot subcommand:\n"
184 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
185 " '-a' applies a snapshot (revert disk to saved state)\n"
186 " '-c' creates a snapshot\n"
187 " '-d' deletes a snapshot\n"
188 " '-l' lists all snapshots in the given image\n"
190 "Parameters to compare subcommand:\n"
191 " '-f' first image format\n"
192 " '-F' second image format\n"
193 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
195 "Parameters to dd subcommand:\n"
196 " 'bs=BYTES' read and write up to BYTES bytes at a time "
198 " 'count=N' copy only N input blocks\n"
199 " 'if=FILE' read from FILE\n"
200 " 'of=FILE' write to FILE\n"
201 " 'skip=N' skip N bs-sized blocks at the start of input\n";
203 printf("%s\nSupported formats:", help_msg);
204 bdrv_iterate_format(format_print, NULL, false);
205 printf("\n\n" QEMU_HELP_BOTTOM "\n");
209 static QemuOptsList qemu_object_opts = {
211 .implied_opt_name = "qom-type",
212 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
218 static QemuOptsList qemu_source_opts = {
220 .implied_opt_name = "file",
221 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
227 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
233 ret = vprintf(fmt, args);
240 static int print_block_option_help(const char *filename, const char *fmt)
242 BlockDriver *drv, *proto_drv;
243 QemuOptsList *create_opts = NULL;
244 Error *local_err = NULL;
246 /* Find driver and parse its options */
247 drv = bdrv_find_format(fmt);
249 error_report("Unknown file format '%s'", fmt);
253 if (!drv->create_opts) {
254 error_report("Format driver '%s' does not support image creation", fmt);
258 create_opts = qemu_opts_append(create_opts, drv->create_opts);
260 proto_drv = bdrv_find_protocol(filename, true, &local_err);
262 error_report_err(local_err);
263 qemu_opts_free(create_opts);
266 if (!proto_drv->create_opts) {
267 error_report("Protocol driver '%s' does not support image creation",
268 proto_drv->format_name);
269 qemu_opts_free(create_opts);
272 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
276 printf("Supported options:\n");
278 printf("Supported %s options:\n", fmt);
280 qemu_opts_print_help(create_opts, false);
281 qemu_opts_free(create_opts);
285 "The protocol level may support further options.\n"
286 "Specify the target filename to include those options.\n");
293 static BlockBackend *img_open_opts(const char *optstr,
294 QemuOpts *opts, int flags, bool writethrough,
295 bool quiet, bool force_share)
298 Error *local_err = NULL;
300 options = qemu_opts_to_qdict(opts, NULL);
302 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
303 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
304 error_report("--force-share/-U conflicts with image options");
305 qobject_unref(options);
308 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
310 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
312 error_reportf_err(local_err, "Could not open '%s': ", optstr);
315 blk_set_enable_write_cache(blk, !writethrough);
320 static BlockBackend *img_open_file(const char *filename,
322 const char *fmt, int flags,
323 bool writethrough, bool quiet,
327 Error *local_err = NULL;
330 options = qdict_new();
333 qdict_put_str(options, "driver", fmt);
337 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
339 blk = blk_new_open(filename, NULL, options, flags, &local_err);
341 error_reportf_err(local_err, "Could not open '%s': ", filename);
344 blk_set_enable_write_cache(blk, !writethrough);
350 static int img_add_key_secrets(void *opaque,
351 const char *name, const char *value,
354 QDict *options = opaque;
356 if (g_str_has_suffix(name, "key-secret")) {
357 qdict_put_str(options, name, value);
364 static BlockBackend *img_open(bool image_opts,
365 const char *filename,
366 const char *fmt, int flags, bool writethrough,
367 bool quiet, bool force_share)
373 error_report("--image-opts and --format are mutually exclusive");
376 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
381 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
384 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
391 static int add_old_style_options(const char *fmt, QemuOpts *opts,
392 const char *base_filename,
393 const char *base_fmt)
398 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
400 error_report("Backing file not supported for file format '%s'",
407 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
409 error_report("Backing file format not supported for file "
418 static int64_t cvtnum(const char *s)
423 err = qemu_strtosz(s, NULL, &value);
427 if (value > INT64_MAX) {
433 static int img_create(int argc, char **argv)
436 uint64_t img_size = -1;
437 const char *fmt = "raw";
438 const char *base_fmt = NULL;
439 const char *filename;
440 const char *base_filename = NULL;
441 char *options = NULL;
442 Error *local_err = NULL;
447 static const struct option long_options[] = {
448 {"help", no_argument, 0, 'h'},
449 {"object", required_argument, 0, OPTION_OBJECT},
452 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
459 missing_argument(argv[optind - 1]);
462 unrecognized_option(argv[optind - 1]);
471 base_filename = optarg;
477 if (!is_valid_option_list(optarg)) {
478 error_report("Invalid option list: %s", optarg);
482 options = g_strdup(optarg);
484 char *old_options = options;
485 options = g_strdup_printf("%s,%s", options, optarg);
493 flags |= BDRV_O_NO_BACKING;
495 case OPTION_OBJECT: {
497 opts = qemu_opts_parse_noisily(&qemu_object_opts,
506 /* Get the filename */
507 filename = (optind < argc) ? argv[optind] : NULL;
508 if (options && has_help_option(options)) {
510 return print_block_option_help(filename, fmt);
513 if (optind >= argc) {
514 error_exit("Expecting image file name");
518 if (qemu_opts_foreach(&qemu_object_opts,
519 user_creatable_add_opts_foreach,
520 NULL, &error_fatal)) {
524 /* Get image size, if specified */
528 sval = cvtnum(argv[optind++]);
530 if (sval == -ERANGE) {
531 error_report("Image size must be less than 8 EiB!");
533 error_report("Invalid image size specified! You may use k, M, "
534 "G, T, P or E suffixes for ");
535 error_report("kilobytes, megabytes, gigabytes, terabytes, "
536 "petabytes and exabytes.");
540 img_size = (uint64_t)sval;
542 if (optind != argc) {
543 error_exit("Unexpected argument: %s", argv[optind]);
546 bdrv_img_create(filename, fmt, base_filename, base_fmt,
547 options, img_size, flags, quiet, &local_err);
549 error_reportf_err(local_err, "%s: ", filename);
561 static void dump_json_image_check(ImageCheck *check, bool quiet)
565 Visitor *v = qobject_output_visitor_new(&obj);
567 visit_type_ImageCheck(v, NULL, &check, &error_abort);
568 visit_complete(v, &obj);
569 str = qobject_to_json_pretty(obj);
571 qprintf(quiet, "%s\n", qstring_get_str(str));
577 static void dump_human_image_check(ImageCheck *check, bool quiet)
579 if (!(check->corruptions || check->leaks || check->check_errors)) {
580 qprintf(quiet, "No errors were found on the image.\n");
582 if (check->corruptions) {
583 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
584 "Data may be corrupted, or further writes to the image "
591 "\n%" PRId64 " leaked clusters were found on the image.\n"
592 "This means waste of disk space, but no harm to data.\n",
596 if (check->check_errors) {
599 " internal errors have occurred during the check.\n",
600 check->check_errors);
604 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
605 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
606 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
607 check->allocated_clusters, check->total_clusters,
608 check->allocated_clusters * 100.0 / check->total_clusters,
609 check->fragmented_clusters * 100.0 / check->allocated_clusters,
610 check->compressed_clusters * 100.0 /
611 check->allocated_clusters);
614 if (check->image_end_offset) {
616 "Image end offset: %" PRId64 "\n", check->image_end_offset);
620 static int collect_image_check(BlockDriverState *bs,
622 const char *filename,
627 BdrvCheckResult result;
629 ret = bdrv_check(bs, &result, fix);
634 check->filename = g_strdup(filename);
635 check->format = g_strdup(bdrv_get_format_name(bs));
636 check->check_errors = result.check_errors;
637 check->corruptions = result.corruptions;
638 check->has_corruptions = result.corruptions != 0;
639 check->leaks = result.leaks;
640 check->has_leaks = result.leaks != 0;
641 check->corruptions_fixed = result.corruptions_fixed;
642 check->has_corruptions_fixed = result.corruptions != 0;
643 check->leaks_fixed = result.leaks_fixed;
644 check->has_leaks_fixed = result.leaks != 0;
645 check->image_end_offset = result.image_end_offset;
646 check->has_image_end_offset = result.image_end_offset != 0;
647 check->total_clusters = result.bfi.total_clusters;
648 check->has_total_clusters = result.bfi.total_clusters != 0;
649 check->allocated_clusters = result.bfi.allocated_clusters;
650 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
651 check->fragmented_clusters = result.bfi.fragmented_clusters;
652 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
653 check->compressed_clusters = result.bfi.compressed_clusters;
654 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
660 * Checks an image for consistency. Exit codes:
662 * 0 - Check completed, image is good
663 * 1 - Check not completed because of internal errors
664 * 2 - Check completed, image is corrupted
665 * 3 - Check completed, image has leaked clusters, but is good otherwise
666 * 63 - Checks are not supported by the image format
668 static int img_check(int argc, char **argv)
671 OutputFormat output_format = OFORMAT_HUMAN;
672 const char *filename, *fmt, *output, *cache;
674 BlockDriverState *bs;
676 int flags = BDRV_O_CHECK;
680 bool image_opts = false;
681 bool force_share = false;
685 cache = BDRV_DEFAULT_CACHE;
688 int option_index = 0;
689 static const struct option long_options[] = {
690 {"help", no_argument, 0, 'h'},
691 {"format", required_argument, 0, 'f'},
692 {"repair", required_argument, 0, 'r'},
693 {"output", required_argument, 0, OPTION_OUTPUT},
694 {"object", required_argument, 0, OPTION_OBJECT},
695 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
696 {"force-share", no_argument, 0, 'U'},
699 c = getopt_long(argc, argv, ":hf:r:T:qU",
700 long_options, &option_index);
706 missing_argument(argv[optind - 1]);
709 unrecognized_option(argv[optind - 1]);
718 flags |= BDRV_O_RDWR;
720 if (!strcmp(optarg, "leaks")) {
721 fix = BDRV_FIX_LEAKS;
722 } else if (!strcmp(optarg, "all")) {
723 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
725 error_exit("Unknown option value for -r "
726 "(expecting 'leaks' or 'all'): %s", optarg);
741 case OPTION_OBJECT: {
743 opts = qemu_opts_parse_noisily(&qemu_object_opts,
749 case OPTION_IMAGE_OPTS:
754 if (optind != argc - 1) {
755 error_exit("Expecting one image file name");
757 filename = argv[optind++];
759 if (output && !strcmp(output, "json")) {
760 output_format = OFORMAT_JSON;
761 } else if (output && !strcmp(output, "human")) {
762 output_format = OFORMAT_HUMAN;
764 error_report("--output must be used with human or json as argument.");
768 if (qemu_opts_foreach(&qemu_object_opts,
769 user_creatable_add_opts_foreach,
770 NULL, &error_fatal)) {
774 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
776 error_report("Invalid source cache option: %s", cache);
780 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
787 check = g_new0(ImageCheck, 1);
788 ret = collect_image_check(bs, check, filename, fmt, fix);
790 if (ret == -ENOTSUP) {
791 error_report("This image format does not support checks");
796 if (check->corruptions_fixed || check->leaks_fixed) {
797 int corruptions_fixed, leaks_fixed;
799 leaks_fixed = check->leaks_fixed;
800 corruptions_fixed = check->corruptions_fixed;
802 if (output_format == OFORMAT_HUMAN) {
804 "The following inconsistencies were found and repaired:\n\n"
805 " %" PRId64 " leaked clusters\n"
806 " %" PRId64 " corruptions\n\n"
807 "Double checking the fixed image now...\n",
809 check->corruptions_fixed);
812 ret = collect_image_check(bs, check, filename, fmt, 0);
814 check->leaks_fixed = leaks_fixed;
815 check->corruptions_fixed = corruptions_fixed;
819 switch (output_format) {
821 dump_human_image_check(check, quiet);
824 dump_json_image_check(check, quiet);
829 if (ret || check->check_errors) {
831 error_report("Check failed: %s", strerror(-ret));
833 error_report("Check failed");
839 if (check->corruptions) {
841 } else if (check->leaks) {
848 qapi_free_ImageCheck(check);
853 typedef struct CommonBlockJobCBInfo {
854 BlockDriverState *bs;
856 } CommonBlockJobCBInfo;
858 static void common_block_job_cb(void *opaque, int ret)
860 CommonBlockJobCBInfo *cbi = opaque;
863 error_setg_errno(cbi->errp, -ret, "Block job failed");
867 static void run_block_job(BlockJob *job, Error **errp)
869 AioContext *aio_context = blk_get_aio_context(job->blk);
872 aio_context_acquire(aio_context);
875 float progress = 0.0f;
876 aio_poll(aio_context, true);
877 if (job->job.progress_total) {
878 progress = (float)job->job.progress_current /
879 job->job.progress_total * 100.f;
881 qemu_progress_print(progress, 0);
882 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
884 if (!job_is_completed(&job->job)) {
885 ret = job_complete_sync(&job->job, errp);
889 job_unref(&job->job);
890 aio_context_release(aio_context);
892 /* publish completion progress only when success */
894 qemu_progress_print(100.f, 0);
898 static int img_commit(int argc, char **argv)
901 const char *filename, *fmt, *cache, *base;
903 BlockDriverState *bs, *base_bs;
905 bool progress = false, quiet = false, drop = false;
907 Error *local_err = NULL;
908 CommonBlockJobCBInfo cbi;
909 bool image_opts = false;
910 AioContext *aio_context;
913 cache = BDRV_DEFAULT_CACHE;
916 static const struct option long_options[] = {
917 {"help", no_argument, 0, 'h'},
918 {"object", required_argument, 0, OPTION_OBJECT},
919 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
922 c = getopt_long(argc, argv, ":f:ht:b:dpq",
929 missing_argument(argv[optind - 1]);
932 unrecognized_option(argv[optind - 1]);
957 case OPTION_OBJECT: {
959 opts = qemu_opts_parse_noisily(&qemu_object_opts,
965 case OPTION_IMAGE_OPTS:
971 /* Progress is not shown in Quiet mode */
976 if (optind != argc - 1) {
977 error_exit("Expecting one image file name");
979 filename = argv[optind++];
981 if (qemu_opts_foreach(&qemu_object_opts,
982 user_creatable_add_opts_foreach,
983 NULL, &error_fatal)) {
987 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
988 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
990 error_report("Invalid cache option: %s", cache);
994 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1001 qemu_progress_init(progress, 1.f);
1002 qemu_progress_print(0.f, 100);
1005 base_bs = bdrv_find_backing_image(bs, base);
1007 error_setg(&local_err,
1008 "Did not find '%s' in the backing chain of '%s'",
1013 /* This is different from QMP, which by default uses the deepest file in
1014 * the backing chain (i.e., the very base); however, the traditional
1015 * behavior of qemu-img commit is using the immediate backing file. */
1016 base_bs = backing_bs(bs);
1018 error_setg(&local_err, "Image does not have a backing file");
1023 cbi = (CommonBlockJobCBInfo){
1028 aio_context = bdrv_get_aio_context(bs);
1029 aio_context_acquire(aio_context);
1030 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
1031 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1032 &cbi, false, &local_err);
1033 aio_context_release(aio_context);
1038 /* When the block job completes, the BlockBackend reference will point to
1039 * the old backing file. In order to avoid that the top image is already
1040 * deleted, so we can still empty it afterwards, increment the reference
1041 * counter here preemptively. */
1046 job = block_job_get("commit");
1048 run_block_job(job, &local_err);
1053 if (!drop && bs->drv->bdrv_make_empty) {
1054 ret = bs->drv->bdrv_make_empty(bs);
1056 error_setg_errno(&local_err, -ret, "Could not empty %s",
1068 qemu_progress_end();
1073 error_report_err(local_err);
1077 qprintf(quiet, "Image committed.\n");
1082 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1083 * of the first sector boundary within buf where the sector contains a
1084 * non-zero byte. This function is robust to a buffer that is not
1087 static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1090 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1092 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1093 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1097 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1104 * Returns true iff the first sector pointed to by 'buf' contains at least
1107 * 'pnum' is set to the number of sectors (including and immediately following
1108 * the first one) that are known to be in the same allocated/unallocated state.
1109 * The function will try to align the end offset to alignment boundaries so
1110 * that the request will at least end aligned and consequtive requests will
1111 * also start at an aligned offset.
1113 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1114 int64_t sector_num, int alignment)
1123 is_zero = buffer_is_zero(buf, 512);
1124 for(i = 1; i < n; i++) {
1126 if (is_zero != buffer_is_zero(buf, 512)) {
1131 tail = (sector_num + i) & (alignment - 1);
1133 if (is_zero && i <= tail) {
1134 /* treat unallocated areas which only consist
1135 * of a small tail as allocated. */
1139 /* align up end offset of allocated areas. */
1140 i += alignment - tail;
1143 /* align down end offset of zero areas. */
1152 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1153 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1154 * breaking up write requests for only small sparse areas.
1156 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1157 int min, int64_t sector_num, int alignment)
1160 int num_checked, num_used;
1166 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1172 buf += BDRV_SECTOR_SIZE * *pnum;
1174 sector_num += *pnum;
1175 num_checked = num_used;
1178 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1180 buf += BDRV_SECTOR_SIZE * *pnum;
1182 sector_num += *pnum;
1183 num_checked += *pnum;
1185 num_used = num_checked;
1186 } else if (*pnum >= min) {
1196 * Compares two buffers sector by sector. Returns 0 if the first
1197 * sector of each buffer matches, non-zero otherwise.
1199 * pnum is set to the sector-aligned size of the buffer prefix that
1200 * has the same matching status as the first sector.
1202 static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1203 int64_t bytes, int64_t *pnum)
1206 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
1210 res = !!memcmp(buf1, buf2, i);
1212 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
1214 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
1224 #define IO_BUF_SIZE (2 * MiB)
1227 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1229 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1230 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1231 * failure), and 4 on error (the exit status for read errors), after emitting
1234 * @param blk: BlockBackend for the image
1235 * @param offset: Starting offset to check
1236 * @param bytes: Number of bytes to check
1237 * @param filename: Name of disk file we are checking (logging purpose)
1238 * @param buffer: Allocated buffer for storing read data
1239 * @param quiet: Flag for quiet mode
1241 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1242 int64_t bytes, const char *filename,
1243 uint8_t *buffer, bool quiet)
1248 ret = blk_pread(blk, offset, buffer, bytes);
1250 error_report("Error while reading offset %" PRId64 " of %s: %s",
1251 offset, filename, strerror(-ret));
1254 idx = find_nonzero(buffer, bytes);
1256 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1265 * Compares two images. Exit codes:
1267 * 0 - Images are identical
1269 * >1 - Error occurred
1271 static int img_compare(int argc, char **argv)
1273 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1274 BlockBackend *blk1, *blk2;
1275 BlockDriverState *bs1, *bs2;
1276 int64_t total_size1, total_size2;
1277 uint8_t *buf1 = NULL, *buf2 = NULL;
1278 int64_t pnum1, pnum2;
1279 int allocated1, allocated2;
1280 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1281 bool progress = false, quiet = false, strict = false;
1288 uint64_t progress_base;
1289 bool image_opts = false;
1290 bool force_share = false;
1292 cache = BDRV_DEFAULT_CACHE;
1294 static const struct option long_options[] = {
1295 {"help", no_argument, 0, 'h'},
1296 {"object", required_argument, 0, OPTION_OBJECT},
1297 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1298 {"force-share", no_argument, 0, 'U'},
1301 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1302 long_options, NULL);
1308 missing_argument(argv[optind - 1]);
1311 unrecognized_option(argv[optind - 1]);
1337 case OPTION_OBJECT: {
1339 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1346 case OPTION_IMAGE_OPTS:
1352 /* Progress is not shown in Quiet mode */
1358 if (optind != argc - 2) {
1359 error_exit("Expecting two image file names");
1361 filename1 = argv[optind++];
1362 filename2 = argv[optind++];
1364 if (qemu_opts_foreach(&qemu_object_opts,
1365 user_creatable_add_opts_foreach,
1366 NULL, &error_fatal)) {
1371 /* Initialize before goto out */
1372 qemu_progress_init(progress, 2.0);
1375 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1377 error_report("Invalid source cache option: %s", cache);
1382 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1389 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1398 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1399 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1400 total_size1 = blk_getlength(blk1);
1401 if (total_size1 < 0) {
1402 error_report("Can't get size of %s: %s",
1403 filename1, strerror(-total_size1));
1407 total_size2 = blk_getlength(blk2);
1408 if (total_size2 < 0) {
1409 error_report("Can't get size of %s: %s",
1410 filename2, strerror(-total_size2));
1414 total_size = MIN(total_size1, total_size2);
1415 progress_base = MAX(total_size1, total_size2);
1417 qemu_progress_print(0, 100);
1419 if (strict && total_size1 != total_size2) {
1421 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1425 while (offset < total_size) {
1426 int status1, status2;
1428 status1 = bdrv_block_status_above(bs1, NULL, offset,
1429 total_size1 - offset, &pnum1, NULL,
1433 error_report("Sector allocation test failed for %s", filename1);
1436 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1438 status2 = bdrv_block_status_above(bs2, NULL, offset,
1439 total_size2 - offset, &pnum2, NULL,
1443 error_report("Sector allocation test failed for %s", filename2);
1446 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1448 assert(pnum1 && pnum2);
1449 chunk = MIN(pnum1, pnum2);
1452 if (status1 != status2) {
1454 qprintf(quiet, "Strict mode: Offset %" PRId64
1455 " block status mismatch!\n", offset);
1459 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1461 } else if (allocated1 == allocated2) {
1465 chunk = MIN(chunk, IO_BUF_SIZE);
1466 ret = blk_pread(blk1, offset, buf1, chunk);
1468 error_report("Error while reading offset %" PRId64
1470 offset, filename1, strerror(-ret));
1474 ret = blk_pread(blk2, offset, buf2, chunk);
1476 error_report("Error while reading offset %" PRId64
1478 offset, filename2, strerror(-ret));
1482 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1483 if (ret || pnum != chunk) {
1484 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1485 offset + (ret ? 0 : pnum));
1491 chunk = MIN(chunk, IO_BUF_SIZE);
1493 ret = check_empty_sectors(blk1, offset, chunk,
1494 filename1, buf1, quiet);
1496 ret = check_empty_sectors(blk2, offset, chunk,
1497 filename2, buf1, quiet);
1504 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1507 if (total_size1 != total_size2) {
1508 BlockBackend *blk_over;
1509 const char *filename_over;
1511 qprintf(quiet, "Warning: Image size mismatch!\n");
1512 if (total_size1 > total_size2) {
1514 filename_over = filename1;
1517 filename_over = filename2;
1520 while (offset < progress_base) {
1521 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1522 progress_base - offset, &chunk,
1526 error_report("Sector allocation test failed for %s",
1531 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1532 chunk = MIN(chunk, IO_BUF_SIZE);
1533 ret = check_empty_sectors(blk_over, offset, chunk,
1534 filename_over, buf1, quiet);
1540 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1544 qprintf(quiet, "Images are identical.\n");
1554 qemu_progress_end();
1559 enum ImgConvertBlockStatus {
1565 #define MAX_COROUTINES 16
1567 typedef struct ImgConvertState {
1569 int64_t *src_sectors;
1571 int64_t total_sectors;
1572 int64_t allocated_sectors;
1573 int64_t allocated_done;
1576 enum ImgConvertBlockStatus status;
1577 int64_t sector_next_status;
1578 BlockBackend *target;
1581 bool unallocated_blocks_are_zero;
1582 bool target_has_backing;
1583 int64_t target_backing_sectors; /* negative if unknown */
1590 size_t cluster_sectors;
1592 long num_coroutines;
1593 int running_coroutines;
1594 Coroutine *co[MAX_COROUTINES];
1595 int64_t wait_sector_num[MAX_COROUTINES];
1600 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1601 int *src_cur, int64_t *src_cur_offset)
1604 *src_cur_offset = 0;
1605 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1606 *src_cur_offset += s->src_sectors[*src_cur];
1608 assert(*src_cur < s->src_num);
1612 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1614 int64_t src_cur_offset;
1615 int ret, n, src_cur;
1616 bool post_backing_zero = false;
1618 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1620 assert(s->total_sectors > sector_num);
1621 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1623 if (s->target_backing_sectors >= 0) {
1624 if (sector_num >= s->target_backing_sectors) {
1625 post_backing_zero = s->unallocated_blocks_are_zero;
1626 } else if (sector_num + n > s->target_backing_sectors) {
1627 /* Split requests around target_backing_sectors (because
1628 * starting from there, zeros are handled differently) */
1629 n = s->target_backing_sectors - sector_num;
1633 if (s->sector_next_status <= sector_num) {
1634 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1638 count = n * BDRV_SECTOR_SIZE;
1640 if (s->target_has_backing) {
1641 ret = bdrv_block_status(blk_bs(s->src[src_cur]), offset,
1642 count, &count, NULL, NULL);
1644 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1645 offset, count, &count, NULL,
1653 warn_report("error while reading block status at "
1654 "offset %" PRIu64 ": %s", offset,
1657 /* Just try to read the data, then */
1658 ret = BDRV_BLOCK_DATA;
1659 count = BDRV_SECTOR_SIZE;
1661 /* Retry on a shorter range */
1662 n = DIV_ROUND_UP(n, 4);
1665 error_report("error while reading block status at offset "
1666 "%" PRIu64 ": %s", offset, strerror(-ret));
1672 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1674 if (ret & BDRV_BLOCK_ZERO) {
1675 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
1676 } else if (ret & BDRV_BLOCK_DATA) {
1677 s->status = BLK_DATA;
1679 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1682 s->sector_next_status = sector_num + n;
1685 n = MIN(n, s->sector_next_status - sector_num);
1686 if (s->status == BLK_DATA) {
1687 n = MIN(n, s->buf_sectors);
1690 /* We need to write complete clusters for compressed images, so if an
1691 * unallocated area is shorter than that, we must consider the whole
1692 * cluster allocated. */
1693 if (s->compressed) {
1694 if (n < s->cluster_sectors) {
1695 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1696 s->status = BLK_DATA;
1698 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1705 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1706 int nb_sectors, uint8_t *buf)
1708 uint64_t single_read_until = 0;
1711 assert(nb_sectors <= s->buf_sectors);
1712 while (nb_sectors > 0) {
1715 int64_t bs_sectors, src_cur_offset;
1718 /* In the case of compression with multiple source files, we can get a
1719 * nb_sectors that spreads into the next part. So we must be able to
1720 * read across multiple BDSes for one convert_read() call. */
1721 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1722 blk = s->src[src_cur];
1723 bs_sectors = s->src_sectors[src_cur];
1725 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1727 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1728 if (single_read_until > offset) {
1732 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
1736 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1740 warn_report("error while reading offset %" PRIu64
1741 ": %s", offset, strerror(-ret));
1743 memset(buf, 0, BDRV_SECTOR_SIZE);
1752 buf += n * BDRV_SECTOR_SIZE;
1759 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1760 int nb_sectors, uint8_t *buf,
1761 enum ImgConvertBlockStatus status)
1765 while (nb_sectors > 0) {
1767 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1770 case BLK_BACKING_FILE:
1771 /* If we have a backing file, leave clusters unallocated that are
1772 * unallocated in the source image, so that the backing file is
1773 * visible at the respective offset. */
1774 assert(s->target_has_backing);
1778 /* If we're told to keep the target fully allocated (-S 0) or there
1779 * is real non-zero data, we must write it. Otherwise we can treat
1780 * it as zero sectors.
1781 * Compressed clusters need to be written as a whole, so in that
1782 * case we can only save the write if the buffer is completely
1784 if (!s->min_sparse ||
1786 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1787 sector_num, s->alignment)) ||
1789 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1791 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1792 n << BDRV_SECTOR_BITS, buf, flags);
1801 if (s->has_zero_init) {
1802 assert(!s->target_has_backing);
1805 ret = blk_co_pwrite_zeroes(s->target,
1806 sector_num << BDRV_SECTOR_BITS,
1807 n << BDRV_SECTOR_BITS,
1808 BDRV_REQ_MAY_UNMAP);
1817 buf += n * BDRV_SECTOR_SIZE;
1823 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1828 while (nb_sectors > 0) {
1831 int64_t bs_sectors, src_cur_offset;
1834 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1835 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1836 blk = s->src[src_cur];
1837 bs_sectors = s->src_sectors[src_cur];
1839 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1841 ret = blk_co_copy_range(blk, offset, s->target,
1842 sector_num << BDRV_SECTOR_BITS,
1843 n << BDRV_SECTOR_BITS, 0, 0);
1854 static void coroutine_fn convert_co_do_copy(void *opaque)
1856 ImgConvertState *s = opaque;
1857 uint8_t *buf = NULL;
1861 for (i = 0; i < s->num_coroutines; i++) {
1862 if (s->co[i] == qemu_coroutine_self()) {
1869 s->running_coroutines++;
1870 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1875 enum ImgConvertBlockStatus status;
1878 qemu_co_mutex_lock(&s->lock);
1879 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1880 qemu_co_mutex_unlock(&s->lock);
1883 n = convert_iteration_sectors(s, s->sector_num);
1885 qemu_co_mutex_unlock(&s->lock);
1889 /* save current sector and allocation status to local variables */
1890 sector_num = s->sector_num;
1892 if (!s->min_sparse && s->status == BLK_ZERO) {
1893 n = MIN(n, s->buf_sectors);
1895 /* increment global sector counter so that other coroutines can
1896 * already continue reading beyond this request */
1898 qemu_co_mutex_unlock(&s->lock);
1900 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1901 s->allocated_done += n;
1902 qemu_progress_print(100.0 * s->allocated_done /
1903 s->allocated_sectors, 0);
1907 copy_range = s->copy_range && s->status == BLK_DATA;
1908 if (status == BLK_DATA && !copy_range) {
1909 ret = convert_co_read(s, sector_num, n, buf);
1911 error_report("error while reading sector %" PRId64
1912 ": %s", sector_num, strerror(-ret));
1915 } else if (!s->min_sparse && status == BLK_ZERO) {
1917 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1920 if (s->wr_in_order) {
1921 /* keep writes in order */
1922 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
1923 s->wait_sector_num[index] = sector_num;
1924 qemu_coroutine_yield();
1926 s->wait_sector_num[index] = -1;
1929 if (s->ret == -EINPROGRESS) {
1931 ret = convert_co_copy_range(s, sector_num, n);
1933 s->copy_range = false;
1937 ret = convert_co_write(s, sector_num, n, buf, status);
1940 error_report("error while writing sector %" PRId64
1941 ": %s", sector_num, strerror(-ret));
1946 if (s->wr_in_order) {
1947 /* reenter the coroutine that might have waited
1948 * for this write to complete */
1949 s->wr_offs = sector_num + n;
1950 for (i = 0; i < s->num_coroutines; i++) {
1951 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1953 * A -> B -> A cannot occur because A has
1954 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1955 * B will never enter A during this time window.
1957 qemu_coroutine_enter(s->co[i]);
1965 s->co[index] = NULL;
1966 s->running_coroutines--;
1967 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1968 /* the convert job finished successfully */
1973 static int convert_do_copy(ImgConvertState *s)
1976 int64_t sector_num = 0;
1978 /* Check whether we have zero initialisation or can get it efficiently */
1979 s->has_zero_init = s->min_sparse && !s->target_has_backing
1980 ? bdrv_has_zero_init(blk_bs(s->target))
1983 if (!s->has_zero_init && !s->target_has_backing &&
1984 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1986 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
1988 s->has_zero_init = true;
1992 /* Allocate buffer for copied data. For compressed images, only one cluster
1993 * can be copied at a time. */
1994 if (s->compressed) {
1995 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1996 error_report("invalid cluster size");
1999 s->buf_sectors = s->cluster_sectors;
2002 while (sector_num < s->total_sectors) {
2003 n = convert_iteration_sectors(s, sector_num);
2007 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2009 s->allocated_sectors += n;
2015 s->sector_next_status = 0;
2016 s->ret = -EINPROGRESS;
2018 qemu_co_mutex_init(&s->lock);
2019 for (i = 0; i < s->num_coroutines; i++) {
2020 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2021 s->wait_sector_num[i] = -1;
2022 qemu_coroutine_enter(s->co[i]);
2025 while (s->running_coroutines) {
2026 main_loop_wait(false);
2029 if (s->compressed && !s->ret) {
2030 /* signal EOF to align */
2031 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
2040 #define MAX_BUF_SECTORS 32768
2042 static int img_convert(int argc, char **argv)
2044 int c, bs_i, flags, src_flags = 0;
2045 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
2046 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2047 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
2048 BlockDriver *drv = NULL, *proto_drv = NULL;
2049 BlockDriverInfo bdi;
2050 BlockDriverState *out_bs;
2051 QemuOpts *opts = NULL, *sn_opts = NULL;
2052 QemuOptsList *create_opts = NULL;
2053 QDict *open_opts = NULL;
2054 char *options = NULL;
2055 Error *local_err = NULL;
2056 bool writethrough, src_writethrough, image_opts = false,
2057 skip_create = false, progress = false, tgt_image_opts = false;
2058 int64_t ret = -EINVAL;
2059 bool force_share = false;
2060 bool explict_min_sparse = false;
2062 ImgConvertState s = (ImgConvertState) {
2063 /* Need at least 4k of zeros for sparse detection */
2065 .copy_range = false,
2066 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2067 .wr_in_order = true,
2068 .num_coroutines = 8,
2072 static const struct option long_options[] = {
2073 {"help", no_argument, 0, 'h'},
2074 {"object", required_argument, 0, OPTION_OBJECT},
2075 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2076 {"force-share", no_argument, 0, 'U'},
2077 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
2078 {"salvage", no_argument, 0, OPTION_SALVAGE},
2081 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2082 long_options, NULL);
2088 missing_argument(argv[optind - 1]);
2091 unrecognized_option(argv[optind - 1]);
2103 out_baseimg = optarg;
2106 s.copy_range = true;
2109 s.compressed = true;
2112 if (!is_valid_option_list(optarg)) {
2113 error_report("Invalid option list: %s", optarg);
2117 options = g_strdup(optarg);
2119 char *old_options = options;
2120 options = g_strdup_printf("%s,%s", options, optarg);
2121 g_free(old_options);
2125 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2126 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2129 error_report("Failed in parsing snapshot param '%s'",
2134 snapshot_name = optarg;
2141 sval = cvtnum(optarg);
2142 if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
2143 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2144 error_report("Invalid buffer size for sparse output specified. "
2145 "Valid sizes are multiples of %llu up to %llu. Select "
2146 "0 to disable sparse detection (fully allocates output).",
2147 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
2151 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2152 explict_min_sparse = true;
2171 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2172 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2173 error_report("Invalid number of coroutines. Allowed number of"
2174 " coroutines is between 1 and %d", MAX_COROUTINES);
2179 s.wr_in_order = false;
2184 case OPTION_OBJECT: {
2185 QemuOpts *object_opts;
2186 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2193 case OPTION_IMAGE_OPTS:
2196 case OPTION_SALVAGE:
2199 case OPTION_TARGET_IMAGE_OPTS:
2200 tgt_image_opts = true;
2205 if (!out_fmt && !tgt_image_opts) {
2209 if (qemu_opts_foreach(&qemu_object_opts,
2210 user_creatable_add_opts_foreach,
2211 NULL, &error_fatal)) {
2215 if (s.compressed && s.copy_range) {
2216 error_report("Cannot enable copy offloading when -c is used");
2220 if (explict_min_sparse && s.copy_range) {
2221 error_report("Cannot enable copy offloading when -S is used");
2225 if (s.copy_range && s.salvage) {
2226 error_report("Cannot use copy offloading in salvaging mode");
2230 if (tgt_image_opts && !skip_create) {
2231 error_report("--target-image-opts requires use of -n flag");
2235 s.src_num = argc - optind - 1;
2236 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2238 if (options && has_help_option(options)) {
2240 ret = print_block_option_help(out_filename, out_fmt);
2243 error_report("Option help requires a format be specified");
2248 if (s.src_num < 1) {
2249 error_report("Must specify image file name");
2254 /* ret is still -EINVAL until here */
2255 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2257 error_report("Invalid source cache option: %s", src_cache);
2261 /* Initialize before goto out */
2265 qemu_progress_init(progress, 1.0);
2266 qemu_progress_print(0, 100);
2268 s.src = g_new0(BlockBackend *, s.src_num);
2269 s.src_sectors = g_new(int64_t, s.src_num);
2271 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2272 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2273 fmt, src_flags, src_writethrough, s.quiet,
2279 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2280 if (s.src_sectors[bs_i] < 0) {
2281 error_report("Could not get size of %s: %s",
2282 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2286 s.total_sectors += s.src_sectors[bs_i];
2290 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2291 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2292 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2294 } else if (snapshot_name != NULL) {
2295 if (s.src_num > 1) {
2296 error_report("No support for concatenating multiple snapshot");
2301 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2305 error_reportf_err(local_err, "Failed to load snapshot: ");
2311 /* Find driver and parse its options */
2312 drv = bdrv_find_format(out_fmt);
2314 error_report("Unknown file format '%s'", out_fmt);
2319 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2321 error_report_err(local_err);
2326 if (!drv->create_opts) {
2327 error_report("Format driver '%s' does not support image creation",
2333 if (!proto_drv->create_opts) {
2334 error_report("Protocol driver '%s' does not support image creation",
2335 proto_drv->format_name);
2340 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2341 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2343 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2345 qemu_opts_do_parse(opts, options, NULL, &local_err);
2347 error_report_err(local_err);
2353 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2355 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2361 /* Get backing file name if -o backing_file was used */
2362 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2363 if (out_baseimg_param) {
2364 out_baseimg = out_baseimg_param;
2366 s.target_has_backing = (bool) out_baseimg;
2368 if (s.src_num > 1 && out_baseimg) {
2369 error_report("Having a backing file for the target makes no sense when "
2370 "concatenating multiple input images");
2375 /* Check if compression is supported */
2378 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2379 const char *encryptfmt =
2380 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2381 const char *preallocation =
2382 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2384 if (drv && !drv->bdrv_co_pwritev_compressed) {
2385 error_report("Compression not supported for this file format");
2390 if (encryption || encryptfmt) {
2391 error_report("Compression and encryption not supported at "
2398 && strcmp(preallocation, "off"))
2400 error_report("Compression and preallocation not supported at "
2408 * The later open call will need any decryption secrets, and
2409 * bdrv_create() will purge "opts", so extract them now before
2413 open_opts = qdict_new();
2414 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2418 /* Create the new image */
2419 ret = bdrv_create(drv, out_filename, opts, &local_err);
2421 error_reportf_err(local_err, "%s: error while converting %s: ",
2422 out_filename, out_fmt);
2427 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2428 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2430 error_report("Invalid cache option: %s", cache);
2435 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2436 flags, writethrough, s.quiet, false);
2438 /* TODO ultimately we should allow --target-image-opts
2439 * to be used even when -n is not given.
2440 * That has to wait for bdrv_create to be improved
2441 * to allow filenames in option syntax
2443 s.target = img_open_file(out_filename, open_opts, out_fmt,
2444 flags, writethrough, s.quiet, false);
2445 open_opts = NULL; /* blk_new_open will have freed it */
2451 out_bs = blk_bs(s.target);
2453 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2454 error_report("Compression not supported for this file format");
2459 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2460 * or discard_alignment of the out_bs is greater. Limit to
2461 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2462 s.buf_sectors = MIN(MAX_BUF_SECTORS,
2464 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2465 out_bs->bl.pdiscard_alignment >>
2466 BDRV_SECTOR_BITS)));
2468 /* try to align the write requests to the destination to avoid unnecessary
2470 s.alignment = MAX(pow2floor(s.min_sparse),
2471 DIV_ROUND_UP(out_bs->bl.request_alignment,
2473 assert(is_power_of_2(s.alignment));
2476 int64_t output_sectors = blk_nb_sectors(s.target);
2477 if (output_sectors < 0) {
2478 error_report("unable to get output image length: %s",
2479 strerror(-output_sectors));
2482 } else if (output_sectors < s.total_sectors) {
2483 error_report("output file is smaller than input file");
2489 if (s.target_has_backing) {
2490 /* Errors are treated as "backing length unknown" (which means
2491 * s.target_backing_sectors has to be negative, which it will
2492 * be automatically). The backing file length is used only
2493 * for optimizations, so such a case is not fatal. */
2494 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2496 s.target_backing_sectors = -1;
2499 ret = bdrv_get_info(out_bs, &bdi);
2502 error_report("could not get block driver info");
2506 s.compressed = s.compressed || bdi.needs_compressed_writes;
2507 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2508 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
2511 ret = convert_do_copy(&s);
2514 qemu_progress_print(100, 0);
2516 qemu_progress_end();
2517 qemu_opts_del(opts);
2518 qemu_opts_free(create_opts);
2519 qemu_opts_del(sn_opts);
2520 qobject_unref(open_opts);
2521 blk_unref(s.target);
2523 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2524 blk_unref(s.src[bs_i]);
2528 g_free(s.src_sectors);
2536 static void dump_snapshots(BlockDriverState *bs)
2538 QEMUSnapshotInfo *sn_tab, *sn;
2541 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2544 printf("Snapshot list:\n");
2545 bdrv_snapshot_dump(NULL);
2547 for(i = 0; i < nb_sns; i++) {
2549 bdrv_snapshot_dump(sn);
2555 static void dump_json_image_info_list(ImageInfoList *list)
2559 Visitor *v = qobject_output_visitor_new(&obj);
2561 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2562 visit_complete(v, &obj);
2563 str = qobject_to_json_pretty(obj);
2564 assert(str != NULL);
2565 printf("%s\n", qstring_get_str(str));
2571 static void dump_json_image_info(ImageInfo *info)
2575 Visitor *v = qobject_output_visitor_new(&obj);
2577 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2578 visit_complete(v, &obj);
2579 str = qobject_to_json_pretty(obj);
2580 assert(str != NULL);
2581 printf("%s\n", qstring_get_str(str));
2587 static void dump_human_image_info_list(ImageInfoList *list)
2589 ImageInfoList *elem;
2592 for (elem = list; elem; elem = elem->next) {
2598 bdrv_image_info_dump(elem->value);
2602 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2604 return strcmp(a, b) == 0;
2608 * Open an image file chain and return an ImageInfoList
2610 * @filename: topmost image filename
2611 * @fmt: topmost image format (may be NULL to autodetect)
2612 * @chain: true - enumerate entire backing file chain
2613 * false - only topmost image file
2615 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2616 * image file. If there was an error a message will have been printed to
2619 static ImageInfoList *collect_image_info_list(bool image_opts,
2620 const char *filename,
2622 bool chain, bool force_share)
2624 ImageInfoList *head = NULL;
2625 ImageInfoList **last = &head;
2626 GHashTable *filenames;
2629 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2633 BlockDriverState *bs;
2635 ImageInfoList *elem;
2637 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2638 error_report("Backing file '%s' creates an infinite loop.",
2642 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2644 blk = img_open(image_opts, filename, fmt,
2645 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2652 bdrv_query_image_info(bs, &info, &err);
2654 error_report_err(err);
2659 elem = g_new0(ImageInfoList, 1);
2666 filename = fmt = NULL;
2668 if (info->has_full_backing_filename) {
2669 filename = info->full_backing_filename;
2670 } else if (info->has_backing_filename) {
2671 error_report("Could not determine absolute backing filename,"
2672 " but backing filename '%s' present",
2673 info->backing_filename);
2676 if (info->has_backing_filename_format) {
2677 fmt = info->backing_filename_format;
2681 g_hash_table_destroy(filenames);
2685 qapi_free_ImageInfoList(head);
2686 g_hash_table_destroy(filenames);
2690 static int img_info(int argc, char **argv)
2693 OutputFormat output_format = OFORMAT_HUMAN;
2695 const char *filename, *fmt, *output;
2696 ImageInfoList *list;
2697 bool image_opts = false;
2698 bool force_share = false;
2703 int option_index = 0;
2704 static const struct option long_options[] = {
2705 {"help", no_argument, 0, 'h'},
2706 {"format", required_argument, 0, 'f'},
2707 {"output", required_argument, 0, OPTION_OUTPUT},
2708 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2709 {"object", required_argument, 0, OPTION_OBJECT},
2710 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2711 {"force-share", no_argument, 0, 'U'},
2714 c = getopt_long(argc, argv, ":f:hU",
2715 long_options, &option_index);
2721 missing_argument(argv[optind - 1]);
2724 unrecognized_option(argv[optind - 1]);
2738 case OPTION_BACKING_CHAIN:
2741 case OPTION_OBJECT: {
2743 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2749 case OPTION_IMAGE_OPTS:
2754 if (optind != argc - 1) {
2755 error_exit("Expecting one image file name");
2757 filename = argv[optind++];
2759 if (output && !strcmp(output, "json")) {
2760 output_format = OFORMAT_JSON;
2761 } else if (output && !strcmp(output, "human")) {
2762 output_format = OFORMAT_HUMAN;
2763 } else if (output) {
2764 error_report("--output must be used with human or json as argument.");
2768 if (qemu_opts_foreach(&qemu_object_opts,
2769 user_creatable_add_opts_foreach,
2770 NULL, &error_fatal)) {
2774 list = collect_image_info_list(image_opts, filename, fmt, chain,
2780 switch (output_format) {
2782 dump_human_image_info_list(list);
2786 dump_json_image_info_list(list);
2788 dump_json_image_info(list->value);
2793 qapi_free_ImageInfoList(list);
2797 static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2800 switch (output_format) {
2802 if (e->data && !e->has_offset) {
2803 error_report("File contains external, encrypted or compressed clusters.");
2806 if (e->data && !e->zero) {
2807 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2808 e->start, e->length,
2809 e->has_offset ? e->offset : 0,
2810 e->has_filename ? e->filename : "");
2812 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2813 * Modify the flags here to allow more coalescing.
2815 if (next && (!next->data || next->zero)) {
2821 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2822 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2823 (e->start == 0 ? "[" : ",\n"),
2824 e->start, e->length, e->depth,
2825 e->zero ? "true" : "false",
2826 e->data ? "true" : "false");
2827 if (e->has_offset) {
2828 printf(", \"offset\": %"PRId64"", e->offset);
2840 static int get_block_status(BlockDriverState *bs, int64_t offset,
2841 int64_t bytes, MapEntry *e)
2845 BlockDriverState *file;
2848 char *filename = NULL;
2850 /* As an optimization, we could cache the current range of unallocated
2851 * clusters in each file of the chain, and avoid querying the same
2857 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
2862 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2865 bs = backing_bs(bs);
2874 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2876 if (file && has_offset) {
2877 bdrv_refresh_filename(file);
2878 filename = file->filename;
2884 .data = !!(ret & BDRV_BLOCK_DATA),
2885 .zero = !!(ret & BDRV_BLOCK_ZERO),
2887 .has_offset = has_offset,
2889 .has_filename = filename,
2890 .filename = filename,
2896 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2898 if (curr->length == 0) {
2901 if (curr->zero != next->zero ||
2902 curr->data != next->data ||
2903 curr->depth != next->depth ||
2904 curr->has_filename != next->has_filename ||
2905 curr->has_offset != next->has_offset) {
2908 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2911 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2917 static int img_map(int argc, char **argv)
2920 OutputFormat output_format = OFORMAT_HUMAN;
2922 BlockDriverState *bs;
2923 const char *filename, *fmt, *output;
2925 MapEntry curr = { .length = 0 }, next;
2927 bool image_opts = false;
2928 bool force_share = false;
2933 int option_index = 0;
2934 static const struct option long_options[] = {
2935 {"help", no_argument, 0, 'h'},
2936 {"format", required_argument, 0, 'f'},
2937 {"output", required_argument, 0, OPTION_OUTPUT},
2938 {"object", required_argument, 0, OPTION_OBJECT},
2939 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2940 {"force-share", no_argument, 0, 'U'},
2943 c = getopt_long(argc, argv, ":f:hU",
2944 long_options, &option_index);
2950 missing_argument(argv[optind - 1]);
2953 unrecognized_option(argv[optind - 1]);
2967 case OPTION_OBJECT: {
2969 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2975 case OPTION_IMAGE_OPTS:
2980 if (optind != argc - 1) {
2981 error_exit("Expecting one image file name");
2983 filename = argv[optind];
2985 if (output && !strcmp(output, "json")) {
2986 output_format = OFORMAT_JSON;
2987 } else if (output && !strcmp(output, "human")) {
2988 output_format = OFORMAT_HUMAN;
2989 } else if (output) {
2990 error_report("--output must be used with human or json as argument.");
2994 if (qemu_opts_foreach(&qemu_object_opts,
2995 user_creatable_add_opts_foreach,
2996 NULL, &error_fatal)) {
3000 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
3006 if (output_format == OFORMAT_HUMAN) {
3007 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3010 length = blk_getlength(blk);
3011 while (curr.start + curr.length < length) {
3012 int64_t offset = curr.start + curr.length;
3015 /* Probe up to 1 GiB at a time. */
3016 n = MIN(1 * GiB, length - offset);
3017 ret = get_block_status(bs, offset, n, &next);
3020 error_report("Could not read file metadata: %s", strerror(-ret));
3024 if (entry_mergeable(&curr, &next)) {
3025 curr.length += next.length;
3029 if (curr.length > 0) {
3030 ret = dump_map_entry(output_format, &curr, &next);
3038 ret = dump_map_entry(output_format, &curr, NULL);
3045 #define SNAPSHOT_LIST 1
3046 #define SNAPSHOT_CREATE 2
3047 #define SNAPSHOT_APPLY 3
3048 #define SNAPSHOT_DELETE 4
3050 static int img_snapshot(int argc, char **argv)
3053 BlockDriverState *bs;
3054 QEMUSnapshotInfo sn;
3055 char *filename, *snapshot_name = NULL;
3056 int c, ret = 0, bdrv_oflags;
3061 bool image_opts = false;
3062 bool force_share = false;
3064 bdrv_oflags = BDRV_O_RDWR;
3065 /* Parse commandline parameters */
3067 static const struct option long_options[] = {
3068 {"help", no_argument, 0, 'h'},
3069 {"object", required_argument, 0, OPTION_OBJECT},
3070 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3071 {"force-share", no_argument, 0, 'U'},
3074 c = getopt_long(argc, argv, ":la:c:d:hqU",
3075 long_options, NULL);
3081 missing_argument(argv[optind - 1]);
3084 unrecognized_option(argv[optind - 1]);
3091 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3094 action = SNAPSHOT_LIST;
3095 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
3099 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3102 action = SNAPSHOT_APPLY;
3103 snapshot_name = optarg;
3107 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3110 action = SNAPSHOT_CREATE;
3111 snapshot_name = optarg;
3115 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3118 action = SNAPSHOT_DELETE;
3119 snapshot_name = optarg;
3127 case OPTION_OBJECT: {
3129 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3135 case OPTION_IMAGE_OPTS:
3141 if (optind != argc - 1) {
3142 error_exit("Expecting one image file name");
3144 filename = argv[optind++];
3146 if (qemu_opts_foreach(&qemu_object_opts,
3147 user_creatable_add_opts_foreach,
3148 NULL, &error_fatal)) {
3152 /* Open the image */
3153 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3160 /* Perform the requested action */
3166 case SNAPSHOT_CREATE:
3167 memset(&sn, 0, sizeof(sn));
3168 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3170 qemu_gettimeofday(&tv);
3171 sn.date_sec = tv.tv_sec;
3172 sn.date_nsec = tv.tv_usec * 1000;
3174 ret = bdrv_snapshot_create(bs, &sn);
3176 error_report("Could not create snapshot '%s': %d (%s)",
3177 snapshot_name, ret, strerror(-ret));
3181 case SNAPSHOT_APPLY:
3182 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3184 error_reportf_err(err, "Could not apply snapshot '%s': ",
3189 case SNAPSHOT_DELETE:
3190 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3192 error_report("Could not delete snapshot '%s': snapshot not "
3193 "found", snapshot_name);
3196 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3198 error_reportf_err(err, "Could not delete snapshot '%s': ",
3214 static int img_rebase(int argc, char **argv)
3216 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3217 uint8_t *buf_old = NULL;
3218 uint8_t *buf_new = NULL;
3219 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
3221 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3222 int c, flags, src_flags, ret;
3223 bool writethrough, src_writethrough;
3225 bool force_share = false;
3228 Error *local_err = NULL;
3229 bool image_opts = false;
3231 /* Parse commandline parameters */
3233 cache = BDRV_DEFAULT_CACHE;
3234 src_cache = BDRV_DEFAULT_CACHE;
3238 static const struct option long_options[] = {
3239 {"help", no_argument, 0, 'h'},
3240 {"object", required_argument, 0, OPTION_OBJECT},
3241 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3242 {"force-share", no_argument, 0, 'U'},
3245 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3246 long_options, NULL);
3252 missing_argument(argv[optind - 1]);
3255 unrecognized_option(argv[optind - 1]);
3264 out_basefmt = optarg;
3267 out_baseimg = optarg;
3284 case OPTION_OBJECT: {
3286 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3292 case OPTION_IMAGE_OPTS:
3305 if (optind != argc - 1) {
3306 error_exit("Expecting one image file name");
3308 if (!unsafe && !out_baseimg) {
3309 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3311 filename = argv[optind++];
3313 if (qemu_opts_foreach(&qemu_object_opts,
3314 user_creatable_add_opts_foreach,
3315 NULL, &error_fatal)) {
3319 qemu_progress_init(progress, 2.0);
3320 qemu_progress_print(0, 100);
3322 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3323 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3325 error_report("Invalid cache option: %s", cache);
3330 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3332 error_report("Invalid source cache option: %s", src_cache);
3336 /* The source files are opened read-only, don't care about WCE */
3337 assert((src_flags & BDRV_O_RDWR) == 0);
3338 (void) src_writethrough;
3343 * Ignore the old backing file for unsafe rebase in case we want to correct
3344 * the reference to a renamed or moved backing file.
3346 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3354 if (out_basefmt != NULL) {
3355 if (bdrv_find_format(out_basefmt) == NULL) {
3356 error_report("Invalid format name: '%s'", out_basefmt);
3362 /* For safe rebasing we need to compare old and new backing file */
3364 QDict *options = NULL;
3365 BlockDriverState *base_bs = backing_bs(bs);
3368 blk_old_backing = blk_new(qemu_get_aio_context(),
3369 BLK_PERM_CONSISTENT_READ,
3371 ret = blk_insert_bs(blk_old_backing, base_bs,
3374 error_reportf_err(local_err,
3375 "Could not reuse old backing file '%s': ",
3380 blk_old_backing = NULL;
3383 if (out_baseimg[0]) {
3384 const char *overlay_filename;
3385 char *out_real_path;
3387 options = qdict_new();
3389 qdict_put_str(options, "driver", out_basefmt);
3392 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3395 bdrv_refresh_filename(bs);
3396 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3399 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3403 qobject_unref(options);
3404 error_reportf_err(local_err,
3405 "Could not resolve backing filename: ");
3411 * Find out whether we rebase an image on top of a previous image
3414 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
3415 if (prefix_chain_bs) {
3416 qobject_unref(options);
3417 g_free(out_real_path);
3419 blk_new_backing = blk_new(qemu_get_aio_context(),
3420 BLK_PERM_CONSISTENT_READ,
3422 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3425 error_reportf_err(local_err,
3426 "Could not reuse backing file '%s': ",
3431 blk_new_backing = blk_new_open(out_real_path, NULL,
3432 options, src_flags, &local_err);
3433 g_free(out_real_path);
3434 if (!blk_new_backing) {
3435 error_reportf_err(local_err,
3436 "Could not open new backing file '%s': ",
3446 * Check each unallocated cluster in the COW file. If it is unallocated,
3447 * accesses go to the backing file. We must therefore compare this cluster
3448 * in the old and new backing file, and if they differ we need to copy it
3449 * from the old backing file into the COW file.
3451 * If qemu-img crashes during this step, no harm is done. The content of
3452 * the image is the same as the original one at any time.
3456 int64_t old_backing_size = 0;
3457 int64_t new_backing_size = 0;
3460 float local_progress = 0;
3462 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3463 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3465 size = blk_getlength(blk);
3467 error_report("Could not get size of '%s': %s",
3468 filename, strerror(-size));
3472 if (blk_old_backing) {
3473 old_backing_size = blk_getlength(blk_old_backing);
3474 if (old_backing_size < 0) {
3475 char backing_name[PATH_MAX];
3477 bdrv_get_backing_filename(bs, backing_name,
3478 sizeof(backing_name));
3479 error_report("Could not get size of '%s': %s",
3480 backing_name, strerror(-old_backing_size));
3485 if (blk_new_backing) {
3486 new_backing_size = blk_getlength(blk_new_backing);
3487 if (new_backing_size < 0) {
3488 error_report("Could not get size of '%s': %s",
3489 out_baseimg, strerror(-new_backing_size));
3496 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3499 for (offset = 0; offset < size; offset += n) {
3500 bool buf_old_is_zero = false;
3502 /* How many bytes can we handle with the next read? */
3503 n = MIN(IO_BUF_SIZE, size - offset);
3505 /* If the cluster is allocated, we don't need to take action */
3506 ret = bdrv_is_allocated(bs, offset, n, &n);
3508 error_report("error while reading image metadata: %s",
3516 if (prefix_chain_bs) {
3518 * If cluster wasn't changed since prefix_chain, we don't need
3521 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
3522 false, offset, n, &n);
3524 error_report("error while reading image metadata: %s",
3534 * Read old and new backing file and take into consideration that
3535 * backing files may be smaller than the COW image.
3537 if (offset >= old_backing_size) {
3538 memset(buf_old, 0, n);
3539 buf_old_is_zero = true;
3541 if (offset + n > old_backing_size) {
3542 n = old_backing_size - offset;
3545 ret = blk_pread(blk_old_backing, offset, buf_old, n);
3547 error_report("error while reading from old backing file");
3552 if (offset >= new_backing_size || !blk_new_backing) {
3553 memset(buf_new, 0, n);
3555 if (offset + n > new_backing_size) {
3556 n = new_backing_size - offset;
3559 ret = blk_pread(blk_new_backing, offset, buf_new, n);
3561 error_report("error while reading from new backing file");
3566 /* If they differ, we need to write to the COW file */
3567 uint64_t written = 0;
3569 while (written < n) {
3572 if (compare_buffers(buf_old + written, buf_new + written,
3573 n - written, &pnum))
3575 if (buf_old_is_zero) {
3576 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3578 ret = blk_pwrite(blk, offset + written,
3579 buf_old + written, pnum, 0);
3582 error_report("Error while writing to COW image: %s",
3590 qemu_progress_print(local_progress, 100);
3595 * Change the backing file. All clusters that are different from the old
3596 * backing file are overwritten in the COW file now, so the visible content
3597 * doesn't change when we switch the backing file.
3599 if (out_baseimg && *out_baseimg) {
3600 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3602 ret = bdrv_change_backing_file(bs, NULL, NULL);
3605 if (ret == -ENOSPC) {
3606 error_report("Could not change the backing file to '%s': No "
3607 "space left in the file header", out_baseimg);
3608 } else if (ret < 0) {
3609 error_report("Could not change the backing file to '%s': %s",
3610 out_baseimg, strerror(-ret));
3613 qemu_progress_print(100, 0);
3615 * TODO At this point it is possible to check if any clusters that are
3616 * allocated in the COW file are the same in the backing file. If so, they
3617 * could be dropped from the COW file. Don't do this before switching the
3618 * backing file, in case of a crash this would lead to corruption.
3621 qemu_progress_end();
3624 blk_unref(blk_old_backing);
3625 blk_unref(blk_new_backing);
3627 qemu_vfree(buf_old);
3628 qemu_vfree(buf_new);
3637 static int img_resize(int argc, char **argv)
3640 int c, ret, relative;
3641 const char *filename, *fmt, *size;
3642 int64_t n, total_size, current_size, new_size;
3644 BlockBackend *blk = NULL;
3645 PreallocMode prealloc = PREALLOC_MODE_OFF;
3648 static QemuOptsList resize_options = {
3649 .name = "resize_options",
3650 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3653 .name = BLOCK_OPT_SIZE,
3654 .type = QEMU_OPT_SIZE,
3655 .help = "Virtual disk size"
3661 bool image_opts = false;
3662 bool shrink = false;
3664 /* Remove size from argv manually so that negative numbers are not treated
3665 * as options by getopt. */
3667 error_exit("Not enough arguments");
3671 size = argv[--argc];
3673 /* Parse getopt arguments */
3676 static const struct option long_options[] = {
3677 {"help", no_argument, 0, 'h'},
3678 {"object", required_argument, 0, OPTION_OBJECT},
3679 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3680 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3681 {"shrink", no_argument, 0, OPTION_SHRINK},
3684 c = getopt_long(argc, argv, ":f:hq",
3685 long_options, NULL);
3691 missing_argument(argv[optind - 1]);
3694 unrecognized_option(argv[optind - 1]);
3705 case OPTION_OBJECT: {
3707 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3713 case OPTION_IMAGE_OPTS:
3716 case OPTION_PREALLOCATION:
3717 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3718 PREALLOC_MODE__MAX, NULL);
3719 if (prealloc == PREALLOC_MODE__MAX) {
3720 error_report("Invalid preallocation mode '%s'", optarg);
3729 if (optind != argc - 1) {
3730 error_exit("Expecting image file name and size");
3732 filename = argv[optind++];
3734 if (qemu_opts_foreach(&qemu_object_opts,
3735 user_creatable_add_opts_foreach,
3736 NULL, &error_fatal)) {
3740 /* Choose grow, shrink, or absolute resize mode */
3756 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3757 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3759 error_report_err(err);
3761 qemu_opts_del(param);
3764 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3765 qemu_opts_del(param);
3767 blk = img_open(image_opts, filename, fmt,
3768 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3775 current_size = blk_getlength(blk);
3776 if (current_size < 0) {
3777 error_report("Failed to inquire current image length: %s",
3778 strerror(-current_size));
3784 total_size = current_size + n * relative;
3788 if (total_size <= 0) {
3789 error_report("New image size must be positive");
3794 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3795 error_report("Preallocation can only be used for growing images");
3800 if (total_size < current_size && !shrink) {
3801 warn_report("Shrinking an image will delete all data beyond the "
3802 "shrunken image's end. Before performing such an "
3803 "operation, make sure there is no important data there.");
3805 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3807 "Use the --shrink option to perform a shrink operation.");
3811 warn_report("Using the --shrink option will suppress this message. "
3812 "Note that future versions of qemu-img may refuse to "
3813 "shrink images without this option.");
3817 ret = blk_truncate(blk, total_size, prealloc, &err);
3819 error_report_err(err);
3823 new_size = blk_getlength(blk);
3825 error_report("Failed to verify truncated image length: %s",
3826 strerror(-new_size));
3831 /* Some block drivers implement a truncation method, but only so
3832 * the user can cause qemu to refresh the image's size from disk.
3833 * The idea is that the user resizes the image outside of qemu and
3834 * then invokes block_resize to inform qemu about it.
3835 * (This includes iscsi and file-posix for device files.)
3836 * Of course, that is not the behavior someone invoking
3837 * qemu-img resize would find useful, so we catch that behavior
3838 * here and tell the user. */
3839 if (new_size != total_size && new_size == current_size) {
3840 error_report("Image was not resized; resizing may not be supported "
3846 if (new_size != total_size) {
3847 warn_report("Image should have been resized to %" PRIi64
3848 " bytes, but was resized to %" PRIi64 " bytes",
3849 total_size, new_size);
3852 qprintf(quiet, "Image resized.\n");
3862 static void amend_status_cb(BlockDriverState *bs,
3863 int64_t offset, int64_t total_work_size,
3866 qemu_progress_print(100.f * offset / total_work_size, 0);
3869 static int print_amend_option_help(const char *format)
3873 /* Find driver and parse its options */
3874 drv = bdrv_find_format(format);
3876 error_report("Unknown file format '%s'", format);
3880 if (!drv->bdrv_amend_options) {
3881 error_report("Format driver '%s' does not support option amendment",
3886 /* Every driver supporting amendment must have create_opts */
3887 assert(drv->create_opts);
3889 printf("Creation options for '%s':\n", format);
3890 qemu_opts_print_help(drv->create_opts, false);
3891 printf("\nNote that not all of these options may be amendable.\n");
3895 static int img_amend(int argc, char **argv)
3899 char *options = NULL;
3900 QemuOptsList *create_opts = NULL;
3901 QemuOpts *opts = NULL;
3902 const char *fmt = NULL, *filename, *cache;
3905 bool quiet = false, progress = false;
3906 BlockBackend *blk = NULL;
3907 BlockDriverState *bs = NULL;
3908 bool image_opts = false;
3910 cache = BDRV_DEFAULT_CACHE;
3912 static const struct option long_options[] = {
3913 {"help", no_argument, 0, 'h'},
3914 {"object", required_argument, 0, OPTION_OBJECT},
3915 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3918 c = getopt_long(argc, argv, ":ho:f:t:pq",
3919 long_options, NULL);
3926 missing_argument(argv[optind - 1]);
3929 unrecognized_option(argv[optind - 1]);
3935 if (!is_valid_option_list(optarg)) {
3936 error_report("Invalid option list: %s", optarg);
3938 goto out_no_progress;
3941 options = g_strdup(optarg);
3943 char *old_options = options;
3944 options = g_strdup_printf("%s,%s", options, optarg);
3945 g_free(old_options);
3961 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3965 goto out_no_progress;
3968 case OPTION_IMAGE_OPTS:
3975 error_exit("Must specify options (-o)");
3978 if (qemu_opts_foreach(&qemu_object_opts,
3979 user_creatable_add_opts_foreach,
3980 NULL, &error_fatal)) {
3982 goto out_no_progress;
3988 qemu_progress_init(progress, 1.0);
3990 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3991 if (fmt && has_help_option(options)) {
3992 /* If a format is explicitly specified (and possibly no filename is
3993 * given), print option help here */
3994 ret = print_amend_option_help(fmt);
3998 if (optind != argc - 1) {
3999 error_report("Expecting one image file name");
4004 flags = BDRV_O_RDWR;
4005 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
4007 error_report("Invalid cache option: %s", cache);
4011 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4019 fmt = bs->drv->format_name;
4021 if (has_help_option(options)) {
4022 /* If the format was auto-detected, print option help here */
4023 ret = print_amend_option_help(fmt);
4027 if (!bs->drv->bdrv_amend_options) {
4028 error_report("Format driver '%s' does not support option amendment",
4034 /* Every driver supporting amendment must have create_opts */
4035 assert(bs->drv->create_opts);
4037 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
4038 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4039 qemu_opts_do_parse(opts, options, NULL, &err);
4041 error_report_err(err);
4046 /* In case the driver does not call amend_status_cb() */
4047 qemu_progress_print(0.f, 0);
4048 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
4049 qemu_progress_print(100.f, 0);
4051 error_report_err(err);
4056 qemu_progress_end();
4060 qemu_opts_del(opts);
4061 qemu_opts_free(create_opts);
4070 typedef struct BenchData {
4072 uint64_t image_size;
4079 bool drain_on_flush;
4088 static void bench_undrained_flush_cb(void *opaque, int ret)
4091 error_report("Failed flush request: %s", strerror(-ret));
4096 static void bench_cb(void *opaque, int ret)
4098 BenchData *b = opaque;
4102 error_report("Failed request: %s", strerror(-ret));
4107 /* Just finished a flush with drained queue: Start next requests */
4108 assert(b->in_flight == 0);
4109 b->in_flush = false;
4110 } else if (b->in_flight > 0) {
4111 int remaining = b->n - b->in_flight;
4116 /* Time for flush? Drain queue if requested, then flush */
4117 if (b->flush_interval && remaining % b->flush_interval == 0) {
4118 if (!b->in_flight || !b->drain_on_flush) {
4119 BlockCompletionFunc *cb;
4121 if (b->drain_on_flush) {
4125 cb = bench_undrained_flush_cb;
4128 acb = blk_aio_flush(b->blk, cb, b);
4130 error_report("Failed to issue flush request");
4134 if (b->drain_on_flush) {
4140 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4141 int64_t offset = b->offset;
4142 /* blk_aio_* might look for completed I/Os and kick bench_cb
4143 * again, so make sure this operation is counted by in_flight
4144 * and b->offset is ready for the next submission.
4147 b->offset += b->step;
4148 b->offset %= b->image_size;
4150 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
4152 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
4155 error_report("Failed to issue request");
4161 static int img_bench(int argc, char **argv)
4164 const char *fmt = NULL, *filename;
4166 bool image_opts = false;
4167 bool is_write = false;
4171 size_t bufsize = 4096;
4174 int flush_interval = 0;
4175 bool drain_on_flush = true;
4177 BlockBackend *blk = NULL;
4178 BenchData data = {};
4180 bool writethrough = false;
4181 struct timeval t1, t2;
4183 bool force_share = false;
4187 static const struct option long_options[] = {
4188 {"help", no_argument, 0, 'h'},
4189 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
4190 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4191 {"pattern", required_argument, 0, OPTION_PATTERN},
4192 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
4193 {"force-share", no_argument, 0, 'U'},
4196 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
4203 missing_argument(argv[optind - 1]);
4206 unrecognized_option(argv[optind - 1]);
4215 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4216 error_report("Invalid request count specified");
4226 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4227 error_report("Invalid queue depth specified");
4237 flags |= BDRV_O_NATIVE_AIO;
4241 offset = cvtnum(optarg);
4243 error_report("Invalid offset specified");
4256 sval = cvtnum(optarg);
4257 if (sval < 0 || sval > INT_MAX) {
4258 error_report("Invalid buffer size specified");
4269 sval = cvtnum(optarg);
4270 if (sval < 0 || sval > INT_MAX) {
4271 error_report("Invalid step size specified");
4279 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4281 error_report("Invalid cache mode");
4287 flags |= BDRV_O_RDWR;
4293 case OPTION_PATTERN:
4297 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4298 error_report("Invalid pattern byte specified");
4304 case OPTION_FLUSH_INTERVAL:
4308 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4309 error_report("Invalid flush interval specified");
4312 flush_interval = res;
4315 case OPTION_NO_DRAIN:
4316 drain_on_flush = false;
4318 case OPTION_IMAGE_OPTS:
4324 if (optind != argc - 1) {
4325 error_exit("Expecting one image file name");
4327 filename = argv[argc - 1];
4329 if (!is_write && flush_interval) {
4330 error_report("--flush-interval is only available in write tests");
4334 if (flush_interval && flush_interval < depth) {
4335 error_report("Flush interval can't be smaller than depth");
4340 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4347 image_size = blk_getlength(blk);
4348 if (image_size < 0) {
4353 data = (BenchData) {
4355 .image_size = image_size,
4357 .step = step ?: bufsize,
4362 .flush_interval = flush_interval,
4363 .drain_on_flush = drain_on_flush,
4365 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4366 "(starting at offset %" PRId64 ", step size %d)\n",
4367 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4368 data.offset, data.step);
4369 if (flush_interval) {
4370 printf("Sending flush every %d requests\n", flush_interval);
4373 buf_size = data.nrreq * data.bufsize;
4374 data.buf = blk_blockalign(blk, buf_size);
4375 memset(data.buf, pattern, data.nrreq * data.bufsize);
4377 blk_register_buf(blk, data.buf, buf_size);
4379 data.qiov = g_new(QEMUIOVector, data.nrreq);
4380 for (i = 0; i < data.nrreq; i++) {
4381 qemu_iovec_init(&data.qiov[i], 1);
4382 qemu_iovec_add(&data.qiov[i],
4383 data.buf + i * data.bufsize, data.bufsize);
4386 gettimeofday(&t1, NULL);
4389 while (data.n > 0) {
4390 main_loop_wait(false);
4392 gettimeofday(&t2, NULL);
4394 printf("Run completed in %3.3f seconds.\n",
4395 (t2.tv_sec - t1.tv_sec)
4396 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4400 blk_unregister_buf(blk, data.buf);
4402 qemu_vfree(data.buf);
4423 int bsz; /* Block size */
4431 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4435 static int img_dd_bs(const char *arg,
4436 struct DdIo *in, struct DdIo *out,
4443 if (res <= 0 || res > INT_MAX) {
4444 error_report("invalid number: '%s'", arg);
4447 in->bsz = out->bsz = res;
4452 static int img_dd_count(const char *arg,
4453 struct DdIo *in, struct DdIo *out,
4456 dd->count = cvtnum(arg);
4458 if (dd->count < 0) {
4459 error_report("invalid number: '%s'", arg);
4466 static int img_dd_if(const char *arg,
4467 struct DdIo *in, struct DdIo *out,
4470 in->filename = g_strdup(arg);
4475 static int img_dd_of(const char *arg,
4476 struct DdIo *in, struct DdIo *out,
4479 out->filename = g_strdup(arg);
4484 static int img_dd_skip(const char *arg,
4485 struct DdIo *in, struct DdIo *out,
4488 in->offset = cvtnum(arg);
4490 if (in->offset < 0) {
4491 error_report("invalid number: '%s'", arg);
4498 static int img_dd(int argc, char **argv)
4503 BlockDriver *drv = NULL, *proto_drv = NULL;
4504 BlockBackend *blk1 = NULL, *blk2 = NULL;
4505 QemuOpts *opts = NULL;
4506 QemuOptsList *create_opts = NULL;
4507 Error *local_err = NULL;
4508 bool image_opts = false;
4510 const char *out_fmt = "raw";
4511 const char *fmt = NULL;
4513 int64_t block_count = 0, out_pos, in_pos;
4514 bool force_share = false;
4515 struct DdInfo dd = {
4520 .bsz = 512, /* Block size is by default 512 bytes */
4532 const struct DdOpts options[] = {
4533 { "bs", img_dd_bs, C_BS },
4534 { "count", img_dd_count, C_COUNT },
4535 { "if", img_dd_if, C_IF },
4536 { "of", img_dd_of, C_OF },
4537 { "skip", img_dd_skip, C_SKIP },
4540 const struct option long_options[] = {
4541 { "help", no_argument, 0, 'h'},
4542 { "object", required_argument, 0, OPTION_OBJECT},
4543 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4544 { "force-share", no_argument, 0, 'U'},
4548 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4560 missing_argument(argv[optind - 1]);
4563 unrecognized_option(argv[optind - 1]);
4572 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4577 case OPTION_IMAGE_OPTS:
4583 for (i = optind; i < argc; i++) {
4585 arg = g_strdup(argv[i]);
4587 tmp = strchr(arg, '=');
4589 error_report("unrecognized operand %s", arg);
4596 for (j = 0; options[j].name != NULL; j++) {
4597 if (!strcmp(arg, options[j].name)) {
4601 if (options[j].name == NULL) {
4602 error_report("unrecognized operand %s", arg);
4607 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4611 dd.flags |= options[j].flag;
4616 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4617 error_report("Must specify both input and output files");
4622 if (qemu_opts_foreach(&qemu_object_opts,
4623 user_creatable_add_opts_foreach,
4624 NULL, &error_fatal)) {
4629 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4637 drv = bdrv_find_format(out_fmt);
4639 error_report("Unknown file format");
4643 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4646 error_report_err(local_err);
4650 if (!drv->create_opts) {
4651 error_report("Format driver '%s' does not support image creation",
4656 if (!proto_drv->create_opts) {
4657 error_report("Protocol driver '%s' does not support image creation",
4658 proto_drv->format_name);
4662 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4663 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4665 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4667 size = blk_getlength(blk1);
4669 error_report("Failed to get size for '%s'", in.filename);
4674 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4675 dd.count * in.bsz < size) {
4676 size = dd.count * in.bsz;
4679 /* Overflow means the specified offset is beyond input image's size */
4680 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4681 size < in.bsz * in.offset)) {
4682 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4684 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4685 size - in.bsz * in.offset, &error_abort);
4688 ret = bdrv_create(drv, out.filename, opts, &local_err);
4690 error_reportf_err(local_err,
4691 "%s: error while creating output image: ",
4697 /* TODO, we can't honour --image-opts for the target,
4698 * since it needs to be given in a format compatible
4699 * with the bdrv_create() call above which does not
4700 * support image-opts style.
4702 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
4703 false, false, false);
4710 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4711 size < in.offset * in.bsz)) {
4712 /* We give a warning if the skip option is bigger than the input
4713 * size and create an empty output disk image (i.e. like dd(1)).
4715 error_report("%s: cannot skip to specified offset", in.filename);
4718 in_pos = in.offset * in.bsz;
4721 in.buf = g_new(uint8_t, in.bsz);
4723 for (out_pos = 0; in_pos < size; block_count++) {
4724 int in_ret, out_ret;
4726 if (in_pos + in.bsz > size) {
4727 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4729 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4732 error_report("error while reading from input image file: %s",
4739 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4742 error_report("error while writing to output image file: %s",
4743 strerror(-out_ret));
4752 qemu_opts_del(opts);
4753 qemu_opts_free(create_opts);
4756 g_free(in.filename);
4757 g_free(out.filename);
4767 static void dump_json_block_measure_info(BlockMeasureInfo *info)
4771 Visitor *v = qobject_output_visitor_new(&obj);
4773 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4774 visit_complete(v, &obj);
4775 str = qobject_to_json_pretty(obj);
4776 assert(str != NULL);
4777 printf("%s\n", qstring_get_str(str));
4783 static int img_measure(int argc, char **argv)
4785 static const struct option long_options[] = {
4786 {"help", no_argument, 0, 'h'},
4787 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4788 {"object", required_argument, 0, OPTION_OBJECT},
4789 {"output", required_argument, 0, OPTION_OUTPUT},
4790 {"size", required_argument, 0, OPTION_SIZE},
4791 {"force-share", no_argument, 0, 'U'},
4794 OutputFormat output_format = OFORMAT_HUMAN;
4795 BlockBackend *in_blk = NULL;
4797 const char *filename = NULL;
4798 const char *fmt = NULL;
4799 const char *out_fmt = "raw";
4800 char *options = NULL;
4801 char *snapshot_name = NULL;
4802 bool force_share = false;
4803 QemuOpts *opts = NULL;
4804 QemuOpts *object_opts = NULL;
4805 QemuOpts *sn_opts = NULL;
4806 QemuOptsList *create_opts = NULL;
4807 bool image_opts = false;
4808 uint64_t img_size = UINT64_MAX;
4809 BlockMeasureInfo *info = NULL;
4810 Error *local_err = NULL;
4814 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4815 long_options, NULL)) != -1) {
4828 if (!is_valid_option_list(optarg)) {
4829 error_report("Invalid option list: %s", optarg);
4833 options = g_strdup(optarg);
4835 char *old_options = options;
4836 options = g_strdup_printf("%s,%s", options, optarg);
4837 g_free(old_options);
4841 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4842 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4845 error_report("Failed in parsing snapshot param '%s'",
4850 snapshot_name = optarg;
4857 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4863 case OPTION_IMAGE_OPTS:
4867 if (!strcmp(optarg, "json")) {
4868 output_format = OFORMAT_JSON;
4869 } else if (!strcmp(optarg, "human")) {
4870 output_format = OFORMAT_HUMAN;
4872 error_report("--output must be used with human or json "
4881 sval = cvtnum(optarg);
4883 if (sval == -ERANGE) {
4884 error_report("Image size must be less than 8 EiB!");
4886 error_report("Invalid image size specified! You may use "
4887 "k, M, G, T, P or E suffixes for ");
4888 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4889 "petabytes and exabytes.");
4893 img_size = (uint64_t)sval;
4899 if (qemu_opts_foreach(&qemu_object_opts,
4900 user_creatable_add_opts_foreach,
4901 NULL, &error_fatal)) {
4905 if (argc - optind > 1) {
4906 error_report("At most one filename argument is allowed.");
4908 } else if (argc - optind == 1) {
4909 filename = argv[optind];
4913 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4914 error_report("--object, --image-opts, -f, and -l "
4915 "require a filename argument.");
4918 if (filename && img_size != UINT64_MAX) {
4919 error_report("--size N cannot be used together with a filename.");
4922 if (!filename && img_size == UINT64_MAX) {
4923 error_report("Either --size N or one filename must be specified.");
4928 in_blk = img_open(image_opts, filename, fmt, 0,
4929 false, false, force_share);
4935 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4936 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4937 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4939 } else if (snapshot_name != NULL) {
4940 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4941 snapshot_name, &local_err);
4944 error_reportf_err(local_err, "Failed to load snapshot: ");
4949 drv = bdrv_find_format(out_fmt);
4951 error_report("Unknown file format '%s'", out_fmt);
4954 if (!drv->create_opts) {
4955 error_report("Format driver '%s' does not support image creation",
4960 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4961 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4962 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4964 qemu_opts_do_parse(opts, options, NULL, &local_err);
4966 error_report_err(local_err);
4967 error_report("Invalid options for file format '%s'", out_fmt);
4971 if (img_size != UINT64_MAX) {
4972 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4975 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4977 error_report_err(local_err);
4981 if (output_format == OFORMAT_HUMAN) {
4982 printf("required size: %" PRIu64 "\n", info->required);
4983 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4985 dump_json_block_measure_info(info);
4991 qapi_free_BlockMeasureInfo(info);
4992 qemu_opts_del(object_opts);
4993 qemu_opts_del(opts);
4994 qemu_opts_del(sn_opts);
4995 qemu_opts_free(create_opts);
5001 static const img_cmd_t img_cmds[] = {
5002 #define DEF(option, callback, arg_string) \
5003 { option, callback },
5004 #include "qemu-img-cmds.h"
5009 int main(int argc, char **argv)
5011 const img_cmd_t *cmd;
5012 const char *cmdname;
5013 Error *local_error = NULL;
5014 char *trace_file = NULL;
5016 static const struct option long_options[] = {
5017 {"help", no_argument, 0, 'h'},
5018 {"version", no_argument, 0, 'V'},
5019 {"trace", required_argument, NULL, 'T'},
5024 signal(SIGPIPE, SIG_IGN);
5027 error_init(argv[0]);
5028 module_call_init(MODULE_INIT_TRACE);
5029 qemu_init_exec_dir(argv[0]);
5031 if (qemu_init_main_loop(&local_error)) {
5032 error_report_err(local_error);
5036 qcrypto_init(&error_fatal);
5038 module_call_init(MODULE_INIT_QOM);
5041 error_exit("Not enough arguments");
5044 qemu_add_opts(&qemu_object_opts);
5045 qemu_add_opts(&qemu_source_opts);
5046 qemu_add_opts(&qemu_trace_opts);
5048 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
5051 missing_argument(argv[optind - 1]);
5054 unrecognized_option(argv[optind - 1]);
5060 printf(QEMU_IMG_VERSION);
5064 trace_file = trace_opt_parse(optarg);
5069 cmdname = argv[optind];
5071 /* reset getopt_long scanning */
5077 qemu_reset_optind();
5079 if (!trace_init_backends()) {
5082 trace_init_file(trace_file);
5083 qemu_set_log(LOG_TRACE);
5085 /* find the command */
5086 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5087 if (!strcmp(cmdname, cmd->name)) {
5088 return cmd->handler(argc, argv);
5093 error_exit("Command not found: %s", cmdname);