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 "qapi/error.h"
26 #include "qapi-visit.h"
27 #include "qapi/qmp-output-visitor.h"
28 #include "qapi/qmp/qerror.h"
29 #include "qapi/qmp/qjson.h"
30 #include "qemu/cutils.h"
31 #include "qemu/config-file.h"
32 #include "qemu/option.h"
33 #include "qemu/error-report.h"
34 #include "qom/object_interfaces.h"
35 #include "sysemu/sysemu.h"
36 #include "sysemu/block-backend.h"
37 #include "block/block_int.h"
38 #include "block/blockjob.h"
39 #include "block/qapi.h"
42 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
43 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
45 typedef struct img_cmd_t {
47 int (*handler)(int argc, char **argv);
52 OPTION_BACKING_CHAIN = 257,
54 OPTION_IMAGE_OPTS = 259,
57 typedef enum OutputFormat {
62 /* Default to cache=writeback as data integrity is not important for qemu-tcg. */
63 #define BDRV_O_FLAGS BDRV_O_CACHE_WB
64 #define BDRV_DEFAULT_CACHE "writeback"
66 static void format_print(void *opaque, const char *name)
71 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
75 error_printf("qemu-img: ");
78 error_vprintf(fmt, ap);
81 error_printf("\nTry 'qemu-img --help' for more information\n");
85 /* Please keep in synch with qemu-img.texi */
86 static void QEMU_NORETURN help(void)
88 const char *help_msg =
90 "usage: qemu-img command [command options]\n"
91 "QEMU disk image utility\n"
94 #define DEF(option, callback, arg_string) \
96 #include "qemu-img-cmds.h"
100 "Command parameters:\n"
101 " 'filename' is a disk image filename\n"
102 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
103 " manual page for a description of the object properties. The most common\n"
104 " object type is a 'secret', which is used to supply passwords and/or\n"
105 " encryption keys.\n"
106 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
107 " 'cache' is the cache mode used to write the output disk image, the valid\n"
108 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
109 " 'directsync' and 'unsafe' (default for convert)\n"
110 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
111 " options are the same as for the 'cache' option\n"
112 " 'size' is the disk image size in bytes. Optional suffixes\n"
113 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
114 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
115 " supported. 'b' is ignored.\n"
116 " 'output_filename' is the destination disk image filename\n"
117 " 'output_fmt' is the destination format\n"
118 " 'options' is a comma separated list of format specific options in a\n"
119 " name=value format. Use -o ? for an overview of the options supported by the\n"
121 " 'snapshot_param' is param used for internal snapshot, format\n"
122 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
124 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
126 " '-c' indicates that target image must be compressed (qcow format only)\n"
127 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
128 " match exactly. The image doesn't need a working backing file before\n"
129 " rebasing in this case (useful for renaming the backing file)\n"
130 " '-h' with or without a command shows this help and lists the supported formats\n"
131 " '-p' show progress of command (only certain commands)\n"
132 " '-q' use Quiet mode - do not print any output (except errors)\n"
133 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
134 " contain only zeros for qemu-img to create a sparse image during\n"
135 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
136 " unallocated or zero sectors, and the destination image will always be\n"
138 " '--output' takes the format in which the output must be done (human or json)\n"
139 " '-n' skips the target volume creation (useful if the volume is created\n"
140 " prior to running qemu-img)\n"
142 "Parameters to check subcommand:\n"
143 " '-r' tries to repair any inconsistencies that are found during the check.\n"
144 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
145 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
146 " hiding corruption that has already occurred.\n"
148 "Parameters to snapshot subcommand:\n"
149 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
150 " '-a' applies a snapshot (revert disk to saved state)\n"
151 " '-c' creates a snapshot\n"
152 " '-d' deletes a snapshot\n"
153 " '-l' lists all snapshots in the given image\n"
155 "Parameters to compare subcommand:\n"
156 " '-f' first image format\n"
157 " '-F' second image format\n"
158 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
160 printf("%s\nSupported formats:", help_msg);
161 bdrv_iterate_format(format_print, NULL);
166 static QemuOptsList qemu_object_opts = {
168 .implied_opt_name = "qom-type",
169 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
175 static QemuOptsList qemu_source_opts = {
177 .implied_opt_name = "file",
178 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
184 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
190 ret = vprintf(fmt, args);
197 static int print_block_option_help(const char *filename, const char *fmt)
199 BlockDriver *drv, *proto_drv;
200 QemuOptsList *create_opts = NULL;
201 Error *local_err = NULL;
203 /* Find driver and parse its options */
204 drv = bdrv_find_format(fmt);
206 error_report("Unknown file format '%s'", fmt);
210 create_opts = qemu_opts_append(create_opts, drv->create_opts);
212 proto_drv = bdrv_find_protocol(filename, true, &local_err);
214 error_report_err(local_err);
215 qemu_opts_free(create_opts);
218 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
221 qemu_opts_print_help(create_opts);
222 qemu_opts_free(create_opts);
227 static int img_open_password(BlockBackend *blk, const char *filename,
228 bool require_io, bool quiet)
230 BlockDriverState *bs;
234 if (bdrv_is_encrypted(bs) && require_io) {
235 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
236 if (qemu_read_password(password, sizeof(password)) < 0) {
237 error_report("No password given");
240 if (bdrv_set_key(bs, password) < 0) {
241 error_report("invalid password");
249 static BlockBackend *img_open_opts(const char *optstr,
250 QemuOpts *opts, int flags,
251 bool require_io, bool quiet)
254 Error *local_err = NULL;
256 options = qemu_opts_to_qdict(opts, NULL);
257 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
259 error_reportf_err(local_err, "Could not open '%s'", optstr);
263 if (img_open_password(blk, optstr, require_io, quiet) < 0) {
270 static BlockBackend *img_open_file(const char *filename,
271 const char *fmt, int flags,
272 bool require_io, bool quiet)
275 Error *local_err = NULL;
276 QDict *options = NULL;
279 options = qdict_new();
280 qdict_put(options, "driver", qstring_from_str(fmt));
283 blk = blk_new_open(filename, NULL, options, flags, &local_err);
285 error_reportf_err(local_err, "Could not open '%s': ", filename);
289 if (img_open_password(blk, filename, require_io, quiet) < 0) {
297 static BlockBackend *img_open(bool image_opts,
298 const char *filename,
299 const char *fmt, int flags,
300 bool require_io, bool quiet)
306 error_report("--image-opts and --format are mutually exclusive");
309 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
314 blk = img_open_opts(filename, opts, flags, true, quiet);
316 blk = img_open_file(filename, fmt, flags, true, quiet);
322 static int add_old_style_options(const char *fmt, QemuOpts *opts,
323 const char *base_filename,
324 const char *base_fmt)
329 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
331 error_report("Backing file not supported for file format '%s'",
338 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
340 error_report("Backing file format not supported for file "
349 static int img_create(int argc, char **argv)
352 uint64_t img_size = -1;
353 const char *fmt = "raw";
354 const char *base_fmt = NULL;
355 const char *filename;
356 const char *base_filename = NULL;
357 char *options = NULL;
358 Error *local_err = NULL;
362 static const struct option long_options[] = {
363 {"help", no_argument, 0, 'h'},
364 {"object", required_argument, 0, OPTION_OBJECT},
367 c = getopt_long(argc, argv, "F:b:f:he6o:q",
381 base_filename = optarg;
387 error_report("option -e is deprecated, please use \'-o "
388 "encryption\' instead!");
391 error_report("option -6 is deprecated, please use \'-o "
392 "compat6\' instead!");
395 if (!is_valid_option_list(optarg)) {
396 error_report("Invalid option list: %s", optarg);
400 options = g_strdup(optarg);
402 char *old_options = options;
403 options = g_strdup_printf("%s,%s", options, optarg);
410 case OPTION_OBJECT: {
412 opts = qemu_opts_parse_noisily(&qemu_object_opts,
421 /* Get the filename */
422 filename = (optind < argc) ? argv[optind] : NULL;
423 if (options && has_help_option(options)) {
425 return print_block_option_help(filename, fmt);
428 if (optind >= argc) {
429 error_exit("Expecting image file name");
433 if (qemu_opts_foreach(&qemu_object_opts,
434 user_creatable_add_opts_foreach,
436 error_report_err(local_err);
440 /* Get image size, if specified */
444 sval = qemu_strtosz_suffix(argv[optind++], &end,
445 QEMU_STRTOSZ_DEFSUFFIX_B);
446 if (sval < 0 || *end) {
447 if (sval == -ERANGE) {
448 error_report("Image size must be less than 8 EiB!");
450 error_report("Invalid image size specified! You may use k, M, "
451 "G, T, P or E suffixes for ");
452 error_report("kilobytes, megabytes, gigabytes, terabytes, "
453 "petabytes and exabytes.");
457 img_size = (uint64_t)sval;
459 if (optind != argc) {
460 error_exit("Unexpected argument: %s", argv[optind]);
463 bdrv_img_create(filename, fmt, base_filename, base_fmt,
464 options, img_size, BDRV_O_FLAGS, &local_err, quiet);
466 error_reportf_err(local_err, "%s: ", filename);
478 static void dump_json_image_check(ImageCheck *check, bool quiet)
480 Error *local_err = NULL;
482 QmpOutputVisitor *ov = qmp_output_visitor_new();
484 visit_type_ImageCheck(qmp_output_get_visitor(ov), NULL, &check,
486 obj = qmp_output_get_qobject(ov);
487 str = qobject_to_json_pretty(obj);
489 qprintf(quiet, "%s\n", qstring_get_str(str));
491 qmp_output_visitor_cleanup(ov);
495 static void dump_human_image_check(ImageCheck *check, bool quiet)
497 if (!(check->corruptions || check->leaks || check->check_errors)) {
498 qprintf(quiet, "No errors were found on the image.\n");
500 if (check->corruptions) {
501 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
502 "Data may be corrupted, or further writes to the image "
509 "\n%" PRId64 " leaked clusters were found on the image.\n"
510 "This means waste of disk space, but no harm to data.\n",
514 if (check->check_errors) {
517 " internal errors have occurred during the check.\n",
518 check->check_errors);
522 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
523 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
524 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
525 check->allocated_clusters, check->total_clusters,
526 check->allocated_clusters * 100.0 / check->total_clusters,
527 check->fragmented_clusters * 100.0 / check->allocated_clusters,
528 check->compressed_clusters * 100.0 /
529 check->allocated_clusters);
532 if (check->image_end_offset) {
534 "Image end offset: %" PRId64 "\n", check->image_end_offset);
538 static int collect_image_check(BlockDriverState *bs,
540 const char *filename,
545 BdrvCheckResult result;
547 ret = bdrv_check(bs, &result, fix);
552 check->filename = g_strdup(filename);
553 check->format = g_strdup(bdrv_get_format_name(bs));
554 check->check_errors = result.check_errors;
555 check->corruptions = result.corruptions;
556 check->has_corruptions = result.corruptions != 0;
557 check->leaks = result.leaks;
558 check->has_leaks = result.leaks != 0;
559 check->corruptions_fixed = result.corruptions_fixed;
560 check->has_corruptions_fixed = result.corruptions != 0;
561 check->leaks_fixed = result.leaks_fixed;
562 check->has_leaks_fixed = result.leaks != 0;
563 check->image_end_offset = result.image_end_offset;
564 check->has_image_end_offset = result.image_end_offset != 0;
565 check->total_clusters = result.bfi.total_clusters;
566 check->has_total_clusters = result.bfi.total_clusters != 0;
567 check->allocated_clusters = result.bfi.allocated_clusters;
568 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
569 check->fragmented_clusters = result.bfi.fragmented_clusters;
570 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
571 check->compressed_clusters = result.bfi.compressed_clusters;
572 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
578 * Checks an image for consistency. Exit codes:
580 * 0 - Check completed, image is good
581 * 1 - Check not completed because of internal errors
582 * 2 - Check completed, image is corrupted
583 * 3 - Check completed, image has leaked clusters, but is good otherwise
584 * 63 - Checks are not supported by the image format
586 static int img_check(int argc, char **argv)
589 OutputFormat output_format = OFORMAT_HUMAN;
590 const char *filename, *fmt, *output, *cache;
592 BlockDriverState *bs;
594 int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
597 Error *local_err = NULL;
598 bool image_opts = false;
602 cache = BDRV_DEFAULT_CACHE;
604 int option_index = 0;
605 static const struct option long_options[] = {
606 {"help", no_argument, 0, 'h'},
607 {"format", required_argument, 0, 'f'},
608 {"repair", required_argument, 0, 'r'},
609 {"output", required_argument, 0, OPTION_OUTPUT},
610 {"object", required_argument, 0, OPTION_OBJECT},
611 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
614 c = getopt_long(argc, argv, "hf:r:T:q",
615 long_options, &option_index);
628 flags |= BDRV_O_RDWR;
630 if (!strcmp(optarg, "leaks")) {
631 fix = BDRV_FIX_LEAKS;
632 } else if (!strcmp(optarg, "all")) {
633 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
635 error_exit("Unknown option value for -r "
636 "(expecting 'leaks' or 'all'): %s", optarg);
648 case OPTION_OBJECT: {
650 opts = qemu_opts_parse_noisily(&qemu_object_opts,
656 case OPTION_IMAGE_OPTS:
661 if (optind != argc - 1) {
662 error_exit("Expecting one image file name");
664 filename = argv[optind++];
666 if (output && !strcmp(output, "json")) {
667 output_format = OFORMAT_JSON;
668 } else if (output && !strcmp(output, "human")) {
669 output_format = OFORMAT_HUMAN;
671 error_report("--output must be used with human or json as argument.");
675 if (qemu_opts_foreach(&qemu_object_opts,
676 user_creatable_add_opts_foreach,
678 error_report_err(local_err);
682 ret = bdrv_parse_cache_flags(cache, &flags);
684 error_report("Invalid source cache option: %s", cache);
688 blk = img_open(image_opts, filename, fmt, flags, true, quiet);
694 check = g_new0(ImageCheck, 1);
695 ret = collect_image_check(bs, check, filename, fmt, fix);
697 if (ret == -ENOTSUP) {
698 error_report("This image format does not support checks");
703 if (check->corruptions_fixed || check->leaks_fixed) {
704 int corruptions_fixed, leaks_fixed;
706 leaks_fixed = check->leaks_fixed;
707 corruptions_fixed = check->corruptions_fixed;
709 if (output_format == OFORMAT_HUMAN) {
711 "The following inconsistencies were found and repaired:\n\n"
712 " %" PRId64 " leaked clusters\n"
713 " %" PRId64 " corruptions\n\n"
714 "Double checking the fixed image now...\n",
716 check->corruptions_fixed);
719 ret = collect_image_check(bs, check, filename, fmt, 0);
721 check->leaks_fixed = leaks_fixed;
722 check->corruptions_fixed = corruptions_fixed;
726 switch (output_format) {
728 dump_human_image_check(check, quiet);
731 dump_json_image_check(check, quiet);
736 if (ret || check->check_errors) {
738 error_report("Check failed: %s", strerror(-ret));
740 error_report("Check failed");
746 if (check->corruptions) {
748 } else if (check->leaks) {
755 qapi_free_ImageCheck(check);
760 typedef struct CommonBlockJobCBInfo {
761 BlockDriverState *bs;
763 } CommonBlockJobCBInfo;
765 static void common_block_job_cb(void *opaque, int ret)
767 CommonBlockJobCBInfo *cbi = opaque;
770 error_setg_errno(cbi->errp, -ret, "Block job failed");
774 static void run_block_job(BlockJob *job, Error **errp)
776 AioContext *aio_context = bdrv_get_aio_context(job->bs);
779 aio_poll(aio_context, true);
780 qemu_progress_print(job->len ?
781 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
782 } while (!job->ready);
784 block_job_complete_sync(job, errp);
786 /* A block job may finish instantaneously without publishing any progress,
787 * so just signal completion here */
788 qemu_progress_print(100.f, 0);
791 static int img_commit(int argc, char **argv)
794 const char *filename, *fmt, *cache, *base;
796 BlockDriverState *bs, *base_bs;
797 bool progress = false, quiet = false, drop = false;
798 Error *local_err = NULL;
799 CommonBlockJobCBInfo cbi;
800 bool image_opts = false;
803 cache = BDRV_DEFAULT_CACHE;
806 static const struct option long_options[] = {
807 {"help", no_argument, 0, 'h'},
808 {"object", required_argument, 0, OPTION_OBJECT},
809 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
812 c = getopt_long(argc, argv, "f:ht:b:dpq",
842 case OPTION_OBJECT: {
844 opts = qemu_opts_parse_noisily(&qemu_object_opts,
850 case OPTION_IMAGE_OPTS:
856 /* Progress is not shown in Quiet mode */
861 if (optind != argc - 1) {
862 error_exit("Expecting one image file name");
864 filename = argv[optind++];
866 if (qemu_opts_foreach(&qemu_object_opts,
867 user_creatable_add_opts_foreach,
869 error_report_err(local_err);
873 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
874 ret = bdrv_parse_cache_flags(cache, &flags);
876 error_report("Invalid cache option: %s", cache);
880 blk = img_open(image_opts, filename, fmt, flags, true, quiet);
886 qemu_progress_init(progress, 1.f);
887 qemu_progress_print(0.f, 100);
890 base_bs = bdrv_find_backing_image(bs, base);
892 error_setg(&local_err, QERR_BASE_NOT_FOUND, base);
896 /* This is different from QMP, which by default uses the deepest file in
897 * the backing chain (i.e., the very base); however, the traditional
898 * behavior of qemu-img commit is using the immediate backing file. */
899 base_bs = backing_bs(bs);
901 error_setg(&local_err, "Image does not have a backing file");
906 cbi = (CommonBlockJobCBInfo){
911 commit_active_start(bs, base_bs, 0, BLOCKDEV_ON_ERROR_REPORT,
912 common_block_job_cb, &cbi, &local_err);
917 /* When the block job completes, the BlockBackend reference will point to
918 * the old backing file. In order to avoid that the top image is already
919 * deleted, so we can still empty it afterwards, increment the reference
920 * counter here preemptively. */
925 run_block_job(bs->job, &local_err);
930 if (!drop && bs->drv->bdrv_make_empty) {
931 ret = bs->drv->bdrv_make_empty(bs);
933 error_setg_errno(&local_err, -ret, "Could not empty %s",
950 error_report_err(local_err);
954 qprintf(quiet, "Image committed.\n");
959 * Returns true iff the first sector pointed to by 'buf' contains at least
962 * 'pnum' is set to the number of sectors (including and immediately following
963 * the first one) that are known to be in the same allocated/unallocated state.
965 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
974 is_zero = buffer_is_zero(buf, 512);
975 for(i = 1; i < n; i++) {
977 if (is_zero != buffer_is_zero(buf, 512)) {
986 * Like is_allocated_sectors, but if the buffer starts with a used sector,
987 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
988 * breaking up write requests for only small sparse areas.
990 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
994 int num_checked, num_used;
1000 ret = is_allocated_sectors(buf, n, pnum);
1006 buf += BDRV_SECTOR_SIZE * *pnum;
1008 num_checked = num_used;
1011 ret = is_allocated_sectors(buf, n, pnum);
1013 buf += BDRV_SECTOR_SIZE * *pnum;
1015 num_checked += *pnum;
1017 num_used = num_checked;
1018 } else if (*pnum >= min) {
1028 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1029 * buffers matches, non-zero otherwise.
1031 * pnum is set to the number of sectors (including and immediately following
1032 * the first one) that are known to have the same comparison result
1034 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1045 res = !!memcmp(buf1, buf2, 512);
1046 for(i = 1; i < n; i++) {
1050 if (!!memcmp(buf1, buf2, 512) != res) {
1059 #define IO_BUF_SIZE (2 * 1024 * 1024)
1061 static int64_t sectors_to_bytes(int64_t sectors)
1063 return sectors << BDRV_SECTOR_BITS;
1066 static int64_t sectors_to_process(int64_t total, int64_t from)
1068 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1072 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1074 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1075 * data and negative value on error.
1077 * @param blk: BlockBackend for the image
1078 * @param sect_num: Number of first sector to check
1079 * @param sect_count: Number of sectors to check
1080 * @param filename: Name of disk file we are checking (logging purpose)
1081 * @param buffer: Allocated buffer for storing read data
1082 * @param quiet: Flag for quiet mode
1084 static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
1085 int sect_count, const char *filename,
1086 uint8_t *buffer, bool quiet)
1089 ret = blk_read(blk, sect_num, buffer, sect_count);
1091 error_report("Error while reading offset %" PRId64 " of %s: %s",
1092 sectors_to_bytes(sect_num), filename, strerror(-ret));
1095 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1096 if (ret || pnum != sect_count) {
1097 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1098 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1106 * Compares two images. Exit codes:
1108 * 0 - Images are identical
1110 * >1 - Error occurred
1112 static int img_compare(int argc, char **argv)
1114 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1115 BlockBackend *blk1, *blk2;
1116 BlockDriverState *bs1, *bs2;
1117 int64_t total_sectors1, total_sectors2;
1118 uint8_t *buf1 = NULL, *buf2 = NULL;
1120 int allocated1, allocated2;
1121 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1122 bool progress = false, quiet = false, strict = false;
1124 int64_t total_sectors;
1125 int64_t sector_num = 0;
1128 uint64_t progress_base;
1129 Error *local_err = NULL;
1130 bool image_opts = false;
1132 cache = BDRV_DEFAULT_CACHE;
1134 static const struct option long_options[] = {
1135 {"help", no_argument, 0, 'h'},
1136 {"object", required_argument, 0, OPTION_OBJECT},
1137 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1140 c = getopt_long(argc, argv, "hf:F:T:pqs",
1141 long_options, NULL);
1168 case OPTION_OBJECT: {
1170 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1177 case OPTION_IMAGE_OPTS:
1183 /* Progress is not shown in Quiet mode */
1189 if (optind != argc - 2) {
1190 error_exit("Expecting two image file names");
1192 filename1 = argv[optind++];
1193 filename2 = argv[optind++];
1195 if (qemu_opts_foreach(&qemu_object_opts,
1196 user_creatable_add_opts_foreach,
1197 NULL, &local_err)) {
1198 error_report_err(local_err);
1203 /* Initialize before goto out */
1204 qemu_progress_init(progress, 2.0);
1206 flags = BDRV_O_FLAGS;
1207 ret = bdrv_parse_cache_flags(cache, &flags);
1209 error_report("Invalid source cache option: %s", cache);
1214 blk1 = img_open(image_opts, filename1, fmt1, flags, true, quiet);
1220 blk2 = img_open(image_opts, filename2, fmt2, flags, true, quiet);
1228 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1229 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1230 total_sectors1 = blk_nb_sectors(blk1);
1231 if (total_sectors1 < 0) {
1232 error_report("Can't get size of %s: %s",
1233 filename1, strerror(-total_sectors1));
1237 total_sectors2 = blk_nb_sectors(blk2);
1238 if (total_sectors2 < 0) {
1239 error_report("Can't get size of %s: %s",
1240 filename2, strerror(-total_sectors2));
1244 total_sectors = MIN(total_sectors1, total_sectors2);
1245 progress_base = MAX(total_sectors1, total_sectors2);
1247 qemu_progress_print(0, 100);
1249 if (strict && total_sectors1 != total_sectors2) {
1251 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1256 int64_t status1, status2;
1257 BlockDriverState *file;
1259 nb_sectors = sectors_to_process(total_sectors, sector_num);
1260 if (nb_sectors <= 0) {
1263 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1264 total_sectors1 - sector_num,
1268 error_report("Sector allocation test failed for %s", filename1);
1271 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1273 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1274 total_sectors2 - sector_num,
1278 error_report("Sector allocation test failed for %s", filename2);
1281 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1283 nb_sectors = MIN(nb_sectors, pnum1);
1286 nb_sectors = MIN(nb_sectors, pnum2);
1290 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1291 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1293 qprintf(quiet, "Strict mode: Offset %" PRId64
1294 " block status mismatch!\n",
1295 sectors_to_bytes(sector_num));
1299 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1300 nb_sectors = MIN(pnum1, pnum2);
1301 } else if (allocated1 == allocated2) {
1303 ret = blk_read(blk1, sector_num, buf1, nb_sectors);
1305 error_report("Error while reading offset %" PRId64 " of %s:"
1306 " %s", sectors_to_bytes(sector_num), filename1,
1311 ret = blk_read(blk2, sector_num, buf2, nb_sectors);
1313 error_report("Error while reading offset %" PRId64
1314 " of %s: %s", sectors_to_bytes(sector_num),
1315 filename2, strerror(-ret));
1319 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1320 if (ret || pnum != nb_sectors) {
1321 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1323 ret ? sector_num : sector_num + pnum));
1331 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
1332 filename1, buf1, quiet);
1334 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
1335 filename2, buf1, quiet);
1339 error_report("Error while reading offset %" PRId64 ": %s",
1340 sectors_to_bytes(sector_num), strerror(-ret));
1346 sector_num += nb_sectors;
1347 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1350 if (total_sectors1 != total_sectors2) {
1351 BlockBackend *blk_over;
1352 int64_t total_sectors_over;
1353 const char *filename_over;
1355 qprintf(quiet, "Warning: Image size mismatch!\n");
1356 if (total_sectors1 > total_sectors2) {
1357 total_sectors_over = total_sectors1;
1359 filename_over = filename1;
1361 total_sectors_over = total_sectors2;
1363 filename_over = filename2;
1367 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1368 if (nb_sectors <= 0) {
1371 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,
1375 error_report("Sector allocation test failed for %s",
1382 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
1383 filename_over, buf1, quiet);
1386 error_report("Error while reading offset %" PRId64
1387 " of %s: %s", sectors_to_bytes(sector_num),
1388 filename_over, strerror(-ret));
1394 sector_num += nb_sectors;
1395 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1399 qprintf(quiet, "Images are identical.\n");
1409 qemu_progress_end();
1414 enum ImgConvertBlockStatus {
1420 typedef struct ImgConvertState {
1422 int64_t *src_sectors;
1423 int src_cur, src_num;
1424 int64_t src_cur_offset;
1425 int64_t total_sectors;
1426 int64_t allocated_sectors;
1427 enum ImgConvertBlockStatus status;
1428 int64_t sector_next_status;
1429 BlockBackend *target;
1432 bool target_has_backing;
1434 size_t cluster_sectors;
1438 static void convert_select_part(ImgConvertState *s, int64_t sector_num)
1440 assert(sector_num >= s->src_cur_offset);
1441 while (sector_num - s->src_cur_offset >= s->src_sectors[s->src_cur]) {
1442 s->src_cur_offset += s->src_sectors[s->src_cur];
1444 assert(s->src_cur < s->src_num);
1448 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1453 convert_select_part(s, sector_num);
1455 assert(s->total_sectors > sector_num);
1456 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1458 if (s->sector_next_status <= sector_num) {
1459 BlockDriverState *file;
1460 ret = bdrv_get_block_status(blk_bs(s->src[s->src_cur]),
1461 sector_num - s->src_cur_offset,
1467 if (ret & BDRV_BLOCK_ZERO) {
1468 s->status = BLK_ZERO;
1469 } else if (ret & BDRV_BLOCK_DATA) {
1470 s->status = BLK_DATA;
1471 } else if (!s->target_has_backing) {
1472 /* Without a target backing file we must copy over the contents of
1473 * the backing file as well. */
1474 /* TODO Check block status of the backing file chain to avoid
1475 * needlessly reading zeroes and limiting the iteration to the
1477 s->status = BLK_DATA;
1479 s->status = BLK_BACKING_FILE;
1482 s->sector_next_status = sector_num + n;
1485 n = MIN(n, s->sector_next_status - sector_num);
1486 if (s->status == BLK_DATA) {
1487 n = MIN(n, s->buf_sectors);
1490 /* We need to write complete clusters for compressed images, so if an
1491 * unallocated area is shorter than that, we must consider the whole
1492 * cluster allocated. */
1493 if (s->compressed) {
1494 if (n < s->cluster_sectors) {
1495 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1496 s->status = BLK_DATA;
1498 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1505 static int convert_read(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1511 if (s->status == BLK_ZERO || s->status == BLK_BACKING_FILE) {
1515 assert(nb_sectors <= s->buf_sectors);
1516 while (nb_sectors > 0) {
1520 /* In the case of compression with multiple source files, we can get a
1521 * nb_sectors that spreads into the next part. So we must be able to
1522 * read across multiple BDSes for one convert_read() call. */
1523 convert_select_part(s, sector_num);
1524 blk = s->src[s->src_cur];
1525 bs_sectors = s->src_sectors[s->src_cur];
1527 n = MIN(nb_sectors, bs_sectors - (sector_num - s->src_cur_offset));
1528 ret = blk_read(blk, sector_num - s->src_cur_offset, buf, n);
1535 buf += n * BDRV_SECTOR_SIZE;
1541 static int convert_write(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1546 while (nb_sectors > 0) {
1549 switch (s->status) {
1550 case BLK_BACKING_FILE:
1551 /* If we have a backing file, leave clusters unallocated that are
1552 * unallocated in the source image, so that the backing file is
1553 * visible at the respective offset. */
1554 assert(s->target_has_backing);
1558 /* We must always write compressed clusters as a whole, so don't
1559 * try to find zeroed parts in the buffer. We can only save the
1560 * write if the buffer is completely zeroed and we're allowed to
1561 * keep the target sparse. */
1562 if (s->compressed) {
1563 if (s->has_zero_init && s->min_sparse &&
1564 buffer_is_zero(buf, n * BDRV_SECTOR_SIZE))
1566 assert(!s->target_has_backing);
1570 ret = blk_write_compressed(s->target, sector_num, buf, n);
1577 /* If there is real non-zero data or we're told to keep the target
1578 * fully allocated (-S 0), we must write it. Otherwise we can treat
1579 * it as zero sectors. */
1580 if (!s->min_sparse ||
1581 is_allocated_sectors_min(buf, n, &n, s->min_sparse))
1583 ret = blk_write(s->target, sector_num, buf, n);
1592 if (s->has_zero_init) {
1595 ret = blk_write_zeroes(s->target, sector_num, n, 0);
1604 buf += n * BDRV_SECTOR_SIZE;
1610 static int convert_do_copy(ImgConvertState *s)
1612 uint8_t *buf = NULL;
1613 int64_t sector_num, allocated_done;
1617 /* Check whether we have zero initialisation or can get it efficiently */
1618 s->has_zero_init = s->min_sparse && !s->target_has_backing
1619 ? bdrv_has_zero_init(blk_bs(s->target))
1622 if (!s->has_zero_init && !s->target_has_backing &&
1623 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1625 ret = bdrv_make_zero(blk_bs(s->target), BDRV_REQ_MAY_UNMAP);
1627 s->has_zero_init = true;
1631 /* Allocate buffer for copied data. For compressed images, only one cluster
1632 * can be copied at a time. */
1633 if (s->compressed) {
1634 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1635 error_report("invalid cluster size");
1639 s->buf_sectors = s->cluster_sectors;
1641 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1643 /* Calculate allocated sectors for progress */
1644 s->allocated_sectors = 0;
1646 while (sector_num < s->total_sectors) {
1647 n = convert_iteration_sectors(s, sector_num);
1652 if (s->status == BLK_DATA) {
1653 s->allocated_sectors += n;
1660 s->src_cur_offset = 0;
1661 s->sector_next_status = 0;
1666 while (sector_num < s->total_sectors) {
1667 n = convert_iteration_sectors(s, sector_num);
1672 if (s->status == BLK_DATA) {
1673 allocated_done += n;
1674 qemu_progress_print(100.0 * allocated_done / s->allocated_sectors,
1678 ret = convert_read(s, sector_num, n, buf);
1680 error_report("error while reading sector %" PRId64
1681 ": %s", sector_num, strerror(-ret));
1685 ret = convert_write(s, sector_num, n, buf);
1687 error_report("error while writing sector %" PRId64
1688 ": %s", sector_num, strerror(-ret));
1695 if (s->compressed) {
1696 /* signal EOF to align */
1697 ret = blk_write_compressed(s->target, 0, NULL, 0);
1709 static int img_convert(int argc, char **argv)
1711 int c, bs_n, bs_i, compress, cluster_sectors, skip_create;
1713 int progress = 0, flags, src_flags;
1714 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
1715 BlockDriver *drv, *proto_drv;
1716 BlockBackend **blk = NULL, *out_blk = NULL;
1717 BlockDriverState **bs = NULL, *out_bs = NULL;
1718 int64_t total_sectors;
1719 int64_t *bs_sectors = NULL;
1720 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
1721 BlockDriverInfo bdi;
1722 QemuOpts *opts = NULL;
1723 QemuOptsList *create_opts = NULL;
1724 const char *out_baseimg_param;
1725 char *options = NULL;
1726 const char *snapshot_name = NULL;
1727 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
1729 Error *local_err = NULL;
1730 QemuOpts *sn_opts = NULL;
1731 ImgConvertState state;
1732 bool image_opts = false;
1737 src_cache = BDRV_DEFAULT_CACHE;
1742 static const struct option long_options[] = {
1743 {"help", no_argument, 0, 'h'},
1744 {"object", required_argument, 0, OPTION_OBJECT},
1745 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1748 c = getopt_long(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn",
1749 long_options, NULL);
1765 out_baseimg = optarg;
1771 error_report("option -e is deprecated, please use \'-o "
1772 "encryption\' instead!");
1776 error_report("option -6 is deprecated, please use \'-o "
1777 "compat6\' instead!");
1781 if (!is_valid_option_list(optarg)) {
1782 error_report("Invalid option list: %s", optarg);
1787 options = g_strdup(optarg);
1789 char *old_options = options;
1790 options = g_strdup_printf("%s,%s", options, optarg);
1791 g_free(old_options);
1795 snapshot_name = optarg;
1798 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1799 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
1802 error_report("Failed in parsing snapshot param '%s'",
1808 snapshot_name = optarg;
1815 sval = qemu_strtosz_suffix(optarg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
1816 if (sval < 0 || *end) {
1817 error_report("Invalid minimum zero buffer size for sparse output specified");
1822 min_sparse = sval / BDRV_SECTOR_SIZE;
1841 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1847 case OPTION_IMAGE_OPTS:
1853 if (qemu_opts_foreach(&qemu_object_opts,
1854 user_creatable_add_opts_foreach,
1855 NULL, &local_err)) {
1856 error_report_err(local_err);
1860 /* Initialize before goto out */
1864 qemu_progress_init(progress, 1.0);
1866 bs_n = argc - optind - 1;
1867 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
1869 if (options && has_help_option(options)) {
1870 ret = print_block_option_help(out_filename, out_fmt);
1875 error_exit("Must specify image file name");
1879 if (bs_n > 1 && out_baseimg) {
1880 error_report("-B makes no sense when concatenating multiple input "
1886 src_flags = BDRV_O_FLAGS;
1887 ret = bdrv_parse_cache_flags(src_cache, &src_flags);
1889 error_report("Invalid source cache option: %s", src_cache);
1893 qemu_progress_print(0, 100);
1895 blk = g_new0(BlockBackend *, bs_n);
1896 bs = g_new0(BlockDriverState *, bs_n);
1897 bs_sectors = g_new(int64_t, bs_n);
1900 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1901 blk[bs_i] = img_open(image_opts, argv[optind + bs_i],
1902 fmt, src_flags, true, quiet);
1907 bs[bs_i] = blk_bs(blk[bs_i]);
1908 bs_sectors[bs_i] = blk_nb_sectors(blk[bs_i]);
1909 if (bs_sectors[bs_i] < 0) {
1910 error_report("Could not get size of %s: %s",
1911 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1915 total_sectors += bs_sectors[bs_i];
1919 ret = bdrv_snapshot_load_tmp(bs[0],
1920 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1921 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1923 } else if (snapshot_name != NULL) {
1925 error_report("No support for concatenating multiple snapshot");
1930 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
1933 error_reportf_err(local_err, "Failed to load snapshot: ");
1938 /* Find driver and parse its options */
1939 drv = bdrv_find_format(out_fmt);
1941 error_report("Unknown file format '%s'", out_fmt);
1946 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
1948 error_report_err(local_err);
1954 if (!drv->create_opts) {
1955 error_report("Format driver '%s' does not support image creation",
1961 if (!proto_drv->create_opts) {
1962 error_report("Protocol driver '%s' does not support image creation",
1963 proto_drv->format_name);
1968 create_opts = qemu_opts_append(create_opts, drv->create_opts);
1969 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
1971 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
1973 qemu_opts_do_parse(opts, options, NULL, &local_err);
1975 error_report_err(local_err);
1981 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512,
1983 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
1989 /* Get backing file name if -o backing_file was used */
1990 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
1991 if (out_baseimg_param) {
1992 out_baseimg = out_baseimg_param;
1995 /* Check if compression is supported */
1998 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
1999 const char *preallocation =
2000 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2002 if (!drv->bdrv_write_compressed) {
2003 error_report("Compression not supported for this file format");
2009 error_report("Compression and encryption not supported at "
2016 && strcmp(preallocation, "off"))
2018 error_report("Compression and preallocation not supported at "
2026 /* Create the new image */
2027 ret = bdrv_create(drv, out_filename, opts, &local_err);
2029 error_reportf_err(local_err, "%s: error while converting %s: ",
2030 out_filename, out_fmt);
2035 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2036 ret = bdrv_parse_cache_flags(cache, &flags);
2038 error_report("Invalid cache option: %s", cache);
2042 /* XXX we should allow --image-opts to trigger use of
2043 * img_open() here, but then we have trouble with
2044 * the bdrv_create() call which takes different params.
2045 * Not critical right now, so fix can wait...
2047 out_blk = img_open_file(out_filename, out_fmt, flags, true, quiet);
2052 out_bs = blk_bs(out_blk);
2054 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
2055 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2057 bufsectors = MIN(32768,
2058 MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
2059 out_bs->bl.discard_alignment))
2063 int64_t output_sectors = blk_nb_sectors(out_blk);
2064 if (output_sectors < 0) {
2065 error_report("unable to get output image length: %s",
2066 strerror(-output_sectors));
2069 } else if (output_sectors < total_sectors) {
2070 error_report("output file is smaller than input file");
2076 cluster_sectors = 0;
2077 ret = bdrv_get_info(out_bs, &bdi);
2080 error_report("could not get block driver info");
2084 compress = compress || bdi.needs_compressed_writes;
2085 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2088 state = (ImgConvertState) {
2090 .src_sectors = bs_sectors,
2092 .total_sectors = total_sectors,
2094 .compressed = compress,
2095 .target_has_backing = (bool) out_baseimg,
2096 .min_sparse = min_sparse,
2097 .cluster_sectors = cluster_sectors,
2098 .buf_sectors = bufsectors,
2100 ret = convert_do_copy(&state);
2104 qemu_progress_print(100, 0);
2106 qemu_progress_end();
2107 qemu_opts_del(opts);
2108 qemu_opts_free(create_opts);
2109 qemu_opts_del(sn_opts);
2113 for (bs_i = 0; bs_i < bs_n; bs_i++) {
2114 blk_unref(blk[bs_i]);
2129 static void dump_snapshots(BlockDriverState *bs)
2131 QEMUSnapshotInfo *sn_tab, *sn;
2134 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2137 printf("Snapshot list:\n");
2138 bdrv_snapshot_dump(fprintf, stdout, NULL);
2140 for(i = 0; i < nb_sns; i++) {
2142 bdrv_snapshot_dump(fprintf, stdout, sn);
2148 static void dump_json_image_info_list(ImageInfoList *list)
2150 Error *local_err = NULL;
2152 QmpOutputVisitor *ov = qmp_output_visitor_new();
2154 visit_type_ImageInfoList(qmp_output_get_visitor(ov), NULL, &list,
2156 obj = qmp_output_get_qobject(ov);
2157 str = qobject_to_json_pretty(obj);
2158 assert(str != NULL);
2159 printf("%s\n", qstring_get_str(str));
2160 qobject_decref(obj);
2161 qmp_output_visitor_cleanup(ov);
2165 static void dump_json_image_info(ImageInfo *info)
2167 Error *local_err = NULL;
2169 QmpOutputVisitor *ov = qmp_output_visitor_new();
2171 visit_type_ImageInfo(qmp_output_get_visitor(ov), NULL, &info, &local_err);
2172 obj = qmp_output_get_qobject(ov);
2173 str = qobject_to_json_pretty(obj);
2174 assert(str != NULL);
2175 printf("%s\n", qstring_get_str(str));
2176 qobject_decref(obj);
2177 qmp_output_visitor_cleanup(ov);
2181 static void dump_human_image_info_list(ImageInfoList *list)
2183 ImageInfoList *elem;
2186 for (elem = list; elem; elem = elem->next) {
2192 bdrv_image_info_dump(fprintf, stdout, elem->value);
2196 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2198 return strcmp(a, b) == 0;
2202 * Open an image file chain and return an ImageInfoList
2204 * @filename: topmost image filename
2205 * @fmt: topmost image format (may be NULL to autodetect)
2206 * @chain: true - enumerate entire backing file chain
2207 * false - only topmost image file
2209 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2210 * image file. If there was an error a message will have been printed to
2213 static ImageInfoList *collect_image_info_list(bool image_opts,
2214 const char *filename,
2218 ImageInfoList *head = NULL;
2219 ImageInfoList **last = &head;
2220 GHashTable *filenames;
2223 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2227 BlockDriverState *bs;
2229 ImageInfoList *elem;
2231 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2232 error_report("Backing file '%s' creates an infinite loop.",
2236 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2238 blk = img_open(image_opts, filename, fmt,
2239 BDRV_O_FLAGS | BDRV_O_NO_BACKING,
2246 bdrv_query_image_info(bs, &info, &err);
2248 error_report_err(err);
2253 elem = g_new0(ImageInfoList, 1);
2260 filename = fmt = NULL;
2262 if (info->has_full_backing_filename) {
2263 filename = info->full_backing_filename;
2264 } else if (info->has_backing_filename) {
2265 error_report("Could not determine absolute backing filename,"
2266 " but backing filename '%s' present",
2267 info->backing_filename);
2270 if (info->has_backing_filename_format) {
2271 fmt = info->backing_filename_format;
2275 g_hash_table_destroy(filenames);
2279 qapi_free_ImageInfoList(head);
2280 g_hash_table_destroy(filenames);
2284 static int img_info(int argc, char **argv)
2287 OutputFormat output_format = OFORMAT_HUMAN;
2289 const char *filename, *fmt, *output;
2290 ImageInfoList *list;
2291 Error *local_err = NULL;
2292 bool image_opts = false;
2297 int option_index = 0;
2298 static const struct option long_options[] = {
2299 {"help", no_argument, 0, 'h'},
2300 {"format", required_argument, 0, 'f'},
2301 {"output", required_argument, 0, OPTION_OUTPUT},
2302 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2303 {"object", required_argument, 0, OPTION_OBJECT},
2304 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2307 c = getopt_long(argc, argv, "f:h",
2308 long_options, &option_index);
2323 case OPTION_BACKING_CHAIN:
2326 case OPTION_OBJECT: {
2328 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2334 case OPTION_IMAGE_OPTS:
2339 if (optind != argc - 1) {
2340 error_exit("Expecting one image file name");
2342 filename = argv[optind++];
2344 if (output && !strcmp(output, "json")) {
2345 output_format = OFORMAT_JSON;
2346 } else if (output && !strcmp(output, "human")) {
2347 output_format = OFORMAT_HUMAN;
2348 } else if (output) {
2349 error_report("--output must be used with human or json as argument.");
2353 if (qemu_opts_foreach(&qemu_object_opts,
2354 user_creatable_add_opts_foreach,
2355 NULL, &local_err)) {
2356 error_report_err(local_err);
2360 list = collect_image_info_list(image_opts, filename, fmt, chain);
2365 switch (output_format) {
2367 dump_human_image_info_list(list);
2371 dump_json_image_info_list(list);
2373 dump_json_image_info(list->value);
2378 qapi_free_ImageInfoList(list);
2382 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2385 switch (output_format) {
2387 if (e->data && !e->has_offset) {
2388 error_report("File contains external, encrypted or compressed clusters.");
2391 if (e->data && !e->zero) {
2392 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2393 e->start, e->length,
2394 e->has_offset ? e->offset : 0,
2395 e->has_filename ? e->filename : "");
2397 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2398 * Modify the flags here to allow more coalescing.
2400 if (next && (!next->data || next->zero)) {
2406 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2407 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2408 (e->start == 0 ? "[" : ",\n"),
2409 e->start, e->length, e->depth,
2410 e->zero ? "true" : "false",
2411 e->data ? "true" : "false");
2412 if (e->has_offset) {
2413 printf(", \"offset\": %"PRId64"", e->offset);
2424 static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2425 int nb_sectors, MapEntry *e)
2429 BlockDriverState *file;
2432 /* As an optimization, we could cache the current range of unallocated
2433 * clusters in each file of the chain, and avoid querying the same
2439 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2445 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2448 bs = backing_bs(bs);
2457 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2460 .start = sector_num * BDRV_SECTOR_SIZE,
2461 .length = nb_sectors * BDRV_SECTOR_SIZE,
2462 .data = !!(ret & BDRV_BLOCK_DATA),
2463 .zero = !!(ret & BDRV_BLOCK_ZERO),
2464 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2465 .has_offset = has_offset,
2467 .has_filename = file && has_offset,
2468 .filename = file && has_offset ? file->filename : NULL,
2474 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2476 if (curr->length == 0) {
2479 if (curr->zero != next->zero ||
2480 curr->data != next->data ||
2481 curr->depth != next->depth ||
2482 curr->has_filename != next->has_filename ||
2483 curr->has_offset != next->has_offset) {
2486 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2489 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2495 static int img_map(int argc, char **argv)
2498 OutputFormat output_format = OFORMAT_HUMAN;
2500 BlockDriverState *bs;
2501 const char *filename, *fmt, *output;
2503 MapEntry curr = { .length = 0 }, next;
2505 Error *local_err = NULL;
2506 bool image_opts = false;
2511 int option_index = 0;
2512 static const struct option long_options[] = {
2513 {"help", no_argument, 0, 'h'},
2514 {"format", required_argument, 0, 'f'},
2515 {"output", required_argument, 0, OPTION_OUTPUT},
2516 {"object", required_argument, 0, OPTION_OBJECT},
2517 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2520 c = getopt_long(argc, argv, "f:h",
2521 long_options, &option_index);
2536 case OPTION_OBJECT: {
2538 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2544 case OPTION_IMAGE_OPTS:
2549 if (optind != argc - 1) {
2550 error_exit("Expecting one image file name");
2552 filename = argv[optind];
2554 if (output && !strcmp(output, "json")) {
2555 output_format = OFORMAT_JSON;
2556 } else if (output && !strcmp(output, "human")) {
2557 output_format = OFORMAT_HUMAN;
2558 } else if (output) {
2559 error_report("--output must be used with human or json as argument.");
2563 if (qemu_opts_foreach(&qemu_object_opts,
2564 user_creatable_add_opts_foreach,
2565 NULL, &local_err)) {
2566 error_report_err(local_err);
2570 blk = img_open(image_opts, filename, fmt, BDRV_O_FLAGS, true, false);
2576 if (output_format == OFORMAT_HUMAN) {
2577 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2580 length = blk_getlength(blk);
2581 while (curr.start + curr.length < length) {
2582 int64_t nsectors_left;
2586 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2588 /* Probe up to 1 GiB at a time. */
2589 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2590 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2591 ret = get_block_status(bs, sector_num, n, &next);
2594 error_report("Could not read file metadata: %s", strerror(-ret));
2598 if (entry_mergeable(&curr, &next)) {
2599 curr.length += next.length;
2603 if (curr.length > 0) {
2604 dump_map_entry(output_format, &curr, &next);
2609 dump_map_entry(output_format, &curr, NULL);
2616 #define SNAPSHOT_LIST 1
2617 #define SNAPSHOT_CREATE 2
2618 #define SNAPSHOT_APPLY 3
2619 #define SNAPSHOT_DELETE 4
2621 static int img_snapshot(int argc, char **argv)
2624 BlockDriverState *bs;
2625 QEMUSnapshotInfo sn;
2626 char *filename, *snapshot_name = NULL;
2627 int c, ret = 0, bdrv_oflags;
2632 bool image_opts = false;
2634 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
2635 /* Parse commandline parameters */
2637 static const struct option long_options[] = {
2638 {"help", no_argument, 0, 'h'},
2639 {"object", required_argument, 0, OPTION_OBJECT},
2640 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2643 c = getopt_long(argc, argv, "la:c:d:hq",
2644 long_options, NULL);
2655 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2658 action = SNAPSHOT_LIST;
2659 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
2663 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2666 action = SNAPSHOT_APPLY;
2667 snapshot_name = optarg;
2671 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2674 action = SNAPSHOT_CREATE;
2675 snapshot_name = optarg;
2679 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2682 action = SNAPSHOT_DELETE;
2683 snapshot_name = optarg;
2688 case OPTION_OBJECT: {
2690 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2696 case OPTION_IMAGE_OPTS:
2702 if (optind != argc - 1) {
2703 error_exit("Expecting one image file name");
2705 filename = argv[optind++];
2707 if (qemu_opts_foreach(&qemu_object_opts,
2708 user_creatable_add_opts_foreach,
2710 error_report_err(err);
2714 /* Open the image */
2715 blk = img_open(image_opts, filename, NULL, bdrv_oflags, true, quiet);
2721 /* Perform the requested action */
2727 case SNAPSHOT_CREATE:
2728 memset(&sn, 0, sizeof(sn));
2729 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2731 qemu_gettimeofday(&tv);
2732 sn.date_sec = tv.tv_sec;
2733 sn.date_nsec = tv.tv_usec * 1000;
2735 ret = bdrv_snapshot_create(bs, &sn);
2737 error_report("Could not create snapshot '%s': %d (%s)",
2738 snapshot_name, ret, strerror(-ret));
2742 case SNAPSHOT_APPLY:
2743 ret = bdrv_snapshot_goto(bs, snapshot_name);
2745 error_report("Could not apply snapshot '%s': %d (%s)",
2746 snapshot_name, ret, strerror(-ret));
2750 case SNAPSHOT_DELETE:
2751 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
2753 error_reportf_err(err, "Could not delete snapshot '%s': ",
2768 static int img_rebase(int argc, char **argv)
2770 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
2771 uint8_t *buf_old = NULL;
2772 uint8_t *buf_new = NULL;
2773 BlockDriverState *bs = NULL;
2775 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2776 int c, flags, src_flags, ret;
2780 Error *local_err = NULL;
2781 bool image_opts = false;
2783 /* Parse commandline parameters */
2785 cache = BDRV_DEFAULT_CACHE;
2786 src_cache = BDRV_DEFAULT_CACHE;
2790 static const struct option long_options[] = {
2791 {"help", no_argument, 0, 'h'},
2792 {"object", required_argument, 0, OPTION_OBJECT},
2793 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2796 c = getopt_long(argc, argv, "hf:F:b:upt:T:q",
2797 long_options, NULL);
2810 out_basefmt = optarg;
2813 out_baseimg = optarg;
2830 case OPTION_OBJECT: {
2832 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2838 case OPTION_IMAGE_OPTS:
2848 if (optind != argc - 1) {
2849 error_exit("Expecting one image file name");
2851 if (!unsafe && !out_baseimg) {
2852 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
2854 filename = argv[optind++];
2856 if (qemu_opts_foreach(&qemu_object_opts,
2857 user_creatable_add_opts_foreach,
2858 NULL, &local_err)) {
2859 error_report_err(local_err);
2863 qemu_progress_init(progress, 2.0);
2864 qemu_progress_print(0, 100);
2866 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
2867 ret = bdrv_parse_cache_flags(cache, &flags);
2869 error_report("Invalid cache option: %s", cache);
2873 src_flags = BDRV_O_FLAGS;
2874 ret = bdrv_parse_cache_flags(src_cache, &src_flags);
2876 error_report("Invalid source cache option: %s", src_cache);
2883 * Ignore the old backing file for unsafe rebase in case we want to correct
2884 * the reference to a renamed or moved backing file.
2886 blk = img_open(image_opts, filename, fmt, flags, true, quiet);
2893 if (out_basefmt != NULL) {
2894 if (bdrv_find_format(out_basefmt) == NULL) {
2895 error_report("Invalid format name: '%s'", out_basefmt);
2901 /* For safe rebasing we need to compare old and new backing file */
2903 char backing_name[PATH_MAX];
2904 QDict *options = NULL;
2906 if (bs->backing_format[0] != '\0') {
2907 options = qdict_new();
2908 qdict_put(options, "driver", qstring_from_str(bs->backing_format));
2911 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2912 blk_old_backing = blk_new_open(backing_name, NULL,
2913 options, src_flags, &local_err);
2914 if (!blk_old_backing) {
2915 error_reportf_err(local_err,
2916 "Could not open old backing file '%s': ",
2921 if (out_baseimg[0]) {
2923 options = qdict_new();
2924 qdict_put(options, "driver", qstring_from_str(out_basefmt));
2929 blk_new_backing = blk_new_open(out_baseimg, NULL,
2930 options, src_flags, &local_err);
2931 if (!blk_new_backing) {
2932 error_reportf_err(local_err,
2933 "Could not open new backing file '%s': ",
2941 * Check each unallocated cluster in the COW file. If it is unallocated,
2942 * accesses go to the backing file. We must therefore compare this cluster
2943 * in the old and new backing file, and if they differ we need to copy it
2944 * from the old backing file into the COW file.
2946 * If qemu-img crashes during this step, no harm is done. The content of
2947 * the image is the same as the original one at any time.
2950 int64_t num_sectors;
2951 int64_t old_backing_num_sectors;
2952 int64_t new_backing_num_sectors = 0;
2955 float local_progress = 0;
2957 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
2958 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
2960 num_sectors = blk_nb_sectors(blk);
2961 if (num_sectors < 0) {
2962 error_report("Could not get size of '%s': %s",
2963 filename, strerror(-num_sectors));
2967 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
2968 if (old_backing_num_sectors < 0) {
2969 char backing_name[PATH_MAX];
2971 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2972 error_report("Could not get size of '%s': %s",
2973 backing_name, strerror(-old_backing_num_sectors));
2977 if (blk_new_backing) {
2978 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
2979 if (new_backing_num_sectors < 0) {
2980 error_report("Could not get size of '%s': %s",
2981 out_baseimg, strerror(-new_backing_num_sectors));
2987 if (num_sectors != 0) {
2988 local_progress = (float)100 /
2989 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
2992 for (sector = 0; sector < num_sectors; sector += n) {
2994 /* How many sectors can we handle with the next read? */
2995 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
2996 n = (IO_BUF_SIZE / 512);
2998 n = num_sectors - sector;
3001 /* If the cluster is allocated, we don't need to take action */
3002 ret = bdrv_is_allocated(bs, sector, n, &n);
3004 error_report("error while reading image metadata: %s",
3013 * Read old and new backing file and take into consideration that
3014 * backing files may be smaller than the COW image.
3016 if (sector >= old_backing_num_sectors) {
3017 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3019 if (sector + n > old_backing_num_sectors) {
3020 n = old_backing_num_sectors - sector;
3023 ret = blk_read(blk_old_backing, sector, buf_old, n);
3025 error_report("error while reading from old backing file");
3030 if (sector >= new_backing_num_sectors || !blk_new_backing) {
3031 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3033 if (sector + n > new_backing_num_sectors) {
3034 n = new_backing_num_sectors - sector;
3037 ret = blk_read(blk_new_backing, sector, buf_new, n);
3039 error_report("error while reading from new backing file");
3044 /* If they differ, we need to write to the COW file */
3045 uint64_t written = 0;
3047 while (written < n) {
3050 if (compare_sectors(buf_old + written * 512,
3051 buf_new + written * 512, n - written, &pnum))
3053 ret = blk_write(blk, sector + written,
3054 buf_old + written * 512, pnum);
3056 error_report("Error while writing to COW image: %s",
3064 qemu_progress_print(local_progress, 100);
3069 * Change the backing file. All clusters that are different from the old
3070 * backing file are overwritten in the COW file now, so the visible content
3071 * doesn't change when we switch the backing file.
3073 if (out_baseimg && *out_baseimg) {
3074 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3076 ret = bdrv_change_backing_file(bs, NULL, NULL);
3079 if (ret == -ENOSPC) {
3080 error_report("Could not change the backing file to '%s': No "
3081 "space left in the file header", out_baseimg);
3082 } else if (ret < 0) {
3083 error_report("Could not change the backing file to '%s': %s",
3084 out_baseimg, strerror(-ret));
3087 qemu_progress_print(100, 0);
3089 * TODO At this point it is possible to check if any clusters that are
3090 * allocated in the COW file are the same in the backing file. If so, they
3091 * could be dropped from the COW file. Don't do this before switching the
3092 * backing file, in case of a crash this would lead to corruption.
3095 qemu_progress_end();
3098 blk_unref(blk_old_backing);
3099 blk_unref(blk_new_backing);
3101 qemu_vfree(buf_old);
3102 qemu_vfree(buf_new);
3111 static int img_resize(int argc, char **argv)
3114 int c, ret, relative;
3115 const char *filename, *fmt, *size;
3116 int64_t n, total_size;
3118 BlockBackend *blk = NULL;
3120 Error *local_err = NULL;
3122 static QemuOptsList resize_options = {
3123 .name = "resize_options",
3124 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3127 .name = BLOCK_OPT_SIZE,
3128 .type = QEMU_OPT_SIZE,
3129 .help = "Virtual disk size"
3135 bool image_opts = false;
3137 /* Remove size from argv manually so that negative numbers are not treated
3138 * as options by getopt. */
3140 error_exit("Not enough arguments");
3144 size = argv[--argc];
3146 /* Parse getopt arguments */
3149 static const struct option long_options[] = {
3150 {"help", no_argument, 0, 'h'},
3151 {"object", required_argument, 0, OPTION_OBJECT},
3152 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3155 c = getopt_long(argc, argv, "f:hq",
3156 long_options, NULL);
3171 case OPTION_OBJECT: {
3173 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3179 case OPTION_IMAGE_OPTS:
3184 if (optind != argc - 1) {
3185 error_exit("Expecting one image file name");
3187 filename = argv[optind++];
3189 if (qemu_opts_foreach(&qemu_object_opts,
3190 user_creatable_add_opts_foreach,
3191 NULL, &local_err)) {
3192 error_report_err(local_err);
3196 /* Choose grow, shrink, or absolute resize mode */
3212 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3213 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3215 error_report_err(err);
3217 qemu_opts_del(param);
3220 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3221 qemu_opts_del(param);
3223 blk = img_open(image_opts, filename, fmt,
3224 BDRV_O_FLAGS | BDRV_O_RDWR, true, quiet);
3231 total_size = blk_getlength(blk) + n * relative;
3235 if (total_size <= 0) {
3236 error_report("New image size must be positive");
3241 ret = blk_truncate(blk, total_size);
3244 qprintf(quiet, "Image resized.\n");
3247 error_report("This image does not support resize");
3250 error_report("Image is read-only");
3253 error_report("Error resizing image (%d)", -ret);
3264 static void amend_status_cb(BlockDriverState *bs,
3265 int64_t offset, int64_t total_work_size,
3268 qemu_progress_print(100.f * offset / total_work_size, 0);
3271 static int img_amend(int argc, char **argv)
3275 char *options = NULL;
3276 QemuOptsList *create_opts = NULL;
3277 QemuOpts *opts = NULL;
3278 const char *fmt = NULL, *filename, *cache;
3280 bool quiet = false, progress = false;
3281 BlockBackend *blk = NULL;
3282 BlockDriverState *bs = NULL;
3283 Error *local_err = NULL;
3284 bool image_opts = false;
3286 cache = BDRV_DEFAULT_CACHE;
3288 static const struct option long_options[] = {
3289 {"help", no_argument, 0, 'h'},
3290 {"object", required_argument, 0, OPTION_OBJECT},
3291 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3294 c = getopt_long(argc, argv, "ho:f:t:pq",
3295 long_options, NULL);
3306 if (!is_valid_option_list(optarg)) {
3307 error_report("Invalid option list: %s", optarg);
3309 goto out_no_progress;
3312 options = g_strdup(optarg);
3314 char *old_options = options;
3315 options = g_strdup_printf("%s,%s", options, optarg);
3316 g_free(old_options);
3332 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3336 goto out_no_progress;
3339 case OPTION_IMAGE_OPTS:
3346 error_exit("Must specify options (-o)");
3349 if (qemu_opts_foreach(&qemu_object_opts,
3350 user_creatable_add_opts_foreach,
3351 NULL, &local_err)) {
3352 error_report_err(local_err);
3354 goto out_no_progress;
3360 qemu_progress_init(progress, 1.0);
3362 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3363 if (fmt && has_help_option(options)) {
3364 /* If a format is explicitly specified (and possibly no filename is
3365 * given), print option help here */
3366 ret = print_block_option_help(filename, fmt);
3370 if (optind != argc - 1) {
3371 error_report("Expecting one image file name");
3376 flags = BDRV_O_FLAGS | BDRV_O_RDWR;
3377 ret = bdrv_parse_cache_flags(cache, &flags);
3379 error_report("Invalid cache option: %s", cache);
3383 blk = img_open(image_opts, filename, fmt, flags, true, quiet);
3390 fmt = bs->drv->format_name;
3392 if (has_help_option(options)) {
3393 /* If the format was auto-detected, print option help here */
3394 ret = print_block_option_help(filename, fmt);
3398 if (!bs->drv->create_opts) {
3399 error_report("Format driver '%s' does not support any options to amend",
3405 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
3406 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3408 qemu_opts_do_parse(opts, options, NULL, &err);
3410 error_report_err(err);
3416 /* In case the driver does not call amend_status_cb() */
3417 qemu_progress_print(0.f, 0);
3418 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
3419 qemu_progress_print(100.f, 0);
3421 error_report("Error while amending options: %s", strerror(-ret));
3426 qemu_progress_end();
3430 qemu_opts_del(opts);
3431 qemu_opts_free(create_opts);
3440 static const img_cmd_t img_cmds[] = {
3441 #define DEF(option, callback, arg_string) \
3442 { option, callback },
3443 #include "qemu-img-cmds.h"
3449 int main(int argc, char **argv)
3451 const img_cmd_t *cmd;
3452 const char *cmdname;
3453 Error *local_error = NULL;
3455 static const struct option long_options[] = {
3456 {"help", no_argument, 0, 'h'},
3457 {"version", no_argument, 0, 'v'},
3462 signal(SIGPIPE, SIG_IGN);
3465 error_set_progname(argv[0]);
3466 qemu_init_exec_dir(argv[0]);
3468 if (qemu_init_main_loop(&local_error)) {
3469 error_report_err(local_error);
3473 module_call_init(MODULE_INIT_QOM);
3476 error_exit("Not enough arguments");
3480 qemu_add_opts(&qemu_object_opts);
3481 qemu_add_opts(&qemu_source_opts);
3483 /* find the command */
3484 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
3485 if (!strcmp(cmdname, cmd->name)) {
3486 return cmd->handler(argc - 1, argv + 1);
3490 c = getopt_long(argc, argv, "h", long_options, NULL);
3496 printf(QEMU_IMG_VERSION);
3501 error_exit("Command not found: %s", cmdname);