2 * QEMU disk image utility
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 #include "qemu/osdep.h"
25 #include "qapi/error.h"
26 #include "qapi-visit.h"
27 #include "qapi/qmp-output-visitor.h"
28 #include "qapi/qmp/qerror.h"
29 #include "qapi/qmp/qjson.h"
30 #include "qemu/cutils.h"
31 #include "qemu/config-file.h"
32 #include "qemu/option.h"
33 #include "qemu/error-report.h"
34 #include "qom/object_interfaces.h"
35 #include "sysemu/sysemu.h"
36 #include "sysemu/block-backend.h"
37 #include "block/block_int.h"
38 #include "block/blockjob.h"
39 #include "block/qapi.h"
42 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
43 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
45 typedef struct img_cmd_t {
47 int (*handler)(int argc, char **argv);
52 OPTION_BACKING_CHAIN = 257,
54 OPTION_IMAGE_OPTS = 259,
57 typedef enum OutputFormat {
62 /* Default to cache=writeback as data integrity is not important for qemu-img */
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 int flags, bool quiet)
229 BlockDriverState *bs;
233 if (bdrv_is_encrypted(bs) && bdrv_key_required(bs) &&
234 !(flags & BDRV_O_NO_IO)) {
235 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
236 if (qemu_read_password(password, sizeof(password)) < 0) {
237 error_report("No password given");
240 if (bdrv_set_key(bs, password) < 0) {
241 error_report("invalid password");
249 static BlockBackend *img_open_opts(const char *optstr,
250 QemuOpts *opts, int flags, bool writethrough,
254 Error *local_err = NULL;
256 options = qemu_opts_to_qdict(opts, NULL);
257 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
259 error_reportf_err(local_err, "Could not open '%s'", optstr);
262 blk_set_enable_write_cache(blk, !writethrough);
264 if (img_open_password(blk, optstr, flags, quiet) < 0) {
271 static BlockBackend *img_open_file(const char *filename,
272 const char *fmt, int flags,
273 bool writethrough, bool quiet)
276 Error *local_err = NULL;
277 QDict *options = NULL;
280 options = qdict_new();
281 qdict_put(options, "driver", qstring_from_str(fmt));
284 blk = blk_new_open(filename, NULL, options, flags, &local_err);
286 error_reportf_err(local_err, "Could not open '%s': ", filename);
289 blk_set_enable_write_cache(blk, !writethrough);
291 if (img_open_password(blk, filename, flags, quiet) < 0) {
299 static BlockBackend *img_open(bool image_opts,
300 const char *filename,
301 const char *fmt, int flags, bool writethrough,
308 error_report("--image-opts and --format are mutually exclusive");
311 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
316 blk = img_open_opts(filename, opts, flags, writethrough, quiet);
318 blk = img_open_file(filename, fmt, flags, writethrough, quiet);
324 static int add_old_style_options(const char *fmt, QemuOpts *opts,
325 const char *base_filename,
326 const char *base_fmt)
331 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
333 error_report("Backing file not supported for file format '%s'",
340 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
342 error_report("Backing file format not supported for file "
351 static int img_create(int argc, char **argv)
354 uint64_t img_size = -1;
355 const char *fmt = "raw";
356 const char *base_fmt = NULL;
357 const char *filename;
358 const char *base_filename = NULL;
359 char *options = NULL;
360 Error *local_err = NULL;
364 static const struct option long_options[] = {
365 {"help", no_argument, 0, 'h'},
366 {"object", required_argument, 0, OPTION_OBJECT},
369 c = getopt_long(argc, argv, "F:b:f:he6o:q",
383 base_filename = optarg;
389 error_report("option -e is deprecated, please use \'-o "
390 "encryption\' instead!");
393 error_report("option -6 is deprecated, please use \'-o "
394 "compat6\' instead!");
397 if (!is_valid_option_list(optarg)) {
398 error_report("Invalid option list: %s", optarg);
402 options = g_strdup(optarg);
404 char *old_options = options;
405 options = g_strdup_printf("%s,%s", options, optarg);
412 case OPTION_OBJECT: {
414 opts = qemu_opts_parse_noisily(&qemu_object_opts,
423 /* Get the filename */
424 filename = (optind < argc) ? argv[optind] : NULL;
425 if (options && has_help_option(options)) {
427 return print_block_option_help(filename, fmt);
430 if (optind >= argc) {
431 error_exit("Expecting image file name");
435 if (qemu_opts_foreach(&qemu_object_opts,
436 user_creatable_add_opts_foreach,
438 error_report_err(local_err);
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 Error *local_err = NULL;
601 bool image_opts = false;
605 cache = BDRV_DEFAULT_CACHE;
608 int option_index = 0;
609 static const struct option long_options[] = {
610 {"help", no_argument, 0, 'h'},
611 {"format", required_argument, 0, 'f'},
612 {"repair", required_argument, 0, 'r'},
613 {"output", required_argument, 0, OPTION_OUTPUT},
614 {"object", required_argument, 0, OPTION_OBJECT},
615 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
618 c = getopt_long(argc, argv, "hf:r:T:q",
619 long_options, &option_index);
632 flags |= BDRV_O_RDWR;
634 if (!strcmp(optarg, "leaks")) {
635 fix = BDRV_FIX_LEAKS;
636 } else if (!strcmp(optarg, "all")) {
637 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
639 error_exit("Unknown option value for -r "
640 "(expecting 'leaks' or 'all'): %s", optarg);
652 case OPTION_OBJECT: {
654 opts = qemu_opts_parse_noisily(&qemu_object_opts,
660 case OPTION_IMAGE_OPTS:
665 if (optind != argc - 1) {
666 error_exit("Expecting one image file name");
668 filename = argv[optind++];
670 if (output && !strcmp(output, "json")) {
671 output_format = OFORMAT_JSON;
672 } else if (output && !strcmp(output, "human")) {
673 output_format = OFORMAT_HUMAN;
675 error_report("--output must be used with human or json as argument.");
679 if (qemu_opts_foreach(&qemu_object_opts,
680 user_creatable_add_opts_foreach,
682 error_report_err(local_err);
686 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
688 error_report("Invalid source cache option: %s", cache);
692 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
698 check = g_new0(ImageCheck, 1);
699 ret = collect_image_check(bs, check, filename, fmt, fix);
701 if (ret == -ENOTSUP) {
702 error_report("This image format does not support checks");
707 if (check->corruptions_fixed || check->leaks_fixed) {
708 int corruptions_fixed, leaks_fixed;
710 leaks_fixed = check->leaks_fixed;
711 corruptions_fixed = check->corruptions_fixed;
713 if (output_format == OFORMAT_HUMAN) {
715 "The following inconsistencies were found and repaired:\n\n"
716 " %" PRId64 " leaked clusters\n"
717 " %" PRId64 " corruptions\n\n"
718 "Double checking the fixed image now...\n",
720 check->corruptions_fixed);
723 ret = collect_image_check(bs, check, filename, fmt, 0);
725 check->leaks_fixed = leaks_fixed;
726 check->corruptions_fixed = corruptions_fixed;
730 switch (output_format) {
732 dump_human_image_check(check, quiet);
735 dump_json_image_check(check, quiet);
740 if (ret || check->check_errors) {
742 error_report("Check failed: %s", strerror(-ret));
744 error_report("Check failed");
750 if (check->corruptions) {
752 } else if (check->leaks) {
759 qapi_free_ImageCheck(check);
764 typedef struct CommonBlockJobCBInfo {
765 BlockDriverState *bs;
767 } CommonBlockJobCBInfo;
769 static void common_block_job_cb(void *opaque, int ret)
771 CommonBlockJobCBInfo *cbi = opaque;
774 error_setg_errno(cbi->errp, -ret, "Block job failed");
778 static void run_block_job(BlockJob *job, Error **errp)
780 AioContext *aio_context = bdrv_get_aio_context(job->bs);
783 aio_poll(aio_context, true);
784 qemu_progress_print(job->len ?
785 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
786 } while (!job->ready);
788 block_job_complete_sync(job, errp);
790 /* A block job may finish instantaneously without publishing any progress,
791 * so just signal completion here */
792 qemu_progress_print(100.f, 0);
795 static int img_commit(int argc, char **argv)
798 const char *filename, *fmt, *cache, *base;
800 BlockDriverState *bs, *base_bs;
801 bool progress = false, quiet = false, drop = false;
803 Error *local_err = NULL;
804 CommonBlockJobCBInfo cbi;
805 bool image_opts = false;
808 cache = BDRV_DEFAULT_CACHE;
811 static const struct option long_options[] = {
812 {"help", no_argument, 0, 'h'},
813 {"object", required_argument, 0, OPTION_OBJECT},
814 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
817 c = getopt_long(argc, argv, "f:ht:b:dpq",
847 case OPTION_OBJECT: {
849 opts = qemu_opts_parse_noisily(&qemu_object_opts,
855 case OPTION_IMAGE_OPTS:
861 /* Progress is not shown in Quiet mode */
866 if (optind != argc - 1) {
867 error_exit("Expecting one image file name");
869 filename = argv[optind++];
871 if (qemu_opts_foreach(&qemu_object_opts,
872 user_creatable_add_opts_foreach,
874 error_report_err(local_err);
878 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
879 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
881 error_report("Invalid cache option: %s", cache);
885 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
891 qemu_progress_init(progress, 1.f);
892 qemu_progress_print(0.f, 100);
895 base_bs = bdrv_find_backing_image(bs, base);
897 error_setg(&local_err, QERR_BASE_NOT_FOUND, base);
901 /* This is different from QMP, which by default uses the deepest file in
902 * the backing chain (i.e., the very base); however, the traditional
903 * behavior of qemu-img commit is using the immediate backing file. */
904 base_bs = backing_bs(bs);
906 error_setg(&local_err, "Image does not have a backing file");
911 cbi = (CommonBlockJobCBInfo){
916 commit_active_start(bs, base_bs, 0, BLOCKDEV_ON_ERROR_REPORT,
917 common_block_job_cb, &cbi, &local_err);
922 /* When the block job completes, the BlockBackend reference will point to
923 * the old backing file. In order to avoid that the top image is already
924 * deleted, so we can still empty it afterwards, increment the reference
925 * counter here preemptively. */
930 run_block_job(bs->job, &local_err);
935 if (!drop && bs->drv->bdrv_make_empty) {
936 ret = bs->drv->bdrv_make_empty(bs);
938 error_setg_errno(&local_err, -ret, "Could not empty %s",
955 error_report_err(local_err);
959 qprintf(quiet, "Image committed.\n");
964 * Returns true iff the first sector pointed to by 'buf' contains at least
967 * 'pnum' is set to the number of sectors (including and immediately following
968 * the first one) that are known to be in the same allocated/unallocated state.
970 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
979 is_zero = buffer_is_zero(buf, 512);
980 for(i = 1; i < n; i++) {
982 if (is_zero != buffer_is_zero(buf, 512)) {
991 * Like is_allocated_sectors, but if the buffer starts with a used sector,
992 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
993 * breaking up write requests for only small sparse areas.
995 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
999 int num_checked, num_used;
1005 ret = is_allocated_sectors(buf, n, pnum);
1011 buf += BDRV_SECTOR_SIZE * *pnum;
1013 num_checked = num_used;
1016 ret = is_allocated_sectors(buf, n, pnum);
1018 buf += BDRV_SECTOR_SIZE * *pnum;
1020 num_checked += *pnum;
1022 num_used = num_checked;
1023 } else if (*pnum >= min) {
1033 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1034 * buffers matches, non-zero otherwise.
1036 * pnum is set to the number of sectors (including and immediately following
1037 * the first one) that are known to have the same comparison result
1039 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1050 res = !!memcmp(buf1, buf2, 512);
1051 for(i = 1; i < n; i++) {
1055 if (!!memcmp(buf1, buf2, 512) != res) {
1064 #define IO_BUF_SIZE (2 * 1024 * 1024)
1066 static int64_t sectors_to_bytes(int64_t sectors)
1068 return sectors << BDRV_SECTOR_BITS;
1071 static int64_t sectors_to_process(int64_t total, int64_t from)
1073 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1077 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1079 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1080 * data and negative value on error.
1082 * @param blk: BlockBackend for the image
1083 * @param sect_num: Number of first sector to check
1084 * @param sect_count: Number of sectors to check
1085 * @param filename: Name of disk file we are checking (logging purpose)
1086 * @param buffer: Allocated buffer for storing read data
1087 * @param quiet: Flag for quiet mode
1089 static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
1090 int sect_count, const char *filename,
1091 uint8_t *buffer, bool quiet)
1094 ret = blk_read(blk, sect_num, buffer, sect_count);
1096 error_report("Error while reading offset %" PRId64 " of %s: %s",
1097 sectors_to_bytes(sect_num), filename, strerror(-ret));
1100 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1101 if (ret || pnum != sect_count) {
1102 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1103 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1111 * Compares two images. Exit codes:
1113 * 0 - Images are identical
1115 * >1 - Error occurred
1117 static int img_compare(int argc, char **argv)
1119 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1120 BlockBackend *blk1, *blk2;
1121 BlockDriverState *bs1, *bs2;
1122 int64_t total_sectors1, total_sectors2;
1123 uint8_t *buf1 = NULL, *buf2 = NULL;
1125 int allocated1, allocated2;
1126 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1127 bool progress = false, quiet = false, strict = false;
1130 int64_t total_sectors;
1131 int64_t sector_num = 0;
1134 uint64_t progress_base;
1135 Error *local_err = NULL;
1136 bool image_opts = false;
1138 cache = BDRV_DEFAULT_CACHE;
1140 static const struct option long_options[] = {
1141 {"help", no_argument, 0, 'h'},
1142 {"object", required_argument, 0, OPTION_OBJECT},
1143 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1146 c = getopt_long(argc, argv, "hf:F:T:pqs",
1147 long_options, NULL);
1174 case OPTION_OBJECT: {
1176 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1183 case OPTION_IMAGE_OPTS:
1189 /* Progress is not shown in Quiet mode */
1195 if (optind != argc - 2) {
1196 error_exit("Expecting two image file names");
1198 filename1 = argv[optind++];
1199 filename2 = argv[optind++];
1201 if (qemu_opts_foreach(&qemu_object_opts,
1202 user_creatable_add_opts_foreach,
1203 NULL, &local_err)) {
1204 error_report_err(local_err);
1209 /* Initialize before goto out */
1210 qemu_progress_init(progress, 2.0);
1213 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1215 error_report("Invalid source cache option: %s", cache);
1220 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet);
1226 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet);
1234 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1235 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1236 total_sectors1 = blk_nb_sectors(blk1);
1237 if (total_sectors1 < 0) {
1238 error_report("Can't get size of %s: %s",
1239 filename1, strerror(-total_sectors1));
1243 total_sectors2 = blk_nb_sectors(blk2);
1244 if (total_sectors2 < 0) {
1245 error_report("Can't get size of %s: %s",
1246 filename2, strerror(-total_sectors2));
1250 total_sectors = MIN(total_sectors1, total_sectors2);
1251 progress_base = MAX(total_sectors1, total_sectors2);
1253 qemu_progress_print(0, 100);
1255 if (strict && total_sectors1 != total_sectors2) {
1257 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1262 int64_t status1, status2;
1263 BlockDriverState *file;
1265 nb_sectors = sectors_to_process(total_sectors, sector_num);
1266 if (nb_sectors <= 0) {
1269 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1270 total_sectors1 - sector_num,
1274 error_report("Sector allocation test failed for %s", filename1);
1277 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1279 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1280 total_sectors2 - sector_num,
1284 error_report("Sector allocation test failed for %s", filename2);
1287 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1289 nb_sectors = MIN(nb_sectors, pnum1);
1292 nb_sectors = MIN(nb_sectors, pnum2);
1296 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1297 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1299 qprintf(quiet, "Strict mode: Offset %" PRId64
1300 " block status mismatch!\n",
1301 sectors_to_bytes(sector_num));
1305 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1306 nb_sectors = MIN(pnum1, pnum2);
1307 } else if (allocated1 == allocated2) {
1309 ret = blk_read(blk1, sector_num, buf1, nb_sectors);
1311 error_report("Error while reading offset %" PRId64 " of %s:"
1312 " %s", sectors_to_bytes(sector_num), filename1,
1317 ret = blk_read(blk2, sector_num, buf2, nb_sectors);
1319 error_report("Error while reading offset %" PRId64
1320 " of %s: %s", sectors_to_bytes(sector_num),
1321 filename2, strerror(-ret));
1325 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1326 if (ret || pnum != nb_sectors) {
1327 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1329 ret ? sector_num : sector_num + pnum));
1337 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
1338 filename1, buf1, quiet);
1340 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
1341 filename2, buf1, quiet);
1345 error_report("Error while reading offset %" PRId64 ": %s",
1346 sectors_to_bytes(sector_num), strerror(-ret));
1352 sector_num += nb_sectors;
1353 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1356 if (total_sectors1 != total_sectors2) {
1357 BlockBackend *blk_over;
1358 int64_t total_sectors_over;
1359 const char *filename_over;
1361 qprintf(quiet, "Warning: Image size mismatch!\n");
1362 if (total_sectors1 > total_sectors2) {
1363 total_sectors_over = total_sectors1;
1365 filename_over = filename1;
1367 total_sectors_over = total_sectors2;
1369 filename_over = filename2;
1373 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1374 if (nb_sectors <= 0) {
1377 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,
1381 error_report("Sector allocation test failed for %s",
1388 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
1389 filename_over, buf1, quiet);
1392 error_report("Error while reading offset %" PRId64
1393 " of %s: %s", sectors_to_bytes(sector_num),
1394 filename_over, strerror(-ret));
1400 sector_num += nb_sectors;
1401 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1405 qprintf(quiet, "Images are identical.\n");
1415 qemu_progress_end();
1420 enum ImgConvertBlockStatus {
1426 typedef struct ImgConvertState {
1428 int64_t *src_sectors;
1429 int src_cur, src_num;
1430 int64_t src_cur_offset;
1431 int64_t total_sectors;
1432 int64_t allocated_sectors;
1433 enum ImgConvertBlockStatus status;
1434 int64_t sector_next_status;
1435 BlockBackend *target;
1438 bool target_has_backing;
1440 size_t cluster_sectors;
1444 static void convert_select_part(ImgConvertState *s, int64_t sector_num)
1446 assert(sector_num >= s->src_cur_offset);
1447 while (sector_num - s->src_cur_offset >= s->src_sectors[s->src_cur]) {
1448 s->src_cur_offset += s->src_sectors[s->src_cur];
1450 assert(s->src_cur < s->src_num);
1454 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1459 convert_select_part(s, sector_num);
1461 assert(s->total_sectors > sector_num);
1462 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1464 if (s->sector_next_status <= sector_num) {
1465 BlockDriverState *file;
1466 ret = bdrv_get_block_status(blk_bs(s->src[s->src_cur]),
1467 sector_num - s->src_cur_offset,
1473 if (ret & BDRV_BLOCK_ZERO) {
1474 s->status = BLK_ZERO;
1475 } else if (ret & BDRV_BLOCK_DATA) {
1476 s->status = BLK_DATA;
1477 } else if (!s->target_has_backing) {
1478 /* Without a target backing file we must copy over the contents of
1479 * the backing file as well. */
1480 /* TODO Check block status of the backing file chain to avoid
1481 * needlessly reading zeroes and limiting the iteration to the
1483 s->status = BLK_DATA;
1485 s->status = BLK_BACKING_FILE;
1488 s->sector_next_status = sector_num + n;
1491 n = MIN(n, s->sector_next_status - sector_num);
1492 if (s->status == BLK_DATA) {
1493 n = MIN(n, s->buf_sectors);
1496 /* We need to write complete clusters for compressed images, so if an
1497 * unallocated area is shorter than that, we must consider the whole
1498 * cluster allocated. */
1499 if (s->compressed) {
1500 if (n < s->cluster_sectors) {
1501 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1502 s->status = BLK_DATA;
1504 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1511 static int convert_read(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1517 assert(nb_sectors <= s->buf_sectors);
1518 while (nb_sectors > 0) {
1522 /* In the case of compression with multiple source files, we can get a
1523 * nb_sectors that spreads into the next part. So we must be able to
1524 * read across multiple BDSes for one convert_read() call. */
1525 convert_select_part(s, sector_num);
1526 blk = s->src[s->src_cur];
1527 bs_sectors = s->src_sectors[s->src_cur];
1529 n = MIN(nb_sectors, bs_sectors - (sector_num - s->src_cur_offset));
1530 ret = blk_read(blk, sector_num - s->src_cur_offset, buf, n);
1537 buf += n * BDRV_SECTOR_SIZE;
1543 static int convert_write(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1548 while (nb_sectors > 0) {
1551 switch (s->status) {
1552 case BLK_BACKING_FILE:
1553 /* If we have a backing file, leave clusters unallocated that are
1554 * unallocated in the source image, so that the backing file is
1555 * visible at the respective offset. */
1556 assert(s->target_has_backing);
1560 /* We must always write compressed clusters as a whole, so don't
1561 * try to find zeroed parts in the buffer. We can only save the
1562 * write if the buffer is completely zeroed and we're allowed to
1563 * keep the target sparse. */
1564 if (s->compressed) {
1565 if (s->has_zero_init && s->min_sparse &&
1566 buffer_is_zero(buf, n * BDRV_SECTOR_SIZE))
1568 assert(!s->target_has_backing);
1572 ret = blk_write_compressed(s->target, sector_num, buf, n);
1579 /* If there is real non-zero data or we're told to keep the target
1580 * fully allocated (-S 0), we must write it. Otherwise we can treat
1581 * it as zero sectors. */
1582 if (!s->min_sparse ||
1583 is_allocated_sectors_min(buf, n, &n, s->min_sparse))
1585 ret = blk_write(s->target, sector_num, buf, n);
1594 if (s->has_zero_init) {
1597 ret = blk_write_zeroes(s->target, sector_num, n, 0);
1606 buf += n * BDRV_SECTOR_SIZE;
1612 static int convert_do_copy(ImgConvertState *s)
1614 uint8_t *buf = NULL;
1615 int64_t sector_num, allocated_done;
1619 /* Check whether we have zero initialisation or can get it efficiently */
1620 s->has_zero_init = s->min_sparse && !s->target_has_backing
1621 ? bdrv_has_zero_init(blk_bs(s->target))
1624 if (!s->has_zero_init && !s->target_has_backing &&
1625 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1627 ret = bdrv_make_zero(blk_bs(s->target), BDRV_REQ_MAY_UNMAP);
1629 s->has_zero_init = true;
1633 /* Allocate buffer for copied data. For compressed images, only one cluster
1634 * can be copied at a time. */
1635 if (s->compressed) {
1636 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1637 error_report("invalid cluster size");
1641 s->buf_sectors = s->cluster_sectors;
1643 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1645 /* Calculate allocated sectors for progress */
1646 s->allocated_sectors = 0;
1648 while (sector_num < s->total_sectors) {
1649 n = convert_iteration_sectors(s, sector_num);
1654 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1656 s->allocated_sectors += n;
1663 s->src_cur_offset = 0;
1664 s->sector_next_status = 0;
1669 while (sector_num < s->total_sectors) {
1670 n = convert_iteration_sectors(s, sector_num);
1675 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1677 allocated_done += n;
1678 qemu_progress_print(100.0 * allocated_done / s->allocated_sectors,
1682 if (s->status == BLK_DATA) {
1683 ret = convert_read(s, sector_num, n, buf);
1685 error_report("error while reading sector %" PRId64
1686 ": %s", sector_num, strerror(-ret));
1689 } else if (!s->min_sparse && s->status == BLK_ZERO) {
1690 n = MIN(n, s->buf_sectors);
1691 memset(buf, 0, n * BDRV_SECTOR_SIZE);
1692 s->status = BLK_DATA;
1695 ret = convert_write(s, sector_num, n, buf);
1697 error_report("error while writing sector %" PRId64
1698 ": %s", sector_num, strerror(-ret));
1705 if (s->compressed) {
1706 /* signal EOF to align */
1707 ret = blk_write_compressed(s->target, 0, NULL, 0);
1719 static int img_convert(int argc, char **argv)
1721 int c, bs_n, bs_i, compress, cluster_sectors, skip_create;
1723 int progress = 0, flags, src_flags;
1724 bool writethrough, src_writethrough;
1725 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
1726 BlockDriver *drv, *proto_drv;
1727 BlockBackend **blk = NULL, *out_blk = NULL;
1728 BlockDriverState **bs = NULL, *out_bs = NULL;
1729 int64_t total_sectors;
1730 int64_t *bs_sectors = NULL;
1731 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
1732 BlockDriverInfo bdi;
1733 QemuOpts *opts = NULL;
1734 QemuOptsList *create_opts = NULL;
1735 const char *out_baseimg_param;
1736 char *options = NULL;
1737 const char *snapshot_name = NULL;
1738 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
1740 Error *local_err = NULL;
1741 QemuOpts *sn_opts = NULL;
1742 ImgConvertState state;
1743 bool image_opts = false;
1748 src_cache = BDRV_DEFAULT_CACHE;
1753 static const struct option long_options[] = {
1754 {"help", no_argument, 0, 'h'},
1755 {"object", required_argument, 0, OPTION_OBJECT},
1756 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1759 c = getopt_long(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn",
1760 long_options, NULL);
1776 out_baseimg = optarg;
1782 error_report("option -e is deprecated, please use \'-o "
1783 "encryption\' instead!");
1787 error_report("option -6 is deprecated, please use \'-o "
1788 "compat6\' instead!");
1792 if (!is_valid_option_list(optarg)) {
1793 error_report("Invalid option list: %s", optarg);
1798 options = g_strdup(optarg);
1800 char *old_options = options;
1801 options = g_strdup_printf("%s,%s", options, optarg);
1802 g_free(old_options);
1806 snapshot_name = optarg;
1809 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1810 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
1813 error_report("Failed in parsing snapshot param '%s'",
1819 snapshot_name = optarg;
1826 sval = qemu_strtosz_suffix(optarg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
1827 if (sval < 0 || *end) {
1828 error_report("Invalid minimum zero buffer size for sparse output specified");
1833 min_sparse = sval / BDRV_SECTOR_SIZE;
1852 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1858 case OPTION_IMAGE_OPTS:
1864 if (qemu_opts_foreach(&qemu_object_opts,
1865 user_creatable_add_opts_foreach,
1866 NULL, &local_err)) {
1867 error_report_err(local_err);
1871 /* Initialize before goto out */
1875 qemu_progress_init(progress, 1.0);
1877 bs_n = argc - optind - 1;
1878 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
1880 if (options && has_help_option(options)) {
1881 ret = print_block_option_help(out_filename, out_fmt);
1886 error_exit("Must specify image file name");
1890 if (bs_n > 1 && out_baseimg) {
1891 error_report("-B makes no sense when concatenating multiple input "
1898 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
1900 error_report("Invalid source cache option: %s", src_cache);
1904 qemu_progress_print(0, 100);
1906 blk = g_new0(BlockBackend *, bs_n);
1907 bs = g_new0(BlockDriverState *, bs_n);
1908 bs_sectors = g_new(int64_t, bs_n);
1911 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1912 blk[bs_i] = img_open(image_opts, argv[optind + bs_i],
1913 fmt, src_flags, src_writethrough, quiet);
1918 bs[bs_i] = blk_bs(blk[bs_i]);
1919 bs_sectors[bs_i] = blk_nb_sectors(blk[bs_i]);
1920 if (bs_sectors[bs_i] < 0) {
1921 error_report("Could not get size of %s: %s",
1922 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1926 total_sectors += bs_sectors[bs_i];
1930 ret = bdrv_snapshot_load_tmp(bs[0],
1931 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1932 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1934 } else if (snapshot_name != NULL) {
1936 error_report("No support for concatenating multiple snapshot");
1941 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
1944 error_reportf_err(local_err, "Failed to load snapshot: ");
1949 /* Find driver and parse its options */
1950 drv = bdrv_find_format(out_fmt);
1952 error_report("Unknown file format '%s'", out_fmt);
1957 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
1959 error_report_err(local_err);
1965 if (!drv->create_opts) {
1966 error_report("Format driver '%s' does not support image creation",
1972 if (!proto_drv->create_opts) {
1973 error_report("Protocol driver '%s' does not support image creation",
1974 proto_drv->format_name);
1979 create_opts = qemu_opts_append(create_opts, drv->create_opts);
1980 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
1982 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
1984 qemu_opts_do_parse(opts, options, NULL, &local_err);
1986 error_report_err(local_err);
1992 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512,
1994 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2000 /* Get backing file name if -o backing_file was used */
2001 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2002 if (out_baseimg_param) {
2003 out_baseimg = out_baseimg_param;
2006 /* Check if compression is supported */
2009 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2010 const char *preallocation =
2011 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2013 if (!drv->bdrv_write_compressed) {
2014 error_report("Compression not supported for this file format");
2020 error_report("Compression and encryption not supported at "
2027 && strcmp(preallocation, "off"))
2029 error_report("Compression and preallocation not supported at "
2037 /* Create the new image */
2038 ret = bdrv_create(drv, out_filename, opts, &local_err);
2040 error_reportf_err(local_err, "%s: error while converting %s: ",
2041 out_filename, out_fmt);
2046 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2047 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2049 error_report("Invalid cache option: %s", cache);
2053 /* XXX we should allow --image-opts to trigger use of
2054 * img_open() here, but then we have trouble with
2055 * the bdrv_create() call which takes different params.
2056 * Not critical right now, so fix can wait...
2058 out_blk = img_open_file(out_filename, out_fmt, flags, writethrough, quiet);
2063 out_bs = blk_bs(out_blk);
2065 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
2066 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2068 bufsectors = MIN(32768,
2069 MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
2070 out_bs->bl.discard_alignment))
2074 int64_t output_sectors = blk_nb_sectors(out_blk);
2075 if (output_sectors < 0) {
2076 error_report("unable to get output image length: %s",
2077 strerror(-output_sectors));
2080 } else if (output_sectors < total_sectors) {
2081 error_report("output file is smaller than input file");
2087 cluster_sectors = 0;
2088 ret = bdrv_get_info(out_bs, &bdi);
2091 error_report("could not get block driver info");
2095 compress = compress || bdi.needs_compressed_writes;
2096 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2099 state = (ImgConvertState) {
2101 .src_sectors = bs_sectors,
2103 .total_sectors = total_sectors,
2105 .compressed = compress,
2106 .target_has_backing = (bool) out_baseimg,
2107 .min_sparse = min_sparse,
2108 .cluster_sectors = cluster_sectors,
2109 .buf_sectors = bufsectors,
2111 ret = convert_do_copy(&state);
2115 qemu_progress_print(100, 0);
2117 qemu_progress_end();
2118 qemu_opts_del(opts);
2119 qemu_opts_free(create_opts);
2120 qemu_opts_del(sn_opts);
2124 for (bs_i = 0; bs_i < bs_n; bs_i++) {
2125 blk_unref(blk[bs_i]);
2140 static void dump_snapshots(BlockDriverState *bs)
2142 QEMUSnapshotInfo *sn_tab, *sn;
2145 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2148 printf("Snapshot list:\n");
2149 bdrv_snapshot_dump(fprintf, stdout, NULL);
2151 for(i = 0; i < nb_sns; i++) {
2153 bdrv_snapshot_dump(fprintf, stdout, sn);
2159 static void dump_json_image_info_list(ImageInfoList *list)
2161 Error *local_err = NULL;
2163 QmpOutputVisitor *ov = qmp_output_visitor_new();
2165 visit_type_ImageInfoList(qmp_output_get_visitor(ov), NULL, &list,
2167 obj = qmp_output_get_qobject(ov);
2168 str = qobject_to_json_pretty(obj);
2169 assert(str != NULL);
2170 printf("%s\n", qstring_get_str(str));
2171 qobject_decref(obj);
2172 qmp_output_visitor_cleanup(ov);
2176 static void dump_json_image_info(ImageInfo *info)
2178 Error *local_err = NULL;
2180 QmpOutputVisitor *ov = qmp_output_visitor_new();
2182 visit_type_ImageInfo(qmp_output_get_visitor(ov), NULL, &info, &local_err);
2183 obj = qmp_output_get_qobject(ov);
2184 str = qobject_to_json_pretty(obj);
2185 assert(str != NULL);
2186 printf("%s\n", qstring_get_str(str));
2187 qobject_decref(obj);
2188 qmp_output_visitor_cleanup(ov);
2192 static void dump_human_image_info_list(ImageInfoList *list)
2194 ImageInfoList *elem;
2197 for (elem = list; elem; elem = elem->next) {
2203 bdrv_image_info_dump(fprintf, stdout, elem->value);
2207 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2209 return strcmp(a, b) == 0;
2213 * Open an image file chain and return an ImageInfoList
2215 * @filename: topmost image filename
2216 * @fmt: topmost image format (may be NULL to autodetect)
2217 * @chain: true - enumerate entire backing file chain
2218 * false - only topmost image file
2220 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2221 * image file. If there was an error a message will have been printed to
2224 static ImageInfoList *collect_image_info_list(bool image_opts,
2225 const char *filename,
2229 ImageInfoList *head = NULL;
2230 ImageInfoList **last = &head;
2231 GHashTable *filenames;
2234 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2238 BlockDriverState *bs;
2240 ImageInfoList *elem;
2242 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2243 error_report("Backing file '%s' creates an infinite loop.",
2247 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2249 blk = img_open(image_opts, filename, fmt,
2250 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false);
2256 bdrv_query_image_info(bs, &info, &err);
2258 error_report_err(err);
2263 elem = g_new0(ImageInfoList, 1);
2270 filename = fmt = NULL;
2272 if (info->has_full_backing_filename) {
2273 filename = info->full_backing_filename;
2274 } else if (info->has_backing_filename) {
2275 error_report("Could not determine absolute backing filename,"
2276 " but backing filename '%s' present",
2277 info->backing_filename);
2280 if (info->has_backing_filename_format) {
2281 fmt = info->backing_filename_format;
2285 g_hash_table_destroy(filenames);
2289 qapi_free_ImageInfoList(head);
2290 g_hash_table_destroy(filenames);
2294 static int img_info(int argc, char **argv)
2297 OutputFormat output_format = OFORMAT_HUMAN;
2299 const char *filename, *fmt, *output;
2300 ImageInfoList *list;
2301 Error *local_err = NULL;
2302 bool image_opts = false;
2307 int option_index = 0;
2308 static const struct option long_options[] = {
2309 {"help", no_argument, 0, 'h'},
2310 {"format", required_argument, 0, 'f'},
2311 {"output", required_argument, 0, OPTION_OUTPUT},
2312 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2313 {"object", required_argument, 0, OPTION_OBJECT},
2314 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2317 c = getopt_long(argc, argv, "f:h",
2318 long_options, &option_index);
2333 case OPTION_BACKING_CHAIN:
2336 case OPTION_OBJECT: {
2338 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2344 case OPTION_IMAGE_OPTS:
2349 if (optind != argc - 1) {
2350 error_exit("Expecting one image file name");
2352 filename = argv[optind++];
2354 if (output && !strcmp(output, "json")) {
2355 output_format = OFORMAT_JSON;
2356 } else if (output && !strcmp(output, "human")) {
2357 output_format = OFORMAT_HUMAN;
2358 } else if (output) {
2359 error_report("--output must be used with human or json as argument.");
2363 if (qemu_opts_foreach(&qemu_object_opts,
2364 user_creatable_add_opts_foreach,
2365 NULL, &local_err)) {
2366 error_report_err(local_err);
2370 list = collect_image_info_list(image_opts, filename, fmt, chain);
2375 switch (output_format) {
2377 dump_human_image_info_list(list);
2381 dump_json_image_info_list(list);
2383 dump_json_image_info(list->value);
2388 qapi_free_ImageInfoList(list);
2392 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2395 switch (output_format) {
2397 if (e->data && !e->has_offset) {
2398 error_report("File contains external, encrypted or compressed clusters.");
2401 if (e->data && !e->zero) {
2402 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2403 e->start, e->length,
2404 e->has_offset ? e->offset : 0,
2405 e->has_filename ? e->filename : "");
2407 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2408 * Modify the flags here to allow more coalescing.
2410 if (next && (!next->data || next->zero)) {
2416 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2417 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2418 (e->start == 0 ? "[" : ",\n"),
2419 e->start, e->length, e->depth,
2420 e->zero ? "true" : "false",
2421 e->data ? "true" : "false");
2422 if (e->has_offset) {
2423 printf(", \"offset\": %"PRId64"", e->offset);
2434 static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2435 int nb_sectors, MapEntry *e)
2439 BlockDriverState *file;
2442 /* As an optimization, we could cache the current range of unallocated
2443 * clusters in each file of the chain, and avoid querying the same
2449 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2455 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2458 bs = backing_bs(bs);
2467 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2470 .start = sector_num * BDRV_SECTOR_SIZE,
2471 .length = nb_sectors * BDRV_SECTOR_SIZE,
2472 .data = !!(ret & BDRV_BLOCK_DATA),
2473 .zero = !!(ret & BDRV_BLOCK_ZERO),
2474 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2475 .has_offset = has_offset,
2477 .has_filename = file && has_offset,
2478 .filename = file && has_offset ? file->filename : NULL,
2484 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2486 if (curr->length == 0) {
2489 if (curr->zero != next->zero ||
2490 curr->data != next->data ||
2491 curr->depth != next->depth ||
2492 curr->has_filename != next->has_filename ||
2493 curr->has_offset != next->has_offset) {
2496 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2499 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2505 static int img_map(int argc, char **argv)
2508 OutputFormat output_format = OFORMAT_HUMAN;
2510 BlockDriverState *bs;
2511 const char *filename, *fmt, *output;
2513 MapEntry curr = { .length = 0 }, next;
2515 Error *local_err = NULL;
2516 bool image_opts = false;
2521 int option_index = 0;
2522 static const struct option long_options[] = {
2523 {"help", no_argument, 0, 'h'},
2524 {"format", required_argument, 0, 'f'},
2525 {"output", required_argument, 0, OPTION_OUTPUT},
2526 {"object", required_argument, 0, OPTION_OBJECT},
2527 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2530 c = getopt_long(argc, argv, "f:h",
2531 long_options, &option_index);
2546 case OPTION_OBJECT: {
2548 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2554 case OPTION_IMAGE_OPTS:
2559 if (optind != argc - 1) {
2560 error_exit("Expecting one image file name");
2562 filename = argv[optind];
2564 if (output && !strcmp(output, "json")) {
2565 output_format = OFORMAT_JSON;
2566 } else if (output && !strcmp(output, "human")) {
2567 output_format = OFORMAT_HUMAN;
2568 } else if (output) {
2569 error_report("--output must be used with human or json as argument.");
2573 if (qemu_opts_foreach(&qemu_object_opts,
2574 user_creatable_add_opts_foreach,
2575 NULL, &local_err)) {
2576 error_report_err(local_err);
2580 blk = img_open(image_opts, filename, fmt, 0, false, false);
2586 if (output_format == OFORMAT_HUMAN) {
2587 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2590 length = blk_getlength(blk);
2591 while (curr.start + curr.length < length) {
2592 int64_t nsectors_left;
2596 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2598 /* Probe up to 1 GiB at a time. */
2599 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2600 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2601 ret = get_block_status(bs, sector_num, n, &next);
2604 error_report("Could not read file metadata: %s", strerror(-ret));
2608 if (entry_mergeable(&curr, &next)) {
2609 curr.length += next.length;
2613 if (curr.length > 0) {
2614 dump_map_entry(output_format, &curr, &next);
2619 dump_map_entry(output_format, &curr, NULL);
2626 #define SNAPSHOT_LIST 1
2627 #define SNAPSHOT_CREATE 2
2628 #define SNAPSHOT_APPLY 3
2629 #define SNAPSHOT_DELETE 4
2631 static int img_snapshot(int argc, char **argv)
2634 BlockDriverState *bs;
2635 QEMUSnapshotInfo sn;
2636 char *filename, *snapshot_name = NULL;
2637 int c, ret = 0, bdrv_oflags;
2642 bool image_opts = false;
2644 bdrv_oflags = BDRV_O_RDWR;
2645 /* Parse commandline parameters */
2647 static const struct option long_options[] = {
2648 {"help", no_argument, 0, 'h'},
2649 {"object", required_argument, 0, OPTION_OBJECT},
2650 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2653 c = getopt_long(argc, argv, "la:c:d:hq",
2654 long_options, NULL);
2665 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2668 action = SNAPSHOT_LIST;
2669 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
2673 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2676 action = SNAPSHOT_APPLY;
2677 snapshot_name = optarg;
2681 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2684 action = SNAPSHOT_CREATE;
2685 snapshot_name = optarg;
2689 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2692 action = SNAPSHOT_DELETE;
2693 snapshot_name = optarg;
2698 case OPTION_OBJECT: {
2700 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2706 case OPTION_IMAGE_OPTS:
2712 if (optind != argc - 1) {
2713 error_exit("Expecting one image file name");
2715 filename = argv[optind++];
2717 if (qemu_opts_foreach(&qemu_object_opts,
2718 user_creatable_add_opts_foreach,
2720 error_report_err(err);
2724 /* Open the image */
2725 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet);
2731 /* Perform the requested action */
2737 case SNAPSHOT_CREATE:
2738 memset(&sn, 0, sizeof(sn));
2739 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2741 qemu_gettimeofday(&tv);
2742 sn.date_sec = tv.tv_sec;
2743 sn.date_nsec = tv.tv_usec * 1000;
2745 ret = bdrv_snapshot_create(bs, &sn);
2747 error_report("Could not create snapshot '%s': %d (%s)",
2748 snapshot_name, ret, strerror(-ret));
2752 case SNAPSHOT_APPLY:
2753 ret = bdrv_snapshot_goto(bs, snapshot_name);
2755 error_report("Could not apply snapshot '%s': %d (%s)",
2756 snapshot_name, ret, strerror(-ret));
2760 case SNAPSHOT_DELETE:
2761 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
2763 error_reportf_err(err, "Could not delete snapshot '%s': ",
2778 static int img_rebase(int argc, char **argv)
2780 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
2781 uint8_t *buf_old = NULL;
2782 uint8_t *buf_new = NULL;
2783 BlockDriverState *bs = NULL;
2785 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2786 int c, flags, src_flags, ret;
2787 bool writethrough, src_writethrough;
2791 Error *local_err = NULL;
2792 bool image_opts = false;
2794 /* Parse commandline parameters */
2796 cache = BDRV_DEFAULT_CACHE;
2797 src_cache = BDRV_DEFAULT_CACHE;
2801 static const struct option long_options[] = {
2802 {"help", no_argument, 0, 'h'},
2803 {"object", required_argument, 0, OPTION_OBJECT},
2804 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2807 c = getopt_long(argc, argv, "hf:F:b:upt:T:q",
2808 long_options, NULL);
2821 out_basefmt = optarg;
2824 out_baseimg = optarg;
2841 case OPTION_OBJECT: {
2843 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2849 case OPTION_IMAGE_OPTS:
2859 if (optind != argc - 1) {
2860 error_exit("Expecting one image file name");
2862 if (!unsafe && !out_baseimg) {
2863 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
2865 filename = argv[optind++];
2867 if (qemu_opts_foreach(&qemu_object_opts,
2868 user_creatable_add_opts_foreach,
2869 NULL, &local_err)) {
2870 error_report_err(local_err);
2874 qemu_progress_init(progress, 2.0);
2875 qemu_progress_print(0, 100);
2877 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
2878 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2880 error_report("Invalid cache option: %s", cache);
2885 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2887 error_report("Invalid source cache option: %s", src_cache);
2891 /* The source files are opened read-only, don't care about WCE */
2892 assert((src_flags & BDRV_O_RDWR) == 0);
2893 (void) src_writethrough;
2898 * Ignore the old backing file for unsafe rebase in case we want to correct
2899 * the reference to a renamed or moved backing file.
2901 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
2908 if (out_basefmt != NULL) {
2909 if (bdrv_find_format(out_basefmt) == NULL) {
2910 error_report("Invalid format name: '%s'", out_basefmt);
2916 /* For safe rebasing we need to compare old and new backing file */
2918 char backing_name[PATH_MAX];
2919 QDict *options = NULL;
2921 if (bs->backing_format[0] != '\0') {
2922 options = qdict_new();
2923 qdict_put(options, "driver", qstring_from_str(bs->backing_format));
2926 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2927 blk_old_backing = blk_new_open(backing_name, NULL,
2928 options, src_flags, &local_err);
2929 if (!blk_old_backing) {
2930 error_reportf_err(local_err,
2931 "Could not open old backing file '%s': ",
2936 if (out_baseimg[0]) {
2938 options = qdict_new();
2939 qdict_put(options, "driver", qstring_from_str(out_basefmt));
2944 blk_new_backing = blk_new_open(out_baseimg, NULL,
2945 options, src_flags, &local_err);
2946 if (!blk_new_backing) {
2947 error_reportf_err(local_err,
2948 "Could not open new backing file '%s': ",
2956 * Check each unallocated cluster in the COW file. If it is unallocated,
2957 * accesses go to the backing file. We must therefore compare this cluster
2958 * in the old and new backing file, and if they differ we need to copy it
2959 * from the old backing file into the COW file.
2961 * If qemu-img crashes during this step, no harm is done. The content of
2962 * the image is the same as the original one at any time.
2965 int64_t num_sectors;
2966 int64_t old_backing_num_sectors;
2967 int64_t new_backing_num_sectors = 0;
2970 float local_progress = 0;
2972 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
2973 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
2975 num_sectors = blk_nb_sectors(blk);
2976 if (num_sectors < 0) {
2977 error_report("Could not get size of '%s': %s",
2978 filename, strerror(-num_sectors));
2982 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
2983 if (old_backing_num_sectors < 0) {
2984 char backing_name[PATH_MAX];
2986 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2987 error_report("Could not get size of '%s': %s",
2988 backing_name, strerror(-old_backing_num_sectors));
2992 if (blk_new_backing) {
2993 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
2994 if (new_backing_num_sectors < 0) {
2995 error_report("Could not get size of '%s': %s",
2996 out_baseimg, strerror(-new_backing_num_sectors));
3002 if (num_sectors != 0) {
3003 local_progress = (float)100 /
3004 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3007 for (sector = 0; sector < num_sectors; sector += n) {
3009 /* How many sectors can we handle with the next read? */
3010 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3011 n = (IO_BUF_SIZE / 512);
3013 n = num_sectors - sector;
3016 /* If the cluster is allocated, we don't need to take action */
3017 ret = bdrv_is_allocated(bs, sector, n, &n);
3019 error_report("error while reading image metadata: %s",
3028 * Read old and new backing file and take into consideration that
3029 * backing files may be smaller than the COW image.
3031 if (sector >= old_backing_num_sectors) {
3032 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3034 if (sector + n > old_backing_num_sectors) {
3035 n = old_backing_num_sectors - sector;
3038 ret = blk_read(blk_old_backing, sector, buf_old, n);
3040 error_report("error while reading from old backing file");
3045 if (sector >= new_backing_num_sectors || !blk_new_backing) {
3046 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3048 if (sector + n > new_backing_num_sectors) {
3049 n = new_backing_num_sectors - sector;
3052 ret = blk_read(blk_new_backing, sector, buf_new, n);
3054 error_report("error while reading from new backing file");
3059 /* If they differ, we need to write to the COW file */
3060 uint64_t written = 0;
3062 while (written < n) {
3065 if (compare_sectors(buf_old + written * 512,
3066 buf_new + written * 512, n - written, &pnum))
3068 ret = blk_write(blk, sector + written,
3069 buf_old + written * 512, pnum);
3071 error_report("Error while writing to COW image: %s",
3079 qemu_progress_print(local_progress, 100);
3084 * Change the backing file. All clusters that are different from the old
3085 * backing file are overwritten in the COW file now, so the visible content
3086 * doesn't change when we switch the backing file.
3088 if (out_baseimg && *out_baseimg) {
3089 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3091 ret = bdrv_change_backing_file(bs, NULL, NULL);
3094 if (ret == -ENOSPC) {
3095 error_report("Could not change the backing file to '%s': No "
3096 "space left in the file header", out_baseimg);
3097 } else if (ret < 0) {
3098 error_report("Could not change the backing file to '%s': %s",
3099 out_baseimg, strerror(-ret));
3102 qemu_progress_print(100, 0);
3104 * TODO At this point it is possible to check if any clusters that are
3105 * allocated in the COW file are the same in the backing file. If so, they
3106 * could be dropped from the COW file. Don't do this before switching the
3107 * backing file, in case of a crash this would lead to corruption.
3110 qemu_progress_end();
3113 blk_unref(blk_old_backing);
3114 blk_unref(blk_new_backing);
3116 qemu_vfree(buf_old);
3117 qemu_vfree(buf_new);
3126 static int img_resize(int argc, char **argv)
3129 int c, ret, relative;
3130 const char *filename, *fmt, *size;
3131 int64_t n, total_size;
3133 BlockBackend *blk = NULL;
3135 Error *local_err = NULL;
3137 static QemuOptsList resize_options = {
3138 .name = "resize_options",
3139 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3142 .name = BLOCK_OPT_SIZE,
3143 .type = QEMU_OPT_SIZE,
3144 .help = "Virtual disk size"
3150 bool image_opts = false;
3152 /* Remove size from argv manually so that negative numbers are not treated
3153 * as options by getopt. */
3155 error_exit("Not enough arguments");
3159 size = argv[--argc];
3161 /* Parse getopt arguments */
3164 static const struct option long_options[] = {
3165 {"help", no_argument, 0, 'h'},
3166 {"object", required_argument, 0, OPTION_OBJECT},
3167 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3170 c = getopt_long(argc, argv, "f:hq",
3171 long_options, NULL);
3186 case OPTION_OBJECT: {
3188 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3194 case OPTION_IMAGE_OPTS:
3199 if (optind != argc - 1) {
3200 error_exit("Expecting one image file name");
3202 filename = argv[optind++];
3204 if (qemu_opts_foreach(&qemu_object_opts,
3205 user_creatable_add_opts_foreach,
3206 NULL, &local_err)) {
3207 error_report_err(local_err);
3211 /* Choose grow, shrink, or absolute resize mode */
3227 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3228 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3230 error_report_err(err);
3232 qemu_opts_del(param);
3235 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3236 qemu_opts_del(param);
3238 blk = img_open(image_opts, filename, fmt,
3239 BDRV_O_RDWR, false, quiet);
3246 total_size = blk_getlength(blk) + n * relative;
3250 if (total_size <= 0) {
3251 error_report("New image size must be positive");
3256 ret = blk_truncate(blk, total_size);
3259 qprintf(quiet, "Image resized.\n");
3262 error_report("This image does not support resize");
3265 error_report("Image is read-only");
3268 error_report("Error resizing image (%d)", -ret);
3279 static void amend_status_cb(BlockDriverState *bs,
3280 int64_t offset, int64_t total_work_size,
3283 qemu_progress_print(100.f * offset / total_work_size, 0);
3286 static int img_amend(int argc, char **argv)
3290 char *options = NULL;
3291 QemuOptsList *create_opts = NULL;
3292 QemuOpts *opts = NULL;
3293 const char *fmt = NULL, *filename, *cache;
3296 bool quiet = false, progress = false;
3297 BlockBackend *blk = NULL;
3298 BlockDriverState *bs = NULL;
3299 Error *local_err = NULL;
3300 bool image_opts = false;
3302 cache = BDRV_DEFAULT_CACHE;
3304 static const struct option long_options[] = {
3305 {"help", no_argument, 0, 'h'},
3306 {"object", required_argument, 0, OPTION_OBJECT},
3307 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3310 c = getopt_long(argc, argv, "ho:f:t:pq",
3311 long_options, NULL);
3322 if (!is_valid_option_list(optarg)) {
3323 error_report("Invalid option list: %s", optarg);
3325 goto out_no_progress;
3328 options = g_strdup(optarg);
3330 char *old_options = options;
3331 options = g_strdup_printf("%s,%s", options, optarg);
3332 g_free(old_options);
3348 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3352 goto out_no_progress;
3355 case OPTION_IMAGE_OPTS:
3362 error_exit("Must specify options (-o)");
3365 if (qemu_opts_foreach(&qemu_object_opts,
3366 user_creatable_add_opts_foreach,
3367 NULL, &local_err)) {
3368 error_report_err(local_err);
3370 goto out_no_progress;
3376 qemu_progress_init(progress, 1.0);
3378 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3379 if (fmt && has_help_option(options)) {
3380 /* If a format is explicitly specified (and possibly no filename is
3381 * given), print option help here */
3382 ret = print_block_option_help(filename, fmt);
3386 if (optind != argc - 1) {
3387 error_report("Expecting one image file name");
3392 flags = BDRV_O_RDWR;
3393 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3395 error_report("Invalid cache option: %s", cache);
3399 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
3406 fmt = bs->drv->format_name;
3408 if (has_help_option(options)) {
3409 /* If the format was auto-detected, print option help here */
3410 ret = print_block_option_help(filename, fmt);
3414 if (!bs->drv->create_opts) {
3415 error_report("Format driver '%s' does not support any options to amend",
3421 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
3422 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3424 qemu_opts_do_parse(opts, options, NULL, &err);
3426 error_report_err(err);
3432 /* In case the driver does not call amend_status_cb() */
3433 qemu_progress_print(0.f, 0);
3434 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
3435 qemu_progress_print(100.f, 0);
3437 error_report("Error while amending options: %s", strerror(-ret));
3442 qemu_progress_end();
3446 qemu_opts_del(opts);
3447 qemu_opts_free(create_opts);
3456 static const img_cmd_t img_cmds[] = {
3457 #define DEF(option, callback, arg_string) \
3458 { option, callback },
3459 #include "qemu-img-cmds.h"
3465 int main(int argc, char **argv)
3467 const img_cmd_t *cmd;
3468 const char *cmdname;
3469 Error *local_error = NULL;
3471 static const struct option long_options[] = {
3472 {"help", no_argument, 0, 'h'},
3473 {"version", no_argument, 0, 'v'},
3478 signal(SIGPIPE, SIG_IGN);
3481 error_set_progname(argv[0]);
3482 qemu_init_exec_dir(argv[0]);
3484 if (qemu_init_main_loop(&local_error)) {
3485 error_report_err(local_error);
3489 module_call_init(MODULE_INIT_QOM);
3492 error_exit("Not enough arguments");
3496 qemu_add_opts(&qemu_object_opts);
3497 qemu_add_opts(&qemu_source_opts);
3499 /* find the command */
3500 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
3501 if (!strcmp(cmdname, cmd->name)) {
3502 return cmd->handler(argc - 1, argv + 1);
3506 c = getopt_long(argc, argv, "h", long_options, NULL);
3512 printf(QEMU_IMG_VERSION);
3517 error_exit("Command not found: %s", cmdname);