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-visit.h"
26 #include "qapi/qmp-output-visitor.h"
27 #include "qapi/qmp/qerror.h"
28 #include "qapi/qmp/qjson.h"
29 #include "qemu-common.h"
30 #include "qemu/config-file.h"
31 #include "qemu/option.h"
32 #include "qemu/error-report.h"
33 #include "qom/object_interfaces.h"
34 #include "sysemu/sysemu.h"
35 #include "sysemu/block-backend.h"
36 #include "block/block_int.h"
37 #include "block/blockjob.h"
38 #include "block/qapi.h"
41 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
42 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
44 typedef struct img_cmd_t {
46 int (*handler)(int argc, char **argv);
51 OPTION_BACKING_CHAIN = 257,
53 OPTION_IMAGE_OPTS = 259,
56 typedef enum OutputFormat {
61 /* Default to cache=writeback as data integrity is not important for qemu-tcg. */
62 #define BDRV_O_FLAGS BDRV_O_CACHE_WB
63 #define BDRV_DEFAULT_CACHE "writeback"
65 static void format_print(void *opaque, const char *name)
70 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
74 error_printf("qemu-img: ");
77 error_vprintf(fmt, ap);
80 error_printf("\nTry 'qemu-img --help' for more information\n");
84 /* Please keep in synch with qemu-img.texi */
85 static void QEMU_NORETURN help(void)
87 const char *help_msg =
89 "usage: qemu-img command [command options]\n"
90 "QEMU disk image utility\n"
93 #define DEF(option, callback, arg_string) \
95 #include "qemu-img-cmds.h"
99 "Command parameters:\n"
100 " 'filename' is a disk image filename\n"
101 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
102 " manual page for a description of the object properties. The most common\n"
103 " object type is a 'secret', which is used to supply passwords and/or\n"
104 " encryption keys.\n"
105 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
106 " 'cache' is the cache mode used to write the output disk image, the valid\n"
107 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
108 " 'directsync' and 'unsafe' (default for convert)\n"
109 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
110 " options are the same as for the 'cache' option\n"
111 " 'size' is the disk image size in bytes. Optional suffixes\n"
112 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
113 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
114 " supported. 'b' is ignored.\n"
115 " 'output_filename' is the destination disk image filename\n"
116 " 'output_fmt' is the destination format\n"
117 " 'options' is a comma separated list of format specific options in a\n"
118 " name=value format. Use -o ? for an overview of the options supported by the\n"
120 " 'snapshot_param' is param used for internal snapshot, format\n"
121 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
123 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
125 " '-c' indicates that target image must be compressed (qcow format only)\n"
126 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
127 " match exactly. The image doesn't need a working backing file before\n"
128 " rebasing in this case (useful for renaming the backing file)\n"
129 " '-h' with or without a command shows this help and lists the supported formats\n"
130 " '-p' show progress of command (only certain commands)\n"
131 " '-q' use Quiet mode - do not print any output (except errors)\n"
132 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
133 " contain only zeros for qemu-img to create a sparse image during\n"
134 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
135 " unallocated or zero sectors, and the destination image will always be\n"
137 " '--output' takes the format in which the output must be done (human or json)\n"
138 " '-n' skips the target volume creation (useful if the volume is created\n"
139 " prior to running qemu-img)\n"
141 "Parameters to check subcommand:\n"
142 " '-r' tries to repair any inconsistencies that are found during the check.\n"
143 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
144 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
145 " hiding corruption that has already occurred.\n"
147 "Parameters to snapshot subcommand:\n"
148 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
149 " '-a' applies a snapshot (revert disk to saved state)\n"
150 " '-c' creates a snapshot\n"
151 " '-d' deletes a snapshot\n"
152 " '-l' lists all snapshots in the given image\n"
154 "Parameters to compare subcommand:\n"
155 " '-f' first image format\n"
156 " '-F' second image format\n"
157 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
159 printf("%s\nSupported formats:", help_msg);
160 bdrv_iterate_format(format_print, NULL);
165 static QemuOptsList qemu_object_opts = {
167 .implied_opt_name = "qom-type",
168 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
174 static QemuOptsList qemu_source_opts = {
176 .implied_opt_name = "file",
177 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
183 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
189 ret = vprintf(fmt, args);
196 static int print_block_option_help(const char *filename, const char *fmt)
198 BlockDriver *drv, *proto_drv;
199 QemuOptsList *create_opts = NULL;
200 Error *local_err = NULL;
202 /* Find driver and parse its options */
203 drv = bdrv_find_format(fmt);
205 error_report("Unknown file format '%s'", fmt);
209 create_opts = qemu_opts_append(create_opts, drv->create_opts);
211 proto_drv = bdrv_find_protocol(filename, true, &local_err);
213 error_report_err(local_err);
214 qemu_opts_free(create_opts);
217 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
220 qemu_opts_print_help(create_opts);
221 qemu_opts_free(create_opts);
226 static int img_open_password(BlockBackend *blk, const char *filename,
227 bool require_io, bool quiet)
229 BlockDriverState *bs;
233 if (bdrv_is_encrypted(bs) && require_io) {
234 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
235 if (qemu_read_password(password, sizeof(password)) < 0) {
236 error_report("No password given");
239 if (bdrv_set_key(bs, password) < 0) {
240 error_report("invalid password");
248 static BlockBackend *img_open_opts(const char *optstr,
249 QemuOpts *opts, int flags,
250 bool require_io, bool quiet)
253 Error *local_err = NULL;
255 options = qemu_opts_to_qdict(opts, NULL);
256 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
258 error_reportf_err(local_err, "Could not open '%s'", optstr);
262 if (img_open_password(blk, optstr, require_io, quiet) < 0) {
269 static BlockBackend *img_open_file(const char *filename,
270 const char *fmt, int flags,
271 bool require_io, bool quiet)
274 Error *local_err = NULL;
275 QDict *options = NULL;
278 options = qdict_new();
279 qdict_put(options, "driver", qstring_from_str(fmt));
282 blk = blk_new_open(filename, NULL, options, flags, &local_err);
284 error_reportf_err(local_err, "Could not open '%s': ", filename);
288 if (img_open_password(blk, filename, require_io, quiet) < 0) {
296 static BlockBackend *img_open(bool image_opts,
297 const char *filename,
298 const char *fmt, int flags,
299 bool require_io, bool quiet)
305 error_report("--image-opts and --format are mutually exclusive");
308 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
313 blk = img_open_opts(filename, opts, flags, true, quiet);
315 blk = img_open_file(filename, fmt, flags, true, quiet);
321 static int add_old_style_options(const char *fmt, QemuOpts *opts,
322 const char *base_filename,
323 const char *base_fmt)
328 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
330 error_report("Backing file not supported for file format '%s'",
337 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
339 error_report("Backing file format not supported for file "
348 static int img_create(int argc, char **argv)
351 uint64_t img_size = -1;
352 const char *fmt = "raw";
353 const char *base_fmt = NULL;
354 const char *filename;
355 const char *base_filename = NULL;
356 char *options = NULL;
357 Error *local_err = NULL;
361 static const struct option long_options[] = {
362 {"help", no_argument, 0, 'h'},
363 {"object", required_argument, 0, OPTION_OBJECT},
366 c = getopt_long(argc, argv, "F:b:f:he6o:q",
380 base_filename = optarg;
386 error_report("option -e is deprecated, please use \'-o "
387 "encryption\' instead!");
390 error_report("option -6 is deprecated, please use \'-o "
391 "compat6\' instead!");
394 if (!is_valid_option_list(optarg)) {
395 error_report("Invalid option list: %s", optarg);
399 options = g_strdup(optarg);
401 char *old_options = options;
402 options = g_strdup_printf("%s,%s", options, optarg);
409 case OPTION_OBJECT: {
411 opts = qemu_opts_parse_noisily(&qemu_object_opts,
420 /* Get the filename */
421 filename = (optind < argc) ? argv[optind] : NULL;
422 if (options && has_help_option(options)) {
424 return print_block_option_help(filename, fmt);
427 if (optind >= argc) {
428 error_exit("Expecting image file name");
432 if (qemu_opts_foreach(&qemu_object_opts,
433 user_creatable_add_opts_foreach,
435 error_report_err(local_err);
439 /* Get image size, if specified */
443 sval = qemu_strtosz_suffix(argv[optind++], &end,
444 QEMU_STRTOSZ_DEFSUFFIX_B);
445 if (sval < 0 || *end) {
446 if (sval == -ERANGE) {
447 error_report("Image size must be less than 8 EiB!");
449 error_report("Invalid image size specified! You may use k, M, "
450 "G, T, P or E suffixes for ");
451 error_report("kilobytes, megabytes, gigabytes, terabytes, "
452 "petabytes and exabytes.");
456 img_size = (uint64_t)sval;
458 if (optind != argc) {
459 error_exit("Unexpected argument: %s", argv[optind]);
462 bdrv_img_create(filename, fmt, base_filename, base_fmt,
463 options, img_size, BDRV_O_FLAGS, &local_err, quiet);
465 error_reportf_err(local_err, "%s: ", filename);
477 static void dump_json_image_check(ImageCheck *check, bool quiet)
479 Error *local_err = NULL;
481 QmpOutputVisitor *ov = qmp_output_visitor_new();
483 visit_type_ImageCheck(qmp_output_get_visitor(ov), NULL, &check,
485 obj = qmp_output_get_qobject(ov);
486 str = qobject_to_json_pretty(obj);
488 qprintf(quiet, "%s\n", qstring_get_str(str));
490 qmp_output_visitor_cleanup(ov);
494 static void dump_human_image_check(ImageCheck *check, bool quiet)
496 if (!(check->corruptions || check->leaks || check->check_errors)) {
497 qprintf(quiet, "No errors were found on the image.\n");
499 if (check->corruptions) {
500 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
501 "Data may be corrupted, or further writes to the image "
508 "\n%" PRId64 " leaked clusters were found on the image.\n"
509 "This means waste of disk space, but no harm to data.\n",
513 if (check->check_errors) {
516 " internal errors have occurred during the check.\n",
517 check->check_errors);
521 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
522 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
523 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
524 check->allocated_clusters, check->total_clusters,
525 check->allocated_clusters * 100.0 / check->total_clusters,
526 check->fragmented_clusters * 100.0 / check->allocated_clusters,
527 check->compressed_clusters * 100.0 /
528 check->allocated_clusters);
531 if (check->image_end_offset) {
533 "Image end offset: %" PRId64 "\n", check->image_end_offset);
537 static int collect_image_check(BlockDriverState *bs,
539 const char *filename,
544 BdrvCheckResult result;
546 ret = bdrv_check(bs, &result, fix);
551 check->filename = g_strdup(filename);
552 check->format = g_strdup(bdrv_get_format_name(bs));
553 check->check_errors = result.check_errors;
554 check->corruptions = result.corruptions;
555 check->has_corruptions = result.corruptions != 0;
556 check->leaks = result.leaks;
557 check->has_leaks = result.leaks != 0;
558 check->corruptions_fixed = result.corruptions_fixed;
559 check->has_corruptions_fixed = result.corruptions != 0;
560 check->leaks_fixed = result.leaks_fixed;
561 check->has_leaks_fixed = result.leaks != 0;
562 check->image_end_offset = result.image_end_offset;
563 check->has_image_end_offset = result.image_end_offset != 0;
564 check->total_clusters = result.bfi.total_clusters;
565 check->has_total_clusters = result.bfi.total_clusters != 0;
566 check->allocated_clusters = result.bfi.allocated_clusters;
567 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
568 check->fragmented_clusters = result.bfi.fragmented_clusters;
569 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
570 check->compressed_clusters = result.bfi.compressed_clusters;
571 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
577 * Checks an image for consistency. Exit codes:
579 * 0 - Check completed, image is good
580 * 1 - Check not completed because of internal errors
581 * 2 - Check completed, image is corrupted
582 * 3 - Check completed, image has leaked clusters, but is good otherwise
583 * 63 - Checks are not supported by the image format
585 static int img_check(int argc, char **argv)
588 OutputFormat output_format = OFORMAT_HUMAN;
589 const char *filename, *fmt, *output, *cache;
591 BlockDriverState *bs;
593 int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
596 Error *local_err = NULL;
597 bool image_opts = false;
601 cache = BDRV_DEFAULT_CACHE;
603 int option_index = 0;
604 static const struct option long_options[] = {
605 {"help", no_argument, 0, 'h'},
606 {"format", required_argument, 0, 'f'},
607 {"repair", required_argument, 0, 'r'},
608 {"output", required_argument, 0, OPTION_OUTPUT},
609 {"object", required_argument, 0, OPTION_OBJECT},
610 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
613 c = getopt_long(argc, argv, "hf:r:T:q",
614 long_options, &option_index);
627 flags |= BDRV_O_RDWR;
629 if (!strcmp(optarg, "leaks")) {
630 fix = BDRV_FIX_LEAKS;
631 } else if (!strcmp(optarg, "all")) {
632 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
634 error_exit("Unknown option value for -r "
635 "(expecting 'leaks' or 'all'): %s", optarg);
647 case OPTION_OBJECT: {
649 opts = qemu_opts_parse_noisily(&qemu_object_opts,
655 case OPTION_IMAGE_OPTS:
660 if (optind != argc - 1) {
661 error_exit("Expecting one image file name");
663 filename = argv[optind++];
665 if (output && !strcmp(output, "json")) {
666 output_format = OFORMAT_JSON;
667 } else if (output && !strcmp(output, "human")) {
668 output_format = OFORMAT_HUMAN;
670 error_report("--output must be used with human or json as argument.");
674 if (qemu_opts_foreach(&qemu_object_opts,
675 user_creatable_add_opts_foreach,
677 error_report_err(local_err);
681 ret = bdrv_parse_cache_flags(cache, &flags);
683 error_report("Invalid source cache option: %s", cache);
687 blk = img_open(image_opts, filename, fmt, flags, true, quiet);
693 check = g_new0(ImageCheck, 1);
694 ret = collect_image_check(bs, check, filename, fmt, fix);
696 if (ret == -ENOTSUP) {
697 error_report("This image format does not support checks");
702 if (check->corruptions_fixed || check->leaks_fixed) {
703 int corruptions_fixed, leaks_fixed;
705 leaks_fixed = check->leaks_fixed;
706 corruptions_fixed = check->corruptions_fixed;
708 if (output_format == OFORMAT_HUMAN) {
710 "The following inconsistencies were found and repaired:\n\n"
711 " %" PRId64 " leaked clusters\n"
712 " %" PRId64 " corruptions\n\n"
713 "Double checking the fixed image now...\n",
715 check->corruptions_fixed);
718 ret = collect_image_check(bs, check, filename, fmt, 0);
720 check->leaks_fixed = leaks_fixed;
721 check->corruptions_fixed = corruptions_fixed;
725 switch (output_format) {
727 dump_human_image_check(check, quiet);
730 dump_json_image_check(check, quiet);
735 if (ret || check->check_errors) {
737 error_report("Check failed: %s", strerror(-ret));
739 error_report("Check failed");
745 if (check->corruptions) {
747 } else if (check->leaks) {
754 qapi_free_ImageCheck(check);
759 typedef struct CommonBlockJobCBInfo {
760 BlockDriverState *bs;
762 } CommonBlockJobCBInfo;
764 static void common_block_job_cb(void *opaque, int ret)
766 CommonBlockJobCBInfo *cbi = opaque;
769 error_setg_errno(cbi->errp, -ret, "Block job failed");
773 static void run_block_job(BlockJob *job, Error **errp)
775 AioContext *aio_context = bdrv_get_aio_context(job->bs);
778 aio_poll(aio_context, true);
779 qemu_progress_print(job->len ?
780 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
781 } while (!job->ready);
783 block_job_complete_sync(job, errp);
785 /* A block job may finish instantaneously without publishing any progress,
786 * so just signal completion here */
787 qemu_progress_print(100.f, 0);
790 static int img_commit(int argc, char **argv)
793 const char *filename, *fmt, *cache, *base;
795 BlockDriverState *bs, *base_bs;
796 bool progress = false, quiet = false, drop = false;
797 Error *local_err = NULL;
798 CommonBlockJobCBInfo cbi;
799 bool image_opts = false;
802 cache = BDRV_DEFAULT_CACHE;
805 static const struct option long_options[] = {
806 {"help", no_argument, 0, 'h'},
807 {"object", required_argument, 0, OPTION_OBJECT},
808 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
811 c = getopt_long(argc, argv, "f:ht:b:dpq",
841 case OPTION_OBJECT: {
843 opts = qemu_opts_parse_noisily(&qemu_object_opts,
849 case OPTION_IMAGE_OPTS:
855 /* Progress is not shown in Quiet mode */
860 if (optind != argc - 1) {
861 error_exit("Expecting one image file name");
863 filename = argv[optind++];
865 if (qemu_opts_foreach(&qemu_object_opts,
866 user_creatable_add_opts_foreach,
868 error_report_err(local_err);
872 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
873 ret = bdrv_parse_cache_flags(cache, &flags);
875 error_report("Invalid cache option: %s", cache);
879 blk = img_open(image_opts, filename, fmt, flags, true, quiet);
885 qemu_progress_init(progress, 1.f);
886 qemu_progress_print(0.f, 100);
889 base_bs = bdrv_find_backing_image(bs, base);
891 error_setg(&local_err, QERR_BASE_NOT_FOUND, base);
895 /* This is different from QMP, which by default uses the deepest file in
896 * the backing chain (i.e., the very base); however, the traditional
897 * behavior of qemu-img commit is using the immediate backing file. */
898 base_bs = backing_bs(bs);
900 error_setg(&local_err, "Image does not have a backing file");
905 cbi = (CommonBlockJobCBInfo){
910 commit_active_start(bs, base_bs, 0, BLOCKDEV_ON_ERROR_REPORT,
911 common_block_job_cb, &cbi, &local_err);
916 /* When the block job completes, the BlockBackend reference will point to
917 * the old backing file. In order to avoid that the top image is already
918 * deleted, so we can still empty it afterwards, increment the reference
919 * counter here preemptively. */
924 run_block_job(bs->job, &local_err);
929 if (!drop && bs->drv->bdrv_make_empty) {
930 ret = bs->drv->bdrv_make_empty(bs);
932 error_setg_errno(&local_err, -ret, "Could not empty %s",
949 error_report_err(local_err);
953 qprintf(quiet, "Image committed.\n");
958 * Returns true iff the first sector pointed to by 'buf' contains at least
961 * 'pnum' is set to the number of sectors (including and immediately following
962 * the first one) that are known to be in the same allocated/unallocated state.
964 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
973 is_zero = buffer_is_zero(buf, 512);
974 for(i = 1; i < n; i++) {
976 if (is_zero != buffer_is_zero(buf, 512)) {
985 * Like is_allocated_sectors, but if the buffer starts with a used sector,
986 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
987 * breaking up write requests for only small sparse areas.
989 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
993 int num_checked, num_used;
999 ret = is_allocated_sectors(buf, n, pnum);
1005 buf += BDRV_SECTOR_SIZE * *pnum;
1007 num_checked = num_used;
1010 ret = is_allocated_sectors(buf, n, pnum);
1012 buf += BDRV_SECTOR_SIZE * *pnum;
1014 num_checked += *pnum;
1016 num_used = num_checked;
1017 } else if (*pnum >= min) {
1027 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1028 * buffers matches, non-zero otherwise.
1030 * pnum is set to the number of sectors (including and immediately following
1031 * the first one) that are known to have the same comparison result
1033 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1044 res = !!memcmp(buf1, buf2, 512);
1045 for(i = 1; i < n; i++) {
1049 if (!!memcmp(buf1, buf2, 512) != res) {
1058 #define IO_BUF_SIZE (2 * 1024 * 1024)
1060 static int64_t sectors_to_bytes(int64_t sectors)
1062 return sectors << BDRV_SECTOR_BITS;
1065 static int64_t sectors_to_process(int64_t total, int64_t from)
1067 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1071 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1073 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1074 * data and negative value on error.
1076 * @param blk: BlockBackend for the image
1077 * @param sect_num: Number of first sector to check
1078 * @param sect_count: Number of sectors to check
1079 * @param filename: Name of disk file we are checking (logging purpose)
1080 * @param buffer: Allocated buffer for storing read data
1081 * @param quiet: Flag for quiet mode
1083 static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
1084 int sect_count, const char *filename,
1085 uint8_t *buffer, bool quiet)
1088 ret = blk_read(blk, sect_num, buffer, sect_count);
1090 error_report("Error while reading offset %" PRId64 " of %s: %s",
1091 sectors_to_bytes(sect_num), filename, strerror(-ret));
1094 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1095 if (ret || pnum != sect_count) {
1096 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1097 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1105 * Compares two images. Exit codes:
1107 * 0 - Images are identical
1109 * >1 - Error occurred
1111 static int img_compare(int argc, char **argv)
1113 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1114 BlockBackend *blk1, *blk2;
1115 BlockDriverState *bs1, *bs2;
1116 int64_t total_sectors1, total_sectors2;
1117 uint8_t *buf1 = NULL, *buf2 = NULL;
1119 int allocated1, allocated2;
1120 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1121 bool progress = false, quiet = false, strict = false;
1123 int64_t total_sectors;
1124 int64_t sector_num = 0;
1127 uint64_t progress_base;
1128 Error *local_err = NULL;
1129 bool image_opts = false;
1131 cache = BDRV_DEFAULT_CACHE;
1133 static const struct option long_options[] = {
1134 {"help", no_argument, 0, 'h'},
1135 {"object", required_argument, 0, OPTION_OBJECT},
1136 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1139 c = getopt_long(argc, argv, "hf:F:T:pqs",
1140 long_options, NULL);
1167 case OPTION_OBJECT: {
1169 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1176 case OPTION_IMAGE_OPTS:
1182 /* Progress is not shown in Quiet mode */
1188 if (optind != argc - 2) {
1189 error_exit("Expecting two image file names");
1191 filename1 = argv[optind++];
1192 filename2 = argv[optind++];
1194 if (qemu_opts_foreach(&qemu_object_opts,
1195 user_creatable_add_opts_foreach,
1196 NULL, &local_err)) {
1197 error_report_err(local_err);
1202 /* Initialize before goto out */
1203 qemu_progress_init(progress, 2.0);
1205 flags = BDRV_O_FLAGS;
1206 ret = bdrv_parse_cache_flags(cache, &flags);
1208 error_report("Invalid source cache option: %s", cache);
1213 blk1 = img_open(image_opts, filename1, fmt1, flags, true, quiet);
1219 blk2 = img_open(image_opts, filename2, fmt2, flags, true, quiet);
1227 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1228 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1229 total_sectors1 = blk_nb_sectors(blk1);
1230 if (total_sectors1 < 0) {
1231 error_report("Can't get size of %s: %s",
1232 filename1, strerror(-total_sectors1));
1236 total_sectors2 = blk_nb_sectors(blk2);
1237 if (total_sectors2 < 0) {
1238 error_report("Can't get size of %s: %s",
1239 filename2, strerror(-total_sectors2));
1243 total_sectors = MIN(total_sectors1, total_sectors2);
1244 progress_base = MAX(total_sectors1, total_sectors2);
1246 qemu_progress_print(0, 100);
1248 if (strict && total_sectors1 != total_sectors2) {
1250 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1255 int64_t status1, status2;
1256 BlockDriverState *file;
1258 nb_sectors = sectors_to_process(total_sectors, sector_num);
1259 if (nb_sectors <= 0) {
1262 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1263 total_sectors1 - sector_num,
1267 error_report("Sector allocation test failed for %s", filename1);
1270 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1272 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1273 total_sectors2 - sector_num,
1277 error_report("Sector allocation test failed for %s", filename2);
1280 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1282 nb_sectors = MIN(nb_sectors, pnum1);
1285 nb_sectors = MIN(nb_sectors, pnum2);
1289 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1290 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1292 qprintf(quiet, "Strict mode: Offset %" PRId64
1293 " block status mismatch!\n",
1294 sectors_to_bytes(sector_num));
1298 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1299 nb_sectors = MIN(pnum1, pnum2);
1300 } else if (allocated1 == allocated2) {
1302 ret = blk_read(blk1, sector_num, buf1, nb_sectors);
1304 error_report("Error while reading offset %" PRId64 " of %s:"
1305 " %s", sectors_to_bytes(sector_num), filename1,
1310 ret = blk_read(blk2, sector_num, buf2, nb_sectors);
1312 error_report("Error while reading offset %" PRId64
1313 " of %s: %s", sectors_to_bytes(sector_num),
1314 filename2, strerror(-ret));
1318 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1319 if (ret || pnum != nb_sectors) {
1320 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1322 ret ? sector_num : sector_num + pnum));
1330 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
1331 filename1, buf1, quiet);
1333 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
1334 filename2, buf1, quiet);
1338 error_report("Error while reading offset %" PRId64 ": %s",
1339 sectors_to_bytes(sector_num), strerror(-ret));
1345 sector_num += nb_sectors;
1346 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1349 if (total_sectors1 != total_sectors2) {
1350 BlockBackend *blk_over;
1351 int64_t total_sectors_over;
1352 const char *filename_over;
1354 qprintf(quiet, "Warning: Image size mismatch!\n");
1355 if (total_sectors1 > total_sectors2) {
1356 total_sectors_over = total_sectors1;
1358 filename_over = filename1;
1360 total_sectors_over = total_sectors2;
1362 filename_over = filename2;
1366 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1367 if (nb_sectors <= 0) {
1370 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,
1374 error_report("Sector allocation test failed for %s",
1381 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
1382 filename_over, buf1, quiet);
1385 error_report("Error while reading offset %" PRId64
1386 " of %s: %s", sectors_to_bytes(sector_num),
1387 filename_over, strerror(-ret));
1393 sector_num += nb_sectors;
1394 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1398 qprintf(quiet, "Images are identical.\n");
1408 qemu_progress_end();
1413 enum ImgConvertBlockStatus {
1419 typedef struct ImgConvertState {
1421 int64_t *src_sectors;
1422 int src_cur, src_num;
1423 int64_t src_cur_offset;
1424 int64_t total_sectors;
1425 int64_t allocated_sectors;
1426 enum ImgConvertBlockStatus status;
1427 int64_t sector_next_status;
1428 BlockBackend *target;
1431 bool target_has_backing;
1433 size_t cluster_sectors;
1437 static void convert_select_part(ImgConvertState *s, int64_t sector_num)
1439 assert(sector_num >= s->src_cur_offset);
1440 while (sector_num - s->src_cur_offset >= s->src_sectors[s->src_cur]) {
1441 s->src_cur_offset += s->src_sectors[s->src_cur];
1443 assert(s->src_cur < s->src_num);
1447 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1452 convert_select_part(s, sector_num);
1454 assert(s->total_sectors > sector_num);
1455 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1457 if (s->sector_next_status <= sector_num) {
1458 BlockDriverState *file;
1459 ret = bdrv_get_block_status(blk_bs(s->src[s->src_cur]),
1460 sector_num - s->src_cur_offset,
1466 if (ret & BDRV_BLOCK_ZERO) {
1467 s->status = BLK_ZERO;
1468 } else if (ret & BDRV_BLOCK_DATA) {
1469 s->status = BLK_DATA;
1470 } else if (!s->target_has_backing) {
1471 /* Without a target backing file we must copy over the contents of
1472 * the backing file as well. */
1473 /* TODO Check block status of the backing file chain to avoid
1474 * needlessly reading zeroes and limiting the iteration to the
1476 s->status = BLK_DATA;
1478 s->status = BLK_BACKING_FILE;
1481 s->sector_next_status = sector_num + n;
1484 n = MIN(n, s->sector_next_status - sector_num);
1485 if (s->status == BLK_DATA) {
1486 n = MIN(n, s->buf_sectors);
1489 /* We need to write complete clusters for compressed images, so if an
1490 * unallocated area is shorter than that, we must consider the whole
1491 * cluster allocated. */
1492 if (s->compressed) {
1493 if (n < s->cluster_sectors) {
1494 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1495 s->status = BLK_DATA;
1497 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1504 static int convert_read(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1510 if (s->status == BLK_ZERO || s->status == BLK_BACKING_FILE) {
1514 assert(nb_sectors <= s->buf_sectors);
1515 while (nb_sectors > 0) {
1519 /* In the case of compression with multiple source files, we can get a
1520 * nb_sectors that spreads into the next part. So we must be able to
1521 * read across multiple BDSes for one convert_read() call. */
1522 convert_select_part(s, sector_num);
1523 blk = s->src[s->src_cur];
1524 bs_sectors = s->src_sectors[s->src_cur];
1526 n = MIN(nb_sectors, bs_sectors - (sector_num - s->src_cur_offset));
1527 ret = blk_read(blk, sector_num - s->src_cur_offset, buf, n);
1534 buf += n * BDRV_SECTOR_SIZE;
1540 static int convert_write(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1545 while (nb_sectors > 0) {
1548 switch (s->status) {
1549 case BLK_BACKING_FILE:
1550 /* If we have a backing file, leave clusters unallocated that are
1551 * unallocated in the source image, so that the backing file is
1552 * visible at the respective offset. */
1553 assert(s->target_has_backing);
1557 /* We must always write compressed clusters as a whole, so don't
1558 * try to find zeroed parts in the buffer. We can only save the
1559 * write if the buffer is completely zeroed and we're allowed to
1560 * keep the target sparse. */
1561 if (s->compressed) {
1562 if (s->has_zero_init && s->min_sparse &&
1563 buffer_is_zero(buf, n * BDRV_SECTOR_SIZE))
1565 assert(!s->target_has_backing);
1569 ret = blk_write_compressed(s->target, sector_num, buf, n);
1576 /* If there is real non-zero data or we're told to keep the target
1577 * fully allocated (-S 0), we must write it. Otherwise we can treat
1578 * it as zero sectors. */
1579 if (!s->min_sparse ||
1580 is_allocated_sectors_min(buf, n, &n, s->min_sparse))
1582 ret = blk_write(s->target, sector_num, buf, n);
1591 if (s->has_zero_init) {
1594 ret = blk_write_zeroes(s->target, sector_num, n, 0);
1603 buf += n * BDRV_SECTOR_SIZE;
1609 static int convert_do_copy(ImgConvertState *s)
1611 uint8_t *buf = NULL;
1612 int64_t sector_num, allocated_done;
1616 /* Check whether we have zero initialisation or can get it efficiently */
1617 s->has_zero_init = s->min_sparse && !s->target_has_backing
1618 ? bdrv_has_zero_init(blk_bs(s->target))
1621 if (!s->has_zero_init && !s->target_has_backing &&
1622 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1624 ret = bdrv_make_zero(blk_bs(s->target), BDRV_REQ_MAY_UNMAP);
1626 s->has_zero_init = true;
1630 /* Allocate buffer for copied data. For compressed images, only one cluster
1631 * can be copied at a time. */
1632 if (s->compressed) {
1633 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1634 error_report("invalid cluster size");
1638 s->buf_sectors = s->cluster_sectors;
1640 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1642 /* Calculate allocated sectors for progress */
1643 s->allocated_sectors = 0;
1645 while (sector_num < s->total_sectors) {
1646 n = convert_iteration_sectors(s, sector_num);
1651 if (s->status == BLK_DATA) {
1652 s->allocated_sectors += n;
1659 s->src_cur_offset = 0;
1660 s->sector_next_status = 0;
1665 while (sector_num < s->total_sectors) {
1666 n = convert_iteration_sectors(s, sector_num);
1671 if (s->status == BLK_DATA) {
1672 allocated_done += n;
1673 qemu_progress_print(100.0 * allocated_done / s->allocated_sectors,
1677 ret = convert_read(s, sector_num, n, buf);
1679 error_report("error while reading sector %" PRId64
1680 ": %s", sector_num, strerror(-ret));
1684 ret = convert_write(s, sector_num, n, buf);
1686 error_report("error while writing sector %" PRId64
1687 ": %s", sector_num, strerror(-ret));
1694 if (s->compressed) {
1695 /* signal EOF to align */
1696 ret = blk_write_compressed(s->target, 0, NULL, 0);
1708 static int img_convert(int argc, char **argv)
1710 int c, bs_n, bs_i, compress, cluster_sectors, skip_create;
1712 int progress = 0, flags, src_flags;
1713 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
1714 BlockDriver *drv, *proto_drv;
1715 BlockBackend **blk = NULL, *out_blk = NULL;
1716 BlockDriverState **bs = NULL, *out_bs = NULL;
1717 int64_t total_sectors;
1718 int64_t *bs_sectors = NULL;
1719 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
1720 BlockDriverInfo bdi;
1721 QemuOpts *opts = NULL;
1722 QemuOptsList *create_opts = NULL;
1723 const char *out_baseimg_param;
1724 char *options = NULL;
1725 const char *snapshot_name = NULL;
1726 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
1728 Error *local_err = NULL;
1729 QemuOpts *sn_opts = NULL;
1730 ImgConvertState state;
1731 bool image_opts = false;
1736 src_cache = BDRV_DEFAULT_CACHE;
1741 static const struct option long_options[] = {
1742 {"help", no_argument, 0, 'h'},
1743 {"object", required_argument, 0, OPTION_OBJECT},
1744 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1747 c = getopt_long(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn",
1748 long_options, NULL);
1764 out_baseimg = optarg;
1770 error_report("option -e is deprecated, please use \'-o "
1771 "encryption\' instead!");
1775 error_report("option -6 is deprecated, please use \'-o "
1776 "compat6\' instead!");
1780 if (!is_valid_option_list(optarg)) {
1781 error_report("Invalid option list: %s", optarg);
1786 options = g_strdup(optarg);
1788 char *old_options = options;
1789 options = g_strdup_printf("%s,%s", options, optarg);
1790 g_free(old_options);
1794 snapshot_name = optarg;
1797 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1798 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
1801 error_report("Failed in parsing snapshot param '%s'",
1807 snapshot_name = optarg;
1814 sval = qemu_strtosz_suffix(optarg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
1815 if (sval < 0 || *end) {
1816 error_report("Invalid minimum zero buffer size for sparse output specified");
1821 min_sparse = sval / BDRV_SECTOR_SIZE;
1840 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1846 case OPTION_IMAGE_OPTS:
1852 if (qemu_opts_foreach(&qemu_object_opts,
1853 user_creatable_add_opts_foreach,
1854 NULL, &local_err)) {
1855 error_report_err(local_err);
1859 /* Initialize before goto out */
1863 qemu_progress_init(progress, 1.0);
1865 bs_n = argc - optind - 1;
1866 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
1868 if (options && has_help_option(options)) {
1869 ret = print_block_option_help(out_filename, out_fmt);
1874 error_exit("Must specify image file name");
1878 if (bs_n > 1 && out_baseimg) {
1879 error_report("-B makes no sense when concatenating multiple input "
1885 src_flags = BDRV_O_FLAGS;
1886 ret = bdrv_parse_cache_flags(src_cache, &src_flags);
1888 error_report("Invalid source cache option: %s", src_cache);
1892 qemu_progress_print(0, 100);
1894 blk = g_new0(BlockBackend *, bs_n);
1895 bs = g_new0(BlockDriverState *, bs_n);
1896 bs_sectors = g_new(int64_t, bs_n);
1899 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1900 blk[bs_i] = img_open(image_opts, argv[optind + bs_i],
1901 fmt, src_flags, true, quiet);
1906 bs[bs_i] = blk_bs(blk[bs_i]);
1907 bs_sectors[bs_i] = blk_nb_sectors(blk[bs_i]);
1908 if (bs_sectors[bs_i] < 0) {
1909 error_report("Could not get size of %s: %s",
1910 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1914 total_sectors += bs_sectors[bs_i];
1918 ret = bdrv_snapshot_load_tmp(bs[0],
1919 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1920 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1922 } else if (snapshot_name != NULL) {
1924 error_report("No support for concatenating multiple snapshot");
1929 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
1932 error_reportf_err(local_err, "Failed to load snapshot: ");
1937 /* Find driver and parse its options */
1938 drv = bdrv_find_format(out_fmt);
1940 error_report("Unknown file format '%s'", out_fmt);
1945 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
1947 error_report_err(local_err);
1953 if (!drv->create_opts) {
1954 error_report("Format driver '%s' does not support image creation",
1960 if (!proto_drv->create_opts) {
1961 error_report("Protocol driver '%s' does not support image creation",
1962 proto_drv->format_name);
1967 create_opts = qemu_opts_append(create_opts, drv->create_opts);
1968 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
1970 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
1972 qemu_opts_do_parse(opts, options, NULL, &local_err);
1974 error_report_err(local_err);
1980 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512,
1982 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
1988 /* Get backing file name if -o backing_file was used */
1989 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
1990 if (out_baseimg_param) {
1991 out_baseimg = out_baseimg_param;
1994 /* Check if compression is supported */
1997 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
1998 const char *preallocation =
1999 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2001 if (!drv->bdrv_write_compressed) {
2002 error_report("Compression not supported for this file format");
2008 error_report("Compression and encryption not supported at "
2015 && strcmp(preallocation, "off"))
2017 error_report("Compression and preallocation not supported at "
2025 /* Create the new image */
2026 ret = bdrv_create(drv, out_filename, opts, &local_err);
2028 error_reportf_err(local_err, "%s: error while converting %s: ",
2029 out_filename, out_fmt);
2034 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2035 ret = bdrv_parse_cache_flags(cache, &flags);
2037 error_report("Invalid cache option: %s", cache);
2041 /* XXX we should allow --image-opts to trigger use of
2042 * img_open() here, but then we have trouble with
2043 * the bdrv_create() call which takes different params.
2044 * Not critical right now, so fix can wait...
2046 out_blk = img_open_file(out_filename, out_fmt, flags, true, quiet);
2051 out_bs = blk_bs(out_blk);
2053 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
2054 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2056 bufsectors = MIN(32768,
2057 MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
2058 out_bs->bl.discard_alignment))
2062 int64_t output_sectors = blk_nb_sectors(out_blk);
2063 if (output_sectors < 0) {
2064 error_report("unable to get output image length: %s",
2065 strerror(-output_sectors));
2068 } else if (output_sectors < total_sectors) {
2069 error_report("output file is smaller than input file");
2075 cluster_sectors = 0;
2076 ret = bdrv_get_info(out_bs, &bdi);
2079 error_report("could not get block driver info");
2083 compress = compress || bdi.needs_compressed_writes;
2084 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2087 state = (ImgConvertState) {
2089 .src_sectors = bs_sectors,
2091 .total_sectors = total_sectors,
2093 .compressed = compress,
2094 .target_has_backing = (bool) out_baseimg,
2095 .min_sparse = min_sparse,
2096 .cluster_sectors = cluster_sectors,
2097 .buf_sectors = bufsectors,
2099 ret = convert_do_copy(&state);
2103 qemu_progress_print(100, 0);
2105 qemu_progress_end();
2106 qemu_opts_del(opts);
2107 qemu_opts_free(create_opts);
2108 qemu_opts_del(sn_opts);
2112 for (bs_i = 0; bs_i < bs_n; bs_i++) {
2113 blk_unref(blk[bs_i]);
2128 static void dump_snapshots(BlockDriverState *bs)
2130 QEMUSnapshotInfo *sn_tab, *sn;
2133 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2136 printf("Snapshot list:\n");
2137 bdrv_snapshot_dump(fprintf, stdout, NULL);
2139 for(i = 0; i < nb_sns; i++) {
2141 bdrv_snapshot_dump(fprintf, stdout, sn);
2147 static void dump_json_image_info_list(ImageInfoList *list)
2149 Error *local_err = NULL;
2151 QmpOutputVisitor *ov = qmp_output_visitor_new();
2153 visit_type_ImageInfoList(qmp_output_get_visitor(ov), NULL, &list,
2155 obj = qmp_output_get_qobject(ov);
2156 str = qobject_to_json_pretty(obj);
2157 assert(str != NULL);
2158 printf("%s\n", qstring_get_str(str));
2159 qobject_decref(obj);
2160 qmp_output_visitor_cleanup(ov);
2164 static void dump_json_image_info(ImageInfo *info)
2166 Error *local_err = NULL;
2168 QmpOutputVisitor *ov = qmp_output_visitor_new();
2170 visit_type_ImageInfo(qmp_output_get_visitor(ov), NULL, &info, &local_err);
2171 obj = qmp_output_get_qobject(ov);
2172 str = qobject_to_json_pretty(obj);
2173 assert(str != NULL);
2174 printf("%s\n", qstring_get_str(str));
2175 qobject_decref(obj);
2176 qmp_output_visitor_cleanup(ov);
2180 static void dump_human_image_info_list(ImageInfoList *list)
2182 ImageInfoList *elem;
2185 for (elem = list; elem; elem = elem->next) {
2191 bdrv_image_info_dump(fprintf, stdout, elem->value);
2195 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2197 return strcmp(a, b) == 0;
2201 * Open an image file chain and return an ImageInfoList
2203 * @filename: topmost image filename
2204 * @fmt: topmost image format (may be NULL to autodetect)
2205 * @chain: true - enumerate entire backing file chain
2206 * false - only topmost image file
2208 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2209 * image file. If there was an error a message will have been printed to
2212 static ImageInfoList *collect_image_info_list(bool image_opts,
2213 const char *filename,
2217 ImageInfoList *head = NULL;
2218 ImageInfoList **last = &head;
2219 GHashTable *filenames;
2222 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2226 BlockDriverState *bs;
2228 ImageInfoList *elem;
2230 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2231 error_report("Backing file '%s' creates an infinite loop.",
2235 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2237 blk = img_open(image_opts, filename, fmt,
2238 BDRV_O_FLAGS | BDRV_O_NO_BACKING,
2245 bdrv_query_image_info(bs, &info, &err);
2247 error_report_err(err);
2252 elem = g_new0(ImageInfoList, 1);
2259 filename = fmt = NULL;
2261 if (info->has_full_backing_filename) {
2262 filename = info->full_backing_filename;
2263 } else if (info->has_backing_filename) {
2264 error_report("Could not determine absolute backing filename,"
2265 " but backing filename '%s' present",
2266 info->backing_filename);
2269 if (info->has_backing_filename_format) {
2270 fmt = info->backing_filename_format;
2274 g_hash_table_destroy(filenames);
2278 qapi_free_ImageInfoList(head);
2279 g_hash_table_destroy(filenames);
2283 static int img_info(int argc, char **argv)
2286 OutputFormat output_format = OFORMAT_HUMAN;
2288 const char *filename, *fmt, *output;
2289 ImageInfoList *list;
2290 Error *local_err = NULL;
2291 bool image_opts = false;
2296 int option_index = 0;
2297 static const struct option long_options[] = {
2298 {"help", no_argument, 0, 'h'},
2299 {"format", required_argument, 0, 'f'},
2300 {"output", required_argument, 0, OPTION_OUTPUT},
2301 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2302 {"object", required_argument, 0, OPTION_OBJECT},
2303 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2306 c = getopt_long(argc, argv, "f:h",
2307 long_options, &option_index);
2322 case OPTION_BACKING_CHAIN:
2325 case OPTION_OBJECT: {
2327 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2333 case OPTION_IMAGE_OPTS:
2338 if (optind != argc - 1) {
2339 error_exit("Expecting one image file name");
2341 filename = argv[optind++];
2343 if (output && !strcmp(output, "json")) {
2344 output_format = OFORMAT_JSON;
2345 } else if (output && !strcmp(output, "human")) {
2346 output_format = OFORMAT_HUMAN;
2347 } else if (output) {
2348 error_report("--output must be used with human or json as argument.");
2352 if (qemu_opts_foreach(&qemu_object_opts,
2353 user_creatable_add_opts_foreach,
2354 NULL, &local_err)) {
2355 error_report_err(local_err);
2359 list = collect_image_info_list(image_opts, filename, fmt, chain);
2364 switch (output_format) {
2366 dump_human_image_info_list(list);
2370 dump_json_image_info_list(list);
2372 dump_json_image_info(list->value);
2377 qapi_free_ImageInfoList(list);
2381 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2384 switch (output_format) {
2386 if (e->data && !e->has_offset) {
2387 error_report("File contains external, encrypted or compressed clusters.");
2390 if (e->data && !e->zero) {
2391 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2392 e->start, e->length,
2393 e->has_offset ? e->offset : 0,
2394 e->has_filename ? e->filename : "");
2396 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2397 * Modify the flags here to allow more coalescing.
2399 if (next && (!next->data || next->zero)) {
2405 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2406 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2407 (e->start == 0 ? "[" : ",\n"),
2408 e->start, e->length, e->depth,
2409 e->zero ? "true" : "false",
2410 e->data ? "true" : "false");
2411 if (e->has_offset) {
2412 printf(", \"offset\": %"PRId64"", e->offset);
2423 static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2424 int nb_sectors, MapEntry *e)
2428 BlockDriverState *file;
2431 /* As an optimization, we could cache the current range of unallocated
2432 * clusters in each file of the chain, and avoid querying the same
2438 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2444 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2447 bs = backing_bs(bs);
2456 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2459 .start = sector_num * BDRV_SECTOR_SIZE,
2460 .length = nb_sectors * BDRV_SECTOR_SIZE,
2461 .data = !!(ret & BDRV_BLOCK_DATA),
2462 .zero = !!(ret & BDRV_BLOCK_ZERO),
2463 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2464 .has_offset = has_offset,
2466 .has_filename = file && has_offset,
2467 .filename = file && has_offset ? file->filename : NULL,
2473 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2475 if (curr->length == 0) {
2478 if (curr->zero != next->zero ||
2479 curr->data != next->data ||
2480 curr->depth != next->depth ||
2481 curr->has_filename != next->has_filename ||
2482 curr->has_offset != next->has_offset) {
2485 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2488 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2494 static int img_map(int argc, char **argv)
2497 OutputFormat output_format = OFORMAT_HUMAN;
2499 BlockDriverState *bs;
2500 const char *filename, *fmt, *output;
2502 MapEntry curr = { .length = 0 }, next;
2504 Error *local_err = NULL;
2505 bool image_opts = false;
2510 int option_index = 0;
2511 static const struct option long_options[] = {
2512 {"help", no_argument, 0, 'h'},
2513 {"format", required_argument, 0, 'f'},
2514 {"output", required_argument, 0, OPTION_OUTPUT},
2515 {"object", required_argument, 0, OPTION_OBJECT},
2516 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2519 c = getopt_long(argc, argv, "f:h",
2520 long_options, &option_index);
2535 case OPTION_OBJECT: {
2537 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2543 case OPTION_IMAGE_OPTS:
2548 if (optind != argc - 1) {
2549 error_exit("Expecting one image file name");
2551 filename = argv[optind];
2553 if (output && !strcmp(output, "json")) {
2554 output_format = OFORMAT_JSON;
2555 } else if (output && !strcmp(output, "human")) {
2556 output_format = OFORMAT_HUMAN;
2557 } else if (output) {
2558 error_report("--output must be used with human or json as argument.");
2562 if (qemu_opts_foreach(&qemu_object_opts,
2563 user_creatable_add_opts_foreach,
2564 NULL, &local_err)) {
2565 error_report_err(local_err);
2569 blk = img_open(image_opts, filename, fmt, BDRV_O_FLAGS, true, false);
2575 if (output_format == OFORMAT_HUMAN) {
2576 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2579 length = blk_getlength(blk);
2580 while (curr.start + curr.length < length) {
2581 int64_t nsectors_left;
2585 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2587 /* Probe up to 1 GiB at a time. */
2588 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2589 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2590 ret = get_block_status(bs, sector_num, n, &next);
2593 error_report("Could not read file metadata: %s", strerror(-ret));
2597 if (entry_mergeable(&curr, &next)) {
2598 curr.length += next.length;
2602 if (curr.length > 0) {
2603 dump_map_entry(output_format, &curr, &next);
2608 dump_map_entry(output_format, &curr, NULL);
2615 #define SNAPSHOT_LIST 1
2616 #define SNAPSHOT_CREATE 2
2617 #define SNAPSHOT_APPLY 3
2618 #define SNAPSHOT_DELETE 4
2620 static int img_snapshot(int argc, char **argv)
2623 BlockDriverState *bs;
2624 QEMUSnapshotInfo sn;
2625 char *filename, *snapshot_name = NULL;
2626 int c, ret = 0, bdrv_oflags;
2631 bool image_opts = false;
2633 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
2634 /* Parse commandline parameters */
2636 static const struct option long_options[] = {
2637 {"help", no_argument, 0, 'h'},
2638 {"object", required_argument, 0, OPTION_OBJECT},
2639 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2642 c = getopt_long(argc, argv, "la:c:d:hq",
2643 long_options, NULL);
2654 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2657 action = SNAPSHOT_LIST;
2658 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
2662 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2665 action = SNAPSHOT_APPLY;
2666 snapshot_name = optarg;
2670 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2673 action = SNAPSHOT_CREATE;
2674 snapshot_name = optarg;
2678 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2681 action = SNAPSHOT_DELETE;
2682 snapshot_name = optarg;
2687 case OPTION_OBJECT: {
2689 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2695 case OPTION_IMAGE_OPTS:
2701 if (optind != argc - 1) {
2702 error_exit("Expecting one image file name");
2704 filename = argv[optind++];
2706 if (qemu_opts_foreach(&qemu_object_opts,
2707 user_creatable_add_opts_foreach,
2709 error_report_err(err);
2713 /* Open the image */
2714 blk = img_open(image_opts, filename, NULL, bdrv_oflags, true, quiet);
2720 /* Perform the requested action */
2726 case SNAPSHOT_CREATE:
2727 memset(&sn, 0, sizeof(sn));
2728 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2730 qemu_gettimeofday(&tv);
2731 sn.date_sec = tv.tv_sec;
2732 sn.date_nsec = tv.tv_usec * 1000;
2734 ret = bdrv_snapshot_create(bs, &sn);
2736 error_report("Could not create snapshot '%s': %d (%s)",
2737 snapshot_name, ret, strerror(-ret));
2741 case SNAPSHOT_APPLY:
2742 ret = bdrv_snapshot_goto(bs, snapshot_name);
2744 error_report("Could not apply snapshot '%s': %d (%s)",
2745 snapshot_name, ret, strerror(-ret));
2749 case SNAPSHOT_DELETE:
2750 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
2752 error_reportf_err(err, "Could not delete snapshot '%s': ",
2767 static int img_rebase(int argc, char **argv)
2769 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
2770 uint8_t *buf_old = NULL;
2771 uint8_t *buf_new = NULL;
2772 BlockDriverState *bs = NULL;
2774 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2775 int c, flags, src_flags, ret;
2779 Error *local_err = NULL;
2780 bool image_opts = false;
2782 /* Parse commandline parameters */
2784 cache = BDRV_DEFAULT_CACHE;
2785 src_cache = BDRV_DEFAULT_CACHE;
2789 static const struct option long_options[] = {
2790 {"help", no_argument, 0, 'h'},
2791 {"object", required_argument, 0, OPTION_OBJECT},
2792 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2795 c = getopt_long(argc, argv, "hf:F:b:upt:T:q",
2796 long_options, NULL);
2809 out_basefmt = optarg;
2812 out_baseimg = optarg;
2829 case OPTION_OBJECT: {
2831 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2837 case OPTION_IMAGE_OPTS:
2847 if (optind != argc - 1) {
2848 error_exit("Expecting one image file name");
2850 if (!unsafe && !out_baseimg) {
2851 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
2853 filename = argv[optind++];
2855 if (qemu_opts_foreach(&qemu_object_opts,
2856 user_creatable_add_opts_foreach,
2857 NULL, &local_err)) {
2858 error_report_err(local_err);
2862 qemu_progress_init(progress, 2.0);
2863 qemu_progress_print(0, 100);
2865 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
2866 ret = bdrv_parse_cache_flags(cache, &flags);
2868 error_report("Invalid cache option: %s", cache);
2872 src_flags = BDRV_O_FLAGS;
2873 ret = bdrv_parse_cache_flags(src_cache, &src_flags);
2875 error_report("Invalid source cache option: %s", src_cache);
2882 * Ignore the old backing file for unsafe rebase in case we want to correct
2883 * the reference to a renamed or moved backing file.
2885 blk = img_open(image_opts, filename, fmt, flags, true, quiet);
2892 if (out_basefmt != NULL) {
2893 if (bdrv_find_format(out_basefmt) == NULL) {
2894 error_report("Invalid format name: '%s'", out_basefmt);
2900 /* For safe rebasing we need to compare old and new backing file */
2902 char backing_name[PATH_MAX];
2903 QDict *options = NULL;
2905 if (bs->backing_format[0] != '\0') {
2906 options = qdict_new();
2907 qdict_put(options, "driver", qstring_from_str(bs->backing_format));
2910 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2911 blk_old_backing = blk_new_open(backing_name, NULL,
2912 options, src_flags, &local_err);
2913 if (!blk_old_backing) {
2914 error_reportf_err(local_err,
2915 "Could not open old backing file '%s': ",
2920 if (out_baseimg[0]) {
2922 options = qdict_new();
2923 qdict_put(options, "driver", qstring_from_str(out_basefmt));
2928 blk_new_backing = blk_new_open(out_baseimg, NULL,
2929 options, src_flags, &local_err);
2930 if (!blk_new_backing) {
2931 error_reportf_err(local_err,
2932 "Could not open new backing file '%s': ",
2940 * Check each unallocated cluster in the COW file. If it is unallocated,
2941 * accesses go to the backing file. We must therefore compare this cluster
2942 * in the old and new backing file, and if they differ we need to copy it
2943 * from the old backing file into the COW file.
2945 * If qemu-img crashes during this step, no harm is done. The content of
2946 * the image is the same as the original one at any time.
2949 int64_t num_sectors;
2950 int64_t old_backing_num_sectors;
2951 int64_t new_backing_num_sectors = 0;
2954 float local_progress = 0;
2956 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
2957 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
2959 num_sectors = blk_nb_sectors(blk);
2960 if (num_sectors < 0) {
2961 error_report("Could not get size of '%s': %s",
2962 filename, strerror(-num_sectors));
2966 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
2967 if (old_backing_num_sectors < 0) {
2968 char backing_name[PATH_MAX];
2970 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2971 error_report("Could not get size of '%s': %s",
2972 backing_name, strerror(-old_backing_num_sectors));
2976 if (blk_new_backing) {
2977 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
2978 if (new_backing_num_sectors < 0) {
2979 error_report("Could not get size of '%s': %s",
2980 out_baseimg, strerror(-new_backing_num_sectors));
2986 if (num_sectors != 0) {
2987 local_progress = (float)100 /
2988 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
2991 for (sector = 0; sector < num_sectors; sector += n) {
2993 /* How many sectors can we handle with the next read? */
2994 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
2995 n = (IO_BUF_SIZE / 512);
2997 n = num_sectors - sector;
3000 /* If the cluster is allocated, we don't need to take action */
3001 ret = bdrv_is_allocated(bs, sector, n, &n);
3003 error_report("error while reading image metadata: %s",
3012 * Read old and new backing file and take into consideration that
3013 * backing files may be smaller than the COW image.
3015 if (sector >= old_backing_num_sectors) {
3016 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3018 if (sector + n > old_backing_num_sectors) {
3019 n = old_backing_num_sectors - sector;
3022 ret = blk_read(blk_old_backing, sector, buf_old, n);
3024 error_report("error while reading from old backing file");
3029 if (sector >= new_backing_num_sectors || !blk_new_backing) {
3030 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3032 if (sector + n > new_backing_num_sectors) {
3033 n = new_backing_num_sectors - sector;
3036 ret = blk_read(blk_new_backing, sector, buf_new, n);
3038 error_report("error while reading from new backing file");
3043 /* If they differ, we need to write to the COW file */
3044 uint64_t written = 0;
3046 while (written < n) {
3049 if (compare_sectors(buf_old + written * 512,
3050 buf_new + written * 512, n - written, &pnum))
3052 ret = blk_write(blk, sector + written,
3053 buf_old + written * 512, pnum);
3055 error_report("Error while writing to COW image: %s",
3063 qemu_progress_print(local_progress, 100);
3068 * Change the backing file. All clusters that are different from the old
3069 * backing file are overwritten in the COW file now, so the visible content
3070 * doesn't change when we switch the backing file.
3072 if (out_baseimg && *out_baseimg) {
3073 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3075 ret = bdrv_change_backing_file(bs, NULL, NULL);
3078 if (ret == -ENOSPC) {
3079 error_report("Could not change the backing file to '%s': No "
3080 "space left in the file header", out_baseimg);
3081 } else if (ret < 0) {
3082 error_report("Could not change the backing file to '%s': %s",
3083 out_baseimg, strerror(-ret));
3086 qemu_progress_print(100, 0);
3088 * TODO At this point it is possible to check if any clusters that are
3089 * allocated in the COW file are the same in the backing file. If so, they
3090 * could be dropped from the COW file. Don't do this before switching the
3091 * backing file, in case of a crash this would lead to corruption.
3094 qemu_progress_end();
3097 blk_unref(blk_old_backing);
3098 blk_unref(blk_new_backing);
3100 qemu_vfree(buf_old);
3101 qemu_vfree(buf_new);
3110 static int img_resize(int argc, char **argv)
3113 int c, ret, relative;
3114 const char *filename, *fmt, *size;
3115 int64_t n, total_size;
3117 BlockBackend *blk = NULL;
3119 Error *local_err = NULL;
3121 static QemuOptsList resize_options = {
3122 .name = "resize_options",
3123 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3126 .name = BLOCK_OPT_SIZE,
3127 .type = QEMU_OPT_SIZE,
3128 .help = "Virtual disk size"
3134 bool image_opts = false;
3136 /* Remove size from argv manually so that negative numbers are not treated
3137 * as options by getopt. */
3139 error_exit("Not enough arguments");
3143 size = argv[--argc];
3145 /* Parse getopt arguments */
3148 static const struct option long_options[] = {
3149 {"help", no_argument, 0, 'h'},
3150 {"object", required_argument, 0, OPTION_OBJECT},
3151 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3154 c = getopt_long(argc, argv, "f:hq",
3155 long_options, NULL);
3170 case OPTION_OBJECT: {
3172 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3178 case OPTION_IMAGE_OPTS:
3183 if (optind != argc - 1) {
3184 error_exit("Expecting one image file name");
3186 filename = argv[optind++];
3188 if (qemu_opts_foreach(&qemu_object_opts,
3189 user_creatable_add_opts_foreach,
3190 NULL, &local_err)) {
3191 error_report_err(local_err);
3195 /* Choose grow, shrink, or absolute resize mode */
3211 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3212 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3214 error_report_err(err);
3216 qemu_opts_del(param);
3219 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3220 qemu_opts_del(param);
3222 blk = img_open(image_opts, filename, fmt,
3223 BDRV_O_FLAGS | BDRV_O_RDWR, true, quiet);
3230 total_size = blk_getlength(blk) + n * relative;
3234 if (total_size <= 0) {
3235 error_report("New image size must be positive");
3240 ret = blk_truncate(blk, total_size);
3243 qprintf(quiet, "Image resized.\n");
3246 error_report("This image does not support resize");
3249 error_report("Image is read-only");
3252 error_report("Error resizing image (%d)", -ret);
3263 static void amend_status_cb(BlockDriverState *bs,
3264 int64_t offset, int64_t total_work_size,
3267 qemu_progress_print(100.f * offset / total_work_size, 0);
3270 static int img_amend(int argc, char **argv)
3274 char *options = NULL;
3275 QemuOptsList *create_opts = NULL;
3276 QemuOpts *opts = NULL;
3277 const char *fmt = NULL, *filename, *cache;
3279 bool quiet = false, progress = false;
3280 BlockBackend *blk = NULL;
3281 BlockDriverState *bs = NULL;
3282 Error *local_err = NULL;
3283 bool image_opts = false;
3285 cache = BDRV_DEFAULT_CACHE;
3287 static const struct option long_options[] = {
3288 {"help", no_argument, 0, 'h'},
3289 {"object", required_argument, 0, OPTION_OBJECT},
3290 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3293 c = getopt_long(argc, argv, "ho:f:t:pq",
3294 long_options, NULL);
3305 if (!is_valid_option_list(optarg)) {
3306 error_report("Invalid option list: %s", optarg);
3308 goto out_no_progress;
3311 options = g_strdup(optarg);
3313 char *old_options = options;
3314 options = g_strdup_printf("%s,%s", options, optarg);
3315 g_free(old_options);
3331 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3335 goto out_no_progress;
3338 case OPTION_IMAGE_OPTS:
3345 error_exit("Must specify options (-o)");
3348 if (qemu_opts_foreach(&qemu_object_opts,
3349 user_creatable_add_opts_foreach,
3350 NULL, &local_err)) {
3351 error_report_err(local_err);
3353 goto out_no_progress;
3359 qemu_progress_init(progress, 1.0);
3361 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3362 if (fmt && has_help_option(options)) {
3363 /* If a format is explicitly specified (and possibly no filename is
3364 * given), print option help here */
3365 ret = print_block_option_help(filename, fmt);
3369 if (optind != argc - 1) {
3370 error_report("Expecting one image file name");
3375 flags = BDRV_O_FLAGS | BDRV_O_RDWR;
3376 ret = bdrv_parse_cache_flags(cache, &flags);
3378 error_report("Invalid cache option: %s", cache);
3382 blk = img_open(image_opts, filename, fmt, flags, true, quiet);
3389 fmt = bs->drv->format_name;
3391 if (has_help_option(options)) {
3392 /* If the format was auto-detected, print option help here */
3393 ret = print_block_option_help(filename, fmt);
3397 if (!bs->drv->create_opts) {
3398 error_report("Format driver '%s' does not support any options to amend",
3404 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
3405 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3407 qemu_opts_do_parse(opts, options, NULL, &err);
3409 error_report_err(err);
3415 /* In case the driver does not call amend_status_cb() */
3416 qemu_progress_print(0.f, 0);
3417 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
3418 qemu_progress_print(100.f, 0);
3420 error_report("Error while amending options: %s", strerror(-ret));
3425 qemu_progress_end();
3429 qemu_opts_del(opts);
3430 qemu_opts_free(create_opts);
3439 static const img_cmd_t img_cmds[] = {
3440 #define DEF(option, callback, arg_string) \
3441 { option, callback },
3442 #include "qemu-img-cmds.h"
3448 int main(int argc, char **argv)
3450 const img_cmd_t *cmd;
3451 const char *cmdname;
3452 Error *local_error = NULL;
3454 static const struct option long_options[] = {
3455 {"help", no_argument, 0, 'h'},
3456 {"version", no_argument, 0, 'v'},
3461 signal(SIGPIPE, SIG_IGN);
3464 error_set_progname(argv[0]);
3465 qemu_init_exec_dir(argv[0]);
3467 if (qemu_init_main_loop(&local_error)) {
3468 error_report_err(local_error);
3472 module_call_init(MODULE_INIT_QOM);
3475 error_exit("Not enough arguments");
3479 qemu_add_opts(&qemu_object_opts);
3480 qemu_add_opts(&qemu_source_opts);
3482 /* find the command */
3483 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
3484 if (!strcmp(cmdname, cmd->name)) {
3485 return cmd->handler(argc - 1, argv + 1);
3489 c = getopt_long(argc, argv, "h", long_options, NULL);
3495 printf(QEMU_IMG_VERSION);
3500 error_exit("Command not found: %s", cmdname);