2 * QEMU disk image utility
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 #include "qemu/osdep.h"
25 #include "qemu-version.h"
26 #include "qapi/error.h"
27 #include "qapi-visit.h"
28 #include "qapi/qobject-output-visitor.h"
29 #include "qapi/qmp/qerror.h"
30 #include "qapi/qmp/qjson.h"
31 #include "qapi/qmp/qbool.h"
32 #include "qemu/cutils.h"
33 #include "qemu/config-file.h"
34 #include "qemu/option.h"
35 #include "qemu/error-report.h"
37 #include "qom/object_interfaces.h"
38 #include "sysemu/sysemu.h"
39 #include "sysemu/block-backend.h"
40 #include "block/block_int.h"
41 #include "block/blockjob.h"
42 #include "block/qapi.h"
43 #include "crypto/init.h"
44 #include "trace/control.h"
47 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
48 "\n" QEMU_COPYRIGHT "\n"
50 typedef struct img_cmd_t {
52 int (*handler)(int argc, char **argv);
57 OPTION_BACKING_CHAIN = 257,
59 OPTION_IMAGE_OPTS = 259,
61 OPTION_FLUSH_INTERVAL = 261,
62 OPTION_NO_DRAIN = 262,
65 typedef enum OutputFormat {
70 /* Default to cache=writeback as data integrity is not important for qemu-img */
71 #define BDRV_DEFAULT_CACHE "writeback"
73 static void format_print(void *opaque, const char *name)
78 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
82 error_printf("qemu-img: ");
85 error_vprintf(fmt, ap);
88 error_printf("\nTry 'qemu-img --help' for more information\n");
92 static void QEMU_NORETURN missing_argument(const char *option)
94 error_exit("missing argument for option '%s'", option);
97 static void QEMU_NORETURN unrecognized_option(const char *option)
99 error_exit("unrecognized option '%s'", option);
102 /* Please keep in synch with qemu-img.texi */
103 static void QEMU_NORETURN help(void)
105 const char *help_msg =
107 "usage: qemu-img [standard options] command [command options]\n"
108 "QEMU disk image utility\n"
110 " '-h', '--help' display this help and exit\n"
111 " '-V', '--version' output version information and exit\n"
112 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
113 " specify tracing options\n"
116 #define DEF(option, callback, arg_string) \
118 #include "qemu-img-cmds.h"
122 "Command parameters:\n"
123 " 'filename' is a disk image filename\n"
124 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
125 " manual page for a description of the object properties. The most common\n"
126 " object type is a 'secret', which is used to supply passwords and/or\n"
127 " encryption keys.\n"
128 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
129 " 'cache' is the cache mode used to write the output disk image, the valid\n"
130 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
131 " 'directsync' and 'unsafe' (default for convert)\n"
132 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
133 " options are the same as for the 'cache' option\n"
134 " 'size' is the disk image size in bytes. Optional suffixes\n"
135 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
136 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
137 " supported. 'b' is ignored.\n"
138 " 'output_filename' is the destination disk image filename\n"
139 " 'output_fmt' is the destination format\n"
140 " 'options' is a comma separated list of format specific options in a\n"
141 " name=value format. Use -o ? for an overview of the options supported by the\n"
143 " 'snapshot_param' is param used for internal snapshot, format\n"
144 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
146 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
148 " '-c' indicates that target image must be compressed (qcow format only)\n"
149 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
150 " match exactly. The image doesn't need a working backing file before\n"
151 " rebasing in this case (useful for renaming the backing file)\n"
152 " '-h' with or without a command shows this help and lists the supported formats\n"
153 " '-p' show progress of command (only certain commands)\n"
154 " '-q' use Quiet mode - do not print any output (except errors)\n"
155 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
156 " contain only zeros for qemu-img to create a sparse image during\n"
157 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
158 " unallocated or zero sectors, and the destination image will always be\n"
160 " '--output' takes the format in which the output must be done (human or json)\n"
161 " '-n' skips the target volume creation (useful if the volume is created\n"
162 " prior to running qemu-img)\n"
164 "Parameters to check subcommand:\n"
165 " '-r' tries to repair any inconsistencies that are found during the check.\n"
166 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
167 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
168 " hiding corruption that has already occurred.\n"
170 "Parameters to convert subcommand:\n"
171 " '-m' specifies how many coroutines work in parallel during the convert\n"
172 " process (defaults to 8)\n"
173 " '-W' allow to write to the target out of order rather than sequential\n"
175 "Parameters to snapshot subcommand:\n"
176 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
177 " '-a' applies a snapshot (revert disk to saved state)\n"
178 " '-c' creates a snapshot\n"
179 " '-d' deletes a snapshot\n"
180 " '-l' lists all snapshots in the given image\n"
182 "Parameters to compare subcommand:\n"
183 " '-f' first image format\n"
184 " '-F' second image format\n"
185 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
187 "Parameters to dd subcommand:\n"
188 " 'bs=BYTES' read and write up to BYTES bytes at a time "
190 " 'count=N' copy only N input blocks\n"
191 " 'if=FILE' read from FILE\n"
192 " 'of=FILE' write to FILE\n"
193 " 'skip=N' skip N bs-sized blocks at the start of input\n";
195 printf("%s\nSupported formats:", help_msg);
196 bdrv_iterate_format(format_print, NULL);
201 static QemuOptsList qemu_object_opts = {
203 .implied_opt_name = "qom-type",
204 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
210 static QemuOptsList qemu_source_opts = {
212 .implied_opt_name = "file",
213 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
219 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
225 ret = vprintf(fmt, args);
232 static int print_block_option_help(const char *filename, const char *fmt)
234 BlockDriver *drv, *proto_drv;
235 QemuOptsList *create_opts = NULL;
236 Error *local_err = NULL;
238 /* Find driver and parse its options */
239 drv = bdrv_find_format(fmt);
241 error_report("Unknown file format '%s'", fmt);
245 create_opts = qemu_opts_append(create_opts, drv->create_opts);
247 proto_drv = bdrv_find_protocol(filename, true, &local_err);
249 error_report_err(local_err);
250 qemu_opts_free(create_opts);
253 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
256 qemu_opts_print_help(create_opts);
257 qemu_opts_free(create_opts);
262 static int img_open_password(BlockBackend *blk, const char *filename,
263 int flags, bool quiet)
265 BlockDriverState *bs;
269 if (bdrv_is_encrypted(bs) && bdrv_key_required(bs) &&
270 !(flags & BDRV_O_NO_IO)) {
271 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
272 if (qemu_read_password(password, sizeof(password)) < 0) {
273 error_report("No password given");
276 if (bdrv_set_key(bs, password) < 0) {
277 error_report("invalid password");
285 static BlockBackend *img_open_opts(const char *optstr,
286 QemuOpts *opts, int flags, bool writethrough,
287 bool quiet, bool force_share)
290 Error *local_err = NULL;
292 options = qemu_opts_to_qdict(opts, NULL);
294 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
295 && !qdict_get_bool(options, BDRV_OPT_FORCE_SHARE)) {
296 error_report("--force-share/-U conflicts with image options");
299 qdict_put(options, BDRV_OPT_FORCE_SHARE, qbool_from_bool(true));
301 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
303 error_reportf_err(local_err, "Could not open '%s': ", optstr);
306 blk_set_enable_write_cache(blk, !writethrough);
308 if (img_open_password(blk, optstr, flags, quiet) < 0) {
315 static BlockBackend *img_open_file(const char *filename,
316 const char *fmt, int flags,
317 bool writethrough, bool quiet,
321 Error *local_err = NULL;
322 QDict *options = qdict_new();
325 qdict_put_str(options, "driver", fmt);
329 qdict_put(options, BDRV_OPT_FORCE_SHARE, qbool_from_bool(true));
331 blk = blk_new_open(filename, NULL, options, flags, &local_err);
333 error_reportf_err(local_err, "Could not open '%s': ", filename);
336 blk_set_enable_write_cache(blk, !writethrough);
338 if (img_open_password(blk, filename, flags, quiet) < 0) {
346 static BlockBackend *img_open(bool image_opts,
347 const char *filename,
348 const char *fmt, int flags, bool writethrough,
349 bool quiet, bool force_share)
355 error_report("--image-opts and --format are mutually exclusive");
358 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
363 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
366 blk = img_open_file(filename, fmt, flags, writethrough, quiet,
373 static int add_old_style_options(const char *fmt, QemuOpts *opts,
374 const char *base_filename,
375 const char *base_fmt)
380 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
382 error_report("Backing file not supported for file format '%s'",
389 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
391 error_report("Backing file format not supported for file "
400 static int64_t cvtnum(const char *s)
405 err = qemu_strtosz(s, NULL, &value);
409 if (value > INT64_MAX) {
415 static int img_create(int argc, char **argv)
418 uint64_t img_size = -1;
419 const char *fmt = "raw";
420 const char *base_fmt = NULL;
421 const char *filename;
422 const char *base_filename = NULL;
423 char *options = NULL;
424 Error *local_err = NULL;
428 static const struct option long_options[] = {
429 {"help", no_argument, 0, 'h'},
430 {"object", required_argument, 0, OPTION_OBJECT},
433 c = getopt_long(argc, argv, ":F:b:f:he6o:q",
440 missing_argument(argv[optind - 1]);
443 unrecognized_option(argv[optind - 1]);
452 base_filename = optarg;
458 error_report("option -e is deprecated, please use \'-o "
459 "encryption\' instead!");
462 error_report("option -6 is deprecated, please use \'-o "
463 "compat6\' instead!");
466 if (!is_valid_option_list(optarg)) {
467 error_report("Invalid option list: %s", optarg);
471 options = g_strdup(optarg);
473 char *old_options = options;
474 options = g_strdup_printf("%s,%s", options, optarg);
481 case OPTION_OBJECT: {
483 opts = qemu_opts_parse_noisily(&qemu_object_opts,
492 /* Get the filename */
493 filename = (optind < argc) ? argv[optind] : NULL;
494 if (options && has_help_option(options)) {
496 return print_block_option_help(filename, fmt);
499 if (optind >= argc) {
500 error_exit("Expecting image file name");
504 if (qemu_opts_foreach(&qemu_object_opts,
505 user_creatable_add_opts_foreach,
510 /* Get image size, if specified */
514 sval = cvtnum(argv[optind++]);
516 if (sval == -ERANGE) {
517 error_report("Image size must be less than 8 EiB!");
519 error_report("Invalid image size specified! You may use k, M, "
520 "G, T, P or E suffixes for ");
521 error_report("kilobytes, megabytes, gigabytes, terabytes, "
522 "petabytes and exabytes.");
526 img_size = (uint64_t)sval;
528 if (optind != argc) {
529 error_exit("Unexpected argument: %s", argv[optind]);
532 bdrv_img_create(filename, fmt, base_filename, base_fmt,
533 options, img_size, 0, quiet, &local_err);
535 error_reportf_err(local_err, "%s: ", filename);
547 static void dump_json_image_check(ImageCheck *check, bool quiet)
551 Visitor *v = qobject_output_visitor_new(&obj);
553 visit_type_ImageCheck(v, NULL, &check, &error_abort);
554 visit_complete(v, &obj);
555 str = qobject_to_json_pretty(obj);
557 qprintf(quiet, "%s\n", qstring_get_str(str));
563 static void dump_human_image_check(ImageCheck *check, bool quiet)
565 if (!(check->corruptions || check->leaks || check->check_errors)) {
566 qprintf(quiet, "No errors were found on the image.\n");
568 if (check->corruptions) {
569 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
570 "Data may be corrupted, or further writes to the image "
577 "\n%" PRId64 " leaked clusters were found on the image.\n"
578 "This means waste of disk space, but no harm to data.\n",
582 if (check->check_errors) {
585 " internal errors have occurred during the check.\n",
586 check->check_errors);
590 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
591 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
592 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
593 check->allocated_clusters, check->total_clusters,
594 check->allocated_clusters * 100.0 / check->total_clusters,
595 check->fragmented_clusters * 100.0 / check->allocated_clusters,
596 check->compressed_clusters * 100.0 /
597 check->allocated_clusters);
600 if (check->image_end_offset) {
602 "Image end offset: %" PRId64 "\n", check->image_end_offset);
606 static int collect_image_check(BlockDriverState *bs,
608 const char *filename,
613 BdrvCheckResult result;
615 ret = bdrv_check(bs, &result, fix);
620 check->filename = g_strdup(filename);
621 check->format = g_strdup(bdrv_get_format_name(bs));
622 check->check_errors = result.check_errors;
623 check->corruptions = result.corruptions;
624 check->has_corruptions = result.corruptions != 0;
625 check->leaks = result.leaks;
626 check->has_leaks = result.leaks != 0;
627 check->corruptions_fixed = result.corruptions_fixed;
628 check->has_corruptions_fixed = result.corruptions != 0;
629 check->leaks_fixed = result.leaks_fixed;
630 check->has_leaks_fixed = result.leaks != 0;
631 check->image_end_offset = result.image_end_offset;
632 check->has_image_end_offset = result.image_end_offset != 0;
633 check->total_clusters = result.bfi.total_clusters;
634 check->has_total_clusters = result.bfi.total_clusters != 0;
635 check->allocated_clusters = result.bfi.allocated_clusters;
636 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
637 check->fragmented_clusters = result.bfi.fragmented_clusters;
638 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
639 check->compressed_clusters = result.bfi.compressed_clusters;
640 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
646 * Checks an image for consistency. Exit codes:
648 * 0 - Check completed, image is good
649 * 1 - Check not completed because of internal errors
650 * 2 - Check completed, image is corrupted
651 * 3 - Check completed, image has leaked clusters, but is good otherwise
652 * 63 - Checks are not supported by the image format
654 static int img_check(int argc, char **argv)
657 OutputFormat output_format = OFORMAT_HUMAN;
658 const char *filename, *fmt, *output, *cache;
660 BlockDriverState *bs;
662 int flags = BDRV_O_CHECK;
666 bool image_opts = false;
667 bool force_share = false;
671 cache = BDRV_DEFAULT_CACHE;
674 int option_index = 0;
675 static const struct option long_options[] = {
676 {"help", no_argument, 0, 'h'},
677 {"format", required_argument, 0, 'f'},
678 {"repair", required_argument, 0, 'r'},
679 {"output", required_argument, 0, OPTION_OUTPUT},
680 {"object", required_argument, 0, OPTION_OBJECT},
681 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
682 {"force-share", no_argument, 0, 'U'},
685 c = getopt_long(argc, argv, ":hf:r:T:qU",
686 long_options, &option_index);
692 missing_argument(argv[optind - 1]);
695 unrecognized_option(argv[optind - 1]);
704 flags |= BDRV_O_RDWR;
706 if (!strcmp(optarg, "leaks")) {
707 fix = BDRV_FIX_LEAKS;
708 } else if (!strcmp(optarg, "all")) {
709 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
711 error_exit("Unknown option value for -r "
712 "(expecting 'leaks' or 'all'): %s", optarg);
727 case OPTION_OBJECT: {
729 opts = qemu_opts_parse_noisily(&qemu_object_opts,
735 case OPTION_IMAGE_OPTS:
740 if (optind != argc - 1) {
741 error_exit("Expecting one image file name");
743 filename = argv[optind++];
745 if (output && !strcmp(output, "json")) {
746 output_format = OFORMAT_JSON;
747 } else if (output && !strcmp(output, "human")) {
748 output_format = OFORMAT_HUMAN;
750 error_report("--output must be used with human or json as argument.");
754 if (qemu_opts_foreach(&qemu_object_opts,
755 user_creatable_add_opts_foreach,
760 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
762 error_report("Invalid source cache option: %s", cache);
766 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
773 check = g_new0(ImageCheck, 1);
774 ret = collect_image_check(bs, check, filename, fmt, fix);
776 if (ret == -ENOTSUP) {
777 error_report("This image format does not support checks");
782 if (check->corruptions_fixed || check->leaks_fixed) {
783 int corruptions_fixed, leaks_fixed;
785 leaks_fixed = check->leaks_fixed;
786 corruptions_fixed = check->corruptions_fixed;
788 if (output_format == OFORMAT_HUMAN) {
790 "The following inconsistencies were found and repaired:\n\n"
791 " %" PRId64 " leaked clusters\n"
792 " %" PRId64 " corruptions\n\n"
793 "Double checking the fixed image now...\n",
795 check->corruptions_fixed);
798 ret = collect_image_check(bs, check, filename, fmt, 0);
800 check->leaks_fixed = leaks_fixed;
801 check->corruptions_fixed = corruptions_fixed;
805 switch (output_format) {
807 dump_human_image_check(check, quiet);
810 dump_json_image_check(check, quiet);
815 if (ret || check->check_errors) {
817 error_report("Check failed: %s", strerror(-ret));
819 error_report("Check failed");
825 if (check->corruptions) {
827 } else if (check->leaks) {
834 qapi_free_ImageCheck(check);
839 typedef struct CommonBlockJobCBInfo {
840 BlockDriverState *bs;
842 } CommonBlockJobCBInfo;
844 static void common_block_job_cb(void *opaque, int ret)
846 CommonBlockJobCBInfo *cbi = opaque;
849 error_setg_errno(cbi->errp, -ret, "Block job failed");
853 static void run_block_job(BlockJob *job, Error **errp)
855 AioContext *aio_context = blk_get_aio_context(job->blk);
857 /* FIXME In error cases, the job simply goes away and we access a dangling
859 aio_context_acquire(aio_context);
861 aio_poll(aio_context, true);
862 qemu_progress_print(job->len ?
863 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
864 } while (!job->ready);
866 block_job_complete_sync(job, errp);
867 aio_context_release(aio_context);
869 /* A block job may finish instantaneously without publishing any progress,
870 * so just signal completion here */
871 qemu_progress_print(100.f, 0);
874 static int img_commit(int argc, char **argv)
877 const char *filename, *fmt, *cache, *base;
879 BlockDriverState *bs, *base_bs;
881 bool progress = false, quiet = false, drop = false;
883 Error *local_err = NULL;
884 CommonBlockJobCBInfo cbi;
885 bool image_opts = false;
886 AioContext *aio_context;
889 cache = BDRV_DEFAULT_CACHE;
892 static const struct option long_options[] = {
893 {"help", no_argument, 0, 'h'},
894 {"object", required_argument, 0, OPTION_OBJECT},
895 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
898 c = getopt_long(argc, argv, ":f:ht:b:dpq",
905 missing_argument(argv[optind - 1]);
908 unrecognized_option(argv[optind - 1]);
933 case OPTION_OBJECT: {
935 opts = qemu_opts_parse_noisily(&qemu_object_opts,
941 case OPTION_IMAGE_OPTS:
947 /* Progress is not shown in Quiet mode */
952 if (optind != argc - 1) {
953 error_exit("Expecting one image file name");
955 filename = argv[optind++];
957 if (qemu_opts_foreach(&qemu_object_opts,
958 user_creatable_add_opts_foreach,
963 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
964 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
966 error_report("Invalid cache option: %s", cache);
970 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
977 qemu_progress_init(progress, 1.f);
978 qemu_progress_print(0.f, 100);
981 base_bs = bdrv_find_backing_image(bs, base);
983 error_setg(&local_err,
984 "Did not find '%s' in the backing chain of '%s'",
989 /* This is different from QMP, which by default uses the deepest file in
990 * the backing chain (i.e., the very base); however, the traditional
991 * behavior of qemu-img commit is using the immediate backing file. */
992 base_bs = backing_bs(bs);
994 error_setg(&local_err, "Image does not have a backing file");
999 cbi = (CommonBlockJobCBInfo){
1004 aio_context = bdrv_get_aio_context(bs);
1005 aio_context_acquire(aio_context);
1006 commit_active_start("commit", bs, base_bs, BLOCK_JOB_DEFAULT, 0,
1007 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1008 &cbi, false, &local_err);
1009 aio_context_release(aio_context);
1014 /* When the block job completes, the BlockBackend reference will point to
1015 * the old backing file. In order to avoid that the top image is already
1016 * deleted, so we can still empty it afterwards, increment the reference
1017 * counter here preemptively. */
1022 job = block_job_get("commit");
1023 run_block_job(job, &local_err);
1028 if (!drop && bs->drv->bdrv_make_empty) {
1029 ret = bs->drv->bdrv_make_empty(bs);
1031 error_setg_errno(&local_err, -ret, "Could not empty %s",
1043 qemu_progress_end();
1048 error_report_err(local_err);
1052 qprintf(quiet, "Image committed.\n");
1057 * Returns true iff the first sector pointed to by 'buf' contains at least
1060 * 'pnum' is set to the number of sectors (including and immediately following
1061 * the first one) that are known to be in the same allocated/unallocated state.
1063 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
1072 is_zero = buffer_is_zero(buf, 512);
1073 for(i = 1; i < n; i++) {
1075 if (is_zero != buffer_is_zero(buf, 512)) {
1084 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1085 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1086 * breaking up write requests for only small sparse areas.
1088 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1092 int num_checked, num_used;
1098 ret = is_allocated_sectors(buf, n, pnum);
1104 buf += BDRV_SECTOR_SIZE * *pnum;
1106 num_checked = num_used;
1109 ret = is_allocated_sectors(buf, n, pnum);
1111 buf += BDRV_SECTOR_SIZE * *pnum;
1113 num_checked += *pnum;
1115 num_used = num_checked;
1116 } else if (*pnum >= min) {
1126 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1127 * buffers matches, non-zero otherwise.
1129 * pnum is set to the number of sectors (including and immediately following
1130 * the first one) that are known to have the same comparison result
1132 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1143 res = !!memcmp(buf1, buf2, 512);
1144 for(i = 1; i < n; i++) {
1148 if (!!memcmp(buf1, buf2, 512) != res) {
1157 #define IO_BUF_SIZE (2 * 1024 * 1024)
1159 static int64_t sectors_to_bytes(int64_t sectors)
1161 return sectors << BDRV_SECTOR_BITS;
1164 static int64_t sectors_to_process(int64_t total, int64_t from)
1166 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1170 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1172 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1173 * data and negative value on error.
1175 * @param blk: BlockBackend for the image
1176 * @param sect_num: Number of first sector to check
1177 * @param sect_count: Number of sectors to check
1178 * @param filename: Name of disk file we are checking (logging purpose)
1179 * @param buffer: Allocated buffer for storing read data
1180 * @param quiet: Flag for quiet mode
1182 static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
1183 int sect_count, const char *filename,
1184 uint8_t *buffer, bool quiet)
1187 ret = blk_pread(blk, sect_num << BDRV_SECTOR_BITS, buffer,
1188 sect_count << BDRV_SECTOR_BITS);
1190 error_report("Error while reading offset %" PRId64 " of %s: %s",
1191 sectors_to_bytes(sect_num), filename, strerror(-ret));
1194 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1195 if (ret || pnum != sect_count) {
1196 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1197 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1205 * Compares two images. Exit codes:
1207 * 0 - Images are identical
1209 * >1 - Error occurred
1211 static int img_compare(int argc, char **argv)
1213 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1214 BlockBackend *blk1, *blk2;
1215 BlockDriverState *bs1, *bs2;
1216 int64_t total_sectors1, total_sectors2;
1217 uint8_t *buf1 = NULL, *buf2 = NULL;
1219 int allocated1, allocated2;
1220 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1221 bool progress = false, quiet = false, strict = false;
1224 int64_t total_sectors;
1225 int64_t sector_num = 0;
1228 uint64_t progress_base;
1229 bool image_opts = false;
1230 bool force_share = false;
1232 cache = BDRV_DEFAULT_CACHE;
1234 static const struct option long_options[] = {
1235 {"help", no_argument, 0, 'h'},
1236 {"object", required_argument, 0, OPTION_OBJECT},
1237 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1238 {"force-share", no_argument, 0, 'U'},
1241 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1242 long_options, NULL);
1248 missing_argument(argv[optind - 1]);
1251 unrecognized_option(argv[optind - 1]);
1277 case OPTION_OBJECT: {
1279 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1286 case OPTION_IMAGE_OPTS:
1292 /* Progress is not shown in Quiet mode */
1298 if (optind != argc - 2) {
1299 error_exit("Expecting two image file names");
1301 filename1 = argv[optind++];
1302 filename2 = argv[optind++];
1304 if (qemu_opts_foreach(&qemu_object_opts,
1305 user_creatable_add_opts_foreach,
1311 /* Initialize before goto out */
1312 qemu_progress_init(progress, 2.0);
1315 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1317 error_report("Invalid source cache option: %s", cache);
1322 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1329 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1338 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1339 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1340 total_sectors1 = blk_nb_sectors(blk1);
1341 if (total_sectors1 < 0) {
1342 error_report("Can't get size of %s: %s",
1343 filename1, strerror(-total_sectors1));
1347 total_sectors2 = blk_nb_sectors(blk2);
1348 if (total_sectors2 < 0) {
1349 error_report("Can't get size of %s: %s",
1350 filename2, strerror(-total_sectors2));
1354 total_sectors = MIN(total_sectors1, total_sectors2);
1355 progress_base = MAX(total_sectors1, total_sectors2);
1357 qemu_progress_print(0, 100);
1359 if (strict && total_sectors1 != total_sectors2) {
1361 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1366 int64_t status1, status2;
1367 BlockDriverState *file;
1369 nb_sectors = sectors_to_process(total_sectors, sector_num);
1370 if (nb_sectors <= 0) {
1373 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1374 total_sectors1 - sector_num,
1378 error_report("Sector allocation test failed for %s", filename1);
1381 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1383 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1384 total_sectors2 - sector_num,
1388 error_report("Sector allocation test failed for %s", filename2);
1391 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1393 nb_sectors = MIN(nb_sectors, pnum1);
1396 nb_sectors = MIN(nb_sectors, pnum2);
1400 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1401 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1403 qprintf(quiet, "Strict mode: Offset %" PRId64
1404 " block status mismatch!\n",
1405 sectors_to_bytes(sector_num));
1409 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1410 nb_sectors = MIN(pnum1, pnum2);
1411 } else if (allocated1 == allocated2) {
1413 ret = blk_pread(blk1, sector_num << BDRV_SECTOR_BITS, buf1,
1414 nb_sectors << BDRV_SECTOR_BITS);
1416 error_report("Error while reading offset %" PRId64 " of %s:"
1417 " %s", sectors_to_bytes(sector_num), filename1,
1422 ret = blk_pread(blk2, sector_num << BDRV_SECTOR_BITS, buf2,
1423 nb_sectors << BDRV_SECTOR_BITS);
1425 error_report("Error while reading offset %" PRId64
1426 " of %s: %s", sectors_to_bytes(sector_num),
1427 filename2, strerror(-ret));
1431 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1432 if (ret || pnum != nb_sectors) {
1433 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1435 ret ? sector_num : sector_num + pnum));
1443 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
1444 filename1, buf1, quiet);
1446 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
1447 filename2, buf1, quiet);
1451 error_report("Error while reading offset %" PRId64 ": %s",
1452 sectors_to_bytes(sector_num), strerror(-ret));
1458 sector_num += nb_sectors;
1459 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1462 if (total_sectors1 != total_sectors2) {
1463 BlockBackend *blk_over;
1464 int64_t total_sectors_over;
1465 const char *filename_over;
1467 qprintf(quiet, "Warning: Image size mismatch!\n");
1468 if (total_sectors1 > total_sectors2) {
1469 total_sectors_over = total_sectors1;
1471 filename_over = filename1;
1473 total_sectors_over = total_sectors2;
1475 filename_over = filename2;
1479 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1480 if (nb_sectors <= 0) {
1483 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,
1487 error_report("Sector allocation test failed for %s",
1494 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
1495 filename_over, buf1, quiet);
1498 error_report("Error while reading offset %" PRId64
1499 " of %s: %s", sectors_to_bytes(sector_num),
1500 filename_over, strerror(-ret));
1506 sector_num += nb_sectors;
1507 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1511 qprintf(quiet, "Images are identical.\n");
1521 qemu_progress_end();
1526 enum ImgConvertBlockStatus {
1532 #define MAX_COROUTINES 16
1534 typedef struct ImgConvertState {
1536 int64_t *src_sectors;
1538 int64_t total_sectors;
1539 int64_t allocated_sectors;
1540 int64_t allocated_done;
1543 enum ImgConvertBlockStatus status;
1544 int64_t sector_next_status;
1545 BlockBackend *target;
1548 bool target_has_backing;
1551 size_t cluster_sectors;
1553 long num_coroutines;
1554 int running_coroutines;
1555 Coroutine *co[MAX_COROUTINES];
1556 int64_t wait_sector_num[MAX_COROUTINES];
1561 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1562 int *src_cur, int64_t *src_cur_offset)
1565 *src_cur_offset = 0;
1566 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1567 *src_cur_offset += s->src_sectors[*src_cur];
1569 assert(*src_cur < s->src_num);
1573 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1575 int64_t ret, src_cur_offset;
1578 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1580 assert(s->total_sectors > sector_num);
1581 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1583 if (s->sector_next_status <= sector_num) {
1584 BlockDriverState *file;
1585 if (s->target_has_backing) {
1586 ret = bdrv_get_block_status(blk_bs(s->src[src_cur]),
1587 sector_num - src_cur_offset,
1590 ret = bdrv_get_block_status_above(blk_bs(s->src[src_cur]), NULL,
1591 sector_num - src_cur_offset,
1598 if (ret & BDRV_BLOCK_ZERO) {
1599 s->status = BLK_ZERO;
1600 } else if (ret & BDRV_BLOCK_DATA) {
1601 s->status = BLK_DATA;
1603 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1606 s->sector_next_status = sector_num + n;
1609 n = MIN(n, s->sector_next_status - sector_num);
1610 if (s->status == BLK_DATA) {
1611 n = MIN(n, s->buf_sectors);
1614 /* We need to write complete clusters for compressed images, so if an
1615 * unallocated area is shorter than that, we must consider the whole
1616 * cluster allocated. */
1617 if (s->compressed) {
1618 if (n < s->cluster_sectors) {
1619 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1620 s->status = BLK_DATA;
1622 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1629 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1630 int nb_sectors, uint8_t *buf)
1636 assert(nb_sectors <= s->buf_sectors);
1637 while (nb_sectors > 0) {
1640 int64_t bs_sectors, src_cur_offset;
1642 /* In the case of compression with multiple source files, we can get a
1643 * nb_sectors that spreads into the next part. So we must be able to
1644 * read across multiple BDSes for one convert_read() call. */
1645 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1646 blk = s->src[src_cur];
1647 bs_sectors = s->src_sectors[src_cur];
1649 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1651 iov.iov_len = n << BDRV_SECTOR_BITS;
1652 qemu_iovec_init_external(&qiov, &iov, 1);
1654 ret = blk_co_preadv(
1655 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1656 n << BDRV_SECTOR_BITS, &qiov, 0);
1663 buf += n * BDRV_SECTOR_SIZE;
1670 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1671 int nb_sectors, uint8_t *buf,
1672 enum ImgConvertBlockStatus status)
1678 while (nb_sectors > 0) {
1680 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1683 case BLK_BACKING_FILE:
1684 /* If we have a backing file, leave clusters unallocated that are
1685 * unallocated in the source image, so that the backing file is
1686 * visible at the respective offset. */
1687 assert(s->target_has_backing);
1691 /* If we're told to keep the target fully allocated (-S 0) or there
1692 * is real non-zero data, we must write it. Otherwise we can treat
1693 * it as zero sectors.
1694 * Compressed clusters need to be written as a whole, so in that
1695 * case we can only save the write if the buffer is completely
1697 if (!s->min_sparse ||
1699 is_allocated_sectors_min(buf, n, &n, s->min_sparse)) ||
1701 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1704 iov.iov_len = n << BDRV_SECTOR_BITS;
1705 qemu_iovec_init_external(&qiov, &iov, 1);
1707 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
1708 n << BDRV_SECTOR_BITS, &qiov, flags);
1717 if (s->has_zero_init) {
1718 assert(!s->target_has_backing);
1721 ret = blk_co_pwrite_zeroes(s->target,
1722 sector_num << BDRV_SECTOR_BITS,
1723 n << BDRV_SECTOR_BITS, 0);
1732 buf += n * BDRV_SECTOR_SIZE;
1738 static void coroutine_fn convert_co_do_copy(void *opaque)
1740 ImgConvertState *s = opaque;
1741 uint8_t *buf = NULL;
1745 for (i = 0; i < s->num_coroutines; i++) {
1746 if (s->co[i] == qemu_coroutine_self()) {
1753 s->running_coroutines++;
1754 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1759 enum ImgConvertBlockStatus status;
1761 qemu_co_mutex_lock(&s->lock);
1762 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1763 qemu_co_mutex_unlock(&s->lock);
1766 n = convert_iteration_sectors(s, s->sector_num);
1768 qemu_co_mutex_unlock(&s->lock);
1772 /* save current sector and allocation status to local variables */
1773 sector_num = s->sector_num;
1775 if (!s->min_sparse && s->status == BLK_ZERO) {
1776 n = MIN(n, s->buf_sectors);
1778 /* increment global sector counter so that other coroutines can
1779 * already continue reading beyond this request */
1781 qemu_co_mutex_unlock(&s->lock);
1783 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1784 s->allocated_done += n;
1785 qemu_progress_print(100.0 * s->allocated_done /
1786 s->allocated_sectors, 0);
1789 if (status == BLK_DATA) {
1790 ret = convert_co_read(s, sector_num, n, buf);
1792 error_report("error while reading sector %" PRId64
1793 ": %s", sector_num, strerror(-ret));
1797 } else if (!s->min_sparse && status == BLK_ZERO) {
1799 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1802 if (s->wr_in_order) {
1803 /* keep writes in order */
1804 while (s->wr_offs != sector_num) {
1805 if (s->ret != -EINPROGRESS) {
1808 s->wait_sector_num[index] = sector_num;
1809 qemu_coroutine_yield();
1811 s->wait_sector_num[index] = -1;
1814 ret = convert_co_write(s, sector_num, n, buf, status);
1816 error_report("error while writing sector %" PRId64
1817 ": %s", sector_num, strerror(-ret));
1822 if (s->wr_in_order) {
1823 /* reenter the coroutine that might have waited
1824 * for this write to complete */
1825 s->wr_offs = sector_num + n;
1826 for (i = 0; i < s->num_coroutines; i++) {
1827 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1829 * A -> B -> A cannot occur because A has
1830 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1831 * B will never enter A during this time window.
1833 qemu_coroutine_enter(s->co[i]);
1842 s->co[index] = NULL;
1843 s->running_coroutines--;
1844 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1845 /* the convert job finished successfully */
1850 static int convert_do_copy(ImgConvertState *s)
1853 int64_t sector_num = 0;
1855 /* Check whether we have zero initialisation or can get it efficiently */
1856 s->has_zero_init = s->min_sparse && !s->target_has_backing
1857 ? bdrv_has_zero_init(blk_bs(s->target))
1860 if (!s->has_zero_init && !s->target_has_backing &&
1861 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1863 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
1865 s->has_zero_init = true;
1869 /* Allocate buffer for copied data. For compressed images, only one cluster
1870 * can be copied at a time. */
1871 if (s->compressed) {
1872 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1873 error_report("invalid cluster size");
1876 s->buf_sectors = s->cluster_sectors;
1879 while (sector_num < s->total_sectors) {
1880 n = convert_iteration_sectors(s, sector_num);
1884 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1886 s->allocated_sectors += n;
1892 s->sector_next_status = 0;
1893 s->ret = -EINPROGRESS;
1895 qemu_co_mutex_init(&s->lock);
1896 for (i = 0; i < s->num_coroutines; i++) {
1897 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1898 s->wait_sector_num[i] = -1;
1899 qemu_coroutine_enter(s->co[i]);
1902 while (s->ret == -EINPROGRESS) {
1903 main_loop_wait(false);
1906 if (s->compressed && !s->ret) {
1907 /* signal EOF to align */
1908 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
1917 static int img_convert(int argc, char **argv)
1919 int c, bs_i, flags, src_flags = 0;
1920 const char *fmt = NULL, *out_fmt = "raw", *cache = "unsafe",
1921 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
1922 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
1923 BlockDriver *drv, *proto_drv;
1924 BlockDriverInfo bdi;
1925 BlockDriverState *out_bs;
1926 QemuOpts *opts = NULL, *sn_opts = NULL;
1927 QemuOptsList *create_opts = NULL;
1928 char *options = NULL;
1929 Error *local_err = NULL;
1930 bool writethrough, src_writethrough, quiet = false, image_opts = false,
1931 skip_create = false, progress = false;
1932 int64_t ret = -EINVAL;
1933 bool force_share = false;
1935 ImgConvertState s = (ImgConvertState) {
1936 /* Need at least 4k of zeros for sparse detection */
1938 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
1939 .wr_in_order = true,
1940 .num_coroutines = 8,
1944 static const struct option long_options[] = {
1945 {"help", no_argument, 0, 'h'},
1946 {"object", required_argument, 0, OPTION_OBJECT},
1947 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1948 {"force-share", no_argument, 0, 'U'},
1951 c = getopt_long(argc, argv, ":hf:O:B:ce6o:s:l:S:pt:T:qnm:WU",
1952 long_options, NULL);
1958 missing_argument(argv[optind - 1]);
1961 unrecognized_option(argv[optind - 1]);
1973 out_baseimg = optarg;
1976 s.compressed = true;
1979 error_report("option -e is deprecated, please use \'-o "
1980 "encryption\' instead!");
1983 error_report("option -6 is deprecated, please use \'-o "
1984 "compat6\' instead!");
1987 if (!is_valid_option_list(optarg)) {
1988 error_report("Invalid option list: %s", optarg);
1992 options = g_strdup(optarg);
1994 char *old_options = options;
1995 options = g_strdup_printf("%s,%s", options, optarg);
1996 g_free(old_options);
2000 snapshot_name = optarg;
2003 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2004 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2007 error_report("Failed in parsing snapshot param '%s'",
2012 snapshot_name = optarg;
2019 sval = cvtnum(optarg);
2021 error_report("Invalid minimum zero buffer size for sparse output specified");
2025 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2044 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2045 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2046 error_report("Invalid number of coroutines. Allowed number of"
2047 " coroutines is between 1 and %d", MAX_COROUTINES);
2052 s.wr_in_order = false;
2057 case OPTION_OBJECT: {
2058 QemuOpts *object_opts;
2059 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2066 case OPTION_IMAGE_OPTS:
2072 if (qemu_opts_foreach(&qemu_object_opts,
2073 user_creatable_add_opts_foreach,
2078 if (!s.wr_in_order && s.compressed) {
2079 error_report("Out of order write and compress are mutually exclusive");
2083 s.src_num = argc - optind - 1;
2084 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2086 if (options && has_help_option(options)) {
2087 ret = print_block_option_help(out_filename, out_fmt);
2091 if (s.src_num < 1) {
2092 error_report("Must specify image file name");
2097 /* ret is still -EINVAL until here */
2098 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2100 error_report("Invalid source cache option: %s", src_cache);
2104 /* Initialize before goto out */
2108 qemu_progress_init(progress, 1.0);
2109 qemu_progress_print(0, 100);
2111 s.src = g_new0(BlockBackend *, s.src_num);
2112 s.src_sectors = g_new(int64_t, s.src_num);
2114 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2115 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2116 fmt, src_flags, src_writethrough, quiet,
2122 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2123 if (s.src_sectors[bs_i] < 0) {
2124 error_report("Could not get size of %s: %s",
2125 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2129 s.total_sectors += s.src_sectors[bs_i];
2133 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2134 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2135 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2137 } else if (snapshot_name != NULL) {
2138 if (s.src_num > 1) {
2139 error_report("No support for concatenating multiple snapshot");
2144 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2148 error_reportf_err(local_err, "Failed to load snapshot: ");
2153 /* Find driver and parse its options */
2154 drv = bdrv_find_format(out_fmt);
2156 error_report("Unknown file format '%s'", out_fmt);
2161 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2163 error_report_err(local_err);
2169 if (!drv->create_opts) {
2170 error_report("Format driver '%s' does not support image creation",
2176 if (!proto_drv->create_opts) {
2177 error_report("Protocol driver '%s' does not support image creation",
2178 proto_drv->format_name);
2183 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2184 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2186 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2188 qemu_opts_do_parse(opts, options, NULL, &local_err);
2190 error_report_err(local_err);
2196 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2198 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2204 /* Get backing file name if -o backing_file was used */
2205 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2206 if (out_baseimg_param) {
2207 out_baseimg = out_baseimg_param;
2209 s.target_has_backing = (bool) out_baseimg;
2211 if (s.src_num > 1 && out_baseimg) {
2212 error_report("Having a backing file for the target makes no sense when "
2213 "concatenating multiple input images");
2218 /* Check if compression is supported */
2221 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2222 const char *preallocation =
2223 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2225 if (!drv->bdrv_co_pwritev_compressed) {
2226 error_report("Compression not supported for this file format");
2232 error_report("Compression and encryption not supported at "
2239 && strcmp(preallocation, "off"))
2241 error_report("Compression and preallocation not supported at "
2249 /* Create the new image */
2250 ret = bdrv_create(drv, out_filename, opts, &local_err);
2252 error_reportf_err(local_err, "%s: error while converting %s: ",
2253 out_filename, out_fmt);
2258 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2259 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2261 error_report("Invalid cache option: %s", cache);
2265 /* XXX we should allow --image-opts to trigger use of
2266 * img_open() here, but then we have trouble with
2267 * the bdrv_create() call which takes different params.
2268 * Not critical right now, so fix can wait...
2270 s.target = img_open_file(out_filename, out_fmt, flags, writethrough, quiet,
2276 out_bs = blk_bs(s.target);
2278 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2279 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2281 s.buf_sectors = MIN(32768,
2283 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2284 out_bs->bl.pdiscard_alignment >>
2285 BDRV_SECTOR_BITS)));
2288 int64_t output_sectors = blk_nb_sectors(s.target);
2289 if (output_sectors < 0) {
2290 error_report("unable to get output image length: %s",
2291 strerror(-output_sectors));
2294 } else if (output_sectors < s.total_sectors) {
2295 error_report("output file is smaller than input file");
2301 ret = bdrv_get_info(out_bs, &bdi);
2304 error_report("could not get block driver info");
2308 s.compressed = s.compressed || bdi.needs_compressed_writes;
2309 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2312 ret = convert_do_copy(&s);
2315 qemu_progress_print(100, 0);
2317 qemu_progress_end();
2318 qemu_opts_del(opts);
2319 qemu_opts_free(create_opts);
2320 qemu_opts_del(sn_opts);
2321 blk_unref(s.target);
2323 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2324 blk_unref(s.src[bs_i]);
2328 g_free(s.src_sectors);
2336 static void dump_snapshots(BlockDriverState *bs)
2338 QEMUSnapshotInfo *sn_tab, *sn;
2341 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2344 printf("Snapshot list:\n");
2345 bdrv_snapshot_dump(fprintf, stdout, NULL);
2347 for(i = 0; i < nb_sns; i++) {
2349 bdrv_snapshot_dump(fprintf, stdout, sn);
2355 static void dump_json_image_info_list(ImageInfoList *list)
2359 Visitor *v = qobject_output_visitor_new(&obj);
2361 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2362 visit_complete(v, &obj);
2363 str = qobject_to_json_pretty(obj);
2364 assert(str != NULL);
2365 printf("%s\n", qstring_get_str(str));
2366 qobject_decref(obj);
2371 static void dump_json_image_info(ImageInfo *info)
2375 Visitor *v = qobject_output_visitor_new(&obj);
2377 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2378 visit_complete(v, &obj);
2379 str = qobject_to_json_pretty(obj);
2380 assert(str != NULL);
2381 printf("%s\n", qstring_get_str(str));
2382 qobject_decref(obj);
2387 static void dump_human_image_info_list(ImageInfoList *list)
2389 ImageInfoList *elem;
2392 for (elem = list; elem; elem = elem->next) {
2398 bdrv_image_info_dump(fprintf, stdout, elem->value);
2402 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2404 return strcmp(a, b) == 0;
2408 * Open an image file chain and return an ImageInfoList
2410 * @filename: topmost image filename
2411 * @fmt: topmost image format (may be NULL to autodetect)
2412 * @chain: true - enumerate entire backing file chain
2413 * false - only topmost image file
2415 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2416 * image file. If there was an error a message will have been printed to
2419 static ImageInfoList *collect_image_info_list(bool image_opts,
2420 const char *filename,
2422 bool chain, bool force_share)
2424 ImageInfoList *head = NULL;
2425 ImageInfoList **last = &head;
2426 GHashTable *filenames;
2429 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2433 BlockDriverState *bs;
2435 ImageInfoList *elem;
2437 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2438 error_report("Backing file '%s' creates an infinite loop.",
2442 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2444 blk = img_open(image_opts, filename, fmt,
2445 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2452 bdrv_query_image_info(bs, &info, &err);
2454 error_report_err(err);
2459 elem = g_new0(ImageInfoList, 1);
2466 filename = fmt = NULL;
2468 if (info->has_full_backing_filename) {
2469 filename = info->full_backing_filename;
2470 } else if (info->has_backing_filename) {
2471 error_report("Could not determine absolute backing filename,"
2472 " but backing filename '%s' present",
2473 info->backing_filename);
2476 if (info->has_backing_filename_format) {
2477 fmt = info->backing_filename_format;
2481 g_hash_table_destroy(filenames);
2485 qapi_free_ImageInfoList(head);
2486 g_hash_table_destroy(filenames);
2490 static int img_info(int argc, char **argv)
2493 OutputFormat output_format = OFORMAT_HUMAN;
2495 const char *filename, *fmt, *output;
2496 ImageInfoList *list;
2497 bool image_opts = false;
2498 bool force_share = false;
2503 int option_index = 0;
2504 static const struct option long_options[] = {
2505 {"help", no_argument, 0, 'h'},
2506 {"format", required_argument, 0, 'f'},
2507 {"output", required_argument, 0, OPTION_OUTPUT},
2508 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2509 {"object", required_argument, 0, OPTION_OBJECT},
2510 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2511 {"force-share", no_argument, 0, 'U'},
2514 c = getopt_long(argc, argv, ":f:hU",
2515 long_options, &option_index);
2521 missing_argument(argv[optind - 1]);
2524 unrecognized_option(argv[optind - 1]);
2538 case OPTION_BACKING_CHAIN:
2541 case OPTION_OBJECT: {
2543 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2549 case OPTION_IMAGE_OPTS:
2554 if (optind != argc - 1) {
2555 error_exit("Expecting one image file name");
2557 filename = argv[optind++];
2559 if (output && !strcmp(output, "json")) {
2560 output_format = OFORMAT_JSON;
2561 } else if (output && !strcmp(output, "human")) {
2562 output_format = OFORMAT_HUMAN;
2563 } else if (output) {
2564 error_report("--output must be used with human or json as argument.");
2568 if (qemu_opts_foreach(&qemu_object_opts,
2569 user_creatable_add_opts_foreach,
2574 list = collect_image_info_list(image_opts, filename, fmt, chain,
2580 switch (output_format) {
2582 dump_human_image_info_list(list);
2586 dump_json_image_info_list(list);
2588 dump_json_image_info(list->value);
2593 qapi_free_ImageInfoList(list);
2597 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2600 switch (output_format) {
2602 if (e->data && !e->has_offset) {
2603 error_report("File contains external, encrypted or compressed clusters.");
2606 if (e->data && !e->zero) {
2607 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2608 e->start, e->length,
2609 e->has_offset ? e->offset : 0,
2610 e->has_filename ? e->filename : "");
2612 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2613 * Modify the flags here to allow more coalescing.
2615 if (next && (!next->data || next->zero)) {
2621 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2622 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2623 (e->start == 0 ? "[" : ",\n"),
2624 e->start, e->length, e->depth,
2625 e->zero ? "true" : "false",
2626 e->data ? "true" : "false");
2627 if (e->has_offset) {
2628 printf(", \"offset\": %"PRId64"", e->offset);
2639 static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2640 int nb_sectors, MapEntry *e)
2644 BlockDriverState *file;
2647 /* As an optimization, we could cache the current range of unallocated
2648 * clusters in each file of the chain, and avoid querying the same
2654 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2660 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2663 bs = backing_bs(bs);
2672 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2675 .start = sector_num * BDRV_SECTOR_SIZE,
2676 .length = nb_sectors * BDRV_SECTOR_SIZE,
2677 .data = !!(ret & BDRV_BLOCK_DATA),
2678 .zero = !!(ret & BDRV_BLOCK_ZERO),
2679 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2680 .has_offset = has_offset,
2682 .has_filename = file && has_offset,
2683 .filename = file && has_offset ? file->filename : NULL,
2689 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2691 if (curr->length == 0) {
2694 if (curr->zero != next->zero ||
2695 curr->data != next->data ||
2696 curr->depth != next->depth ||
2697 curr->has_filename != next->has_filename ||
2698 curr->has_offset != next->has_offset) {
2701 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2704 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2710 static int img_map(int argc, char **argv)
2713 OutputFormat output_format = OFORMAT_HUMAN;
2715 BlockDriverState *bs;
2716 const char *filename, *fmt, *output;
2718 MapEntry curr = { .length = 0 }, next;
2720 bool image_opts = false;
2721 bool force_share = false;
2726 int option_index = 0;
2727 static const struct option long_options[] = {
2728 {"help", no_argument, 0, 'h'},
2729 {"format", required_argument, 0, 'f'},
2730 {"output", required_argument, 0, OPTION_OUTPUT},
2731 {"object", required_argument, 0, OPTION_OBJECT},
2732 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2733 {"force-share", no_argument, 0, 'U'},
2736 c = getopt_long(argc, argv, ":f:hU",
2737 long_options, &option_index);
2743 missing_argument(argv[optind - 1]);
2746 unrecognized_option(argv[optind - 1]);
2760 case OPTION_OBJECT: {
2762 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2768 case OPTION_IMAGE_OPTS:
2773 if (optind != argc - 1) {
2774 error_exit("Expecting one image file name");
2776 filename = argv[optind];
2778 if (output && !strcmp(output, "json")) {
2779 output_format = OFORMAT_JSON;
2780 } else if (output && !strcmp(output, "human")) {
2781 output_format = OFORMAT_HUMAN;
2782 } else if (output) {
2783 error_report("--output must be used with human or json as argument.");
2787 if (qemu_opts_foreach(&qemu_object_opts,
2788 user_creatable_add_opts_foreach,
2793 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
2799 if (output_format == OFORMAT_HUMAN) {
2800 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2803 length = blk_getlength(blk);
2804 while (curr.start + curr.length < length) {
2805 int64_t nsectors_left;
2809 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2811 /* Probe up to 1 GiB at a time. */
2812 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2813 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2814 ret = get_block_status(bs, sector_num, n, &next);
2817 error_report("Could not read file metadata: %s", strerror(-ret));
2821 if (entry_mergeable(&curr, &next)) {
2822 curr.length += next.length;
2826 if (curr.length > 0) {
2827 dump_map_entry(output_format, &curr, &next);
2832 dump_map_entry(output_format, &curr, NULL);
2839 #define SNAPSHOT_LIST 1
2840 #define SNAPSHOT_CREATE 2
2841 #define SNAPSHOT_APPLY 3
2842 #define SNAPSHOT_DELETE 4
2844 static int img_snapshot(int argc, char **argv)
2847 BlockDriverState *bs;
2848 QEMUSnapshotInfo sn;
2849 char *filename, *snapshot_name = NULL;
2850 int c, ret = 0, bdrv_oflags;
2855 bool image_opts = false;
2856 bool force_share = false;
2858 bdrv_oflags = BDRV_O_RDWR;
2859 /* Parse commandline parameters */
2861 static const struct option long_options[] = {
2862 {"help", no_argument, 0, 'h'},
2863 {"object", required_argument, 0, OPTION_OBJECT},
2864 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2865 {"force-share", no_argument, 0, 'U'},
2868 c = getopt_long(argc, argv, ":la:c:d:hqU",
2869 long_options, NULL);
2875 missing_argument(argv[optind - 1]);
2878 unrecognized_option(argv[optind - 1]);
2885 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2888 action = SNAPSHOT_LIST;
2889 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
2893 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2896 action = SNAPSHOT_APPLY;
2897 snapshot_name = optarg;
2901 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2904 action = SNAPSHOT_CREATE;
2905 snapshot_name = optarg;
2909 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2912 action = SNAPSHOT_DELETE;
2913 snapshot_name = optarg;
2921 case OPTION_OBJECT: {
2923 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2929 case OPTION_IMAGE_OPTS:
2935 if (optind != argc - 1) {
2936 error_exit("Expecting one image file name");
2938 filename = argv[optind++];
2940 if (qemu_opts_foreach(&qemu_object_opts,
2941 user_creatable_add_opts_foreach,
2946 /* Open the image */
2947 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
2954 /* Perform the requested action */
2960 case SNAPSHOT_CREATE:
2961 memset(&sn, 0, sizeof(sn));
2962 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2964 qemu_gettimeofday(&tv);
2965 sn.date_sec = tv.tv_sec;
2966 sn.date_nsec = tv.tv_usec * 1000;
2968 ret = bdrv_snapshot_create(bs, &sn);
2970 error_report("Could not create snapshot '%s': %d (%s)",
2971 snapshot_name, ret, strerror(-ret));
2975 case SNAPSHOT_APPLY:
2976 ret = bdrv_snapshot_goto(bs, snapshot_name);
2978 error_report("Could not apply snapshot '%s': %d (%s)",
2979 snapshot_name, ret, strerror(-ret));
2983 case SNAPSHOT_DELETE:
2984 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
2986 error_reportf_err(err, "Could not delete snapshot '%s': ",
3001 static int img_rebase(int argc, char **argv)
3003 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3004 uint8_t *buf_old = NULL;
3005 uint8_t *buf_new = NULL;
3006 BlockDriverState *bs = NULL;
3008 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3009 int c, flags, src_flags, ret;
3010 bool writethrough, src_writethrough;
3012 bool force_share = false;
3015 Error *local_err = NULL;
3016 bool image_opts = false;
3018 /* Parse commandline parameters */
3020 cache = BDRV_DEFAULT_CACHE;
3021 src_cache = BDRV_DEFAULT_CACHE;
3025 static const struct option long_options[] = {
3026 {"help", no_argument, 0, 'h'},
3027 {"object", required_argument, 0, OPTION_OBJECT},
3028 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3029 {"force-share", no_argument, 0, 'U'},
3032 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3033 long_options, NULL);
3039 missing_argument(argv[optind - 1]);
3042 unrecognized_option(argv[optind - 1]);
3051 out_basefmt = optarg;
3054 out_baseimg = optarg;
3071 case OPTION_OBJECT: {
3073 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3079 case OPTION_IMAGE_OPTS:
3092 if (optind != argc - 1) {
3093 error_exit("Expecting one image file name");
3095 if (!unsafe && !out_baseimg) {
3096 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3098 filename = argv[optind++];
3100 if (qemu_opts_foreach(&qemu_object_opts,
3101 user_creatable_add_opts_foreach,
3106 qemu_progress_init(progress, 2.0);
3107 qemu_progress_print(0, 100);
3109 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3110 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3112 error_report("Invalid cache option: %s", cache);
3117 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3119 error_report("Invalid source cache option: %s", src_cache);
3123 /* The source files are opened read-only, don't care about WCE */
3124 assert((src_flags & BDRV_O_RDWR) == 0);
3125 (void) src_writethrough;
3130 * Ignore the old backing file for unsafe rebase in case we want to correct
3131 * the reference to a renamed or moved backing file.
3133 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3141 if (out_basefmt != NULL) {
3142 if (bdrv_find_format(out_basefmt) == NULL) {
3143 error_report("Invalid format name: '%s'", out_basefmt);
3149 /* For safe rebasing we need to compare old and new backing file */
3151 char backing_name[PATH_MAX];
3152 QDict *options = NULL;
3154 if (bs->backing_format[0] != '\0') {
3155 options = qdict_new();
3156 qdict_put_str(options, "driver", bs->backing_format);
3161 options = qdict_new();
3163 qdict_put(options, BDRV_OPT_FORCE_SHARE,
3164 qbool_from_bool(true));
3166 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3167 blk_old_backing = blk_new_open(backing_name, NULL,
3168 options, src_flags, &local_err);
3169 if (!blk_old_backing) {
3170 error_reportf_err(local_err,
3171 "Could not open old backing file '%s': ",
3177 if (out_baseimg[0]) {
3178 options = qdict_new();
3180 qdict_put_str(options, "driver", out_basefmt);
3183 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3186 blk_new_backing = blk_new_open(out_baseimg, NULL,
3187 options, src_flags, &local_err);
3188 if (!blk_new_backing) {
3189 error_reportf_err(local_err,
3190 "Could not open new backing file '%s': ",
3199 * Check each unallocated cluster in the COW file. If it is unallocated,
3200 * accesses go to the backing file. We must therefore compare this cluster
3201 * in the old and new backing file, and if they differ we need to copy it
3202 * from the old backing file into the COW file.
3204 * If qemu-img crashes during this step, no harm is done. The content of
3205 * the image is the same as the original one at any time.
3208 int64_t num_sectors;
3209 int64_t old_backing_num_sectors;
3210 int64_t new_backing_num_sectors = 0;
3213 float local_progress = 0;
3215 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3216 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3218 num_sectors = blk_nb_sectors(blk);
3219 if (num_sectors < 0) {
3220 error_report("Could not get size of '%s': %s",
3221 filename, strerror(-num_sectors));
3225 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
3226 if (old_backing_num_sectors < 0) {
3227 char backing_name[PATH_MAX];
3229 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3230 error_report("Could not get size of '%s': %s",
3231 backing_name, strerror(-old_backing_num_sectors));
3235 if (blk_new_backing) {
3236 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
3237 if (new_backing_num_sectors < 0) {
3238 error_report("Could not get size of '%s': %s",
3239 out_baseimg, strerror(-new_backing_num_sectors));
3245 if (num_sectors != 0) {
3246 local_progress = (float)100 /
3247 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3250 for (sector = 0; sector < num_sectors; sector += n) {
3252 /* How many sectors can we handle with the next read? */
3253 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3254 n = (IO_BUF_SIZE / 512);
3256 n = num_sectors - sector;
3259 /* If the cluster is allocated, we don't need to take action */
3260 ret = bdrv_is_allocated(bs, sector, n, &n);
3262 error_report("error while reading image metadata: %s",
3271 * Read old and new backing file and take into consideration that
3272 * backing files may be smaller than the COW image.
3274 if (sector >= old_backing_num_sectors) {
3275 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3277 if (sector + n > old_backing_num_sectors) {
3278 n = old_backing_num_sectors - sector;
3281 ret = blk_pread(blk_old_backing, sector << BDRV_SECTOR_BITS,
3282 buf_old, n << BDRV_SECTOR_BITS);
3284 error_report("error while reading from old backing file");
3289 if (sector >= new_backing_num_sectors || !blk_new_backing) {
3290 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3292 if (sector + n > new_backing_num_sectors) {
3293 n = new_backing_num_sectors - sector;
3296 ret = blk_pread(blk_new_backing, sector << BDRV_SECTOR_BITS,
3297 buf_new, n << BDRV_SECTOR_BITS);
3299 error_report("error while reading from new backing file");
3304 /* If they differ, we need to write to the COW file */
3305 uint64_t written = 0;
3307 while (written < n) {
3310 if (compare_sectors(buf_old + written * 512,
3311 buf_new + written * 512, n - written, &pnum))
3313 ret = blk_pwrite(blk,
3314 (sector + written) << BDRV_SECTOR_BITS,
3315 buf_old + written * 512,
3316 pnum << BDRV_SECTOR_BITS, 0);
3318 error_report("Error while writing to COW image: %s",
3326 qemu_progress_print(local_progress, 100);
3331 * Change the backing file. All clusters that are different from the old
3332 * backing file are overwritten in the COW file now, so the visible content
3333 * doesn't change when we switch the backing file.
3335 if (out_baseimg && *out_baseimg) {
3336 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3338 ret = bdrv_change_backing_file(bs, NULL, NULL);
3341 if (ret == -ENOSPC) {
3342 error_report("Could not change the backing file to '%s': No "
3343 "space left in the file header", out_baseimg);
3344 } else if (ret < 0) {
3345 error_report("Could not change the backing file to '%s': %s",
3346 out_baseimg, strerror(-ret));
3349 qemu_progress_print(100, 0);
3351 * TODO At this point it is possible to check if any clusters that are
3352 * allocated in the COW file are the same in the backing file. If so, they
3353 * could be dropped from the COW file. Don't do this before switching the
3354 * backing file, in case of a crash this would lead to corruption.
3357 qemu_progress_end();
3360 blk_unref(blk_old_backing);
3361 blk_unref(blk_new_backing);
3363 qemu_vfree(buf_old);
3364 qemu_vfree(buf_new);
3373 static int img_resize(int argc, char **argv)
3376 int c, ret, relative;
3377 const char *filename, *fmt, *size;
3378 int64_t n, total_size;
3380 BlockBackend *blk = NULL;
3383 static QemuOptsList resize_options = {
3384 .name = "resize_options",
3385 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3388 .name = BLOCK_OPT_SIZE,
3389 .type = QEMU_OPT_SIZE,
3390 .help = "Virtual disk size"
3396 bool image_opts = false;
3398 /* Remove size from argv manually so that negative numbers are not treated
3399 * as options by getopt. */
3401 error_exit("Not enough arguments");
3405 size = argv[--argc];
3407 /* Parse getopt arguments */
3410 static const struct option long_options[] = {
3411 {"help", no_argument, 0, 'h'},
3412 {"object", required_argument, 0, OPTION_OBJECT},
3413 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3416 c = getopt_long(argc, argv, ":f:hq",
3417 long_options, NULL);
3423 missing_argument(argv[optind - 1]);
3426 unrecognized_option(argv[optind - 1]);
3437 case OPTION_OBJECT: {
3439 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3445 case OPTION_IMAGE_OPTS:
3450 if (optind != argc - 1) {
3451 error_exit("Expecting one image file name");
3453 filename = argv[optind++];
3455 if (qemu_opts_foreach(&qemu_object_opts,
3456 user_creatable_add_opts_foreach,
3461 /* Choose grow, shrink, or absolute resize mode */
3477 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3478 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3480 error_report_err(err);
3482 qemu_opts_del(param);
3485 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3486 qemu_opts_del(param);
3488 blk = img_open(image_opts, filename, fmt,
3489 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3497 total_size = blk_getlength(blk) + n * relative;
3501 if (total_size <= 0) {
3502 error_report("New image size must be positive");
3507 ret = blk_truncate(blk, total_size, &err);
3509 qprintf(quiet, "Image resized.\n");
3511 error_report_err(err);
3521 static void amend_status_cb(BlockDriverState *bs,
3522 int64_t offset, int64_t total_work_size,
3525 qemu_progress_print(100.f * offset / total_work_size, 0);
3528 static int img_amend(int argc, char **argv)
3532 char *options = NULL;
3533 QemuOptsList *create_opts = NULL;
3534 QemuOpts *opts = NULL;
3535 const char *fmt = NULL, *filename, *cache;
3538 bool quiet = false, progress = false;
3539 BlockBackend *blk = NULL;
3540 BlockDriverState *bs = NULL;
3541 bool image_opts = false;
3543 cache = BDRV_DEFAULT_CACHE;
3545 static const struct option long_options[] = {
3546 {"help", no_argument, 0, 'h'},
3547 {"object", required_argument, 0, OPTION_OBJECT},
3548 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3551 c = getopt_long(argc, argv, ":ho:f:t:pq",
3552 long_options, NULL);
3559 missing_argument(argv[optind - 1]);
3562 unrecognized_option(argv[optind - 1]);
3568 if (!is_valid_option_list(optarg)) {
3569 error_report("Invalid option list: %s", optarg);
3571 goto out_no_progress;
3574 options = g_strdup(optarg);
3576 char *old_options = options;
3577 options = g_strdup_printf("%s,%s", options, optarg);
3578 g_free(old_options);
3594 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3598 goto out_no_progress;
3601 case OPTION_IMAGE_OPTS:
3608 error_exit("Must specify options (-o)");
3611 if (qemu_opts_foreach(&qemu_object_opts,
3612 user_creatable_add_opts_foreach,
3615 goto out_no_progress;
3621 qemu_progress_init(progress, 1.0);
3623 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3624 if (fmt && has_help_option(options)) {
3625 /* If a format is explicitly specified (and possibly no filename is
3626 * given), print option help here */
3627 ret = print_block_option_help(filename, fmt);
3631 if (optind != argc - 1) {
3632 error_report("Expecting one image file name");
3637 flags = BDRV_O_RDWR;
3638 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3640 error_report("Invalid cache option: %s", cache);
3644 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3652 fmt = bs->drv->format_name;
3654 if (has_help_option(options)) {
3655 /* If the format was auto-detected, print option help here */
3656 ret = print_block_option_help(filename, fmt);
3660 if (!bs->drv->create_opts) {
3661 error_report("Format driver '%s' does not support any options to amend",
3667 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
3668 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3669 qemu_opts_do_parse(opts, options, NULL, &err);
3671 error_report_err(err);
3676 /* In case the driver does not call amend_status_cb() */
3677 qemu_progress_print(0.f, 0);
3678 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
3679 qemu_progress_print(100.f, 0);
3681 error_report("Error while amending options: %s", strerror(-ret));
3686 qemu_progress_end();
3690 qemu_opts_del(opts);
3691 qemu_opts_free(create_opts);
3700 typedef struct BenchData {
3702 uint64_t image_size;
3709 bool drain_on_flush;
3718 static void bench_undrained_flush_cb(void *opaque, int ret)
3721 error_report("Failed flush request: %s", strerror(-ret));
3726 static void bench_cb(void *opaque, int ret)
3728 BenchData *b = opaque;
3732 error_report("Failed request: %s", strerror(-ret));
3737 /* Just finished a flush with drained queue: Start next requests */
3738 assert(b->in_flight == 0);
3739 b->in_flush = false;
3740 } else if (b->in_flight > 0) {
3741 int remaining = b->n - b->in_flight;
3746 /* Time for flush? Drain queue if requested, then flush */
3747 if (b->flush_interval && remaining % b->flush_interval == 0) {
3748 if (!b->in_flight || !b->drain_on_flush) {
3749 BlockCompletionFunc *cb;
3751 if (b->drain_on_flush) {
3755 cb = bench_undrained_flush_cb;
3758 acb = blk_aio_flush(b->blk, cb, b);
3760 error_report("Failed to issue flush request");
3764 if (b->drain_on_flush) {
3770 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
3771 int64_t offset = b->offset;
3772 /* blk_aio_* might look for completed I/Os and kick bench_cb
3773 * again, so make sure this operation is counted by in_flight
3774 * and b->offset is ready for the next submission.
3777 b->offset += b->step;
3778 b->offset %= b->image_size;
3780 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
3782 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
3785 error_report("Failed to issue request");
3791 static int img_bench(int argc, char **argv)
3794 const char *fmt = NULL, *filename;
3796 bool image_opts = false;
3797 bool is_write = false;
3801 size_t bufsize = 4096;
3804 int flush_interval = 0;
3805 bool drain_on_flush = true;
3807 BlockBackend *blk = NULL;
3808 BenchData data = {};
3810 bool writethrough = false;
3811 struct timeval t1, t2;
3813 bool force_share = false;
3816 static const struct option long_options[] = {
3817 {"help", no_argument, 0, 'h'},
3818 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
3819 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3820 {"pattern", required_argument, 0, OPTION_PATTERN},
3821 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
3822 {"force-share", no_argument, 0, 'U'},
3825 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
3832 missing_argument(argv[optind - 1]);
3835 unrecognized_option(argv[optind - 1]);
3844 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
3845 error_report("Invalid request count specified");
3855 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
3856 error_report("Invalid queue depth specified");
3866 flags |= BDRV_O_NATIVE_AIO;
3870 offset = cvtnum(optarg);
3872 error_report("Invalid offset specified");
3885 sval = cvtnum(optarg);
3886 if (sval < 0 || sval > INT_MAX) {
3887 error_report("Invalid buffer size specified");
3898 sval = cvtnum(optarg);
3899 if (sval < 0 || sval > INT_MAX) {
3900 error_report("Invalid step size specified");
3908 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
3910 error_report("Invalid cache mode");
3916 flags |= BDRV_O_RDWR;
3922 case OPTION_PATTERN:
3926 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
3927 error_report("Invalid pattern byte specified");
3933 case OPTION_FLUSH_INTERVAL:
3937 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
3938 error_report("Invalid flush interval specified");
3941 flush_interval = res;
3944 case OPTION_NO_DRAIN:
3945 drain_on_flush = false;
3947 case OPTION_IMAGE_OPTS:
3953 if (optind != argc - 1) {
3954 error_exit("Expecting one image file name");
3956 filename = argv[argc - 1];
3958 if (!is_write && flush_interval) {
3959 error_report("--flush-interval is only available in write tests");
3963 if (flush_interval && flush_interval < depth) {
3964 error_report("Flush interval can't be smaller than depth");
3969 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3976 image_size = blk_getlength(blk);
3977 if (image_size < 0) {
3982 data = (BenchData) {
3984 .image_size = image_size,
3986 .step = step ?: bufsize,
3991 .flush_interval = flush_interval,
3992 .drain_on_flush = drain_on_flush,
3994 printf("Sending %d %s requests, %d bytes each, %d in parallel "
3995 "(starting at offset %" PRId64 ", step size %d)\n",
3996 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
3997 data.offset, data.step);
3998 if (flush_interval) {
3999 printf("Sending flush every %d requests\n", flush_interval);
4002 data.buf = blk_blockalign(blk, data.nrreq * data.bufsize);
4003 memset(data.buf, pattern, data.nrreq * data.bufsize);
4005 data.qiov = g_new(QEMUIOVector, data.nrreq);
4006 for (i = 0; i < data.nrreq; i++) {
4007 qemu_iovec_init(&data.qiov[i], 1);
4008 qemu_iovec_add(&data.qiov[i],
4009 data.buf + i * data.bufsize, data.bufsize);
4012 gettimeofday(&t1, NULL);
4015 while (data.n > 0) {
4016 main_loop_wait(false);
4018 gettimeofday(&t2, NULL);
4020 printf("Run completed in %3.3f seconds.\n",
4021 (t2.tv_sec - t1.tv_sec)
4022 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4025 qemu_vfree(data.buf);
4046 int bsz; /* Block size */
4054 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4058 static int img_dd_bs(const char *arg,
4059 struct DdIo *in, struct DdIo *out,
4066 if (res <= 0 || res > INT_MAX) {
4067 error_report("invalid number: '%s'", arg);
4070 in->bsz = out->bsz = res;
4075 static int img_dd_count(const char *arg,
4076 struct DdIo *in, struct DdIo *out,
4079 dd->count = cvtnum(arg);
4081 if (dd->count < 0) {
4082 error_report("invalid number: '%s'", arg);
4089 static int img_dd_if(const char *arg,
4090 struct DdIo *in, struct DdIo *out,
4093 in->filename = g_strdup(arg);
4098 static int img_dd_of(const char *arg,
4099 struct DdIo *in, struct DdIo *out,
4102 out->filename = g_strdup(arg);
4107 static int img_dd_skip(const char *arg,
4108 struct DdIo *in, struct DdIo *out,
4111 in->offset = cvtnum(arg);
4113 if (in->offset < 0) {
4114 error_report("invalid number: '%s'", arg);
4121 static int img_dd(int argc, char **argv)
4126 BlockDriver *drv = NULL, *proto_drv = NULL;
4127 BlockBackend *blk1 = NULL, *blk2 = NULL;
4128 QemuOpts *opts = NULL;
4129 QemuOptsList *create_opts = NULL;
4130 Error *local_err = NULL;
4131 bool image_opts = false;
4133 const char *out_fmt = "raw";
4134 const char *fmt = NULL;
4136 int64_t block_count = 0, out_pos, in_pos;
4137 bool force_share = false;
4138 struct DdInfo dd = {
4143 .bsz = 512, /* Block size is by default 512 bytes */
4155 const struct DdOpts options[] = {
4156 { "bs", img_dd_bs, C_BS },
4157 { "count", img_dd_count, C_COUNT },
4158 { "if", img_dd_if, C_IF },
4159 { "of", img_dd_of, C_OF },
4160 { "skip", img_dd_skip, C_SKIP },
4163 const struct option long_options[] = {
4164 { "help", no_argument, 0, 'h'},
4165 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4166 { "force-share", no_argument, 0, 'U'},
4170 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4182 missing_argument(argv[optind - 1]);
4185 unrecognized_option(argv[optind - 1]);
4193 case OPTION_IMAGE_OPTS:
4199 for (i = optind; i < argc; i++) {
4201 arg = g_strdup(argv[i]);
4203 tmp = strchr(arg, '=');
4205 error_report("unrecognized operand %s", arg);
4212 for (j = 0; options[j].name != NULL; j++) {
4213 if (!strcmp(arg, options[j].name)) {
4217 if (options[j].name == NULL) {
4218 error_report("unrecognized operand %s", arg);
4223 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4227 dd.flags |= options[j].flag;
4232 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4233 error_report("Must specify both input and output files");
4237 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4245 drv = bdrv_find_format(out_fmt);
4247 error_report("Unknown file format");
4251 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4254 error_report_err(local_err);
4258 if (!drv->create_opts) {
4259 error_report("Format driver '%s' does not support image creation",
4264 if (!proto_drv->create_opts) {
4265 error_report("Protocol driver '%s' does not support image creation",
4266 proto_drv->format_name);
4270 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4271 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4273 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4275 size = blk_getlength(blk1);
4277 error_report("Failed to get size for '%s'", in.filename);
4282 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4283 dd.count * in.bsz < size) {
4284 size = dd.count * in.bsz;
4287 /* Overflow means the specified offset is beyond input image's size */
4288 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4289 size < in.bsz * in.offset)) {
4290 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4292 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4293 size - in.bsz * in.offset, &error_abort);
4296 ret = bdrv_create(drv, out.filename, opts, &local_err);
4298 error_reportf_err(local_err,
4299 "%s: error while creating output image: ",
4305 blk2 = img_open(image_opts, out.filename, out_fmt, BDRV_O_RDWR,
4306 false, false, false);
4313 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4314 size < in.offset * in.bsz)) {
4315 /* We give a warning if the skip option is bigger than the input
4316 * size and create an empty output disk image (i.e. like dd(1)).
4318 error_report("%s: cannot skip to specified offset", in.filename);
4321 in_pos = in.offset * in.bsz;
4324 in.buf = g_new(uint8_t, in.bsz);
4326 for (out_pos = 0; in_pos < size; block_count++) {
4327 int in_ret, out_ret;
4329 if (in_pos + in.bsz > size) {
4330 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4332 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4335 error_report("error while reading from input image file: %s",
4342 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4345 error_report("error while writing to output image file: %s",
4346 strerror(-out_ret));
4355 qemu_opts_del(opts);
4356 qemu_opts_free(create_opts);
4359 g_free(in.filename);
4360 g_free(out.filename);
4371 static const img_cmd_t img_cmds[] = {
4372 #define DEF(option, callback, arg_string) \
4373 { option, callback },
4374 #include "qemu-img-cmds.h"
4380 int main(int argc, char **argv)
4382 const img_cmd_t *cmd;
4383 const char *cmdname;
4384 Error *local_error = NULL;
4385 char *trace_file = NULL;
4387 static const struct option long_options[] = {
4388 {"help", no_argument, 0, 'h'},
4389 {"version", no_argument, 0, 'V'},
4390 {"trace", required_argument, NULL, 'T'},
4395 signal(SIGPIPE, SIG_IGN);
4398 module_call_init(MODULE_INIT_TRACE);
4399 error_set_progname(argv[0]);
4400 qemu_init_exec_dir(argv[0]);
4402 if (qemu_init_main_loop(&local_error)) {
4403 error_report_err(local_error);
4407 qcrypto_init(&error_fatal);
4409 module_call_init(MODULE_INIT_QOM);
4412 error_exit("Not enough arguments");
4415 qemu_add_opts(&qemu_object_opts);
4416 qemu_add_opts(&qemu_source_opts);
4417 qemu_add_opts(&qemu_trace_opts);
4419 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
4422 missing_argument(argv[optind - 1]);
4425 unrecognized_option(argv[optind - 1]);
4431 printf(QEMU_IMG_VERSION);
4435 trace_file = trace_opt_parse(optarg);
4440 cmdname = argv[optind];
4442 /* reset getopt_long scanning */
4450 if (!trace_init_backends()) {
4453 trace_init_file(trace_file);
4454 qemu_set_log(LOG_TRACE);
4456 /* find the command */
4457 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4458 if (!strcmp(cmdname, cmd->name)) {
4459 return cmd->handler(argc, argv);
4464 error_exit("Command not found: %s", cmdname);