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"
40 #include "crypto/init.h"
43 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
44 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
46 typedef struct img_cmd_t {
48 int (*handler)(int argc, char **argv);
53 OPTION_BACKING_CHAIN = 257,
55 OPTION_IMAGE_OPTS = 259,
58 typedef enum OutputFormat {
63 /* Default to cache=writeback as data integrity is not important for qemu-img */
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 int flags, bool quiet)
230 BlockDriverState *bs;
234 if (bdrv_is_encrypted(bs) && bdrv_key_required(bs) &&
235 !(flags & BDRV_O_NO_IO)) {
236 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
237 if (qemu_read_password(password, sizeof(password)) < 0) {
238 error_report("No password given");
241 if (bdrv_set_key(bs, password) < 0) {
242 error_report("invalid password");
250 static BlockBackend *img_open_opts(const char *optstr,
251 QemuOpts *opts, int flags, bool writethrough,
255 Error *local_err = NULL;
257 options = qemu_opts_to_qdict(opts, NULL);
258 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
260 error_reportf_err(local_err, "Could not open '%s': ", optstr);
263 blk_set_enable_write_cache(blk, !writethrough);
265 if (img_open_password(blk, optstr, flags, quiet) < 0) {
272 static BlockBackend *img_open_file(const char *filename,
273 const char *fmt, int flags,
274 bool writethrough, bool quiet)
277 Error *local_err = NULL;
278 QDict *options = NULL;
281 options = qdict_new();
282 qdict_put(options, "driver", qstring_from_str(fmt));
285 blk = blk_new_open(filename, NULL, options, flags, &local_err);
287 error_reportf_err(local_err, "Could not open '%s': ", filename);
290 blk_set_enable_write_cache(blk, !writethrough);
292 if (img_open_password(blk, filename, flags, quiet) < 0) {
300 static BlockBackend *img_open(bool image_opts,
301 const char *filename,
302 const char *fmt, int flags, bool writethrough,
309 error_report("--image-opts and --format are mutually exclusive");
312 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
317 blk = img_open_opts(filename, opts, flags, writethrough, quiet);
319 blk = img_open_file(filename, fmt, flags, writethrough, quiet);
325 static int add_old_style_options(const char *fmt, QemuOpts *opts,
326 const char *base_filename,
327 const char *base_fmt)
332 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
334 error_report("Backing file not supported for file format '%s'",
341 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
343 error_report("Backing file format not supported for file "
352 static int img_create(int argc, char **argv)
355 uint64_t img_size = -1;
356 const char *fmt = "raw";
357 const char *base_fmt = NULL;
358 const char *filename;
359 const char *base_filename = NULL;
360 char *options = NULL;
361 Error *local_err = NULL;
365 static const struct option long_options[] = {
366 {"help", no_argument, 0, 'h'},
367 {"object", required_argument, 0, OPTION_OBJECT},
370 c = getopt_long(argc, argv, "F:b:f:he6o:q",
384 base_filename = optarg;
390 error_report("option -e is deprecated, please use \'-o "
391 "encryption\' instead!");
394 error_report("option -6 is deprecated, please use \'-o "
395 "compat6\' instead!");
398 if (!is_valid_option_list(optarg)) {
399 error_report("Invalid option list: %s", optarg);
403 options = g_strdup(optarg);
405 char *old_options = options;
406 options = g_strdup_printf("%s,%s", options, optarg);
413 case OPTION_OBJECT: {
415 opts = qemu_opts_parse_noisily(&qemu_object_opts,
424 /* Get the filename */
425 filename = (optind < argc) ? argv[optind] : NULL;
426 if (options && has_help_option(options)) {
428 return print_block_option_help(filename, fmt);
431 if (optind >= argc) {
432 error_exit("Expecting image file name");
436 if (qemu_opts_foreach(&qemu_object_opts,
437 user_creatable_add_opts_foreach,
442 /* Get image size, if specified */
446 sval = qemu_strtosz_suffix(argv[optind++], &end,
447 QEMU_STRTOSZ_DEFSUFFIX_B);
448 if (sval < 0 || *end) {
449 if (sval == -ERANGE) {
450 error_report("Image size must be less than 8 EiB!");
452 error_report("Invalid image size specified! You may use k, M, "
453 "G, T, P or E suffixes for ");
454 error_report("kilobytes, megabytes, gigabytes, terabytes, "
455 "petabytes and exabytes.");
459 img_size = (uint64_t)sval;
461 if (optind != argc) {
462 error_exit("Unexpected argument: %s", argv[optind]);
465 bdrv_img_create(filename, fmt, base_filename, base_fmt,
466 options, img_size, 0, &local_err, quiet);
468 error_reportf_err(local_err, "%s: ", filename);
480 static void dump_json_image_check(ImageCheck *check, bool quiet)
482 Error *local_err = NULL;
484 QmpOutputVisitor *ov = qmp_output_visitor_new();
486 visit_type_ImageCheck(qmp_output_get_visitor(ov), NULL, &check,
488 obj = qmp_output_get_qobject(ov);
489 str = qobject_to_json_pretty(obj);
491 qprintf(quiet, "%s\n", qstring_get_str(str));
493 qmp_output_visitor_cleanup(ov);
497 static void dump_human_image_check(ImageCheck *check, bool quiet)
499 if (!(check->corruptions || check->leaks || check->check_errors)) {
500 qprintf(quiet, "No errors were found on the image.\n");
502 if (check->corruptions) {
503 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
504 "Data may be corrupted, or further writes to the image "
511 "\n%" PRId64 " leaked clusters were found on the image.\n"
512 "This means waste of disk space, but no harm to data.\n",
516 if (check->check_errors) {
519 " internal errors have occurred during the check.\n",
520 check->check_errors);
524 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
525 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
526 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
527 check->allocated_clusters, check->total_clusters,
528 check->allocated_clusters * 100.0 / check->total_clusters,
529 check->fragmented_clusters * 100.0 / check->allocated_clusters,
530 check->compressed_clusters * 100.0 /
531 check->allocated_clusters);
534 if (check->image_end_offset) {
536 "Image end offset: %" PRId64 "\n", check->image_end_offset);
540 static int collect_image_check(BlockDriverState *bs,
542 const char *filename,
547 BdrvCheckResult result;
549 ret = bdrv_check(bs, &result, fix);
554 check->filename = g_strdup(filename);
555 check->format = g_strdup(bdrv_get_format_name(bs));
556 check->check_errors = result.check_errors;
557 check->corruptions = result.corruptions;
558 check->has_corruptions = result.corruptions != 0;
559 check->leaks = result.leaks;
560 check->has_leaks = result.leaks != 0;
561 check->corruptions_fixed = result.corruptions_fixed;
562 check->has_corruptions_fixed = result.corruptions != 0;
563 check->leaks_fixed = result.leaks_fixed;
564 check->has_leaks_fixed = result.leaks != 0;
565 check->image_end_offset = result.image_end_offset;
566 check->has_image_end_offset = result.image_end_offset != 0;
567 check->total_clusters = result.bfi.total_clusters;
568 check->has_total_clusters = result.bfi.total_clusters != 0;
569 check->allocated_clusters = result.bfi.allocated_clusters;
570 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
571 check->fragmented_clusters = result.bfi.fragmented_clusters;
572 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
573 check->compressed_clusters = result.bfi.compressed_clusters;
574 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
580 * Checks an image for consistency. Exit codes:
582 * 0 - Check completed, image is good
583 * 1 - Check not completed because of internal errors
584 * 2 - Check completed, image is corrupted
585 * 3 - Check completed, image has leaked clusters, but is good otherwise
586 * 63 - Checks are not supported by the image format
588 static int img_check(int argc, char **argv)
591 OutputFormat output_format = OFORMAT_HUMAN;
592 const char *filename, *fmt, *output, *cache;
594 BlockDriverState *bs;
596 int flags = BDRV_O_CHECK;
600 bool image_opts = false;
604 cache = BDRV_DEFAULT_CACHE;
607 int option_index = 0;
608 static const struct option long_options[] = {
609 {"help", no_argument, 0, 'h'},
610 {"format", required_argument, 0, 'f'},
611 {"repair", required_argument, 0, 'r'},
612 {"output", required_argument, 0, OPTION_OUTPUT},
613 {"object", required_argument, 0, OPTION_OBJECT},
614 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
617 c = getopt_long(argc, argv, "hf:r:T:q",
618 long_options, &option_index);
631 flags |= BDRV_O_RDWR;
633 if (!strcmp(optarg, "leaks")) {
634 fix = BDRV_FIX_LEAKS;
635 } else if (!strcmp(optarg, "all")) {
636 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
638 error_exit("Unknown option value for -r "
639 "(expecting 'leaks' or 'all'): %s", optarg);
651 case OPTION_OBJECT: {
653 opts = qemu_opts_parse_noisily(&qemu_object_opts,
659 case OPTION_IMAGE_OPTS:
664 if (optind != argc - 1) {
665 error_exit("Expecting one image file name");
667 filename = argv[optind++];
669 if (output && !strcmp(output, "json")) {
670 output_format = OFORMAT_JSON;
671 } else if (output && !strcmp(output, "human")) {
672 output_format = OFORMAT_HUMAN;
674 error_report("--output must be used with human or json as argument.");
678 if (qemu_opts_foreach(&qemu_object_opts,
679 user_creatable_add_opts_foreach,
684 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
686 error_report("Invalid source cache option: %s", cache);
690 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
696 check = g_new0(ImageCheck, 1);
697 ret = collect_image_check(bs, check, filename, fmt, fix);
699 if (ret == -ENOTSUP) {
700 error_report("This image format does not support checks");
705 if (check->corruptions_fixed || check->leaks_fixed) {
706 int corruptions_fixed, leaks_fixed;
708 leaks_fixed = check->leaks_fixed;
709 corruptions_fixed = check->corruptions_fixed;
711 if (output_format == OFORMAT_HUMAN) {
713 "The following inconsistencies were found and repaired:\n\n"
714 " %" PRId64 " leaked clusters\n"
715 " %" PRId64 " corruptions\n\n"
716 "Double checking the fixed image now...\n",
718 check->corruptions_fixed);
721 ret = collect_image_check(bs, check, filename, fmt, 0);
723 check->leaks_fixed = leaks_fixed;
724 check->corruptions_fixed = corruptions_fixed;
728 switch (output_format) {
730 dump_human_image_check(check, quiet);
733 dump_json_image_check(check, quiet);
738 if (ret || check->check_errors) {
740 error_report("Check failed: %s", strerror(-ret));
742 error_report("Check failed");
748 if (check->corruptions) {
750 } else if (check->leaks) {
757 qapi_free_ImageCheck(check);
762 typedef struct CommonBlockJobCBInfo {
763 BlockDriverState *bs;
765 } CommonBlockJobCBInfo;
767 static void common_block_job_cb(void *opaque, int ret)
769 CommonBlockJobCBInfo *cbi = opaque;
772 error_setg_errno(cbi->errp, -ret, "Block job failed");
776 static void run_block_job(BlockJob *job, Error **errp)
778 AioContext *aio_context = bdrv_get_aio_context(job->bs);
781 aio_poll(aio_context, true);
782 qemu_progress_print(job->len ?
783 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
784 } while (!job->ready);
786 block_job_complete_sync(job, errp);
788 /* A block job may finish instantaneously without publishing any progress,
789 * so just signal completion here */
790 qemu_progress_print(100.f, 0);
793 static int img_commit(int argc, char **argv)
796 const char *filename, *fmt, *cache, *base;
798 BlockDriverState *bs, *base_bs;
799 bool progress = false, quiet = false, drop = false;
801 Error *local_err = NULL;
802 CommonBlockJobCBInfo cbi;
803 bool image_opts = false;
806 cache = BDRV_DEFAULT_CACHE;
809 static const struct option long_options[] = {
810 {"help", no_argument, 0, 'h'},
811 {"object", required_argument, 0, OPTION_OBJECT},
812 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
815 c = getopt_long(argc, argv, "f:ht:b:dpq",
845 case OPTION_OBJECT: {
847 opts = qemu_opts_parse_noisily(&qemu_object_opts,
853 case OPTION_IMAGE_OPTS:
859 /* Progress is not shown in Quiet mode */
864 if (optind != argc - 1) {
865 error_exit("Expecting one image file name");
867 filename = argv[optind++];
869 if (qemu_opts_foreach(&qemu_object_opts,
870 user_creatable_add_opts_foreach,
875 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
876 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
878 error_report("Invalid cache option: %s", cache);
882 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
888 qemu_progress_init(progress, 1.f);
889 qemu_progress_print(0.f, 100);
892 base_bs = bdrv_find_backing_image(bs, base);
894 error_setg(&local_err, QERR_BASE_NOT_FOUND, base);
898 /* This is different from QMP, which by default uses the deepest file in
899 * the backing chain (i.e., the very base); however, the traditional
900 * behavior of qemu-img commit is using the immediate backing file. */
901 base_bs = backing_bs(bs);
903 error_setg(&local_err, "Image does not have a backing file");
908 cbi = (CommonBlockJobCBInfo){
913 commit_active_start(bs, base_bs, 0, BLOCKDEV_ON_ERROR_REPORT,
914 common_block_job_cb, &cbi, &local_err);
919 /* When the block job completes, the BlockBackend reference will point to
920 * the old backing file. In order to avoid that the top image is already
921 * deleted, so we can still empty it afterwards, increment the reference
922 * counter here preemptively. */
927 run_block_job(bs->job, &local_err);
932 if (!drop && bs->drv->bdrv_make_empty) {
933 ret = bs->drv->bdrv_make_empty(bs);
935 error_setg_errno(&local_err, -ret, "Could not empty %s",
952 error_report_err(local_err);
956 qprintf(quiet, "Image committed.\n");
961 * Returns true iff the first sector pointed to by 'buf' contains at least
964 * 'pnum' is set to the number of sectors (including and immediately following
965 * the first one) that are known to be in the same allocated/unallocated state.
967 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
976 is_zero = buffer_is_zero(buf, 512);
977 for(i = 1; i < n; i++) {
979 if (is_zero != buffer_is_zero(buf, 512)) {
988 * Like is_allocated_sectors, but if the buffer starts with a used sector,
989 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
990 * breaking up write requests for only small sparse areas.
992 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
996 int num_checked, num_used;
1002 ret = is_allocated_sectors(buf, n, pnum);
1008 buf += BDRV_SECTOR_SIZE * *pnum;
1010 num_checked = num_used;
1013 ret = is_allocated_sectors(buf, n, pnum);
1015 buf += BDRV_SECTOR_SIZE * *pnum;
1017 num_checked += *pnum;
1019 num_used = num_checked;
1020 } else if (*pnum >= min) {
1030 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1031 * buffers matches, non-zero otherwise.
1033 * pnum is set to the number of sectors (including and immediately following
1034 * the first one) that are known to have the same comparison result
1036 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1047 res = !!memcmp(buf1, buf2, 512);
1048 for(i = 1; i < n; i++) {
1052 if (!!memcmp(buf1, buf2, 512) != res) {
1061 #define IO_BUF_SIZE (2 * 1024 * 1024)
1063 static int64_t sectors_to_bytes(int64_t sectors)
1065 return sectors << BDRV_SECTOR_BITS;
1068 static int64_t sectors_to_process(int64_t total, int64_t from)
1070 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1074 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1076 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1077 * data and negative value on error.
1079 * @param blk: BlockBackend for the image
1080 * @param sect_num: Number of first sector to check
1081 * @param sect_count: Number of sectors to check
1082 * @param filename: Name of disk file we are checking (logging purpose)
1083 * @param buffer: Allocated buffer for storing read data
1084 * @param quiet: Flag for quiet mode
1086 static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
1087 int sect_count, const char *filename,
1088 uint8_t *buffer, bool quiet)
1091 ret = blk_read(blk, sect_num, buffer, sect_count);
1093 error_report("Error while reading offset %" PRId64 " of %s: %s",
1094 sectors_to_bytes(sect_num), filename, strerror(-ret));
1097 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1098 if (ret || pnum != sect_count) {
1099 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1100 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1108 * Compares two images. Exit codes:
1110 * 0 - Images are identical
1112 * >1 - Error occurred
1114 static int img_compare(int argc, char **argv)
1116 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1117 BlockBackend *blk1, *blk2;
1118 BlockDriverState *bs1, *bs2;
1119 int64_t total_sectors1, total_sectors2;
1120 uint8_t *buf1 = NULL, *buf2 = NULL;
1122 int allocated1, allocated2;
1123 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1124 bool progress = false, quiet = false, strict = false;
1127 int64_t total_sectors;
1128 int64_t sector_num = 0;
1131 uint64_t progress_base;
1132 bool image_opts = false;
1134 cache = BDRV_DEFAULT_CACHE;
1136 static const struct option long_options[] = {
1137 {"help", no_argument, 0, 'h'},
1138 {"object", required_argument, 0, OPTION_OBJECT},
1139 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1142 c = getopt_long(argc, argv, "hf:F:T:pqs",
1143 long_options, NULL);
1170 case OPTION_OBJECT: {
1172 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1179 case OPTION_IMAGE_OPTS:
1185 /* Progress is not shown in Quiet mode */
1191 if (optind != argc - 2) {
1192 error_exit("Expecting two image file names");
1194 filename1 = argv[optind++];
1195 filename2 = argv[optind++];
1197 if (qemu_opts_foreach(&qemu_object_opts,
1198 user_creatable_add_opts_foreach,
1204 /* Initialize before goto out */
1205 qemu_progress_init(progress, 2.0);
1208 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1210 error_report("Invalid source cache option: %s", cache);
1215 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet);
1221 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet);
1229 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1230 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1231 total_sectors1 = blk_nb_sectors(blk1);
1232 if (total_sectors1 < 0) {
1233 error_report("Can't get size of %s: %s",
1234 filename1, strerror(-total_sectors1));
1238 total_sectors2 = blk_nb_sectors(blk2);
1239 if (total_sectors2 < 0) {
1240 error_report("Can't get size of %s: %s",
1241 filename2, strerror(-total_sectors2));
1245 total_sectors = MIN(total_sectors1, total_sectors2);
1246 progress_base = MAX(total_sectors1, total_sectors2);
1248 qemu_progress_print(0, 100);
1250 if (strict && total_sectors1 != total_sectors2) {
1252 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1257 int64_t status1, status2;
1258 BlockDriverState *file;
1260 nb_sectors = sectors_to_process(total_sectors, sector_num);
1261 if (nb_sectors <= 0) {
1264 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1265 total_sectors1 - sector_num,
1269 error_report("Sector allocation test failed for %s", filename1);
1272 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1274 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1275 total_sectors2 - sector_num,
1279 error_report("Sector allocation test failed for %s", filename2);
1282 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1284 nb_sectors = MIN(nb_sectors, pnum1);
1287 nb_sectors = MIN(nb_sectors, pnum2);
1291 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1292 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1294 qprintf(quiet, "Strict mode: Offset %" PRId64
1295 " block status mismatch!\n",
1296 sectors_to_bytes(sector_num));
1300 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1301 nb_sectors = MIN(pnum1, pnum2);
1302 } else if (allocated1 == allocated2) {
1304 ret = blk_read(blk1, sector_num, buf1, nb_sectors);
1306 error_report("Error while reading offset %" PRId64 " of %s:"
1307 " %s", sectors_to_bytes(sector_num), filename1,
1312 ret = blk_read(blk2, sector_num, buf2, nb_sectors);
1314 error_report("Error while reading offset %" PRId64
1315 " of %s: %s", sectors_to_bytes(sector_num),
1316 filename2, strerror(-ret));
1320 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1321 if (ret || pnum != nb_sectors) {
1322 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1324 ret ? sector_num : sector_num + pnum));
1332 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
1333 filename1, buf1, quiet);
1335 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
1336 filename2, buf1, quiet);
1340 error_report("Error while reading offset %" PRId64 ": %s",
1341 sectors_to_bytes(sector_num), strerror(-ret));
1347 sector_num += nb_sectors;
1348 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1351 if (total_sectors1 != total_sectors2) {
1352 BlockBackend *blk_over;
1353 int64_t total_sectors_over;
1354 const char *filename_over;
1356 qprintf(quiet, "Warning: Image size mismatch!\n");
1357 if (total_sectors1 > total_sectors2) {
1358 total_sectors_over = total_sectors1;
1360 filename_over = filename1;
1362 total_sectors_over = total_sectors2;
1364 filename_over = filename2;
1368 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1369 if (nb_sectors <= 0) {
1372 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,
1376 error_report("Sector allocation test failed for %s",
1383 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
1384 filename_over, buf1, quiet);
1387 error_report("Error while reading offset %" PRId64
1388 " of %s: %s", sectors_to_bytes(sector_num),
1389 filename_over, strerror(-ret));
1395 sector_num += nb_sectors;
1396 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1400 qprintf(quiet, "Images are identical.\n");
1410 qemu_progress_end();
1415 enum ImgConvertBlockStatus {
1421 typedef struct ImgConvertState {
1423 int64_t *src_sectors;
1424 int src_cur, src_num;
1425 int64_t src_cur_offset;
1426 int64_t total_sectors;
1427 int64_t allocated_sectors;
1428 enum ImgConvertBlockStatus status;
1429 int64_t sector_next_status;
1430 BlockBackend *target;
1433 bool target_has_backing;
1435 size_t cluster_sectors;
1439 static void convert_select_part(ImgConvertState *s, int64_t sector_num)
1441 assert(sector_num >= s->src_cur_offset);
1442 while (sector_num - s->src_cur_offset >= s->src_sectors[s->src_cur]) {
1443 s->src_cur_offset += s->src_sectors[s->src_cur];
1445 assert(s->src_cur < s->src_num);
1449 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1454 convert_select_part(s, sector_num);
1456 assert(s->total_sectors > sector_num);
1457 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1459 if (s->sector_next_status <= sector_num) {
1460 BlockDriverState *file;
1461 ret = bdrv_get_block_status(blk_bs(s->src[s->src_cur]),
1462 sector_num - s->src_cur_offset,
1468 if (ret & BDRV_BLOCK_ZERO) {
1469 s->status = BLK_ZERO;
1470 } else if (ret & BDRV_BLOCK_DATA) {
1471 s->status = BLK_DATA;
1472 } else if (!s->target_has_backing) {
1473 /* Without a target backing file we must copy over the contents of
1474 * the backing file as well. */
1475 /* TODO Check block status of the backing file chain to avoid
1476 * needlessly reading zeroes and limiting the iteration to the
1478 s->status = BLK_DATA;
1480 s->status = BLK_BACKING_FILE;
1483 s->sector_next_status = sector_num + n;
1486 n = MIN(n, s->sector_next_status - sector_num);
1487 if (s->status == BLK_DATA) {
1488 n = MIN(n, s->buf_sectors);
1491 /* We need to write complete clusters for compressed images, so if an
1492 * unallocated area is shorter than that, we must consider the whole
1493 * cluster allocated. */
1494 if (s->compressed) {
1495 if (n < s->cluster_sectors) {
1496 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1497 s->status = BLK_DATA;
1499 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1506 static int convert_read(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1512 assert(nb_sectors <= s->buf_sectors);
1513 while (nb_sectors > 0) {
1517 /* In the case of compression with multiple source files, we can get a
1518 * nb_sectors that spreads into the next part. So we must be able to
1519 * read across multiple BDSes for one convert_read() call. */
1520 convert_select_part(s, sector_num);
1521 blk = s->src[s->src_cur];
1522 bs_sectors = s->src_sectors[s->src_cur];
1524 n = MIN(nb_sectors, bs_sectors - (sector_num - s->src_cur_offset));
1525 ret = blk_read(blk, sector_num - s->src_cur_offset, buf, n);
1532 buf += n * BDRV_SECTOR_SIZE;
1538 static int convert_write(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1543 while (nb_sectors > 0) {
1546 switch (s->status) {
1547 case BLK_BACKING_FILE:
1548 /* If we have a backing file, leave clusters unallocated that are
1549 * unallocated in the source image, so that the backing file is
1550 * visible at the respective offset. */
1551 assert(s->target_has_backing);
1555 /* We must always write compressed clusters as a whole, so don't
1556 * try to find zeroed parts in the buffer. We can only save the
1557 * write if the buffer is completely zeroed and we're allowed to
1558 * keep the target sparse. */
1559 if (s->compressed) {
1560 if (s->has_zero_init && s->min_sparse &&
1561 buffer_is_zero(buf, n * BDRV_SECTOR_SIZE))
1563 assert(!s->target_has_backing);
1567 ret = blk_write_compressed(s->target, sector_num, buf, n);
1574 /* If there is real non-zero data or we're told to keep the target
1575 * fully allocated (-S 0), we must write it. Otherwise we can treat
1576 * it as zero sectors. */
1577 if (!s->min_sparse ||
1578 is_allocated_sectors_min(buf, n, &n, s->min_sparse))
1580 ret = blk_write(s->target, sector_num, buf, n);
1589 if (s->has_zero_init) {
1592 ret = blk_write_zeroes(s->target, sector_num, n, 0);
1601 buf += n * BDRV_SECTOR_SIZE;
1607 static int convert_do_copy(ImgConvertState *s)
1609 uint8_t *buf = NULL;
1610 int64_t sector_num, allocated_done;
1614 /* Check whether we have zero initialisation or can get it efficiently */
1615 s->has_zero_init = s->min_sparse && !s->target_has_backing
1616 ? bdrv_has_zero_init(blk_bs(s->target))
1619 if (!s->has_zero_init && !s->target_has_backing &&
1620 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1622 ret = bdrv_make_zero(blk_bs(s->target), BDRV_REQ_MAY_UNMAP);
1624 s->has_zero_init = true;
1628 /* Allocate buffer for copied data. For compressed images, only one cluster
1629 * can be copied at a time. */
1630 if (s->compressed) {
1631 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1632 error_report("invalid cluster size");
1636 s->buf_sectors = s->cluster_sectors;
1638 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1640 /* Calculate allocated sectors for progress */
1641 s->allocated_sectors = 0;
1643 while (sector_num < s->total_sectors) {
1644 n = convert_iteration_sectors(s, sector_num);
1649 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1651 s->allocated_sectors += n;
1658 s->src_cur_offset = 0;
1659 s->sector_next_status = 0;
1664 while (sector_num < s->total_sectors) {
1665 n = convert_iteration_sectors(s, sector_num);
1670 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1672 allocated_done += n;
1673 qemu_progress_print(100.0 * allocated_done / s->allocated_sectors,
1677 if (s->status == BLK_DATA) {
1678 ret = convert_read(s, sector_num, n, buf);
1680 error_report("error while reading sector %" PRId64
1681 ": %s", sector_num, strerror(-ret));
1684 } else if (!s->min_sparse && s->status == BLK_ZERO) {
1685 n = MIN(n, s->buf_sectors);
1686 memset(buf, 0, n * BDRV_SECTOR_SIZE);
1687 s->status = BLK_DATA;
1690 ret = convert_write(s, sector_num, n, buf);
1692 error_report("error while writing sector %" PRId64
1693 ": %s", sector_num, strerror(-ret));
1700 if (s->compressed) {
1701 /* signal EOF to align */
1702 ret = blk_write_compressed(s->target, 0, NULL, 0);
1714 static int img_convert(int argc, char **argv)
1716 int c, bs_n, bs_i, compress, cluster_sectors, skip_create;
1718 int progress = 0, flags, src_flags;
1719 bool writethrough, src_writethrough;
1720 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
1721 BlockDriver *drv, *proto_drv;
1722 BlockBackend **blk = NULL, *out_blk = NULL;
1723 BlockDriverState **bs = NULL, *out_bs = NULL;
1724 int64_t total_sectors;
1725 int64_t *bs_sectors = NULL;
1726 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
1727 BlockDriverInfo bdi;
1728 QemuOpts *opts = NULL;
1729 QemuOptsList *create_opts = NULL;
1730 const char *out_baseimg_param;
1731 char *options = NULL;
1732 const char *snapshot_name = NULL;
1733 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
1735 Error *local_err = NULL;
1736 QemuOpts *sn_opts = NULL;
1737 ImgConvertState state;
1738 bool image_opts = false;
1743 src_cache = BDRV_DEFAULT_CACHE;
1748 static const struct option long_options[] = {
1749 {"help", no_argument, 0, 'h'},
1750 {"object", required_argument, 0, OPTION_OBJECT},
1751 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1754 c = getopt_long(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn",
1755 long_options, NULL);
1771 out_baseimg = optarg;
1777 error_report("option -e is deprecated, please use \'-o "
1778 "encryption\' instead!");
1782 error_report("option -6 is deprecated, please use \'-o "
1783 "compat6\' instead!");
1787 if (!is_valid_option_list(optarg)) {
1788 error_report("Invalid option list: %s", optarg);
1793 options = g_strdup(optarg);
1795 char *old_options = options;
1796 options = g_strdup_printf("%s,%s", options, optarg);
1797 g_free(old_options);
1801 snapshot_name = optarg;
1804 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1805 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
1808 error_report("Failed in parsing snapshot param '%s'",
1814 snapshot_name = optarg;
1821 sval = qemu_strtosz_suffix(optarg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
1822 if (sval < 0 || *end) {
1823 error_report("Invalid minimum zero buffer size for sparse output specified");
1828 min_sparse = sval / BDRV_SECTOR_SIZE;
1847 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1853 case OPTION_IMAGE_OPTS:
1859 if (qemu_opts_foreach(&qemu_object_opts,
1860 user_creatable_add_opts_foreach,
1865 /* Initialize before goto out */
1869 qemu_progress_init(progress, 1.0);
1871 bs_n = argc - optind - 1;
1872 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
1874 if (options && has_help_option(options)) {
1875 ret = print_block_option_help(out_filename, out_fmt);
1880 error_exit("Must specify image file name");
1884 if (bs_n > 1 && out_baseimg) {
1885 error_report("-B makes no sense when concatenating multiple input "
1892 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
1894 error_report("Invalid source cache option: %s", src_cache);
1898 qemu_progress_print(0, 100);
1900 blk = g_new0(BlockBackend *, bs_n);
1901 bs = g_new0(BlockDriverState *, bs_n);
1902 bs_sectors = g_new(int64_t, bs_n);
1905 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1906 blk[bs_i] = img_open(image_opts, argv[optind + bs_i],
1907 fmt, src_flags, src_writethrough, quiet);
1912 bs[bs_i] = blk_bs(blk[bs_i]);
1913 bs_sectors[bs_i] = blk_nb_sectors(blk[bs_i]);
1914 if (bs_sectors[bs_i] < 0) {
1915 error_report("Could not get size of %s: %s",
1916 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1920 total_sectors += bs_sectors[bs_i];
1924 ret = bdrv_snapshot_load_tmp(bs[0],
1925 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1926 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1928 } else if (snapshot_name != NULL) {
1930 error_report("No support for concatenating multiple snapshot");
1935 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
1938 error_reportf_err(local_err, "Failed to load snapshot: ");
1943 /* Find driver and parse its options */
1944 drv = bdrv_find_format(out_fmt);
1946 error_report("Unknown file format '%s'", out_fmt);
1951 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
1953 error_report_err(local_err);
1959 if (!drv->create_opts) {
1960 error_report("Format driver '%s' does not support image creation",
1966 if (!proto_drv->create_opts) {
1967 error_report("Protocol driver '%s' does not support image creation",
1968 proto_drv->format_name);
1973 create_opts = qemu_opts_append(create_opts, drv->create_opts);
1974 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
1976 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
1978 qemu_opts_do_parse(opts, options, NULL, &local_err);
1980 error_report_err(local_err);
1986 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512,
1988 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
1994 /* Get backing file name if -o backing_file was used */
1995 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
1996 if (out_baseimg_param) {
1997 out_baseimg = out_baseimg_param;
2000 /* Check if compression is supported */
2003 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2004 const char *preallocation =
2005 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2007 if (!drv->bdrv_write_compressed) {
2008 error_report("Compression not supported for this file format");
2014 error_report("Compression and encryption not supported at "
2021 && strcmp(preallocation, "off"))
2023 error_report("Compression and preallocation not supported at "
2031 /* Create the new image */
2032 ret = bdrv_create(drv, out_filename, opts, &local_err);
2034 error_reportf_err(local_err, "%s: error while converting %s: ",
2035 out_filename, out_fmt);
2040 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2041 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2043 error_report("Invalid cache option: %s", cache);
2047 /* XXX we should allow --image-opts to trigger use of
2048 * img_open() here, but then we have trouble with
2049 * the bdrv_create() call which takes different params.
2050 * Not critical right now, so fix can wait...
2052 out_blk = img_open_file(out_filename, out_fmt, flags, writethrough, quiet);
2057 out_bs = blk_bs(out_blk);
2059 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
2060 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2062 bufsectors = MIN(32768,
2063 MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
2064 out_bs->bl.discard_alignment))
2068 int64_t output_sectors = blk_nb_sectors(out_blk);
2069 if (output_sectors < 0) {
2070 error_report("unable to get output image length: %s",
2071 strerror(-output_sectors));
2074 } else if (output_sectors < total_sectors) {
2075 error_report("output file is smaller than input file");
2081 cluster_sectors = 0;
2082 ret = bdrv_get_info(out_bs, &bdi);
2085 error_report("could not get block driver info");
2089 compress = compress || bdi.needs_compressed_writes;
2090 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2093 state = (ImgConvertState) {
2095 .src_sectors = bs_sectors,
2097 .total_sectors = total_sectors,
2099 .compressed = compress,
2100 .target_has_backing = (bool) out_baseimg,
2101 .min_sparse = min_sparse,
2102 .cluster_sectors = cluster_sectors,
2103 .buf_sectors = bufsectors,
2105 ret = convert_do_copy(&state);
2109 qemu_progress_print(100, 0);
2111 qemu_progress_end();
2112 qemu_opts_del(opts);
2113 qemu_opts_free(create_opts);
2114 qemu_opts_del(sn_opts);
2118 for (bs_i = 0; bs_i < bs_n; bs_i++) {
2119 blk_unref(blk[bs_i]);
2134 static void dump_snapshots(BlockDriverState *bs)
2136 QEMUSnapshotInfo *sn_tab, *sn;
2139 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2142 printf("Snapshot list:\n");
2143 bdrv_snapshot_dump(fprintf, stdout, NULL);
2145 for(i = 0; i < nb_sns; i++) {
2147 bdrv_snapshot_dump(fprintf, stdout, sn);
2153 static void dump_json_image_info_list(ImageInfoList *list)
2155 Error *local_err = NULL;
2157 QmpOutputVisitor *ov = qmp_output_visitor_new();
2159 visit_type_ImageInfoList(qmp_output_get_visitor(ov), NULL, &list,
2161 obj = qmp_output_get_qobject(ov);
2162 str = qobject_to_json_pretty(obj);
2163 assert(str != NULL);
2164 printf("%s\n", qstring_get_str(str));
2165 qobject_decref(obj);
2166 qmp_output_visitor_cleanup(ov);
2170 static void dump_json_image_info(ImageInfo *info)
2172 Error *local_err = NULL;
2174 QmpOutputVisitor *ov = qmp_output_visitor_new();
2176 visit_type_ImageInfo(qmp_output_get_visitor(ov), NULL, &info, &local_err);
2177 obj = qmp_output_get_qobject(ov);
2178 str = qobject_to_json_pretty(obj);
2179 assert(str != NULL);
2180 printf("%s\n", qstring_get_str(str));
2181 qobject_decref(obj);
2182 qmp_output_visitor_cleanup(ov);
2186 static void dump_human_image_info_list(ImageInfoList *list)
2188 ImageInfoList *elem;
2191 for (elem = list; elem; elem = elem->next) {
2197 bdrv_image_info_dump(fprintf, stdout, elem->value);
2201 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2203 return strcmp(a, b) == 0;
2207 * Open an image file chain and return an ImageInfoList
2209 * @filename: topmost image filename
2210 * @fmt: topmost image format (may be NULL to autodetect)
2211 * @chain: true - enumerate entire backing file chain
2212 * false - only topmost image file
2214 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2215 * image file. If there was an error a message will have been printed to
2218 static ImageInfoList *collect_image_info_list(bool image_opts,
2219 const char *filename,
2223 ImageInfoList *head = NULL;
2224 ImageInfoList **last = &head;
2225 GHashTable *filenames;
2228 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2232 BlockDriverState *bs;
2234 ImageInfoList *elem;
2236 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2237 error_report("Backing file '%s' creates an infinite loop.",
2241 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2243 blk = img_open(image_opts, filename, fmt,
2244 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false);
2250 bdrv_query_image_info(bs, &info, &err);
2252 error_report_err(err);
2257 elem = g_new0(ImageInfoList, 1);
2264 filename = fmt = NULL;
2266 if (info->has_full_backing_filename) {
2267 filename = info->full_backing_filename;
2268 } else if (info->has_backing_filename) {
2269 error_report("Could not determine absolute backing filename,"
2270 " but backing filename '%s' present",
2271 info->backing_filename);
2274 if (info->has_backing_filename_format) {
2275 fmt = info->backing_filename_format;
2279 g_hash_table_destroy(filenames);
2283 qapi_free_ImageInfoList(head);
2284 g_hash_table_destroy(filenames);
2288 static int img_info(int argc, char **argv)
2291 OutputFormat output_format = OFORMAT_HUMAN;
2293 const char *filename, *fmt, *output;
2294 ImageInfoList *list;
2295 bool image_opts = false;
2300 int option_index = 0;
2301 static const struct option long_options[] = {
2302 {"help", no_argument, 0, 'h'},
2303 {"format", required_argument, 0, 'f'},
2304 {"output", required_argument, 0, OPTION_OUTPUT},
2305 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2306 {"object", required_argument, 0, OPTION_OBJECT},
2307 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2310 c = getopt_long(argc, argv, "f:h",
2311 long_options, &option_index);
2326 case OPTION_BACKING_CHAIN:
2329 case OPTION_OBJECT: {
2331 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2337 case OPTION_IMAGE_OPTS:
2342 if (optind != argc - 1) {
2343 error_exit("Expecting one image file name");
2345 filename = argv[optind++];
2347 if (output && !strcmp(output, "json")) {
2348 output_format = OFORMAT_JSON;
2349 } else if (output && !strcmp(output, "human")) {
2350 output_format = OFORMAT_HUMAN;
2351 } else if (output) {
2352 error_report("--output must be used with human or json as argument.");
2356 if (qemu_opts_foreach(&qemu_object_opts,
2357 user_creatable_add_opts_foreach,
2362 list = collect_image_info_list(image_opts, filename, fmt, chain);
2367 switch (output_format) {
2369 dump_human_image_info_list(list);
2373 dump_json_image_info_list(list);
2375 dump_json_image_info(list->value);
2380 qapi_free_ImageInfoList(list);
2384 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2387 switch (output_format) {
2389 if (e->data && !e->has_offset) {
2390 error_report("File contains external, encrypted or compressed clusters.");
2393 if (e->data && !e->zero) {
2394 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2395 e->start, e->length,
2396 e->has_offset ? e->offset : 0,
2397 e->has_filename ? e->filename : "");
2399 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2400 * Modify the flags here to allow more coalescing.
2402 if (next && (!next->data || next->zero)) {
2408 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2409 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2410 (e->start == 0 ? "[" : ",\n"),
2411 e->start, e->length, e->depth,
2412 e->zero ? "true" : "false",
2413 e->data ? "true" : "false");
2414 if (e->has_offset) {
2415 printf(", \"offset\": %"PRId64"", e->offset);
2426 static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2427 int nb_sectors, MapEntry *e)
2431 BlockDriverState *file;
2434 /* As an optimization, we could cache the current range of unallocated
2435 * clusters in each file of the chain, and avoid querying the same
2441 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2447 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2450 bs = backing_bs(bs);
2459 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2462 .start = sector_num * BDRV_SECTOR_SIZE,
2463 .length = nb_sectors * BDRV_SECTOR_SIZE,
2464 .data = !!(ret & BDRV_BLOCK_DATA),
2465 .zero = !!(ret & BDRV_BLOCK_ZERO),
2466 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2467 .has_offset = has_offset,
2469 .has_filename = file && has_offset,
2470 .filename = file && has_offset ? file->filename : NULL,
2476 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2478 if (curr->length == 0) {
2481 if (curr->zero != next->zero ||
2482 curr->data != next->data ||
2483 curr->depth != next->depth ||
2484 curr->has_filename != next->has_filename ||
2485 curr->has_offset != next->has_offset) {
2488 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2491 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2497 static int img_map(int argc, char **argv)
2500 OutputFormat output_format = OFORMAT_HUMAN;
2502 BlockDriverState *bs;
2503 const char *filename, *fmt, *output;
2505 MapEntry curr = { .length = 0 }, next;
2507 bool image_opts = false;
2512 int option_index = 0;
2513 static const struct option long_options[] = {
2514 {"help", no_argument, 0, 'h'},
2515 {"format", required_argument, 0, 'f'},
2516 {"output", required_argument, 0, OPTION_OUTPUT},
2517 {"object", required_argument, 0, OPTION_OBJECT},
2518 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2521 c = getopt_long(argc, argv, "f:h",
2522 long_options, &option_index);
2537 case OPTION_OBJECT: {
2539 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2545 case OPTION_IMAGE_OPTS:
2550 if (optind != argc - 1) {
2551 error_exit("Expecting one image file name");
2553 filename = argv[optind];
2555 if (output && !strcmp(output, "json")) {
2556 output_format = OFORMAT_JSON;
2557 } else if (output && !strcmp(output, "human")) {
2558 output_format = OFORMAT_HUMAN;
2559 } else if (output) {
2560 error_report("--output must be used with human or json as argument.");
2564 if (qemu_opts_foreach(&qemu_object_opts,
2565 user_creatable_add_opts_foreach,
2570 blk = img_open(image_opts, filename, fmt, 0, false, 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_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,
2713 /* Open the image */
2714 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, 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;
2776 bool writethrough, src_writethrough;
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,
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_mode(cache, &flags, &writethrough);
2868 error_report("Invalid cache option: %s", cache);
2873 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2875 error_report("Invalid source cache option: %s", src_cache);
2879 /* The source files are opened read-only, don't care about WCE */
2880 assert((src_flags & BDRV_O_RDWR) == 0);
2881 (void) src_writethrough;
2886 * Ignore the old backing file for unsafe rebase in case we want to correct
2887 * the reference to a renamed or moved backing file.
2889 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
2896 if (out_basefmt != NULL) {
2897 if (bdrv_find_format(out_basefmt) == NULL) {
2898 error_report("Invalid format name: '%s'", out_basefmt);
2904 /* For safe rebasing we need to compare old and new backing file */
2906 char backing_name[PATH_MAX];
2907 QDict *options = NULL;
2909 if (bs->backing_format[0] != '\0') {
2910 options = qdict_new();
2911 qdict_put(options, "driver", qstring_from_str(bs->backing_format));
2914 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2915 blk_old_backing = blk_new_open(backing_name, NULL,
2916 options, src_flags, &local_err);
2917 if (!blk_old_backing) {
2918 error_reportf_err(local_err,
2919 "Could not open old backing file '%s': ",
2924 if (out_baseimg[0]) {
2926 options = qdict_new();
2927 qdict_put(options, "driver", qstring_from_str(out_basefmt));
2932 blk_new_backing = blk_new_open(out_baseimg, NULL,
2933 options, src_flags, &local_err);
2934 if (!blk_new_backing) {
2935 error_reportf_err(local_err,
2936 "Could not open new backing file '%s': ",
2944 * Check each unallocated cluster in the COW file. If it is unallocated,
2945 * accesses go to the backing file. We must therefore compare this cluster
2946 * in the old and new backing file, and if they differ we need to copy it
2947 * from the old backing file into the COW file.
2949 * If qemu-img crashes during this step, no harm is done. The content of
2950 * the image is the same as the original one at any time.
2953 int64_t num_sectors;
2954 int64_t old_backing_num_sectors;
2955 int64_t new_backing_num_sectors = 0;
2958 float local_progress = 0;
2960 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
2961 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
2963 num_sectors = blk_nb_sectors(blk);
2964 if (num_sectors < 0) {
2965 error_report("Could not get size of '%s': %s",
2966 filename, strerror(-num_sectors));
2970 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
2971 if (old_backing_num_sectors < 0) {
2972 char backing_name[PATH_MAX];
2974 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2975 error_report("Could not get size of '%s': %s",
2976 backing_name, strerror(-old_backing_num_sectors));
2980 if (blk_new_backing) {
2981 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
2982 if (new_backing_num_sectors < 0) {
2983 error_report("Could not get size of '%s': %s",
2984 out_baseimg, strerror(-new_backing_num_sectors));
2990 if (num_sectors != 0) {
2991 local_progress = (float)100 /
2992 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
2995 for (sector = 0; sector < num_sectors; sector += n) {
2997 /* How many sectors can we handle with the next read? */
2998 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
2999 n = (IO_BUF_SIZE / 512);
3001 n = num_sectors - sector;
3004 /* If the cluster is allocated, we don't need to take action */
3005 ret = bdrv_is_allocated(bs, sector, n, &n);
3007 error_report("error while reading image metadata: %s",
3016 * Read old and new backing file and take into consideration that
3017 * backing files may be smaller than the COW image.
3019 if (sector >= old_backing_num_sectors) {
3020 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3022 if (sector + n > old_backing_num_sectors) {
3023 n = old_backing_num_sectors - sector;
3026 ret = blk_read(blk_old_backing, sector, buf_old, n);
3028 error_report("error while reading from old backing file");
3033 if (sector >= new_backing_num_sectors || !blk_new_backing) {
3034 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3036 if (sector + n > new_backing_num_sectors) {
3037 n = new_backing_num_sectors - sector;
3040 ret = blk_read(blk_new_backing, sector, buf_new, n);
3042 error_report("error while reading from new backing file");
3047 /* If they differ, we need to write to the COW file */
3048 uint64_t written = 0;
3050 while (written < n) {
3053 if (compare_sectors(buf_old + written * 512,
3054 buf_new + written * 512, n - written, &pnum))
3056 ret = blk_write(blk, sector + written,
3057 buf_old + written * 512, pnum);
3059 error_report("Error while writing to COW image: %s",
3067 qemu_progress_print(local_progress, 100);
3072 * Change the backing file. All clusters that are different from the old
3073 * backing file are overwritten in the COW file now, so the visible content
3074 * doesn't change when we switch the backing file.
3076 if (out_baseimg && *out_baseimg) {
3077 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3079 ret = bdrv_change_backing_file(bs, NULL, NULL);
3082 if (ret == -ENOSPC) {
3083 error_report("Could not change the backing file to '%s': No "
3084 "space left in the file header", out_baseimg);
3085 } else if (ret < 0) {
3086 error_report("Could not change the backing file to '%s': %s",
3087 out_baseimg, strerror(-ret));
3090 qemu_progress_print(100, 0);
3092 * TODO At this point it is possible to check if any clusters that are
3093 * allocated in the COW file are the same in the backing file. If so, they
3094 * could be dropped from the COW file. Don't do this before switching the
3095 * backing file, in case of a crash this would lead to corruption.
3098 qemu_progress_end();
3101 blk_unref(blk_old_backing);
3102 blk_unref(blk_new_backing);
3104 qemu_vfree(buf_old);
3105 qemu_vfree(buf_new);
3114 static int img_resize(int argc, char **argv)
3117 int c, ret, relative;
3118 const char *filename, *fmt, *size;
3119 int64_t n, total_size;
3121 BlockBackend *blk = NULL;
3124 static QemuOptsList resize_options = {
3125 .name = "resize_options",
3126 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3129 .name = BLOCK_OPT_SIZE,
3130 .type = QEMU_OPT_SIZE,
3131 .help = "Virtual disk size"
3137 bool image_opts = false;
3139 /* Remove size from argv manually so that negative numbers are not treated
3140 * as options by getopt. */
3142 error_exit("Not enough arguments");
3146 size = argv[--argc];
3148 /* Parse getopt arguments */
3151 static const struct option long_options[] = {
3152 {"help", no_argument, 0, 'h'},
3153 {"object", required_argument, 0, OPTION_OBJECT},
3154 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3157 c = getopt_long(argc, argv, "f:hq",
3158 long_options, NULL);
3173 case OPTION_OBJECT: {
3175 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3181 case OPTION_IMAGE_OPTS:
3186 if (optind != argc - 1) {
3187 error_exit("Expecting one image file name");
3189 filename = argv[optind++];
3191 if (qemu_opts_foreach(&qemu_object_opts,
3192 user_creatable_add_opts_foreach,
3197 /* Choose grow, shrink, or absolute resize mode */
3213 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3214 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3216 error_report_err(err);
3218 qemu_opts_del(param);
3221 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3222 qemu_opts_del(param);
3224 blk = img_open(image_opts, filename, fmt,
3225 BDRV_O_RDWR, false, quiet);
3232 total_size = blk_getlength(blk) + n * relative;
3236 if (total_size <= 0) {
3237 error_report("New image size must be positive");
3242 ret = blk_truncate(blk, total_size);
3245 qprintf(quiet, "Image resized.\n");
3248 error_report("This image does not support resize");
3251 error_report("Image is read-only");
3254 error_report("Error resizing image (%d)", -ret);
3265 static void amend_status_cb(BlockDriverState *bs,
3266 int64_t offset, int64_t total_work_size,
3269 qemu_progress_print(100.f * offset / total_work_size, 0);
3272 static int img_amend(int argc, char **argv)
3276 char *options = NULL;
3277 QemuOptsList *create_opts = NULL;
3278 QemuOpts *opts = NULL;
3279 const char *fmt = NULL, *filename, *cache;
3282 bool quiet = false, progress = false;
3283 BlockBackend *blk = NULL;
3284 BlockDriverState *bs = NULL;
3285 bool image_opts = false;
3287 cache = BDRV_DEFAULT_CACHE;
3289 static const struct option long_options[] = {
3290 {"help", no_argument, 0, 'h'},
3291 {"object", required_argument, 0, OPTION_OBJECT},
3292 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3295 c = getopt_long(argc, argv, "ho:f:t:pq",
3296 long_options, NULL);
3307 if (!is_valid_option_list(optarg)) {
3308 error_report("Invalid option list: %s", optarg);
3310 goto out_no_progress;
3313 options = g_strdup(optarg);
3315 char *old_options = options;
3316 options = g_strdup_printf("%s,%s", options, optarg);
3317 g_free(old_options);
3333 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3337 goto out_no_progress;
3340 case OPTION_IMAGE_OPTS:
3347 error_exit("Must specify options (-o)");
3350 if (qemu_opts_foreach(&qemu_object_opts,
3351 user_creatable_add_opts_foreach,
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_RDWR;
3377 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3379 error_report("Invalid cache option: %s", cache);
3383 blk = img_open(image_opts, filename, fmt, flags, writethrough, 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 if (qcrypto_init(&local_error) < 0) {
3474 error_reportf_err(local_error, "cannot initialize crypto: ");
3478 module_call_init(MODULE_INIT_QOM);
3481 error_exit("Not enough arguments");
3485 qemu_add_opts(&qemu_object_opts);
3486 qemu_add_opts(&qemu_source_opts);
3488 /* find the command */
3489 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
3490 if (!strcmp(cmdname, cmd->name)) {
3491 return cmd->handler(argc - 1, argv + 1);
3495 c = getopt_long(argc, argv, "h", long_options, NULL);
3501 printf(QEMU_IMG_VERSION);
3506 error_exit("Command not found: %s", cmdname);