2 * QEMU disk image utility
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 #include "qemu/osdep.h"
27 #include "qemu-version.h"
28 #include "qapi/error.h"
29 #include "qapi-visit.h"
30 #include "qapi/qobject-output-visitor.h"
31 #include "qapi/qmp/qerror.h"
32 #include "qapi/qmp/qjson.h"
33 #include "qapi/qmp/qbool.h"
34 #include "qemu/cutils.h"
35 #include "qemu/config-file.h"
36 #include "qemu/option.h"
37 #include "qemu/error-report.h"
39 #include "qom/object_interfaces.h"
40 #include "sysemu/sysemu.h"
41 #include "sysemu/block-backend.h"
42 #include "block/block_int.h"
43 #include "block/blockjob.h"
44 #include "block/qapi.h"
45 #include "crypto/init.h"
46 #include "trace/control.h"
48 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
49 "\n" QEMU_COPYRIGHT "\n"
51 typedef struct img_cmd_t {
53 int (*handler)(int argc, char **argv);
58 OPTION_BACKING_CHAIN = 257,
60 OPTION_IMAGE_OPTS = 259,
62 OPTION_FLUSH_INTERVAL = 261,
63 OPTION_NO_DRAIN = 262,
64 OPTION_TARGET_IMAGE_OPTS = 263,
66 OPTION_PREALLOCATION = 265,
70 typedef enum OutputFormat {
75 /* Default to cache=writeback as data integrity is not important for qemu-img */
76 #define BDRV_DEFAULT_CACHE "writeback"
78 static void format_print(void *opaque, const char *name)
83 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
87 error_printf("qemu-img: ");
90 error_vprintf(fmt, ap);
93 error_printf("\nTry 'qemu-img --help' for more information\n");
97 static void QEMU_NORETURN missing_argument(const char *option)
99 error_exit("missing argument for option '%s'", option);
102 static void QEMU_NORETURN unrecognized_option(const char *option)
104 error_exit("unrecognized option '%s'", option);
107 /* Please keep in synch with qemu-img.texi */
108 static void QEMU_NORETURN help(void)
110 const char *help_msg =
112 "usage: qemu-img [standard options] command [command options]\n"
113 "QEMU disk image utility\n"
115 " '-h', '--help' display this help and exit\n"
116 " '-V', '--version' output version information and exit\n"
117 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
118 " specify tracing options\n"
121 #define DEF(option, callback, arg_string) \
123 #include "qemu-img-cmds.h"
127 "Command parameters:\n"
128 " 'filename' is a disk image filename\n"
129 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
130 " manual page for a description of the object properties. The most common\n"
131 " object type is a 'secret', which is used to supply passwords and/or\n"
132 " encryption keys.\n"
133 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
134 " 'cache' is the cache mode used to write the output disk image, the valid\n"
135 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
136 " 'directsync' and 'unsafe' (default for convert)\n"
137 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
138 " options are the same as for the 'cache' option\n"
139 " 'size' is the disk image size in bytes. Optional suffixes\n"
140 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
141 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
142 " supported. 'b' is ignored.\n"
143 " 'output_filename' is the destination disk image filename\n"
144 " 'output_fmt' is the destination format\n"
145 " 'options' is a comma separated list of format specific options in a\n"
146 " name=value format. Use -o ? for an overview of the options supported by the\n"
148 " 'snapshot_param' is param used for internal snapshot, format\n"
149 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
151 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
153 " '-c' indicates that target image must be compressed (qcow format only)\n"
154 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
155 " new backing file match exactly. The image doesn't need a working\n"
156 " backing file before rebasing in this case (useful for renaming the\n"
157 " backing file). For image creation, allow creating without attempting\n"
158 " to open the backing file.\n"
159 " '-h' with or without a command shows this help and lists the supported formats\n"
160 " '-p' show progress of command (only certain commands)\n"
161 " '-q' use Quiet mode - do not print any output (except errors)\n"
162 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
163 " contain only zeros for qemu-img to create a sparse image during\n"
164 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
165 " unallocated or zero sectors, and the destination image will always be\n"
167 " '--output' takes the format in which the output must be done (human or json)\n"
168 " '-n' skips the target volume creation (useful if the volume is created\n"
169 " prior to running qemu-img)\n"
171 "Parameters to check subcommand:\n"
172 " '-r' tries to repair any inconsistencies that are found during the check.\n"
173 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
174 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
175 " hiding corruption that has already occurred.\n"
177 "Parameters to convert subcommand:\n"
178 " '-m' specifies how many coroutines work in parallel during the convert\n"
179 " process (defaults to 8)\n"
180 " '-W' allow to write to the target out of order rather than sequential\n"
182 "Parameters to snapshot subcommand:\n"
183 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
184 " '-a' applies a snapshot (revert disk to saved state)\n"
185 " '-c' creates a snapshot\n"
186 " '-d' deletes a snapshot\n"
187 " '-l' lists all snapshots in the given image\n"
189 "Parameters to compare subcommand:\n"
190 " '-f' first image format\n"
191 " '-F' second image format\n"
192 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
194 "Parameters to dd subcommand:\n"
195 " 'bs=BYTES' read and write up to BYTES bytes at a time "
197 " 'count=N' copy only N input blocks\n"
198 " 'if=FILE' read from FILE\n"
199 " 'of=FILE' write to FILE\n"
200 " 'skip=N' skip N bs-sized blocks at the start of input\n";
202 printf("%s\nSupported formats:", help_msg);
203 bdrv_iterate_format(format_print, NULL);
204 printf("\n\n" QEMU_HELP_BOTTOM "\n");
208 static QemuOptsList qemu_object_opts = {
210 .implied_opt_name = "qom-type",
211 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
217 static QemuOptsList qemu_source_opts = {
219 .implied_opt_name = "file",
220 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
226 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
232 ret = vprintf(fmt, args);
239 static int print_block_option_help(const char *filename, const char *fmt)
241 BlockDriver *drv, *proto_drv;
242 QemuOptsList *create_opts = NULL;
243 Error *local_err = NULL;
245 /* Find driver and parse its options */
246 drv = bdrv_find_format(fmt);
248 error_report("Unknown file format '%s'", fmt);
252 create_opts = qemu_opts_append(create_opts, drv->create_opts);
254 proto_drv = bdrv_find_protocol(filename, true, &local_err);
256 error_report_err(local_err);
257 qemu_opts_free(create_opts);
260 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
263 qemu_opts_print_help(create_opts);
264 qemu_opts_free(create_opts);
269 static BlockBackend *img_open_opts(const char *optstr,
270 QemuOpts *opts, int flags, bool writethrough,
271 bool quiet, bool force_share)
274 Error *local_err = NULL;
276 options = qemu_opts_to_qdict(opts, NULL);
278 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
279 && !qdict_get_bool(options, BDRV_OPT_FORCE_SHARE)) {
280 error_report("--force-share/-U conflicts with image options");
284 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
286 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
288 error_reportf_err(local_err, "Could not open '%s': ", optstr);
291 blk_set_enable_write_cache(blk, !writethrough);
296 static BlockBackend *img_open_file(const char *filename,
298 const char *fmt, int flags,
299 bool writethrough, bool quiet,
303 Error *local_err = NULL;
306 options = qdict_new();
309 qdict_put_str(options, "driver", fmt);
313 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
315 blk = blk_new_open(filename, NULL, options, flags, &local_err);
317 error_reportf_err(local_err, "Could not open '%s': ", filename);
320 blk_set_enable_write_cache(blk, !writethrough);
326 static int img_add_key_secrets(void *opaque,
327 const char *name, const char *value,
330 QDict *options = opaque;
332 if (g_str_has_suffix(name, "key-secret")) {
333 qdict_put_str(options, name, value);
339 static BlockBackend *img_open_new_file(const char *filename,
340 QemuOpts *create_opts,
341 const char *fmt, int flags,
342 bool writethrough, bool quiet,
345 QDict *options = NULL;
347 options = qdict_new();
348 qemu_opt_foreach(create_opts, img_add_key_secrets, options, &error_abort);
350 return img_open_file(filename, options, fmt, flags, writethrough, quiet,
355 static BlockBackend *img_open(bool image_opts,
356 const char *filename,
357 const char *fmt, int flags, bool writethrough,
358 bool quiet, bool force_share)
364 error_report("--image-opts and --format are mutually exclusive");
367 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
372 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
375 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
382 static int add_old_style_options(const char *fmt, QemuOpts *opts,
383 const char *base_filename,
384 const char *base_fmt)
389 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
391 error_report("Backing file not supported for file format '%s'",
398 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
400 error_report("Backing file format not supported for file "
409 static int64_t cvtnum(const char *s)
414 err = qemu_strtosz(s, NULL, &value);
418 if (value > INT64_MAX) {
424 static int img_create(int argc, char **argv)
427 uint64_t img_size = -1;
428 const char *fmt = "raw";
429 const char *base_fmt = NULL;
430 const char *filename;
431 const char *base_filename = NULL;
432 char *options = NULL;
433 Error *local_err = NULL;
438 static const struct option long_options[] = {
439 {"help", no_argument, 0, 'h'},
440 {"object", required_argument, 0, OPTION_OBJECT},
443 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
450 missing_argument(argv[optind - 1]);
453 unrecognized_option(argv[optind - 1]);
462 base_filename = optarg;
468 if (!is_valid_option_list(optarg)) {
469 error_report("Invalid option list: %s", optarg);
473 options = g_strdup(optarg);
475 char *old_options = options;
476 options = g_strdup_printf("%s,%s", options, optarg);
484 flags |= BDRV_O_NO_BACKING;
486 case OPTION_OBJECT: {
488 opts = qemu_opts_parse_noisily(&qemu_object_opts,
497 /* Get the filename */
498 filename = (optind < argc) ? argv[optind] : NULL;
499 if (options && has_help_option(options)) {
501 return print_block_option_help(filename, fmt);
504 if (optind >= argc) {
505 error_exit("Expecting image file name");
509 if (qemu_opts_foreach(&qemu_object_opts,
510 user_creatable_add_opts_foreach,
515 /* Get image size, if specified */
519 sval = cvtnum(argv[optind++]);
521 if (sval == -ERANGE) {
522 error_report("Image size must be less than 8 EiB!");
524 error_report("Invalid image size specified! You may use k, M, "
525 "G, T, P or E suffixes for ");
526 error_report("kilobytes, megabytes, gigabytes, terabytes, "
527 "petabytes and exabytes.");
531 img_size = (uint64_t)sval;
533 if (optind != argc) {
534 error_exit("Unexpected argument: %s", argv[optind]);
537 bdrv_img_create(filename, fmt, base_filename, base_fmt,
538 options, img_size, flags, quiet, &local_err);
540 error_reportf_err(local_err, "%s: ", filename);
552 static void dump_json_image_check(ImageCheck *check, bool quiet)
556 Visitor *v = qobject_output_visitor_new(&obj);
558 visit_type_ImageCheck(v, NULL, &check, &error_abort);
559 visit_complete(v, &obj);
560 str = qobject_to_json_pretty(obj);
562 qprintf(quiet, "%s\n", qstring_get_str(str));
568 static void dump_human_image_check(ImageCheck *check, bool quiet)
570 if (!(check->corruptions || check->leaks || check->check_errors)) {
571 qprintf(quiet, "No errors were found on the image.\n");
573 if (check->corruptions) {
574 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
575 "Data may be corrupted, or further writes to the image "
582 "\n%" PRId64 " leaked clusters were found on the image.\n"
583 "This means waste of disk space, but no harm to data.\n",
587 if (check->check_errors) {
590 " internal errors have occurred during the check.\n",
591 check->check_errors);
595 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
596 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
597 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
598 check->allocated_clusters, check->total_clusters,
599 check->allocated_clusters * 100.0 / check->total_clusters,
600 check->fragmented_clusters * 100.0 / check->allocated_clusters,
601 check->compressed_clusters * 100.0 /
602 check->allocated_clusters);
605 if (check->image_end_offset) {
607 "Image end offset: %" PRId64 "\n", check->image_end_offset);
611 static int collect_image_check(BlockDriverState *bs,
613 const char *filename,
618 BdrvCheckResult result;
620 ret = bdrv_check(bs, &result, fix);
625 check->filename = g_strdup(filename);
626 check->format = g_strdup(bdrv_get_format_name(bs));
627 check->check_errors = result.check_errors;
628 check->corruptions = result.corruptions;
629 check->has_corruptions = result.corruptions != 0;
630 check->leaks = result.leaks;
631 check->has_leaks = result.leaks != 0;
632 check->corruptions_fixed = result.corruptions_fixed;
633 check->has_corruptions_fixed = result.corruptions != 0;
634 check->leaks_fixed = result.leaks_fixed;
635 check->has_leaks_fixed = result.leaks != 0;
636 check->image_end_offset = result.image_end_offset;
637 check->has_image_end_offset = result.image_end_offset != 0;
638 check->total_clusters = result.bfi.total_clusters;
639 check->has_total_clusters = result.bfi.total_clusters != 0;
640 check->allocated_clusters = result.bfi.allocated_clusters;
641 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
642 check->fragmented_clusters = result.bfi.fragmented_clusters;
643 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
644 check->compressed_clusters = result.bfi.compressed_clusters;
645 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
651 * Checks an image for consistency. Exit codes:
653 * 0 - Check completed, image is good
654 * 1 - Check not completed because of internal errors
655 * 2 - Check completed, image is corrupted
656 * 3 - Check completed, image has leaked clusters, but is good otherwise
657 * 63 - Checks are not supported by the image format
659 static int img_check(int argc, char **argv)
662 OutputFormat output_format = OFORMAT_HUMAN;
663 const char *filename, *fmt, *output, *cache;
665 BlockDriverState *bs;
667 int flags = BDRV_O_CHECK;
671 bool image_opts = false;
672 bool force_share = false;
676 cache = BDRV_DEFAULT_CACHE;
679 int option_index = 0;
680 static const struct option long_options[] = {
681 {"help", no_argument, 0, 'h'},
682 {"format", required_argument, 0, 'f'},
683 {"repair", required_argument, 0, 'r'},
684 {"output", required_argument, 0, OPTION_OUTPUT},
685 {"object", required_argument, 0, OPTION_OBJECT},
686 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
687 {"force-share", no_argument, 0, 'U'},
690 c = getopt_long(argc, argv, ":hf:r:T:qU",
691 long_options, &option_index);
697 missing_argument(argv[optind - 1]);
700 unrecognized_option(argv[optind - 1]);
709 flags |= BDRV_O_RDWR;
711 if (!strcmp(optarg, "leaks")) {
712 fix = BDRV_FIX_LEAKS;
713 } else if (!strcmp(optarg, "all")) {
714 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
716 error_exit("Unknown option value for -r "
717 "(expecting 'leaks' or 'all'): %s", optarg);
732 case OPTION_OBJECT: {
734 opts = qemu_opts_parse_noisily(&qemu_object_opts,
740 case OPTION_IMAGE_OPTS:
745 if (optind != argc - 1) {
746 error_exit("Expecting one image file name");
748 filename = argv[optind++];
750 if (output && !strcmp(output, "json")) {
751 output_format = OFORMAT_JSON;
752 } else if (output && !strcmp(output, "human")) {
753 output_format = OFORMAT_HUMAN;
755 error_report("--output must be used with human or json as argument.");
759 if (qemu_opts_foreach(&qemu_object_opts,
760 user_creatable_add_opts_foreach,
765 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
767 error_report("Invalid source cache option: %s", cache);
771 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
778 check = g_new0(ImageCheck, 1);
779 ret = collect_image_check(bs, check, filename, fmt, fix);
781 if (ret == -ENOTSUP) {
782 error_report("This image format does not support checks");
787 if (check->corruptions_fixed || check->leaks_fixed) {
788 int corruptions_fixed, leaks_fixed;
790 leaks_fixed = check->leaks_fixed;
791 corruptions_fixed = check->corruptions_fixed;
793 if (output_format == OFORMAT_HUMAN) {
795 "The following inconsistencies were found and repaired:\n\n"
796 " %" PRId64 " leaked clusters\n"
797 " %" PRId64 " corruptions\n\n"
798 "Double checking the fixed image now...\n",
800 check->corruptions_fixed);
803 ret = collect_image_check(bs, check, filename, fmt, 0);
805 check->leaks_fixed = leaks_fixed;
806 check->corruptions_fixed = corruptions_fixed;
810 switch (output_format) {
812 dump_human_image_check(check, quiet);
815 dump_json_image_check(check, quiet);
820 if (ret || check->check_errors) {
822 error_report("Check failed: %s", strerror(-ret));
824 error_report("Check failed");
830 if (check->corruptions) {
832 } else if (check->leaks) {
839 qapi_free_ImageCheck(check);
844 typedef struct CommonBlockJobCBInfo {
845 BlockDriverState *bs;
847 } CommonBlockJobCBInfo;
849 static void common_block_job_cb(void *opaque, int ret)
851 CommonBlockJobCBInfo *cbi = opaque;
854 error_setg_errno(cbi->errp, -ret, "Block job failed");
858 static void run_block_job(BlockJob *job, Error **errp)
860 AioContext *aio_context = blk_get_aio_context(job->blk);
863 aio_context_acquire(aio_context);
866 aio_poll(aio_context, true);
867 qemu_progress_print(job->len ?
868 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
869 } while (!job->ready && !job->completed);
871 if (!job->completed) {
872 ret = block_job_complete_sync(job, errp);
876 block_job_unref(job);
877 aio_context_release(aio_context);
879 /* publish completion progress only when success */
881 qemu_progress_print(100.f, 0);
885 static int img_commit(int argc, char **argv)
888 const char *filename, *fmt, *cache, *base;
890 BlockDriverState *bs, *base_bs;
892 bool progress = false, quiet = false, drop = false;
894 Error *local_err = NULL;
895 CommonBlockJobCBInfo cbi;
896 bool image_opts = false;
897 AioContext *aio_context;
900 cache = BDRV_DEFAULT_CACHE;
903 static const struct option long_options[] = {
904 {"help", no_argument, 0, 'h'},
905 {"object", required_argument, 0, OPTION_OBJECT},
906 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
909 c = getopt_long(argc, argv, ":f:ht:b:dpq",
916 missing_argument(argv[optind - 1]);
919 unrecognized_option(argv[optind - 1]);
944 case OPTION_OBJECT: {
946 opts = qemu_opts_parse_noisily(&qemu_object_opts,
952 case OPTION_IMAGE_OPTS:
958 /* Progress is not shown in Quiet mode */
963 if (optind != argc - 1) {
964 error_exit("Expecting one image file name");
966 filename = argv[optind++];
968 if (qemu_opts_foreach(&qemu_object_opts,
969 user_creatable_add_opts_foreach,
974 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
975 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
977 error_report("Invalid cache option: %s", cache);
981 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
988 qemu_progress_init(progress, 1.f);
989 qemu_progress_print(0.f, 100);
992 base_bs = bdrv_find_backing_image(bs, base);
994 error_setg(&local_err,
995 "Did not find '%s' in the backing chain of '%s'",
1000 /* This is different from QMP, which by default uses the deepest file in
1001 * the backing chain (i.e., the very base); however, the traditional
1002 * behavior of qemu-img commit is using the immediate backing file. */
1003 base_bs = backing_bs(bs);
1005 error_setg(&local_err, "Image does not have a backing file");
1010 cbi = (CommonBlockJobCBInfo){
1015 aio_context = bdrv_get_aio_context(bs);
1016 aio_context_acquire(aio_context);
1017 commit_active_start("commit", bs, base_bs, BLOCK_JOB_DEFAULT, 0,
1018 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1019 &cbi, false, &local_err);
1020 aio_context_release(aio_context);
1025 /* When the block job completes, the BlockBackend reference will point to
1026 * the old backing file. In order to avoid that the top image is already
1027 * deleted, so we can still empty it afterwards, increment the reference
1028 * counter here preemptively. */
1033 job = block_job_get("commit");
1034 run_block_job(job, &local_err);
1039 if (!drop && bs->drv->bdrv_make_empty) {
1040 ret = bs->drv->bdrv_make_empty(bs);
1042 error_setg_errno(&local_err, -ret, "Could not empty %s",
1054 qemu_progress_end();
1059 error_report_err(local_err);
1063 qprintf(quiet, "Image committed.\n");
1068 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1069 * of the first sector boundary within buf where the sector contains a
1070 * non-zero byte. This function is robust to a buffer that is not
1073 static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1076 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1078 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1079 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1083 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1090 * Returns true iff the first sector pointed to by 'buf' contains at least
1093 * 'pnum' is set to the number of sectors (including and immediately following
1094 * the first one) that are known to be in the same allocated/unallocated state.
1096 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
1105 is_zero = buffer_is_zero(buf, 512);
1106 for(i = 1; i < n; i++) {
1108 if (is_zero != buffer_is_zero(buf, 512)) {
1117 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1118 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1119 * breaking up write requests for only small sparse areas.
1121 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1125 int num_checked, num_used;
1131 ret = is_allocated_sectors(buf, n, pnum);
1137 buf += BDRV_SECTOR_SIZE * *pnum;
1139 num_checked = num_used;
1142 ret = is_allocated_sectors(buf, n, pnum);
1144 buf += BDRV_SECTOR_SIZE * *pnum;
1146 num_checked += *pnum;
1148 num_used = num_checked;
1149 } else if (*pnum >= min) {
1159 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1160 * buffers matches, non-zero otherwise.
1162 * pnum is set to the number of sectors (including and immediately following
1163 * the first one) that are known to have the same comparison result
1165 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1176 res = !!memcmp(buf1, buf2, 512);
1177 for(i = 1; i < n; i++) {
1181 if (!!memcmp(buf1, buf2, 512) != res) {
1190 #define IO_BUF_SIZE (2 * 1024 * 1024)
1192 static int64_t sectors_to_bytes(int64_t sectors)
1194 return sectors << BDRV_SECTOR_BITS;
1198 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1200 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1201 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1202 * failure), and 4 on error (the exit status for read errors), after emitting
1205 * @param blk: BlockBackend for the image
1206 * @param offset: Starting offset to check
1207 * @param bytes: Number of bytes to check
1208 * @param filename: Name of disk file we are checking (logging purpose)
1209 * @param buffer: Allocated buffer for storing read data
1210 * @param quiet: Flag for quiet mode
1212 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1213 int64_t bytes, const char *filename,
1214 uint8_t *buffer, bool quiet)
1219 ret = blk_pread(blk, offset, buffer, bytes);
1221 error_report("Error while reading offset %" PRId64 " of %s: %s",
1222 offset, filename, strerror(-ret));
1225 idx = find_nonzero(buffer, bytes);
1227 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1236 * Compares two images. Exit codes:
1238 * 0 - Images are identical
1240 * >1 - Error occurred
1242 static int img_compare(int argc, char **argv)
1244 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1245 BlockBackend *blk1, *blk2;
1246 BlockDriverState *bs1, *bs2;
1247 int64_t total_sectors1, total_sectors2;
1248 uint8_t *buf1 = NULL, *buf2 = NULL;
1249 int64_t pnum1, pnum2;
1250 int allocated1, allocated2;
1251 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1252 bool progress = false, quiet = false, strict = false;
1255 int64_t total_sectors;
1256 int64_t sector_num = 0;
1259 uint64_t progress_base;
1260 bool image_opts = false;
1261 bool force_share = false;
1263 cache = BDRV_DEFAULT_CACHE;
1265 static const struct option long_options[] = {
1266 {"help", no_argument, 0, 'h'},
1267 {"object", required_argument, 0, OPTION_OBJECT},
1268 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1269 {"force-share", no_argument, 0, 'U'},
1272 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1273 long_options, NULL);
1279 missing_argument(argv[optind - 1]);
1282 unrecognized_option(argv[optind - 1]);
1308 case OPTION_OBJECT: {
1310 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1317 case OPTION_IMAGE_OPTS:
1323 /* Progress is not shown in Quiet mode */
1329 if (optind != argc - 2) {
1330 error_exit("Expecting two image file names");
1332 filename1 = argv[optind++];
1333 filename2 = argv[optind++];
1335 if (qemu_opts_foreach(&qemu_object_opts,
1336 user_creatable_add_opts_foreach,
1342 /* Initialize before goto out */
1343 qemu_progress_init(progress, 2.0);
1346 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1348 error_report("Invalid source cache option: %s", cache);
1353 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1360 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1369 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1370 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1371 total_sectors1 = blk_nb_sectors(blk1);
1372 if (total_sectors1 < 0) {
1373 error_report("Can't get size of %s: %s",
1374 filename1, strerror(-total_sectors1));
1378 total_sectors2 = blk_nb_sectors(blk2);
1379 if (total_sectors2 < 0) {
1380 error_report("Can't get size of %s: %s",
1381 filename2, strerror(-total_sectors2));
1385 total_sectors = MIN(total_sectors1, total_sectors2);
1386 progress_base = MAX(total_sectors1, total_sectors2);
1388 qemu_progress_print(0, 100);
1390 if (strict && total_sectors1 != total_sectors2) {
1392 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1396 while (sector_num < total_sectors) {
1397 int status1, status2;
1399 status1 = bdrv_block_status_above(bs1, NULL,
1400 sector_num * BDRV_SECTOR_SIZE,
1401 (total_sectors1 - sector_num) *
1403 &pnum1, NULL, NULL);
1406 error_report("Sector allocation test failed for %s", filename1);
1409 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1411 status2 = bdrv_block_status_above(bs2, NULL,
1412 sector_num * BDRV_SECTOR_SIZE,
1413 (total_sectors2 - sector_num) *
1415 &pnum2, NULL, NULL);
1418 error_report("Sector allocation test failed for %s", filename2);
1421 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1422 /* TODO: Relax this once comparison is byte-based, and we no longer
1423 * have to worry about sector alignment */
1424 assert(QEMU_IS_ALIGNED(pnum1 | pnum2, BDRV_SECTOR_SIZE));
1426 assert(pnum1 && pnum2);
1427 nb_sectors = MIN(pnum1, pnum2) >> BDRV_SECTOR_BITS;
1430 if (status1 != status2) {
1432 qprintf(quiet, "Strict mode: Offset %" PRId64
1433 " block status mismatch!\n",
1434 sectors_to_bytes(sector_num));
1438 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1440 } else if (allocated1 == allocated2) {
1442 nb_sectors = MIN(nb_sectors, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1443 ret = blk_pread(blk1, sector_num << BDRV_SECTOR_BITS, buf1,
1444 nb_sectors << BDRV_SECTOR_BITS);
1446 error_report("Error while reading offset %" PRId64 " of %s:"
1447 " %s", sectors_to_bytes(sector_num), filename1,
1452 ret = blk_pread(blk2, sector_num << BDRV_SECTOR_BITS, buf2,
1453 nb_sectors << BDRV_SECTOR_BITS);
1455 error_report("Error while reading offset %" PRId64
1456 " of %s: %s", sectors_to_bytes(sector_num),
1457 filename2, strerror(-ret));
1461 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1462 if (ret || pnum != nb_sectors) {
1463 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1465 ret ? sector_num : sector_num + pnum));
1471 nb_sectors = MIN(nb_sectors, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1473 ret = check_empty_sectors(blk1, sector_num * BDRV_SECTOR_SIZE,
1474 nb_sectors * BDRV_SECTOR_SIZE,
1475 filename1, buf1, quiet);
1477 ret = check_empty_sectors(blk2, sector_num * BDRV_SECTOR_SIZE,
1478 nb_sectors * BDRV_SECTOR_SIZE,
1479 filename2, buf1, quiet);
1485 sector_num += nb_sectors;
1486 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1489 if (total_sectors1 != total_sectors2) {
1490 BlockBackend *blk_over;
1491 const char *filename_over;
1493 qprintf(quiet, "Warning: Image size mismatch!\n");
1494 if (total_sectors1 > total_sectors2) {
1496 filename_over = filename1;
1499 filename_over = filename2;
1502 while (sector_num < progress_base) {
1505 ret = bdrv_block_status_above(blk_bs(blk_over), NULL,
1506 sector_num * BDRV_SECTOR_SIZE,
1507 (progress_base - sector_num) *
1509 &count, NULL, NULL);
1512 error_report("Sector allocation test failed for %s",
1517 /* TODO relax this once bdrv_block_status_above does not enforce
1518 * sector alignment */
1519 assert(QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE));
1520 nb_sectors = count >> BDRV_SECTOR_BITS;
1521 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1522 nb_sectors = MIN(nb_sectors, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1523 ret = check_empty_sectors(blk_over,
1524 sector_num * BDRV_SECTOR_SIZE,
1525 nb_sectors * BDRV_SECTOR_SIZE,
1526 filename_over, buf1, quiet);
1531 sector_num += nb_sectors;
1532 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1536 qprintf(quiet, "Images are identical.\n");
1546 qemu_progress_end();
1551 enum ImgConvertBlockStatus {
1557 #define MAX_COROUTINES 16
1559 typedef struct ImgConvertState {
1561 int64_t *src_sectors;
1563 int64_t total_sectors;
1564 int64_t allocated_sectors;
1565 int64_t allocated_done;
1568 enum ImgConvertBlockStatus status;
1569 int64_t sector_next_status;
1570 BlockBackend *target;
1573 bool target_has_backing;
1576 size_t cluster_sectors;
1578 long num_coroutines;
1579 int running_coroutines;
1580 Coroutine *co[MAX_COROUTINES];
1581 int64_t wait_sector_num[MAX_COROUTINES];
1586 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1587 int *src_cur, int64_t *src_cur_offset)
1590 *src_cur_offset = 0;
1591 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1592 *src_cur_offset += s->src_sectors[*src_cur];
1594 assert(*src_cur < s->src_num);
1598 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1600 int64_t src_cur_offset;
1601 int ret, n, src_cur;
1603 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1605 assert(s->total_sectors > sector_num);
1606 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1608 if (s->sector_next_status <= sector_num) {
1609 int64_t count = n * BDRV_SECTOR_SIZE;
1611 if (s->target_has_backing) {
1613 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1614 (sector_num - src_cur_offset) *
1616 count, &count, NULL, NULL);
1618 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1619 (sector_num - src_cur_offset) *
1621 count, &count, NULL, NULL);
1626 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1628 if (ret & BDRV_BLOCK_ZERO) {
1629 s->status = BLK_ZERO;
1630 } else if (ret & BDRV_BLOCK_DATA) {
1631 s->status = BLK_DATA;
1633 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1636 s->sector_next_status = sector_num + n;
1639 n = MIN(n, s->sector_next_status - sector_num);
1640 if (s->status == BLK_DATA) {
1641 n = MIN(n, s->buf_sectors);
1644 /* We need to write complete clusters for compressed images, so if an
1645 * unallocated area is shorter than that, we must consider the whole
1646 * cluster allocated. */
1647 if (s->compressed) {
1648 if (n < s->cluster_sectors) {
1649 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1650 s->status = BLK_DATA;
1652 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1659 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1660 int nb_sectors, uint8_t *buf)
1666 assert(nb_sectors <= s->buf_sectors);
1667 while (nb_sectors > 0) {
1670 int64_t bs_sectors, src_cur_offset;
1672 /* In the case of compression with multiple source files, we can get a
1673 * nb_sectors that spreads into the next part. So we must be able to
1674 * read across multiple BDSes for one convert_read() call. */
1675 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1676 blk = s->src[src_cur];
1677 bs_sectors = s->src_sectors[src_cur];
1679 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1681 iov.iov_len = n << BDRV_SECTOR_BITS;
1682 qemu_iovec_init_external(&qiov, &iov, 1);
1684 ret = blk_co_preadv(
1685 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1686 n << BDRV_SECTOR_BITS, &qiov, 0);
1693 buf += n * BDRV_SECTOR_SIZE;
1700 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1701 int nb_sectors, uint8_t *buf,
1702 enum ImgConvertBlockStatus status)
1708 while (nb_sectors > 0) {
1710 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1713 case BLK_BACKING_FILE:
1714 /* If we have a backing file, leave clusters unallocated that are
1715 * unallocated in the source image, so that the backing file is
1716 * visible at the respective offset. */
1717 assert(s->target_has_backing);
1721 /* If we're told to keep the target fully allocated (-S 0) or there
1722 * is real non-zero data, we must write it. Otherwise we can treat
1723 * it as zero sectors.
1724 * Compressed clusters need to be written as a whole, so in that
1725 * case we can only save the write if the buffer is completely
1727 if (!s->min_sparse ||
1729 is_allocated_sectors_min(buf, n, &n, s->min_sparse)) ||
1731 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1734 iov.iov_len = n << BDRV_SECTOR_BITS;
1735 qemu_iovec_init_external(&qiov, &iov, 1);
1737 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
1738 n << BDRV_SECTOR_BITS, &qiov, flags);
1747 if (s->has_zero_init) {
1748 assert(!s->target_has_backing);
1751 ret = blk_co_pwrite_zeroes(s->target,
1752 sector_num << BDRV_SECTOR_BITS,
1753 n << BDRV_SECTOR_BITS, 0);
1762 buf += n * BDRV_SECTOR_SIZE;
1768 static void coroutine_fn convert_co_do_copy(void *opaque)
1770 ImgConvertState *s = opaque;
1771 uint8_t *buf = NULL;
1775 for (i = 0; i < s->num_coroutines; i++) {
1776 if (s->co[i] == qemu_coroutine_self()) {
1783 s->running_coroutines++;
1784 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1789 enum ImgConvertBlockStatus status;
1791 qemu_co_mutex_lock(&s->lock);
1792 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1793 qemu_co_mutex_unlock(&s->lock);
1796 n = convert_iteration_sectors(s, s->sector_num);
1798 qemu_co_mutex_unlock(&s->lock);
1802 /* save current sector and allocation status to local variables */
1803 sector_num = s->sector_num;
1805 if (!s->min_sparse && s->status == BLK_ZERO) {
1806 n = MIN(n, s->buf_sectors);
1808 /* increment global sector counter so that other coroutines can
1809 * already continue reading beyond this request */
1811 qemu_co_mutex_unlock(&s->lock);
1813 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1814 s->allocated_done += n;
1815 qemu_progress_print(100.0 * s->allocated_done /
1816 s->allocated_sectors, 0);
1819 if (status == BLK_DATA) {
1820 ret = convert_co_read(s, sector_num, n, buf);
1822 error_report("error while reading sector %" PRId64
1823 ": %s", sector_num, strerror(-ret));
1826 } else if (!s->min_sparse && status == BLK_ZERO) {
1828 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1831 if (s->wr_in_order) {
1832 /* keep writes in order */
1833 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
1834 s->wait_sector_num[index] = sector_num;
1835 qemu_coroutine_yield();
1837 s->wait_sector_num[index] = -1;
1840 if (s->ret == -EINPROGRESS) {
1841 ret = convert_co_write(s, sector_num, n, buf, status);
1843 error_report("error while writing sector %" PRId64
1844 ": %s", sector_num, strerror(-ret));
1849 if (s->wr_in_order) {
1850 /* reenter the coroutine that might have waited
1851 * for this write to complete */
1852 s->wr_offs = sector_num + n;
1853 for (i = 0; i < s->num_coroutines; i++) {
1854 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1856 * A -> B -> A cannot occur because A has
1857 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1858 * B will never enter A during this time window.
1860 qemu_coroutine_enter(s->co[i]);
1868 s->co[index] = NULL;
1869 s->running_coroutines--;
1870 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1871 /* the convert job finished successfully */
1876 static int convert_do_copy(ImgConvertState *s)
1879 int64_t sector_num = 0;
1881 /* Check whether we have zero initialisation or can get it efficiently */
1882 s->has_zero_init = s->min_sparse && !s->target_has_backing
1883 ? bdrv_has_zero_init(blk_bs(s->target))
1886 if (!s->has_zero_init && !s->target_has_backing &&
1887 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1889 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
1891 s->has_zero_init = true;
1895 /* Allocate buffer for copied data. For compressed images, only one cluster
1896 * can be copied at a time. */
1897 if (s->compressed) {
1898 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1899 error_report("invalid cluster size");
1902 s->buf_sectors = s->cluster_sectors;
1905 while (sector_num < s->total_sectors) {
1906 n = convert_iteration_sectors(s, sector_num);
1910 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1912 s->allocated_sectors += n;
1918 s->sector_next_status = 0;
1919 s->ret = -EINPROGRESS;
1921 qemu_co_mutex_init(&s->lock);
1922 for (i = 0; i < s->num_coroutines; i++) {
1923 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1924 s->wait_sector_num[i] = -1;
1925 qemu_coroutine_enter(s->co[i]);
1928 while (s->running_coroutines) {
1929 main_loop_wait(false);
1932 if (s->compressed && !s->ret) {
1933 /* signal EOF to align */
1934 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
1943 static int img_convert(int argc, char **argv)
1945 int c, bs_i, flags, src_flags = 0;
1946 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
1947 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
1948 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
1949 BlockDriver *drv = NULL, *proto_drv = NULL;
1950 BlockDriverInfo bdi;
1951 BlockDriverState *out_bs;
1952 QemuOpts *opts = NULL, *sn_opts = NULL;
1953 QemuOptsList *create_opts = NULL;
1954 char *options = NULL;
1955 Error *local_err = NULL;
1956 bool writethrough, src_writethrough, quiet = false, image_opts = false,
1957 skip_create = false, progress = false, tgt_image_opts = false;
1958 int64_t ret = -EINVAL;
1959 bool force_share = false;
1961 ImgConvertState s = (ImgConvertState) {
1962 /* Need at least 4k of zeros for sparse detection */
1964 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
1965 .wr_in_order = true,
1966 .num_coroutines = 8,
1970 static const struct option long_options[] = {
1971 {"help", no_argument, 0, 'h'},
1972 {"object", required_argument, 0, OPTION_OBJECT},
1973 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1974 {"force-share", no_argument, 0, 'U'},
1975 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
1978 c = getopt_long(argc, argv, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
1979 long_options, NULL);
1985 missing_argument(argv[optind - 1]);
1988 unrecognized_option(argv[optind - 1]);
2000 out_baseimg = optarg;
2003 s.compressed = true;
2006 if (!is_valid_option_list(optarg)) {
2007 error_report("Invalid option list: %s", optarg);
2011 options = g_strdup(optarg);
2013 char *old_options = options;
2014 options = g_strdup_printf("%s,%s", options, optarg);
2015 g_free(old_options);
2019 snapshot_name = optarg;
2022 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2023 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2026 error_report("Failed in parsing snapshot param '%s'",
2031 snapshot_name = optarg;
2038 sval = cvtnum(optarg);
2040 error_report("Invalid minimum zero buffer size for sparse output specified");
2044 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2063 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2064 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2065 error_report("Invalid number of coroutines. Allowed number of"
2066 " coroutines is between 1 and %d", MAX_COROUTINES);
2071 s.wr_in_order = false;
2076 case OPTION_OBJECT: {
2077 QemuOpts *object_opts;
2078 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2085 case OPTION_IMAGE_OPTS:
2088 case OPTION_TARGET_IMAGE_OPTS:
2089 tgt_image_opts = true;
2094 if (!out_fmt && !tgt_image_opts) {
2098 if (qemu_opts_foreach(&qemu_object_opts,
2099 user_creatable_add_opts_foreach,
2104 if (!s.wr_in_order && s.compressed) {
2105 error_report("Out of order write and compress are mutually exclusive");
2109 if (tgt_image_opts && !skip_create) {
2110 error_report("--target-image-opts requires use of -n flag");
2114 s.src_num = argc - optind - 1;
2115 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2117 if (options && has_help_option(options)) {
2119 ret = print_block_option_help(out_filename, out_fmt);
2122 error_report("Option help requires a format be specified");
2127 if (s.src_num < 1) {
2128 error_report("Must specify image file name");
2133 /* ret is still -EINVAL until here */
2134 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2136 error_report("Invalid source cache option: %s", src_cache);
2140 /* Initialize before goto out */
2144 qemu_progress_init(progress, 1.0);
2145 qemu_progress_print(0, 100);
2147 s.src = g_new0(BlockBackend *, s.src_num);
2148 s.src_sectors = g_new(int64_t, s.src_num);
2150 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2151 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2152 fmt, src_flags, src_writethrough, quiet,
2158 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2159 if (s.src_sectors[bs_i] < 0) {
2160 error_report("Could not get size of %s: %s",
2161 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2165 s.total_sectors += s.src_sectors[bs_i];
2169 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2170 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2171 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2173 } else if (snapshot_name != NULL) {
2174 if (s.src_num > 1) {
2175 error_report("No support for concatenating multiple snapshot");
2180 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2184 error_reportf_err(local_err, "Failed to load snapshot: ");
2190 /* Find driver and parse its options */
2191 drv = bdrv_find_format(out_fmt);
2193 error_report("Unknown file format '%s'", out_fmt);
2198 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2200 error_report_err(local_err);
2205 if (!drv->create_opts) {
2206 error_report("Format driver '%s' does not support image creation",
2212 if (!proto_drv->create_opts) {
2213 error_report("Protocol driver '%s' does not support image creation",
2214 proto_drv->format_name);
2219 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2220 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2222 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2224 qemu_opts_do_parse(opts, options, NULL, &local_err);
2226 error_report_err(local_err);
2232 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2234 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2240 /* Get backing file name if -o backing_file was used */
2241 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2242 if (out_baseimg_param) {
2243 out_baseimg = out_baseimg_param;
2245 s.target_has_backing = (bool) out_baseimg;
2247 if (s.src_num > 1 && out_baseimg) {
2248 error_report("Having a backing file for the target makes no sense when "
2249 "concatenating multiple input images");
2254 /* Check if compression is supported */
2257 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2258 const char *encryptfmt =
2259 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2260 const char *preallocation =
2261 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2263 if (drv && !drv->bdrv_co_pwritev_compressed) {
2264 error_report("Compression not supported for this file format");
2269 if (encryption || encryptfmt) {
2270 error_report("Compression and encryption not supported at "
2277 && strcmp(preallocation, "off"))
2279 error_report("Compression and preallocation not supported at "
2287 /* Create the new image */
2288 ret = bdrv_create(drv, out_filename, opts, &local_err);
2290 error_reportf_err(local_err, "%s: error while converting %s: ",
2291 out_filename, out_fmt);
2296 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2297 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2299 error_report("Invalid cache option: %s", cache);
2304 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2305 flags, writethrough, quiet, false);
2307 /* TODO ultimately we should allow --target-image-opts
2308 * to be used even when -n is not given.
2309 * That has to wait for bdrv_create to be improved
2310 * to allow filenames in option syntax
2312 s.target = img_open_new_file(out_filename, opts, out_fmt,
2313 flags, writethrough, quiet, false);
2319 out_bs = blk_bs(s.target);
2321 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2322 error_report("Compression not supported for this file format");
2327 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2328 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2330 s.buf_sectors = MIN(32768,
2332 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2333 out_bs->bl.pdiscard_alignment >>
2334 BDRV_SECTOR_BITS)));
2337 int64_t output_sectors = blk_nb_sectors(s.target);
2338 if (output_sectors < 0) {
2339 error_report("unable to get output image length: %s",
2340 strerror(-output_sectors));
2343 } else if (output_sectors < s.total_sectors) {
2344 error_report("output file is smaller than input file");
2350 ret = bdrv_get_info(out_bs, &bdi);
2353 error_report("could not get block driver info");
2357 s.compressed = s.compressed || bdi.needs_compressed_writes;
2358 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2361 ret = convert_do_copy(&s);
2364 qemu_progress_print(100, 0);
2366 qemu_progress_end();
2367 qemu_opts_del(opts);
2368 qemu_opts_free(create_opts);
2369 qemu_opts_del(sn_opts);
2370 blk_unref(s.target);
2372 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2373 blk_unref(s.src[bs_i]);
2377 g_free(s.src_sectors);
2385 static void dump_snapshots(BlockDriverState *bs)
2387 QEMUSnapshotInfo *sn_tab, *sn;
2390 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2393 printf("Snapshot list:\n");
2394 bdrv_snapshot_dump(fprintf, stdout, NULL);
2396 for(i = 0; i < nb_sns; i++) {
2398 bdrv_snapshot_dump(fprintf, stdout, sn);
2404 static void dump_json_image_info_list(ImageInfoList *list)
2408 Visitor *v = qobject_output_visitor_new(&obj);
2410 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2411 visit_complete(v, &obj);
2412 str = qobject_to_json_pretty(obj);
2413 assert(str != NULL);
2414 printf("%s\n", qstring_get_str(str));
2415 qobject_decref(obj);
2420 static void dump_json_image_info(ImageInfo *info)
2424 Visitor *v = qobject_output_visitor_new(&obj);
2426 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2427 visit_complete(v, &obj);
2428 str = qobject_to_json_pretty(obj);
2429 assert(str != NULL);
2430 printf("%s\n", qstring_get_str(str));
2431 qobject_decref(obj);
2436 static void dump_human_image_info_list(ImageInfoList *list)
2438 ImageInfoList *elem;
2441 for (elem = list; elem; elem = elem->next) {
2447 bdrv_image_info_dump(fprintf, stdout, elem->value);
2451 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2453 return strcmp(a, b) == 0;
2457 * Open an image file chain and return an ImageInfoList
2459 * @filename: topmost image filename
2460 * @fmt: topmost image format (may be NULL to autodetect)
2461 * @chain: true - enumerate entire backing file chain
2462 * false - only topmost image file
2464 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2465 * image file. If there was an error a message will have been printed to
2468 static ImageInfoList *collect_image_info_list(bool image_opts,
2469 const char *filename,
2471 bool chain, bool force_share)
2473 ImageInfoList *head = NULL;
2474 ImageInfoList **last = &head;
2475 GHashTable *filenames;
2478 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2482 BlockDriverState *bs;
2484 ImageInfoList *elem;
2486 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2487 error_report("Backing file '%s' creates an infinite loop.",
2491 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2493 blk = img_open(image_opts, filename, fmt,
2494 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2501 bdrv_query_image_info(bs, &info, &err);
2503 error_report_err(err);
2508 elem = g_new0(ImageInfoList, 1);
2515 filename = fmt = NULL;
2517 if (info->has_full_backing_filename) {
2518 filename = info->full_backing_filename;
2519 } else if (info->has_backing_filename) {
2520 error_report("Could not determine absolute backing filename,"
2521 " but backing filename '%s' present",
2522 info->backing_filename);
2525 if (info->has_backing_filename_format) {
2526 fmt = info->backing_filename_format;
2530 g_hash_table_destroy(filenames);
2534 qapi_free_ImageInfoList(head);
2535 g_hash_table_destroy(filenames);
2539 static int img_info(int argc, char **argv)
2542 OutputFormat output_format = OFORMAT_HUMAN;
2544 const char *filename, *fmt, *output;
2545 ImageInfoList *list;
2546 bool image_opts = false;
2547 bool force_share = false;
2552 int option_index = 0;
2553 static const struct option long_options[] = {
2554 {"help", no_argument, 0, 'h'},
2555 {"format", required_argument, 0, 'f'},
2556 {"output", required_argument, 0, OPTION_OUTPUT},
2557 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2558 {"object", required_argument, 0, OPTION_OBJECT},
2559 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2560 {"force-share", no_argument, 0, 'U'},
2563 c = getopt_long(argc, argv, ":f:hU",
2564 long_options, &option_index);
2570 missing_argument(argv[optind - 1]);
2573 unrecognized_option(argv[optind - 1]);
2587 case OPTION_BACKING_CHAIN:
2590 case OPTION_OBJECT: {
2592 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2598 case OPTION_IMAGE_OPTS:
2603 if (optind != argc - 1) {
2604 error_exit("Expecting one image file name");
2606 filename = argv[optind++];
2608 if (output && !strcmp(output, "json")) {
2609 output_format = OFORMAT_JSON;
2610 } else if (output && !strcmp(output, "human")) {
2611 output_format = OFORMAT_HUMAN;
2612 } else if (output) {
2613 error_report("--output must be used with human or json as argument.");
2617 if (qemu_opts_foreach(&qemu_object_opts,
2618 user_creatable_add_opts_foreach,
2623 list = collect_image_info_list(image_opts, filename, fmt, chain,
2629 switch (output_format) {
2631 dump_human_image_info_list(list);
2635 dump_json_image_info_list(list);
2637 dump_json_image_info(list->value);
2642 qapi_free_ImageInfoList(list);
2646 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2649 switch (output_format) {
2651 if (e->data && !e->has_offset) {
2652 error_report("File contains external, encrypted or compressed clusters.");
2655 if (e->data && !e->zero) {
2656 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2657 e->start, e->length,
2658 e->has_offset ? e->offset : 0,
2659 e->has_filename ? e->filename : "");
2661 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2662 * Modify the flags here to allow more coalescing.
2664 if (next && (!next->data || next->zero)) {
2670 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2671 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2672 (e->start == 0 ? "[" : ",\n"),
2673 e->start, e->length, e->depth,
2674 e->zero ? "true" : "false",
2675 e->data ? "true" : "false");
2676 if (e->has_offset) {
2677 printf(", \"offset\": %"PRId64"", e->offset);
2688 static int get_block_status(BlockDriverState *bs, int64_t offset,
2689 int64_t bytes, MapEntry *e)
2693 BlockDriverState *file;
2697 /* As an optimization, we could cache the current range of unallocated
2698 * clusters in each file of the chain, and avoid querying the same
2704 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
2709 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2712 bs = backing_bs(bs);
2721 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2726 .data = !!(ret & BDRV_BLOCK_DATA),
2727 .zero = !!(ret & BDRV_BLOCK_ZERO),
2729 .has_offset = has_offset,
2731 .has_filename = file && has_offset,
2732 .filename = file && has_offset ? file->filename : NULL,
2738 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2740 if (curr->length == 0) {
2743 if (curr->zero != next->zero ||
2744 curr->data != next->data ||
2745 curr->depth != next->depth ||
2746 curr->has_filename != next->has_filename ||
2747 curr->has_offset != next->has_offset) {
2750 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2753 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2759 static int img_map(int argc, char **argv)
2762 OutputFormat output_format = OFORMAT_HUMAN;
2764 BlockDriverState *bs;
2765 const char *filename, *fmt, *output;
2767 MapEntry curr = { .length = 0 }, next;
2769 bool image_opts = false;
2770 bool force_share = false;
2775 int option_index = 0;
2776 static const struct option long_options[] = {
2777 {"help", no_argument, 0, 'h'},
2778 {"format", required_argument, 0, 'f'},
2779 {"output", required_argument, 0, OPTION_OUTPUT},
2780 {"object", required_argument, 0, OPTION_OBJECT},
2781 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2782 {"force-share", no_argument, 0, 'U'},
2785 c = getopt_long(argc, argv, ":f:hU",
2786 long_options, &option_index);
2792 missing_argument(argv[optind - 1]);
2795 unrecognized_option(argv[optind - 1]);
2809 case OPTION_OBJECT: {
2811 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2817 case OPTION_IMAGE_OPTS:
2822 if (optind != argc - 1) {
2823 error_exit("Expecting one image file name");
2825 filename = argv[optind];
2827 if (output && !strcmp(output, "json")) {
2828 output_format = OFORMAT_JSON;
2829 } else if (output && !strcmp(output, "human")) {
2830 output_format = OFORMAT_HUMAN;
2831 } else if (output) {
2832 error_report("--output must be used with human or json as argument.");
2836 if (qemu_opts_foreach(&qemu_object_opts,
2837 user_creatable_add_opts_foreach,
2842 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
2848 if (output_format == OFORMAT_HUMAN) {
2849 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2852 length = blk_getlength(blk);
2853 while (curr.start + curr.length < length) {
2854 int64_t offset = curr.start + curr.length;
2857 /* Probe up to 1 GiB at a time. */
2858 n = QEMU_ALIGN_DOWN(MIN(1 << 30, length - offset), BDRV_SECTOR_SIZE);
2859 ret = get_block_status(bs, offset, n, &next);
2862 error_report("Could not read file metadata: %s", strerror(-ret));
2866 if (entry_mergeable(&curr, &next)) {
2867 curr.length += next.length;
2871 if (curr.length > 0) {
2872 dump_map_entry(output_format, &curr, &next);
2877 dump_map_entry(output_format, &curr, NULL);
2884 #define SNAPSHOT_LIST 1
2885 #define SNAPSHOT_CREATE 2
2886 #define SNAPSHOT_APPLY 3
2887 #define SNAPSHOT_DELETE 4
2889 static int img_snapshot(int argc, char **argv)
2892 BlockDriverState *bs;
2893 QEMUSnapshotInfo sn;
2894 char *filename, *snapshot_name = NULL;
2895 int c, ret = 0, bdrv_oflags;
2900 bool image_opts = false;
2901 bool force_share = false;
2903 bdrv_oflags = BDRV_O_RDWR;
2904 /* Parse commandline parameters */
2906 static const struct option long_options[] = {
2907 {"help", no_argument, 0, 'h'},
2908 {"object", required_argument, 0, OPTION_OBJECT},
2909 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2910 {"force-share", no_argument, 0, 'U'},
2913 c = getopt_long(argc, argv, ":la:c:d:hqU",
2914 long_options, NULL);
2920 missing_argument(argv[optind - 1]);
2923 unrecognized_option(argv[optind - 1]);
2930 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2933 action = SNAPSHOT_LIST;
2934 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
2938 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2941 action = SNAPSHOT_APPLY;
2942 snapshot_name = optarg;
2946 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2949 action = SNAPSHOT_CREATE;
2950 snapshot_name = optarg;
2954 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2957 action = SNAPSHOT_DELETE;
2958 snapshot_name = optarg;
2966 case OPTION_OBJECT: {
2968 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2974 case OPTION_IMAGE_OPTS:
2980 if (optind != argc - 1) {
2981 error_exit("Expecting one image file name");
2983 filename = argv[optind++];
2985 if (qemu_opts_foreach(&qemu_object_opts,
2986 user_creatable_add_opts_foreach,
2991 /* Open the image */
2992 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
2999 /* Perform the requested action */
3005 case SNAPSHOT_CREATE:
3006 memset(&sn, 0, sizeof(sn));
3007 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3009 qemu_gettimeofday(&tv);
3010 sn.date_sec = tv.tv_sec;
3011 sn.date_nsec = tv.tv_usec * 1000;
3013 ret = bdrv_snapshot_create(bs, &sn);
3015 error_report("Could not create snapshot '%s': %d (%s)",
3016 snapshot_name, ret, strerror(-ret));
3020 case SNAPSHOT_APPLY:
3021 ret = bdrv_snapshot_goto(bs, snapshot_name);
3023 error_report("Could not apply snapshot '%s': %d (%s)",
3024 snapshot_name, ret, strerror(-ret));
3028 case SNAPSHOT_DELETE:
3029 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
3031 error_reportf_err(err, "Could not delete snapshot '%s': ",
3046 static int img_rebase(int argc, char **argv)
3048 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3049 uint8_t *buf_old = NULL;
3050 uint8_t *buf_new = NULL;
3051 BlockDriverState *bs = NULL;
3053 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3054 int c, flags, src_flags, ret;
3055 bool writethrough, src_writethrough;
3057 bool force_share = false;
3060 Error *local_err = NULL;
3061 bool image_opts = false;
3063 /* Parse commandline parameters */
3065 cache = BDRV_DEFAULT_CACHE;
3066 src_cache = BDRV_DEFAULT_CACHE;
3070 static const struct option long_options[] = {
3071 {"help", no_argument, 0, 'h'},
3072 {"object", required_argument, 0, OPTION_OBJECT},
3073 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3074 {"force-share", no_argument, 0, 'U'},
3077 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3078 long_options, NULL);
3084 missing_argument(argv[optind - 1]);
3087 unrecognized_option(argv[optind - 1]);
3096 out_basefmt = optarg;
3099 out_baseimg = optarg;
3116 case OPTION_OBJECT: {
3118 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3124 case OPTION_IMAGE_OPTS:
3137 if (optind != argc - 1) {
3138 error_exit("Expecting one image file name");
3140 if (!unsafe && !out_baseimg) {
3141 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3143 filename = argv[optind++];
3145 if (qemu_opts_foreach(&qemu_object_opts,
3146 user_creatable_add_opts_foreach,
3151 qemu_progress_init(progress, 2.0);
3152 qemu_progress_print(0, 100);
3154 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3155 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3157 error_report("Invalid cache option: %s", cache);
3162 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3164 error_report("Invalid source cache option: %s", src_cache);
3168 /* The source files are opened read-only, don't care about WCE */
3169 assert((src_flags & BDRV_O_RDWR) == 0);
3170 (void) src_writethrough;
3175 * Ignore the old backing file for unsafe rebase in case we want to correct
3176 * the reference to a renamed or moved backing file.
3178 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3186 if (out_basefmt != NULL) {
3187 if (bdrv_find_format(out_basefmt) == NULL) {
3188 error_report("Invalid format name: '%s'", out_basefmt);
3194 /* For safe rebasing we need to compare old and new backing file */
3196 char backing_name[PATH_MAX];
3197 QDict *options = NULL;
3199 if (bs->backing_format[0] != '\0') {
3200 options = qdict_new();
3201 qdict_put_str(options, "driver", bs->backing_format);
3206 options = qdict_new();
3208 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3210 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3211 blk_old_backing = blk_new_open(backing_name, NULL,
3212 options, src_flags, &local_err);
3213 if (!blk_old_backing) {
3214 error_reportf_err(local_err,
3215 "Could not open old backing file '%s': ",
3221 if (out_baseimg[0]) {
3222 options = qdict_new();
3224 qdict_put_str(options, "driver", out_basefmt);
3227 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3230 blk_new_backing = blk_new_open(out_baseimg, NULL,
3231 options, src_flags, &local_err);
3232 if (!blk_new_backing) {
3233 error_reportf_err(local_err,
3234 "Could not open new backing file '%s': ",
3243 * Check each unallocated cluster in the COW file. If it is unallocated,
3244 * accesses go to the backing file. We must therefore compare this cluster
3245 * in the old and new backing file, and if they differ we need to copy it
3246 * from the old backing file into the COW file.
3248 * If qemu-img crashes during this step, no harm is done. The content of
3249 * the image is the same as the original one at any time.
3252 int64_t num_sectors;
3253 int64_t old_backing_num_sectors;
3254 int64_t new_backing_num_sectors = 0;
3258 float local_progress = 0;
3260 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3261 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3263 num_sectors = blk_nb_sectors(blk);
3264 if (num_sectors < 0) {
3265 error_report("Could not get size of '%s': %s",
3266 filename, strerror(-num_sectors));
3270 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
3271 if (old_backing_num_sectors < 0) {
3272 char backing_name[PATH_MAX];
3274 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3275 error_report("Could not get size of '%s': %s",
3276 backing_name, strerror(-old_backing_num_sectors));
3280 if (blk_new_backing) {
3281 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
3282 if (new_backing_num_sectors < 0) {
3283 error_report("Could not get size of '%s': %s",
3284 out_baseimg, strerror(-new_backing_num_sectors));
3290 if (num_sectors != 0) {
3291 local_progress = (float)100 /
3292 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3295 for (sector = 0; sector < num_sectors; sector += n) {
3297 /* How many sectors can we handle with the next read? */
3298 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3299 n = (IO_BUF_SIZE / 512);
3301 n = num_sectors - sector;
3304 /* If the cluster is allocated, we don't need to take action */
3305 ret = bdrv_is_allocated(bs, sector << BDRV_SECTOR_BITS,
3306 n << BDRV_SECTOR_BITS, &count);
3308 error_report("error while reading image metadata: %s",
3312 /* TODO relax this once bdrv_is_allocated does not enforce
3313 * sector alignment */
3314 assert(QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE));
3315 n = count >> BDRV_SECTOR_BITS;
3321 * Read old and new backing file and take into consideration that
3322 * backing files may be smaller than the COW image.
3324 if (sector >= old_backing_num_sectors) {
3325 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3327 if (sector + n > old_backing_num_sectors) {
3328 n = old_backing_num_sectors - sector;
3331 ret = blk_pread(blk_old_backing, sector << BDRV_SECTOR_BITS,
3332 buf_old, n << BDRV_SECTOR_BITS);
3334 error_report("error while reading from old backing file");
3339 if (sector >= new_backing_num_sectors || !blk_new_backing) {
3340 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3342 if (sector + n > new_backing_num_sectors) {
3343 n = new_backing_num_sectors - sector;
3346 ret = blk_pread(blk_new_backing, sector << BDRV_SECTOR_BITS,
3347 buf_new, n << BDRV_SECTOR_BITS);
3349 error_report("error while reading from new backing file");
3354 /* If they differ, we need to write to the COW file */
3355 uint64_t written = 0;
3357 while (written < n) {
3360 if (compare_sectors(buf_old + written * 512,
3361 buf_new + written * 512, n - written, &pnum))
3363 ret = blk_pwrite(blk,
3364 (sector + written) << BDRV_SECTOR_BITS,
3365 buf_old + written * 512,
3366 pnum << BDRV_SECTOR_BITS, 0);
3368 error_report("Error while writing to COW image: %s",
3376 qemu_progress_print(local_progress, 100);
3381 * Change the backing file. All clusters that are different from the old
3382 * backing file are overwritten in the COW file now, so the visible content
3383 * doesn't change when we switch the backing file.
3385 if (out_baseimg && *out_baseimg) {
3386 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3388 ret = bdrv_change_backing_file(bs, NULL, NULL);
3391 if (ret == -ENOSPC) {
3392 error_report("Could not change the backing file to '%s': No "
3393 "space left in the file header", out_baseimg);
3394 } else if (ret < 0) {
3395 error_report("Could not change the backing file to '%s': %s",
3396 out_baseimg, strerror(-ret));
3399 qemu_progress_print(100, 0);
3401 * TODO At this point it is possible to check if any clusters that are
3402 * allocated in the COW file are the same in the backing file. If so, they
3403 * could be dropped from the COW file. Don't do this before switching the
3404 * backing file, in case of a crash this would lead to corruption.
3407 qemu_progress_end();
3410 blk_unref(blk_old_backing);
3411 blk_unref(blk_new_backing);
3413 qemu_vfree(buf_old);
3414 qemu_vfree(buf_new);
3423 static int img_resize(int argc, char **argv)
3426 int c, ret, relative;
3427 const char *filename, *fmt, *size;
3428 int64_t n, total_size, current_size;
3430 BlockBackend *blk = NULL;
3431 PreallocMode prealloc = PREALLOC_MODE_OFF;
3434 static QemuOptsList resize_options = {
3435 .name = "resize_options",
3436 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3439 .name = BLOCK_OPT_SIZE,
3440 .type = QEMU_OPT_SIZE,
3441 .help = "Virtual disk size"
3447 bool image_opts = false;
3448 bool shrink = false;
3450 /* Remove size from argv manually so that negative numbers are not treated
3451 * as options by getopt. */
3453 error_exit("Not enough arguments");
3457 size = argv[--argc];
3459 /* Parse getopt arguments */
3462 static const struct option long_options[] = {
3463 {"help", no_argument, 0, 'h'},
3464 {"object", required_argument, 0, OPTION_OBJECT},
3465 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3466 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3467 {"shrink", no_argument, 0, OPTION_SHRINK},
3470 c = getopt_long(argc, argv, ":f:hq",
3471 long_options, NULL);
3477 missing_argument(argv[optind - 1]);
3480 unrecognized_option(argv[optind - 1]);
3491 case OPTION_OBJECT: {
3493 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3499 case OPTION_IMAGE_OPTS:
3502 case OPTION_PREALLOCATION:
3503 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3504 PREALLOC_MODE__MAX, NULL);
3505 if (prealloc == PREALLOC_MODE__MAX) {
3506 error_report("Invalid preallocation mode '%s'", optarg);
3515 if (optind != argc - 1) {
3516 error_exit("Expecting one image file name");
3518 filename = argv[optind++];
3520 if (qemu_opts_foreach(&qemu_object_opts,
3521 user_creatable_add_opts_foreach,
3526 /* Choose grow, shrink, or absolute resize mode */
3542 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3543 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3545 error_report_err(err);
3547 qemu_opts_del(param);
3550 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3551 qemu_opts_del(param);
3553 blk = img_open(image_opts, filename, fmt,
3554 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3561 current_size = blk_getlength(blk);
3562 if (current_size < 0) {
3563 error_report("Failed to inquire current image length: %s",
3564 strerror(-current_size));
3570 total_size = current_size + n * relative;
3574 if (total_size <= 0) {
3575 error_report("New image size must be positive");
3580 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3581 error_report("Preallocation can only be used for growing images");
3586 if (total_size < current_size && !shrink) {
3587 warn_report("Shrinking an image will delete all data beyond the "
3588 "shrunken image's end. Before performing such an "
3589 "operation, make sure there is no important data there.");
3591 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3593 "Use the --shrink option to perform a shrink operation.");
3597 warn_report("Using the --shrink option will suppress this message. "
3598 "Note that future versions of qemu-img may refuse to "
3599 "shrink images without this option.");
3603 ret = blk_truncate(blk, total_size, prealloc, &err);
3605 qprintf(quiet, "Image resized.\n");
3607 error_report_err(err);
3617 static void amend_status_cb(BlockDriverState *bs,
3618 int64_t offset, int64_t total_work_size,
3621 qemu_progress_print(100.f * offset / total_work_size, 0);
3624 static int img_amend(int argc, char **argv)
3628 char *options = NULL;
3629 QemuOptsList *create_opts = NULL;
3630 QemuOpts *opts = NULL;
3631 const char *fmt = NULL, *filename, *cache;
3634 bool quiet = false, progress = false;
3635 BlockBackend *blk = NULL;
3636 BlockDriverState *bs = NULL;
3637 bool image_opts = false;
3639 cache = BDRV_DEFAULT_CACHE;
3641 static const struct option long_options[] = {
3642 {"help", no_argument, 0, 'h'},
3643 {"object", required_argument, 0, OPTION_OBJECT},
3644 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3647 c = getopt_long(argc, argv, ":ho:f:t:pq",
3648 long_options, NULL);
3655 missing_argument(argv[optind - 1]);
3658 unrecognized_option(argv[optind - 1]);
3664 if (!is_valid_option_list(optarg)) {
3665 error_report("Invalid option list: %s", optarg);
3667 goto out_no_progress;
3670 options = g_strdup(optarg);
3672 char *old_options = options;
3673 options = g_strdup_printf("%s,%s", options, optarg);
3674 g_free(old_options);
3690 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3694 goto out_no_progress;
3697 case OPTION_IMAGE_OPTS:
3704 error_exit("Must specify options (-o)");
3707 if (qemu_opts_foreach(&qemu_object_opts,
3708 user_creatable_add_opts_foreach,
3711 goto out_no_progress;
3717 qemu_progress_init(progress, 1.0);
3719 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3720 if (fmt && has_help_option(options)) {
3721 /* If a format is explicitly specified (and possibly no filename is
3722 * given), print option help here */
3723 ret = print_block_option_help(filename, fmt);
3727 if (optind != argc - 1) {
3728 error_report("Expecting one image file name");
3733 flags = BDRV_O_RDWR;
3734 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3736 error_report("Invalid cache option: %s", cache);
3740 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3748 fmt = bs->drv->format_name;
3750 if (has_help_option(options)) {
3751 /* If the format was auto-detected, print option help here */
3752 ret = print_block_option_help(filename, fmt);
3756 if (!bs->drv->create_opts) {
3757 error_report("Format driver '%s' does not support any options to amend",
3763 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
3764 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3765 qemu_opts_do_parse(opts, options, NULL, &err);
3767 error_report_err(err);
3772 /* In case the driver does not call amend_status_cb() */
3773 qemu_progress_print(0.f, 0);
3774 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
3775 qemu_progress_print(100.f, 0);
3777 error_report("Error while amending options: %s", strerror(-ret));
3782 qemu_progress_end();
3786 qemu_opts_del(opts);
3787 qemu_opts_free(create_opts);
3796 typedef struct BenchData {
3798 uint64_t image_size;
3805 bool drain_on_flush;
3814 static void bench_undrained_flush_cb(void *opaque, int ret)
3817 error_report("Failed flush request: %s", strerror(-ret));
3822 static void bench_cb(void *opaque, int ret)
3824 BenchData *b = opaque;
3828 error_report("Failed request: %s", strerror(-ret));
3833 /* Just finished a flush with drained queue: Start next requests */
3834 assert(b->in_flight == 0);
3835 b->in_flush = false;
3836 } else if (b->in_flight > 0) {
3837 int remaining = b->n - b->in_flight;
3842 /* Time for flush? Drain queue if requested, then flush */
3843 if (b->flush_interval && remaining % b->flush_interval == 0) {
3844 if (!b->in_flight || !b->drain_on_flush) {
3845 BlockCompletionFunc *cb;
3847 if (b->drain_on_flush) {
3851 cb = bench_undrained_flush_cb;
3854 acb = blk_aio_flush(b->blk, cb, b);
3856 error_report("Failed to issue flush request");
3860 if (b->drain_on_flush) {
3866 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
3867 int64_t offset = b->offset;
3868 /* blk_aio_* might look for completed I/Os and kick bench_cb
3869 * again, so make sure this operation is counted by in_flight
3870 * and b->offset is ready for the next submission.
3873 b->offset += b->step;
3874 b->offset %= b->image_size;
3876 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
3878 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
3881 error_report("Failed to issue request");
3887 static int img_bench(int argc, char **argv)
3890 const char *fmt = NULL, *filename;
3892 bool image_opts = false;
3893 bool is_write = false;
3897 size_t bufsize = 4096;
3900 int flush_interval = 0;
3901 bool drain_on_flush = true;
3903 BlockBackend *blk = NULL;
3904 BenchData data = {};
3906 bool writethrough = false;
3907 struct timeval t1, t2;
3909 bool force_share = false;
3912 static const struct option long_options[] = {
3913 {"help", no_argument, 0, 'h'},
3914 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
3915 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3916 {"pattern", required_argument, 0, OPTION_PATTERN},
3917 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
3918 {"force-share", no_argument, 0, 'U'},
3921 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
3928 missing_argument(argv[optind - 1]);
3931 unrecognized_option(argv[optind - 1]);
3940 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
3941 error_report("Invalid request count specified");
3951 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
3952 error_report("Invalid queue depth specified");
3962 flags |= BDRV_O_NATIVE_AIO;
3966 offset = cvtnum(optarg);
3968 error_report("Invalid offset specified");
3981 sval = cvtnum(optarg);
3982 if (sval < 0 || sval > INT_MAX) {
3983 error_report("Invalid buffer size specified");
3994 sval = cvtnum(optarg);
3995 if (sval < 0 || sval > INT_MAX) {
3996 error_report("Invalid step size specified");
4004 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4006 error_report("Invalid cache mode");
4012 flags |= BDRV_O_RDWR;
4018 case OPTION_PATTERN:
4022 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4023 error_report("Invalid pattern byte specified");
4029 case OPTION_FLUSH_INTERVAL:
4033 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4034 error_report("Invalid flush interval specified");
4037 flush_interval = res;
4040 case OPTION_NO_DRAIN:
4041 drain_on_flush = false;
4043 case OPTION_IMAGE_OPTS:
4049 if (optind != argc - 1) {
4050 error_exit("Expecting one image file name");
4052 filename = argv[argc - 1];
4054 if (!is_write && flush_interval) {
4055 error_report("--flush-interval is only available in write tests");
4059 if (flush_interval && flush_interval < depth) {
4060 error_report("Flush interval can't be smaller than depth");
4065 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4072 image_size = blk_getlength(blk);
4073 if (image_size < 0) {
4078 data = (BenchData) {
4080 .image_size = image_size,
4082 .step = step ?: bufsize,
4087 .flush_interval = flush_interval,
4088 .drain_on_flush = drain_on_flush,
4090 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4091 "(starting at offset %" PRId64 ", step size %d)\n",
4092 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4093 data.offset, data.step);
4094 if (flush_interval) {
4095 printf("Sending flush every %d requests\n", flush_interval);
4098 data.buf = blk_blockalign(blk, data.nrreq * data.bufsize);
4099 memset(data.buf, pattern, data.nrreq * data.bufsize);
4101 data.qiov = g_new(QEMUIOVector, data.nrreq);
4102 for (i = 0; i < data.nrreq; i++) {
4103 qemu_iovec_init(&data.qiov[i], 1);
4104 qemu_iovec_add(&data.qiov[i],
4105 data.buf + i * data.bufsize, data.bufsize);
4108 gettimeofday(&t1, NULL);
4111 while (data.n > 0) {
4112 main_loop_wait(false);
4114 gettimeofday(&t2, NULL);
4116 printf("Run completed in %3.3f seconds.\n",
4117 (t2.tv_sec - t1.tv_sec)
4118 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4121 qemu_vfree(data.buf);
4142 int bsz; /* Block size */
4150 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4154 static int img_dd_bs(const char *arg,
4155 struct DdIo *in, struct DdIo *out,
4162 if (res <= 0 || res > INT_MAX) {
4163 error_report("invalid number: '%s'", arg);
4166 in->bsz = out->bsz = res;
4171 static int img_dd_count(const char *arg,
4172 struct DdIo *in, struct DdIo *out,
4175 dd->count = cvtnum(arg);
4177 if (dd->count < 0) {
4178 error_report("invalid number: '%s'", arg);
4185 static int img_dd_if(const char *arg,
4186 struct DdIo *in, struct DdIo *out,
4189 in->filename = g_strdup(arg);
4194 static int img_dd_of(const char *arg,
4195 struct DdIo *in, struct DdIo *out,
4198 out->filename = g_strdup(arg);
4203 static int img_dd_skip(const char *arg,
4204 struct DdIo *in, struct DdIo *out,
4207 in->offset = cvtnum(arg);
4209 if (in->offset < 0) {
4210 error_report("invalid number: '%s'", arg);
4217 static int img_dd(int argc, char **argv)
4222 BlockDriver *drv = NULL, *proto_drv = NULL;
4223 BlockBackend *blk1 = NULL, *blk2 = NULL;
4224 QemuOpts *opts = NULL;
4225 QemuOptsList *create_opts = NULL;
4226 Error *local_err = NULL;
4227 bool image_opts = false;
4229 const char *out_fmt = "raw";
4230 const char *fmt = NULL;
4232 int64_t block_count = 0, out_pos, in_pos;
4233 bool force_share = false;
4234 struct DdInfo dd = {
4239 .bsz = 512, /* Block size is by default 512 bytes */
4251 const struct DdOpts options[] = {
4252 { "bs", img_dd_bs, C_BS },
4253 { "count", img_dd_count, C_COUNT },
4254 { "if", img_dd_if, C_IF },
4255 { "of", img_dd_of, C_OF },
4256 { "skip", img_dd_skip, C_SKIP },
4259 const struct option long_options[] = {
4260 { "help", no_argument, 0, 'h'},
4261 { "object", required_argument, 0, OPTION_OBJECT},
4262 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4263 { "force-share", no_argument, 0, 'U'},
4267 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4279 missing_argument(argv[optind - 1]);
4282 unrecognized_option(argv[optind - 1]);
4291 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4296 case OPTION_IMAGE_OPTS:
4302 for (i = optind; i < argc; i++) {
4304 arg = g_strdup(argv[i]);
4306 tmp = strchr(arg, '=');
4308 error_report("unrecognized operand %s", arg);
4315 for (j = 0; options[j].name != NULL; j++) {
4316 if (!strcmp(arg, options[j].name)) {
4320 if (options[j].name == NULL) {
4321 error_report("unrecognized operand %s", arg);
4326 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4330 dd.flags |= options[j].flag;
4335 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4336 error_report("Must specify both input and output files");
4341 if (qemu_opts_foreach(&qemu_object_opts,
4342 user_creatable_add_opts_foreach,
4348 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4356 drv = bdrv_find_format(out_fmt);
4358 error_report("Unknown file format");
4362 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4365 error_report_err(local_err);
4369 if (!drv->create_opts) {
4370 error_report("Format driver '%s' does not support image creation",
4375 if (!proto_drv->create_opts) {
4376 error_report("Protocol driver '%s' does not support image creation",
4377 proto_drv->format_name);
4381 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4382 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4384 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4386 size = blk_getlength(blk1);
4388 error_report("Failed to get size for '%s'", in.filename);
4393 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4394 dd.count * in.bsz < size) {
4395 size = dd.count * in.bsz;
4398 /* Overflow means the specified offset is beyond input image's size */
4399 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4400 size < in.bsz * in.offset)) {
4401 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4403 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4404 size - in.bsz * in.offset, &error_abort);
4407 ret = bdrv_create(drv, out.filename, opts, &local_err);
4409 error_reportf_err(local_err,
4410 "%s: error while creating output image: ",
4416 /* TODO, we can't honour --image-opts for the target,
4417 * since it needs to be given in a format compatible
4418 * with the bdrv_create() call above which does not
4419 * support image-opts style.
4421 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
4422 false, false, false);
4429 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4430 size < in.offset * in.bsz)) {
4431 /* We give a warning if the skip option is bigger than the input
4432 * size and create an empty output disk image (i.e. like dd(1)).
4434 error_report("%s: cannot skip to specified offset", in.filename);
4437 in_pos = in.offset * in.bsz;
4440 in.buf = g_new(uint8_t, in.bsz);
4442 for (out_pos = 0; in_pos < size; block_count++) {
4443 int in_ret, out_ret;
4445 if (in_pos + in.bsz > size) {
4446 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4448 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4451 error_report("error while reading from input image file: %s",
4458 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4461 error_report("error while writing to output image file: %s",
4462 strerror(-out_ret));
4471 qemu_opts_del(opts);
4472 qemu_opts_free(create_opts);
4475 g_free(in.filename);
4476 g_free(out.filename);
4486 static void dump_json_block_measure_info(BlockMeasureInfo *info)
4490 Visitor *v = qobject_output_visitor_new(&obj);
4492 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4493 visit_complete(v, &obj);
4494 str = qobject_to_json_pretty(obj);
4495 assert(str != NULL);
4496 printf("%s\n", qstring_get_str(str));
4497 qobject_decref(obj);
4502 static int img_measure(int argc, char **argv)
4504 static const struct option long_options[] = {
4505 {"help", no_argument, 0, 'h'},
4506 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4507 {"object", required_argument, 0, OPTION_OBJECT},
4508 {"output", required_argument, 0, OPTION_OUTPUT},
4509 {"size", required_argument, 0, OPTION_SIZE},
4510 {"force-share", no_argument, 0, 'U'},
4513 OutputFormat output_format = OFORMAT_HUMAN;
4514 BlockBackend *in_blk = NULL;
4516 const char *filename = NULL;
4517 const char *fmt = NULL;
4518 const char *out_fmt = "raw";
4519 char *options = NULL;
4520 char *snapshot_name = NULL;
4521 bool force_share = false;
4522 QemuOpts *opts = NULL;
4523 QemuOpts *object_opts = NULL;
4524 QemuOpts *sn_opts = NULL;
4525 QemuOptsList *create_opts = NULL;
4526 bool image_opts = false;
4527 uint64_t img_size = UINT64_MAX;
4528 BlockMeasureInfo *info = NULL;
4529 Error *local_err = NULL;
4533 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4534 long_options, NULL)) != -1) {
4547 if (!is_valid_option_list(optarg)) {
4548 error_report("Invalid option list: %s", optarg);
4552 options = g_strdup(optarg);
4554 char *old_options = options;
4555 options = g_strdup_printf("%s,%s", options, optarg);
4556 g_free(old_options);
4560 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4561 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4564 error_report("Failed in parsing snapshot param '%s'",
4569 snapshot_name = optarg;
4576 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4582 case OPTION_IMAGE_OPTS:
4586 if (!strcmp(optarg, "json")) {
4587 output_format = OFORMAT_JSON;
4588 } else if (!strcmp(optarg, "human")) {
4589 output_format = OFORMAT_HUMAN;
4591 error_report("--output must be used with human or json "
4600 sval = cvtnum(optarg);
4602 if (sval == -ERANGE) {
4603 error_report("Image size must be less than 8 EiB!");
4605 error_report("Invalid image size specified! You may use "
4606 "k, M, G, T, P or E suffixes for ");
4607 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4608 "petabytes and exabytes.");
4612 img_size = (uint64_t)sval;
4618 if (qemu_opts_foreach(&qemu_object_opts,
4619 user_creatable_add_opts_foreach,
4624 if (argc - optind > 1) {
4625 error_report("At most one filename argument is allowed.");
4627 } else if (argc - optind == 1) {
4628 filename = argv[optind];
4632 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4633 error_report("--object, --image-opts, -f, and -l "
4634 "require a filename argument.");
4637 if (filename && img_size != UINT64_MAX) {
4638 error_report("--size N cannot be used together with a filename.");
4641 if (!filename && img_size == UINT64_MAX) {
4642 error_report("Either --size N or one filename must be specified.");
4647 in_blk = img_open(image_opts, filename, fmt, 0,
4648 false, false, force_share);
4654 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4655 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4656 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4658 } else if (snapshot_name != NULL) {
4659 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4660 snapshot_name, &local_err);
4663 error_reportf_err(local_err, "Failed to load snapshot: ");
4668 drv = bdrv_find_format(out_fmt);
4670 error_report("Unknown file format '%s'", out_fmt);
4673 if (!drv->create_opts) {
4674 error_report("Format driver '%s' does not support image creation",
4679 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4680 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4681 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4683 qemu_opts_do_parse(opts, options, NULL, &local_err);
4685 error_report_err(local_err);
4686 error_report("Invalid options for file format '%s'", out_fmt);
4690 if (img_size != UINT64_MAX) {
4691 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4694 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4696 error_report_err(local_err);
4700 if (output_format == OFORMAT_HUMAN) {
4701 printf("required size: %" PRIu64 "\n", info->required);
4702 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4704 dump_json_block_measure_info(info);
4710 qapi_free_BlockMeasureInfo(info);
4711 qemu_opts_del(object_opts);
4712 qemu_opts_del(opts);
4713 qemu_opts_del(sn_opts);
4714 qemu_opts_free(create_opts);
4720 static const img_cmd_t img_cmds[] = {
4721 #define DEF(option, callback, arg_string) \
4722 { option, callback },
4723 #include "qemu-img-cmds.h"
4729 int main(int argc, char **argv)
4731 const img_cmd_t *cmd;
4732 const char *cmdname;
4733 Error *local_error = NULL;
4734 char *trace_file = NULL;
4736 static const struct option long_options[] = {
4737 {"help", no_argument, 0, 'h'},
4738 {"version", no_argument, 0, 'V'},
4739 {"trace", required_argument, NULL, 'T'},
4744 signal(SIGPIPE, SIG_IGN);
4747 module_call_init(MODULE_INIT_TRACE);
4748 error_set_progname(argv[0]);
4749 qemu_init_exec_dir(argv[0]);
4751 if (qemu_init_main_loop(&local_error)) {
4752 error_report_err(local_error);
4756 qcrypto_init(&error_fatal);
4758 module_call_init(MODULE_INIT_QOM);
4761 error_exit("Not enough arguments");
4764 qemu_add_opts(&qemu_object_opts);
4765 qemu_add_opts(&qemu_source_opts);
4766 qemu_add_opts(&qemu_trace_opts);
4768 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
4771 missing_argument(argv[optind - 1]);
4774 unrecognized_option(argv[optind - 1]);
4780 printf(QEMU_IMG_VERSION);
4784 trace_file = trace_opt_parse(optarg);
4789 cmdname = argv[optind];
4791 /* reset getopt_long scanning */
4799 if (!trace_init_backends()) {
4802 trace_init_file(trace_file);
4803 qemu_set_log(LOG_TRACE);
4805 /* find the command */
4806 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4807 if (!strcmp(cmdname, cmd->name)) {
4808 return cmd->handler(argc, argv);
4813 error_exit("Command not found: %s", cmdname);