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 "qapi-visit.h"
25 #include "qapi/qmp-output-visitor.h"
26 #include "qapi/qmp/qjson.h"
27 #include "qemu-common.h"
28 #include "qemu/option.h"
29 #include "qemu/error-report.h"
30 #include "qemu/osdep.h"
31 #include "sysemu/sysemu.h"
32 #include "block/block_int.h"
33 #include "block/qapi.h"
37 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION \
38 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
40 typedef struct img_cmd_t {
42 int (*handler)(int argc, char **argv);
47 OPTION_BACKING_CHAIN = 257,
50 typedef enum OutputFormat {
55 /* Default to cache=writeback as data integrity is not important for qemu-tcg. */
56 #define BDRV_O_FLAGS BDRV_O_CACHE_WB
57 #define BDRV_DEFAULT_CACHE "writeback"
59 static gint compare_data(gconstpointer a, gconstpointer b, gpointer user)
61 return g_strcmp0(a, b);
64 static void print_format(gpointer data, gpointer user)
66 printf(" %s", (char *)data);
69 static void add_format_to_seq(void *opaque, const char *fmt_name)
71 GSequence *seq = opaque;
73 g_sequence_insert_sorted(seq, (gpointer)fmt_name,
77 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
81 error_printf("qemu-img: ");
84 error_vprintf(fmt, ap);
87 error_printf("\nTry 'qemu-img --help' for more information\n");
91 /* Please keep in synch with qemu-img.texi */
92 static void QEMU_NORETURN help(void)
94 const char *help_msg =
96 "usage: qemu-img command [command options]\n"
97 "QEMU disk image utility\n"
100 #define DEF(option, callback, arg_string) \
102 #include "qemu-img-cmds.h"
106 "Command parameters:\n"
107 " 'filename' is a disk image filename\n"
108 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
109 " 'cache' is the cache mode used to write the output disk image, the valid\n"
110 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
111 " 'directsync' and 'unsafe' (default for convert)\n"
112 " 'src_cache' in contrast is the cache mode used to read input disk images\n"
113 " 'size' is the disk image size in bytes. Optional suffixes\n"
114 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
115 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
116 " supported. 'b' is ignored.\n"
117 " 'output_filename' is the destination disk image filename\n"
118 " 'output_fmt' is the destination format\n"
119 " 'options' is a comma separated list of format specific options in a\n"
120 " name=value format. Use -o ? for an overview of the options supported by the\n"
122 " 'snapshot_param' is param used for internal snapshot, format\n"
123 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
125 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
127 " '-c' indicates that target image must be compressed (qcow format only)\n"
128 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
129 " match exactly. The image doesn't need a working backing file before\n"
130 " rebasing in this case (useful for renaming the backing file)\n"
131 " '-h' with or without a command shows this help and lists the supported formats\n"
132 " '-p' show progress of command (only certain commands)\n"
133 " '-q' use Quiet mode - do not print any output (except errors)\n"
134 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
135 " contain only zeros for qemu-img to create a sparse image during\n"
136 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
137 " unallocated or zero sectors, and the destination image will always be\n"
139 " '--output' takes the format in which the output must be done (human or json)\n"
140 " '-n' skips the target volume creation (useful if the volume is created\n"
141 " prior to running qemu-img)\n"
143 "Parameters to check subcommand:\n"
144 " '-r' tries to repair any inconsistencies that are found during the check.\n"
145 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
146 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
147 " hiding corruption that has already occurred.\n"
149 "Parameters to snapshot subcommand:\n"
150 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
151 " '-a' applies a snapshot (revert disk to saved state)\n"
152 " '-c' creates a snapshot\n"
153 " '-d' deletes a snapshot\n"
154 " '-l' lists all snapshots in the given image\n"
156 "Parameters to compare subcommand:\n"
157 " '-f' first image format\n"
158 " '-F' second image format\n"
159 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
162 printf("%s\nSupported formats:", help_msg);
163 seq = g_sequence_new(NULL);
164 bdrv_iterate_format(add_format_to_seq, seq);
165 g_sequence_foreach(seq, print_format, NULL);
167 g_sequence_free(seq);
172 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
178 ret = vprintf(fmt, args);
185 /* XXX: put correct support for win32 */
186 static int read_password(char *buf, int buf_size)
190 printf("Password: ");
198 } else if (c == '\n') {
200 } else if (i < (buf_size - 1)) {
212 static struct termios oldtty;
214 static void term_exit(void)
216 tcsetattr (0, TCSANOW, &oldtty);
219 static void term_init(void)
226 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
227 |INLCR|IGNCR|ICRNL|IXON);
228 tty.c_oflag |= OPOST;
229 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
230 tty.c_cflag &= ~(CSIZE|PARENB);
235 tcsetattr (0, TCSANOW, &tty);
240 static int read_password(char *buf, int buf_size)
245 printf("password: ");
250 ret = read(0, &ch, 1);
252 if (errno == EAGAIN || errno == EINTR) {
257 } else if (ret == 0) {
265 if (i < (buf_size - 1))
276 static int print_block_option_help(const char *filename, const char *fmt)
278 BlockDriver *drv, *proto_drv;
279 QemuOptsList *create_opts = NULL;
281 /* Find driver and parse its options */
282 drv = bdrv_find_format(fmt);
284 error_report("Unknown file format '%s'", fmt);
288 create_opts = qemu_opts_append(create_opts, drv->create_opts);
290 proto_drv = bdrv_find_protocol(filename, true);
292 error_report("Unknown protocol '%s'", filename);
293 qemu_opts_free(create_opts);
296 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
299 qemu_opts_print_help(create_opts);
300 qemu_opts_free(create_opts);
304 static BlockDriverState *bdrv_new_open(const char *id,
305 const char *filename,
311 BlockDriverState *bs;
314 Error *local_err = NULL;
317 bs = bdrv_new(id, &error_abort);
320 drv = bdrv_find_format(fmt);
322 error_report("Unknown file format '%s'", fmt);
329 ret = bdrv_open(&bs, filename, NULL, NULL, flags, drv, &local_err);
331 error_report("Could not open '%s': %s", filename,
332 error_get_pretty(local_err));
333 error_free(local_err);
337 if (bdrv_is_encrypted(bs) && require_io) {
338 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
339 if (read_password(password, sizeof(password)) < 0) {
340 error_report("No password given");
343 if (bdrv_set_key(bs, password) < 0) {
344 error_report("invalid password");
354 static int add_old_style_options(const char *fmt, QemuOpts *opts,
355 const char *base_filename,
356 const char *base_fmt)
359 if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename)) {
360 error_report("Backing file not supported for file format '%s'",
366 if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt)) {
367 error_report("Backing file format not supported for file "
375 static int img_create(int argc, char **argv)
378 uint64_t img_size = -1;
379 const char *fmt = "raw";
380 const char *base_fmt = NULL;
381 const char *filename;
382 const char *base_filename = NULL;
383 char *options = NULL;
384 Error *local_err = NULL;
388 c = getopt(argc, argv, "F:b:f:he6o:q");
401 base_filename = optarg;
407 error_report("option -e is deprecated, please use \'-o "
408 "encryption\' instead!");
411 error_report("option -6 is deprecated, please use \'-o "
412 "compat6\' instead!");
415 if (!is_valid_option_list(optarg)) {
416 error_report("Invalid option list: %s", optarg);
420 options = g_strdup(optarg);
422 char *old_options = options;
423 options = g_strdup_printf("%s,%s", options, optarg);
433 /* Get the filename */
434 filename = (optind < argc) ? argv[optind] : NULL;
435 if (options && has_help_option(options)) {
437 return print_block_option_help(filename, fmt);
440 if (optind >= argc) {
441 error_exit("Expecting image file name");
445 /* Get image size, if specified */
449 sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
450 if (sval < 0 || *end) {
451 if (sval == -ERANGE) {
452 error_report("Image size must be less than 8 EiB!");
454 error_report("Invalid image size specified! You may use k, M, "
455 "G, T, P or E suffixes for ");
456 error_report("kilobytes, megabytes, gigabytes, terabytes, "
457 "petabytes and exabytes.");
461 img_size = (uint64_t)sval;
463 if (optind != argc) {
464 error_exit("Unexpected argument: %s", argv[optind]);
467 bdrv_img_create(filename, fmt, base_filename, base_fmt,
468 options, img_size, BDRV_O_FLAGS, &local_err, quiet);
470 error_report("%s: %s", filename, error_get_pretty(local_err));
471 error_free(local_err);
483 static void dump_json_image_check(ImageCheck *check, bool quiet)
485 Error *local_err = NULL;
487 QmpOutputVisitor *ov = qmp_output_visitor_new();
489 visit_type_ImageCheck(qmp_output_get_visitor(ov),
490 &check, NULL, &local_err);
491 obj = qmp_output_get_qobject(ov);
492 str = qobject_to_json_pretty(obj);
494 qprintf(quiet, "%s\n", qstring_get_str(str));
496 qmp_output_visitor_cleanup(ov);
500 static void dump_human_image_check(ImageCheck *check, bool quiet)
502 if (!(check->corruptions || check->leaks || check->check_errors)) {
503 qprintf(quiet, "No errors were found on the image.\n");
505 if (check->corruptions) {
506 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
507 "Data may be corrupted, or further writes to the image "
514 "\n%" PRId64 " leaked clusters were found on the image.\n"
515 "This means waste of disk space, but no harm to data.\n",
519 if (check->check_errors) {
522 " internal errors have occurred during the check.\n",
523 check->check_errors);
527 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
528 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
529 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
530 check->allocated_clusters, check->total_clusters,
531 check->allocated_clusters * 100.0 / check->total_clusters,
532 check->fragmented_clusters * 100.0 / check->allocated_clusters,
533 check->compressed_clusters * 100.0 /
534 check->allocated_clusters);
537 if (check->image_end_offset) {
539 "Image end offset: %" PRId64 "\n", check->image_end_offset);
543 static int collect_image_check(BlockDriverState *bs,
545 const char *filename,
550 BdrvCheckResult result;
552 ret = bdrv_check(bs, &result, fix);
557 check->filename = g_strdup(filename);
558 check->format = g_strdup(bdrv_get_format_name(bs));
559 check->check_errors = result.check_errors;
560 check->corruptions = result.corruptions;
561 check->has_corruptions = result.corruptions != 0;
562 check->leaks = result.leaks;
563 check->has_leaks = result.leaks != 0;
564 check->corruptions_fixed = result.corruptions_fixed;
565 check->has_corruptions_fixed = result.corruptions != 0;
566 check->leaks_fixed = result.leaks_fixed;
567 check->has_leaks_fixed = result.leaks != 0;
568 check->image_end_offset = result.image_end_offset;
569 check->has_image_end_offset = result.image_end_offset != 0;
570 check->total_clusters = result.bfi.total_clusters;
571 check->has_total_clusters = result.bfi.total_clusters != 0;
572 check->allocated_clusters = result.bfi.allocated_clusters;
573 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
574 check->fragmented_clusters = result.bfi.fragmented_clusters;
575 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
576 check->compressed_clusters = result.bfi.compressed_clusters;
577 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
583 * Checks an image for consistency. Exit codes:
585 * 0 - Check completed, image is good
586 * 1 - Check not completed because of internal errors
587 * 2 - Check completed, image is corrupted
588 * 3 - Check completed, image has leaked clusters, but is good otherwise
589 * 63 - Checks are not supported by the image format
591 static int img_check(int argc, char **argv)
594 OutputFormat output_format = OFORMAT_HUMAN;
595 const char *filename, *fmt, *output, *cache;
596 BlockDriverState *bs;
598 int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
604 cache = BDRV_DEFAULT_CACHE;
606 int option_index = 0;
607 static const struct option long_options[] = {
608 {"help", no_argument, 0, 'h'},
609 {"format", required_argument, 0, 'f'},
610 {"repair", required_argument, 0, 'r'},
611 {"output", required_argument, 0, OPTION_OUTPUT},
614 c = getopt_long(argc, argv, "hf:r:T:q",
615 long_options, &option_index);
628 flags |= BDRV_O_RDWR;
630 if (!strcmp(optarg, "leaks")) {
631 fix = BDRV_FIX_LEAKS;
632 } else if (!strcmp(optarg, "all")) {
633 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
635 error_exit("Unknown option value for -r "
636 "(expecting 'leaks' or 'all'): %s", optarg);
650 if (optind != argc - 1) {
651 error_exit("Expecting one image file name");
653 filename = argv[optind++];
655 if (output && !strcmp(output, "json")) {
656 output_format = OFORMAT_JSON;
657 } else if (output && !strcmp(output, "human")) {
658 output_format = OFORMAT_HUMAN;
660 error_report("--output must be used with human or json as argument.");
664 ret = bdrv_parse_cache_flags(cache, &flags);
666 error_report("Invalid source cache option: %s", cache);
670 bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
675 check = g_new0(ImageCheck, 1);
676 ret = collect_image_check(bs, check, filename, fmt, fix);
678 if (ret == -ENOTSUP) {
679 error_report("This image format does not support checks");
684 if (check->corruptions_fixed || check->leaks_fixed) {
685 int corruptions_fixed, leaks_fixed;
687 leaks_fixed = check->leaks_fixed;
688 corruptions_fixed = check->corruptions_fixed;
690 if (output_format == OFORMAT_HUMAN) {
692 "The following inconsistencies were found and repaired:\n\n"
693 " %" PRId64 " leaked clusters\n"
694 " %" PRId64 " corruptions\n\n"
695 "Double checking the fixed image now...\n",
697 check->corruptions_fixed);
700 ret = collect_image_check(bs, check, filename, fmt, 0);
702 check->leaks_fixed = leaks_fixed;
703 check->corruptions_fixed = corruptions_fixed;
706 switch (output_format) {
708 dump_human_image_check(check, quiet);
711 dump_json_image_check(check, quiet);
715 if (ret || check->check_errors) {
720 if (check->corruptions) {
722 } else if (check->leaks) {
729 qapi_free_ImageCheck(check);
735 static int img_commit(int argc, char **argv)
738 const char *filename, *fmt, *cache;
739 BlockDriverState *bs;
743 cache = BDRV_DEFAULT_CACHE;
745 c = getopt(argc, argv, "f:ht:q");
765 if (optind != argc - 1) {
766 error_exit("Expecting one image file name");
768 filename = argv[optind++];
771 ret = bdrv_parse_cache_flags(cache, &flags);
773 error_report("Invalid cache option: %s", cache);
777 bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
781 ret = bdrv_commit(bs);
784 qprintf(quiet, "Image committed.\n");
787 error_report("No disk inserted");
790 error_report("Image is read-only");
793 error_report("Image is already committed");
796 error_report("Error while committing image");
808 * Returns true iff the first sector pointed to by 'buf' contains at least
811 * 'pnum' is set to the number of sectors (including and immediately following
812 * the first one) that are known to be in the same allocated/unallocated state.
814 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
823 is_zero = buffer_is_zero(buf, 512);
824 for(i = 1; i < n; i++) {
826 if (is_zero != buffer_is_zero(buf, 512)) {
835 * Like is_allocated_sectors, but if the buffer starts with a used sector,
836 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
837 * breaking up write requests for only small sparse areas.
839 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
843 int num_checked, num_used;
849 ret = is_allocated_sectors(buf, n, pnum);
855 buf += BDRV_SECTOR_SIZE * *pnum;
857 num_checked = num_used;
860 ret = is_allocated_sectors(buf, n, pnum);
862 buf += BDRV_SECTOR_SIZE * *pnum;
864 num_checked += *pnum;
866 num_used = num_checked;
867 } else if (*pnum >= min) {
877 * Compares two buffers sector by sector. Returns 0 if the first sector of both
878 * buffers matches, non-zero otherwise.
880 * pnum is set to the number of sectors (including and immediately following
881 * the first one) that are known to have the same comparison result
883 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
893 res = !!memcmp(buf1, buf2, 512);
894 for(i = 1; i < n; i++) {
898 if (!!memcmp(buf1, buf2, 512) != res) {
907 #define IO_BUF_SIZE (2 * 1024 * 1024)
909 static int64_t sectors_to_bytes(int64_t sectors)
911 return sectors << BDRV_SECTOR_BITS;
914 static int64_t sectors_to_process(int64_t total, int64_t from)
916 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
920 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
922 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
923 * data and negative value on error.
925 * @param bs: Driver used for accessing file
926 * @param sect_num: Number of first sector to check
927 * @param sect_count: Number of sectors to check
928 * @param filename: Name of disk file we are checking (logging purpose)
929 * @param buffer: Allocated buffer for storing read data
930 * @param quiet: Flag for quiet mode
932 static int check_empty_sectors(BlockDriverState *bs, int64_t sect_num,
933 int sect_count, const char *filename,
934 uint8_t *buffer, bool quiet)
937 ret = bdrv_read(bs, sect_num, buffer, sect_count);
939 error_report("Error while reading offset %" PRId64 " of %s: %s",
940 sectors_to_bytes(sect_num), filename, strerror(-ret));
943 ret = is_allocated_sectors(buffer, sect_count, &pnum);
944 if (ret || pnum != sect_count) {
945 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
946 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
954 * Compares two images. Exit codes:
956 * 0 - Images are identical
958 * >1 - Error occurred
960 static int img_compare(int argc, char **argv)
962 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
963 BlockDriverState *bs1, *bs2;
964 int64_t total_sectors1, total_sectors2;
965 uint8_t *buf1 = NULL, *buf2 = NULL;
967 int allocated1, allocated2;
968 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
969 bool progress = false, quiet = false, strict = false;
971 int64_t total_sectors;
972 int64_t sector_num = 0;
975 uint64_t progress_base;
977 cache = BDRV_DEFAULT_CACHE;
979 c = getopt(argc, argv, "hf:F:T:pqs");
1009 /* Progress is not shown in Quiet mode */
1015 if (optind != argc - 2) {
1016 error_exit("Expecting two image file names");
1018 filename1 = argv[optind++];
1019 filename2 = argv[optind++];
1021 flags = BDRV_O_FLAGS;
1022 ret = bdrv_parse_cache_flags(cache, &flags);
1024 error_report("Invalid source cache option: %s", cache);
1029 /* Initialize before goto out */
1030 qemu_progress_init(progress, 2.0);
1032 bs1 = bdrv_new_open("image 1", filename1, fmt1, flags, true, quiet);
1034 error_report("Can't open file %s", filename1);
1039 bs2 = bdrv_new_open("image 2", filename2, fmt2, flags, true, quiet);
1041 error_report("Can't open file %s", filename2);
1046 buf1 = qemu_blockalign(bs1, IO_BUF_SIZE);
1047 buf2 = qemu_blockalign(bs2, IO_BUF_SIZE);
1048 total_sectors1 = bdrv_nb_sectors(bs1);
1049 if (total_sectors1 < 0) {
1050 error_report("Can't get size of %s: %s",
1051 filename1, strerror(-total_sectors1));
1055 total_sectors2 = bdrv_nb_sectors(bs2);
1056 if (total_sectors2 < 0) {
1057 error_report("Can't get size of %s: %s",
1058 filename2, strerror(-total_sectors2));
1062 total_sectors = MIN(total_sectors1, total_sectors2);
1063 progress_base = MAX(total_sectors1, total_sectors2);
1065 qemu_progress_print(0, 100);
1067 if (strict && total_sectors1 != total_sectors2) {
1069 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1074 nb_sectors = sectors_to_process(total_sectors, sector_num);
1075 if (nb_sectors <= 0) {
1078 allocated1 = bdrv_is_allocated_above(bs1, NULL, sector_num, nb_sectors,
1080 if (allocated1 < 0) {
1082 error_report("Sector allocation test failed for %s", filename1);
1086 allocated2 = bdrv_is_allocated_above(bs2, NULL, sector_num, nb_sectors,
1088 if (allocated2 < 0) {
1090 error_report("Sector allocation test failed for %s", filename2);
1093 nb_sectors = MIN(pnum1, pnum2);
1095 if (allocated1 == allocated2) {
1097 ret = bdrv_read(bs1, sector_num, buf1, nb_sectors);
1099 error_report("Error while reading offset %" PRId64 " of %s:"
1100 " %s", sectors_to_bytes(sector_num), filename1,
1105 ret = bdrv_read(bs2, sector_num, buf2, nb_sectors);
1107 error_report("Error while reading offset %" PRId64
1108 " of %s: %s", sectors_to_bytes(sector_num),
1109 filename2, strerror(-ret));
1113 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1114 if (ret || pnum != nb_sectors) {
1115 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1117 ret ? sector_num : sector_num + pnum));
1125 qprintf(quiet, "Strict mode: Offset %" PRId64
1126 " allocation mismatch!\n",
1127 sectors_to_bytes(sector_num));
1132 ret = check_empty_sectors(bs1, sector_num, nb_sectors,
1133 filename1, buf1, quiet);
1135 ret = check_empty_sectors(bs2, sector_num, nb_sectors,
1136 filename2, buf1, quiet);
1140 error_report("Error while reading offset %" PRId64 ": %s",
1141 sectors_to_bytes(sector_num), strerror(-ret));
1147 sector_num += nb_sectors;
1148 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1151 if (total_sectors1 != total_sectors2) {
1152 BlockDriverState *bs_over;
1153 int64_t total_sectors_over;
1154 const char *filename_over;
1156 qprintf(quiet, "Warning: Image size mismatch!\n");
1157 if (total_sectors1 > total_sectors2) {
1158 total_sectors_over = total_sectors1;
1160 filename_over = filename1;
1162 total_sectors_over = total_sectors2;
1164 filename_over = filename2;
1168 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1169 if (nb_sectors <= 0) {
1172 ret = bdrv_is_allocated_above(bs_over, NULL, sector_num,
1176 error_report("Sector allocation test failed for %s",
1183 ret = check_empty_sectors(bs_over, sector_num, nb_sectors,
1184 filename_over, buf1, quiet);
1187 error_report("Error while reading offset %" PRId64
1188 " of %s: %s", sectors_to_bytes(sector_num),
1189 filename_over, strerror(-ret));
1195 sector_num += nb_sectors;
1196 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1200 qprintf(quiet, "Images are identical.\n");
1210 qemu_progress_end();
1214 static int img_convert(int argc, char **argv)
1216 int c, n, n1, bs_n, bs_i, compress, cluster_sectors, skip_create;
1218 int progress = 0, flags, src_flags;
1219 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
1220 BlockDriver *drv, *proto_drv;
1221 BlockDriverState **bs = NULL, *out_bs = NULL;
1222 int64_t total_sectors, nb_sectors, sector_num, bs_offset;
1223 int64_t *bs_sectors = NULL;
1224 uint8_t * buf = NULL;
1225 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
1226 const uint8_t *buf1;
1227 BlockDriverInfo bdi;
1228 QemuOpts *opts = NULL;
1229 QemuOptsList *create_opts = NULL;
1230 const char *out_baseimg_param;
1231 char *options = NULL;
1232 const char *snapshot_name = NULL;
1233 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
1235 Error *local_err = NULL;
1236 QemuOpts *sn_opts = NULL;
1241 src_cache = BDRV_DEFAULT_CACHE;
1246 c = getopt(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn");
1262 out_baseimg = optarg;
1268 error_report("option -e is deprecated, please use \'-o "
1269 "encryption\' instead!");
1273 error_report("option -6 is deprecated, please use \'-o "
1274 "compat6\' instead!");
1278 if (!is_valid_option_list(optarg)) {
1279 error_report("Invalid option list: %s", optarg);
1284 options = g_strdup(optarg);
1286 char *old_options = options;
1287 options = g_strdup_printf("%s,%s", options, optarg);
1288 g_free(old_options);
1292 snapshot_name = optarg;
1295 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1296 sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
1298 error_report("Failed in parsing snapshot param '%s'",
1304 snapshot_name = optarg;
1311 sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
1312 if (sval < 0 || *end) {
1313 error_report("Invalid minimum zero buffer size for sparse output specified");
1318 min_sparse = sval / BDRV_SECTOR_SIZE;
1339 /* Initialize before goto out */
1343 qemu_progress_init(progress, 1.0);
1346 bs_n = argc - optind - 1;
1347 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
1349 if (options && has_help_option(options)) {
1350 ret = print_block_option_help(out_filename, out_fmt);
1355 error_exit("Must specify image file name");
1359 if (bs_n > 1 && out_baseimg) {
1360 error_report("-B makes no sense when concatenating multiple input "
1366 src_flags = BDRV_O_FLAGS;
1367 ret = bdrv_parse_cache_flags(src_cache, &src_flags);
1369 error_report("Invalid source cache option: %s", src_cache);
1373 qemu_progress_print(0, 100);
1375 bs = g_new0(BlockDriverState *, bs_n);
1376 bs_sectors = g_new(int64_t, bs_n);
1379 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1380 char *id = bs_n > 1 ? g_strdup_printf("source %d", bs_i)
1381 : g_strdup("source");
1382 bs[bs_i] = bdrv_new_open(id, argv[optind + bs_i], fmt, src_flags,
1386 error_report("Could not open '%s'", argv[optind + bs_i]);
1390 bs_sectors[bs_i] = bdrv_nb_sectors(bs[bs_i]);
1391 if (bs_sectors[bs_i] < 0) {
1392 error_report("Could not get size of %s: %s",
1393 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1397 total_sectors += bs_sectors[bs_i];
1401 ret = bdrv_snapshot_load_tmp(bs[0],
1402 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1403 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1405 } else if (snapshot_name != NULL) {
1407 error_report("No support for concatenating multiple snapshot");
1412 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
1415 error_report("Failed to load snapshot: %s",
1416 error_get_pretty(local_err));
1417 error_free(local_err);
1422 /* Find driver and parse its options */
1423 drv = bdrv_find_format(out_fmt);
1425 error_report("Unknown file format '%s'", out_fmt);
1430 proto_drv = bdrv_find_protocol(out_filename, true);
1432 error_report("Unknown protocol '%s'", out_filename);
1437 create_opts = qemu_opts_append(create_opts, drv->create_opts);
1438 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
1440 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
1441 if (options && qemu_opts_do_parse(opts, options, NULL)) {
1442 error_report("Invalid options for file format '%s'", out_fmt);
1447 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512);
1448 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
1453 /* Get backing file name if -o backing_file was used */
1454 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
1455 if (out_baseimg_param) {
1456 out_baseimg = out_baseimg_param;
1459 /* Check if compression is supported */
1462 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
1463 const char *preallocation =
1464 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
1466 if (!drv->bdrv_write_compressed) {
1467 error_report("Compression not supported for this file format");
1473 error_report("Compression and encryption not supported at "
1480 && strcmp(preallocation, "off"))
1482 error_report("Compression and preallocation not supported at "
1490 /* Create the new image */
1491 ret = bdrv_create(drv, out_filename, opts, &local_err);
1493 error_report("%s: error while converting %s: %s",
1494 out_filename, out_fmt, error_get_pretty(local_err));
1495 error_free(local_err);
1500 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
1501 ret = bdrv_parse_cache_flags(cache, &flags);
1503 error_report("Invalid cache option: %s", cache);
1507 out_bs = bdrv_new_open("target", out_filename, out_fmt, flags, true, quiet);
1516 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
1517 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
1519 bufsectors = MIN(32768,
1520 MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
1521 out_bs->bl.discard_alignment))
1524 buf = qemu_blockalign(out_bs, bufsectors * BDRV_SECTOR_SIZE);
1527 int64_t output_sectors = bdrv_nb_sectors(out_bs);
1528 if (output_sectors < 0) {
1529 error_report("unable to get output image length: %s\n",
1530 strerror(-output_sectors));
1533 } else if (output_sectors < total_sectors) {
1534 error_report("output file is smaller than input file");
1540 cluster_sectors = 0;
1541 ret = bdrv_get_info(out_bs, &bdi);
1544 error_report("could not get block driver info");
1548 compress = compress || bdi.needs_compressed_writes;
1549 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
1553 if (cluster_sectors <= 0 || cluster_sectors > bufsectors) {
1554 error_report("invalid cluster size");
1560 nb_sectors = total_sectors;
1567 nb_sectors = total_sectors - sector_num;
1568 if (nb_sectors <= 0)
1570 if (nb_sectors >= cluster_sectors)
1571 n = cluster_sectors;
1575 bs_num = sector_num - bs_offset;
1576 assert (bs_num >= 0);
1579 while (remainder > 0) {
1581 while (bs_num == bs_sectors[bs_i]) {
1582 bs_offset += bs_sectors[bs_i];
1584 assert (bs_i < bs_n);
1586 /* printf("changing part: sector_num=%" PRId64 ", "
1587 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
1588 "\n", sector_num, bs_i, bs_offset, bs_sectors[bs_i]); */
1590 assert (bs_num < bs_sectors[bs_i]);
1592 nlow = remainder > bs_sectors[bs_i] - bs_num
1593 ? bs_sectors[bs_i] - bs_num : remainder;
1595 ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
1597 error_report("error while reading sector %" PRId64 ": %s",
1598 bs_num, strerror(-ret));
1607 assert (remainder == 0);
1609 if (!buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)) {
1610 ret = bdrv_write_compressed(out_bs, sector_num, buf, n);
1612 error_report("error while compressing sector %" PRId64
1613 ": %s", sector_num, strerror(-ret));
1618 qemu_progress_print(100.0 * sector_num / total_sectors, 0);
1620 /* signal EOF to align */
1621 bdrv_write_compressed(out_bs, 0, NULL, 0);
1623 int64_t sectors_to_read, sectors_read, sector_num_next_status;
1624 bool count_allocated_sectors;
1625 int has_zero_init = min_sparse ? bdrv_has_zero_init(out_bs) : 0;
1627 if (!has_zero_init && bdrv_can_write_zeroes_with_unmap(out_bs)) {
1628 ret = bdrv_make_zero(out_bs, BDRV_REQ_MAY_UNMAP);
1635 sectors_to_read = total_sectors;
1636 count_allocated_sectors = progress && (out_baseimg || has_zero_init);
1638 sector_num = 0; // total number of sectors converted so far
1640 sector_num_next_status = 0;
1643 nb_sectors = total_sectors - sector_num;
1644 if (nb_sectors <= 0) {
1645 if (count_allocated_sectors) {
1646 sectors_to_read = sectors_read;
1647 count_allocated_sectors = false;
1654 while (sector_num - bs_offset >= bs_sectors[bs_i]) {
1655 bs_offset += bs_sectors[bs_i];
1657 assert (bs_i < bs_n);
1658 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1659 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
1660 sector_num, bs_i, bs_offset, bs_sectors[bs_i]); */
1663 if ((out_baseimg || has_zero_init) &&
1664 sector_num >= sector_num_next_status) {
1665 n = nb_sectors > INT_MAX ? INT_MAX : nb_sectors;
1666 ret = bdrv_get_block_status(bs[bs_i], sector_num - bs_offset,
1669 error_report("error while reading block status of sector %"
1670 PRId64 ": %s", sector_num - bs_offset,
1674 /* If the output image is zero initialized, we are not working
1675 * on a shared base and the input is zero we can skip the next
1677 if (has_zero_init && !out_baseimg && (ret & BDRV_BLOCK_ZERO)) {
1681 /* If the output image is being created as a copy on write
1682 * image, assume that sectors which are unallocated in the
1683 * input image are present in both the output's and input's
1684 * base images (no need to copy them). */
1686 if (!(ret & BDRV_BLOCK_DATA)) {
1690 /* The next 'n1' sectors are allocated in the input image.
1691 * Copy only those as they may be followed by unallocated
1695 /* avoid redundant callouts to get_block_status */
1696 sector_num_next_status = sector_num + n1;
1699 n = MIN(nb_sectors, bufsectors);
1701 /* round down request length to an aligned sector, but
1702 * do not bother doing this on short requests. They happen
1703 * when we found an all-zero area, and the next sector to
1704 * write will not be sector_num + n. */
1705 if (cluster_sectors > 0 && n >= cluster_sectors) {
1706 int64_t next_aligned_sector = (sector_num + n);
1707 next_aligned_sector -= next_aligned_sector % cluster_sectors;
1708 if (sector_num + n > next_aligned_sector) {
1709 n = next_aligned_sector - sector_num;
1713 n = MIN(n, bs_sectors[bs_i] - (sector_num - bs_offset));
1716 if (count_allocated_sectors) {
1722 ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
1724 error_report("error while reading sector %" PRId64 ": %s",
1725 sector_num - bs_offset, strerror(-ret));
1728 /* NOTE: at the same time we convert, we do not write zero
1729 sectors to have a chance to compress the image. Ideally, we
1730 should add a specific call to have the info to go faster */
1733 if (!has_zero_init ||
1734 is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
1735 ret = bdrv_write(out_bs, sector_num, buf1, n1);
1737 error_report("error while writing sector %" PRId64
1738 ": %s", sector_num, strerror(-ret));
1746 qemu_progress_print(100.0 * sectors_read / sectors_to_read, 0);
1751 qemu_progress_print(100, 0);
1753 qemu_progress_end();
1754 qemu_opts_del(opts);
1755 qemu_opts_free(create_opts);
1758 qemu_opts_del(sn_opts);
1764 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1766 bdrv_unref(bs[bs_i]);
1782 static void dump_snapshots(BlockDriverState *bs)
1784 QEMUSnapshotInfo *sn_tab, *sn;
1787 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1790 printf("Snapshot list:\n");
1791 bdrv_snapshot_dump(fprintf, stdout, NULL);
1793 for(i = 0; i < nb_sns; i++) {
1795 bdrv_snapshot_dump(fprintf, stdout, sn);
1801 static void dump_json_image_info_list(ImageInfoList *list)
1803 Error *local_err = NULL;
1805 QmpOutputVisitor *ov = qmp_output_visitor_new();
1807 visit_type_ImageInfoList(qmp_output_get_visitor(ov),
1808 &list, NULL, &local_err);
1809 obj = qmp_output_get_qobject(ov);
1810 str = qobject_to_json_pretty(obj);
1811 assert(str != NULL);
1812 printf("%s\n", qstring_get_str(str));
1813 qobject_decref(obj);
1814 qmp_output_visitor_cleanup(ov);
1818 static void dump_json_image_info(ImageInfo *info)
1820 Error *local_err = NULL;
1822 QmpOutputVisitor *ov = qmp_output_visitor_new();
1824 visit_type_ImageInfo(qmp_output_get_visitor(ov),
1825 &info, NULL, &local_err);
1826 obj = qmp_output_get_qobject(ov);
1827 str = qobject_to_json_pretty(obj);
1828 assert(str != NULL);
1829 printf("%s\n", qstring_get_str(str));
1830 qobject_decref(obj);
1831 qmp_output_visitor_cleanup(ov);
1835 static void dump_human_image_info_list(ImageInfoList *list)
1837 ImageInfoList *elem;
1840 for (elem = list; elem; elem = elem->next) {
1846 bdrv_image_info_dump(fprintf, stdout, elem->value);
1850 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
1852 return strcmp(a, b) == 0;
1856 * Open an image file chain and return an ImageInfoList
1858 * @filename: topmost image filename
1859 * @fmt: topmost image format (may be NULL to autodetect)
1860 * @chain: true - enumerate entire backing file chain
1861 * false - only topmost image file
1863 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1864 * image file. If there was an error a message will have been printed to
1867 static ImageInfoList *collect_image_info_list(const char *filename,
1871 ImageInfoList *head = NULL;
1872 ImageInfoList **last = &head;
1873 GHashTable *filenames;
1876 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
1879 BlockDriverState *bs;
1881 ImageInfoList *elem;
1883 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
1884 error_report("Backing file '%s' creates an infinite loop.",
1888 g_hash_table_insert(filenames, (gpointer)filename, NULL);
1890 bs = bdrv_new_open("image", filename, fmt,
1891 BDRV_O_FLAGS | BDRV_O_NO_BACKING, false, false);
1896 bdrv_query_image_info(bs, &info, &err);
1898 error_report("%s", error_get_pretty(err));
1904 elem = g_new0(ImageInfoList, 1);
1911 filename = fmt = NULL;
1913 if (info->has_full_backing_filename) {
1914 filename = info->full_backing_filename;
1915 } else if (info->has_backing_filename) {
1916 filename = info->backing_filename;
1918 if (info->has_backing_filename_format) {
1919 fmt = info->backing_filename_format;
1923 g_hash_table_destroy(filenames);
1927 qapi_free_ImageInfoList(head);
1928 g_hash_table_destroy(filenames);
1932 static int img_info(int argc, char **argv)
1935 OutputFormat output_format = OFORMAT_HUMAN;
1937 const char *filename, *fmt, *output;
1938 ImageInfoList *list;
1943 int option_index = 0;
1944 static const struct option long_options[] = {
1945 {"help", no_argument, 0, 'h'},
1946 {"format", required_argument, 0, 'f'},
1947 {"output", required_argument, 0, OPTION_OUTPUT},
1948 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
1951 c = getopt_long(argc, argv, "f:h",
1952 long_options, &option_index);
1967 case OPTION_BACKING_CHAIN:
1972 if (optind != argc - 1) {
1973 error_exit("Expecting one image file name");
1975 filename = argv[optind++];
1977 if (output && !strcmp(output, "json")) {
1978 output_format = OFORMAT_JSON;
1979 } else if (output && !strcmp(output, "human")) {
1980 output_format = OFORMAT_HUMAN;
1981 } else if (output) {
1982 error_report("--output must be used with human or json as argument.");
1986 list = collect_image_info_list(filename, fmt, chain);
1991 switch (output_format) {
1993 dump_human_image_info_list(list);
1997 dump_json_image_info_list(list);
1999 dump_json_image_info(list->value);
2004 qapi_free_ImageInfoList(list);
2009 typedef struct MapEntry {
2015 BlockDriverState *bs;
2018 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2021 switch (output_format) {
2023 if ((e->flags & BDRV_BLOCK_DATA) &&
2024 !(e->flags & BDRV_BLOCK_OFFSET_VALID)) {
2025 error_report("File contains external, encrypted or compressed clusters.");
2028 if ((e->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) == BDRV_BLOCK_DATA) {
2029 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2030 e->start, e->length, e->offset, e->bs->filename);
2032 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2033 * Modify the flags here to allow more coalescing.
2036 (next->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) != BDRV_BLOCK_DATA) {
2037 next->flags &= ~BDRV_BLOCK_DATA;
2038 next->flags |= BDRV_BLOCK_ZERO;
2042 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64", \"depth\": %d,"
2043 " \"zero\": %s, \"data\": %s",
2044 (e->start == 0 ? "[" : ",\n"),
2045 e->start, e->length, e->depth,
2046 (e->flags & BDRV_BLOCK_ZERO) ? "true" : "false",
2047 (e->flags & BDRV_BLOCK_DATA) ? "true" : "false");
2048 if (e->flags & BDRV_BLOCK_OFFSET_VALID) {
2049 printf(", \"offset\": %"PRId64"", e->offset);
2060 static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2061 int nb_sectors, MapEntry *e)
2066 /* As an optimization, we could cache the current range of unallocated
2067 * clusters in each file of the chain, and avoid querying the same
2073 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors);
2078 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2081 bs = bs->backing_hd;
2090 e->start = sector_num * BDRV_SECTOR_SIZE;
2091 e->length = nb_sectors * BDRV_SECTOR_SIZE;
2092 e->flags = ret & ~BDRV_BLOCK_OFFSET_MASK;
2093 e->offset = ret & BDRV_BLOCK_OFFSET_MASK;
2099 static int img_map(int argc, char **argv)
2102 OutputFormat output_format = OFORMAT_HUMAN;
2103 BlockDriverState *bs;
2104 const char *filename, *fmt, *output;
2106 MapEntry curr = { .length = 0 }, next;
2112 int option_index = 0;
2113 static const struct option long_options[] = {
2114 {"help", no_argument, 0, 'h'},
2115 {"format", required_argument, 0, 'f'},
2116 {"output", required_argument, 0, OPTION_OUTPUT},
2119 c = getopt_long(argc, argv, "f:h",
2120 long_options, &option_index);
2137 if (optind != argc - 1) {
2138 error_exit("Expecting one image file name");
2140 filename = argv[optind];
2142 if (output && !strcmp(output, "json")) {
2143 output_format = OFORMAT_JSON;
2144 } else if (output && !strcmp(output, "human")) {
2145 output_format = OFORMAT_HUMAN;
2146 } else if (output) {
2147 error_report("--output must be used with human or json as argument.");
2151 bs = bdrv_new_open("image", filename, fmt, BDRV_O_FLAGS, true, false);
2156 if (output_format == OFORMAT_HUMAN) {
2157 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2160 length = bdrv_getlength(bs);
2161 while (curr.start + curr.length < length) {
2162 int64_t nsectors_left;
2166 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2168 /* Probe up to 1 GiB at a time. */
2169 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2170 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2171 ret = get_block_status(bs, sector_num, n, &next);
2174 error_report("Could not read file metadata: %s", strerror(-ret));
2178 if (curr.length != 0 && curr.flags == next.flags &&
2179 curr.depth == next.depth &&
2180 ((curr.flags & BDRV_BLOCK_OFFSET_VALID) == 0 ||
2181 curr.offset + curr.length == next.offset)) {
2182 curr.length += next.length;
2186 if (curr.length > 0) {
2187 dump_map_entry(output_format, &curr, &next);
2192 dump_map_entry(output_format, &curr, NULL);
2199 #define SNAPSHOT_LIST 1
2200 #define SNAPSHOT_CREATE 2
2201 #define SNAPSHOT_APPLY 3
2202 #define SNAPSHOT_DELETE 4
2204 static int img_snapshot(int argc, char **argv)
2206 BlockDriverState *bs;
2207 QEMUSnapshotInfo sn;
2208 char *filename, *snapshot_name = NULL;
2209 int c, ret = 0, bdrv_oflags;
2215 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
2216 /* Parse commandline parameters */
2218 c = getopt(argc, argv, "la:c:d:hq");
2229 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2232 action = SNAPSHOT_LIST;
2233 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
2237 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2240 action = SNAPSHOT_APPLY;
2241 snapshot_name = optarg;
2245 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2248 action = SNAPSHOT_CREATE;
2249 snapshot_name = optarg;
2253 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2256 action = SNAPSHOT_DELETE;
2257 snapshot_name = optarg;
2265 if (optind != argc - 1) {
2266 error_exit("Expecting one image file name");
2268 filename = argv[optind++];
2270 /* Open the image */
2271 bs = bdrv_new_open("image", filename, NULL, bdrv_oflags, true, quiet);
2276 /* Perform the requested action */
2282 case SNAPSHOT_CREATE:
2283 memset(&sn, 0, sizeof(sn));
2284 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2286 qemu_gettimeofday(&tv);
2287 sn.date_sec = tv.tv_sec;
2288 sn.date_nsec = tv.tv_usec * 1000;
2290 ret = bdrv_snapshot_create(bs, &sn);
2292 error_report("Could not create snapshot '%s': %d (%s)",
2293 snapshot_name, ret, strerror(-ret));
2297 case SNAPSHOT_APPLY:
2298 ret = bdrv_snapshot_goto(bs, snapshot_name);
2300 error_report("Could not apply snapshot '%s': %d (%s)",
2301 snapshot_name, ret, strerror(-ret));
2305 case SNAPSHOT_DELETE:
2306 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
2308 error_report("Could not delete snapshot '%s': (%s)",
2309 snapshot_name, error_get_pretty(err));
2324 static int img_rebase(int argc, char **argv)
2326 BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
2327 BlockDriver *old_backing_drv, *new_backing_drv;
2329 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2330 int c, flags, src_flags, ret;
2334 Error *local_err = NULL;
2336 /* Parse commandline parameters */
2338 cache = BDRV_DEFAULT_CACHE;
2339 src_cache = BDRV_DEFAULT_CACHE;
2343 c = getopt(argc, argv, "hf:F:b:upt:T:q");
2356 out_basefmt = optarg;
2359 out_baseimg = optarg;
2383 if (optind != argc - 1) {
2384 error_exit("Expecting one image file name");
2386 if (!unsafe && !out_baseimg) {
2387 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
2389 filename = argv[optind++];
2391 qemu_progress_init(progress, 2.0);
2392 qemu_progress_print(0, 100);
2394 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
2395 ret = bdrv_parse_cache_flags(cache, &flags);
2397 error_report("Invalid cache option: %s", cache);
2401 src_flags = BDRV_O_FLAGS;
2402 ret = bdrv_parse_cache_flags(src_cache, &src_flags);
2404 error_report("Invalid source cache option: %s", src_cache);
2411 * Ignore the old backing file for unsafe rebase in case we want to correct
2412 * the reference to a renamed or moved backing file.
2414 bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
2419 /* Find the right drivers for the backing files */
2420 old_backing_drv = NULL;
2421 new_backing_drv = NULL;
2423 if (!unsafe && bs->backing_format[0] != '\0') {
2424 old_backing_drv = bdrv_find_format(bs->backing_format);
2425 if (old_backing_drv == NULL) {
2426 error_report("Invalid format name: '%s'", bs->backing_format);
2432 if (out_basefmt != NULL) {
2433 new_backing_drv = bdrv_find_format(out_basefmt);
2434 if (new_backing_drv == NULL) {
2435 error_report("Invalid format name: '%s'", out_basefmt);
2441 /* For safe rebasing we need to compare old and new backing file */
2443 /* Make the compiler happy */
2444 bs_old_backing = NULL;
2445 bs_new_backing = NULL;
2447 char backing_name[1024];
2449 bs_old_backing = bdrv_new("old_backing", &error_abort);
2450 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2451 ret = bdrv_open(&bs_old_backing, backing_name, NULL, NULL, src_flags,
2452 old_backing_drv, &local_err);
2454 error_report("Could not open old backing file '%s': %s",
2455 backing_name, error_get_pretty(local_err));
2456 error_free(local_err);
2459 if (out_baseimg[0]) {
2460 bs_new_backing = bdrv_new("new_backing", &error_abort);
2461 ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, NULL, src_flags,
2462 new_backing_drv, &local_err);
2464 error_report("Could not open new backing file '%s': %s",
2465 out_baseimg, error_get_pretty(local_err));
2466 error_free(local_err);
2473 * Check each unallocated cluster in the COW file. If it is unallocated,
2474 * accesses go to the backing file. We must therefore compare this cluster
2475 * in the old and new backing file, and if they differ we need to copy it
2476 * from the old backing file into the COW file.
2478 * If qemu-img crashes during this step, no harm is done. The content of
2479 * the image is the same as the original one at any time.
2482 int64_t num_sectors;
2483 int64_t old_backing_num_sectors;
2484 int64_t new_backing_num_sectors = 0;
2489 float local_progress = 0;
2491 buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
2492 buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
2494 num_sectors = bdrv_nb_sectors(bs);
2495 if (num_sectors < 0) {
2496 error_report("Could not get size of '%s': %s",
2497 filename, strerror(-num_sectors));
2501 old_backing_num_sectors = bdrv_nb_sectors(bs_old_backing);
2502 if (old_backing_num_sectors < 0) {
2503 char backing_name[1024];
2505 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2506 error_report("Could not get size of '%s': %s",
2507 backing_name, strerror(-old_backing_num_sectors));
2511 if (bs_new_backing) {
2512 new_backing_num_sectors = bdrv_nb_sectors(bs_new_backing);
2513 if (new_backing_num_sectors < 0) {
2514 error_report("Could not get size of '%s': %s",
2515 out_baseimg, strerror(-new_backing_num_sectors));
2521 if (num_sectors != 0) {
2522 local_progress = (float)100 /
2523 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
2526 for (sector = 0; sector < num_sectors; sector += n) {
2528 /* How many sectors can we handle with the next read? */
2529 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
2530 n = (IO_BUF_SIZE / 512);
2532 n = num_sectors - sector;
2535 /* If the cluster is allocated, we don't need to take action */
2536 ret = bdrv_is_allocated(bs, sector, n, &n);
2538 error_report("error while reading image metadata: %s",
2547 * Read old and new backing file and take into consideration that
2548 * backing files may be smaller than the COW image.
2550 if (sector >= old_backing_num_sectors) {
2551 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
2553 if (sector + n > old_backing_num_sectors) {
2554 n = old_backing_num_sectors - sector;
2557 ret = bdrv_read(bs_old_backing, sector, buf_old, n);
2559 error_report("error while reading from old backing file");
2564 if (sector >= new_backing_num_sectors || !bs_new_backing) {
2565 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
2567 if (sector + n > new_backing_num_sectors) {
2568 n = new_backing_num_sectors - sector;
2571 ret = bdrv_read(bs_new_backing, sector, buf_new, n);
2573 error_report("error while reading from new backing file");
2578 /* If they differ, we need to write to the COW file */
2579 uint64_t written = 0;
2581 while (written < n) {
2584 if (compare_sectors(buf_old + written * 512,
2585 buf_new + written * 512, n - written, &pnum))
2587 ret = bdrv_write(bs, sector + written,
2588 buf_old + written * 512, pnum);
2590 error_report("Error while writing to COW image: %s",
2598 qemu_progress_print(local_progress, 100);
2601 qemu_vfree(buf_old);
2602 qemu_vfree(buf_new);
2606 * Change the backing file. All clusters that are different from the old
2607 * backing file are overwritten in the COW file now, so the visible content
2608 * doesn't change when we switch the backing file.
2610 if (out_baseimg && *out_baseimg) {
2611 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
2613 ret = bdrv_change_backing_file(bs, NULL, NULL);
2616 if (ret == -ENOSPC) {
2617 error_report("Could not change the backing file to '%s': No "
2618 "space left in the file header", out_baseimg);
2619 } else if (ret < 0) {
2620 error_report("Could not change the backing file to '%s': %s",
2621 out_baseimg, strerror(-ret));
2624 qemu_progress_print(100, 0);
2626 * TODO At this point it is possible to check if any clusters that are
2627 * allocated in the COW file are the same in the backing file. If so, they
2628 * could be dropped from the COW file. Don't do this before switching the
2629 * backing file, in case of a crash this would lead to corruption.
2632 qemu_progress_end();
2635 if (bs_old_backing != NULL) {
2636 bdrv_unref(bs_old_backing);
2638 if (bs_new_backing != NULL) {
2639 bdrv_unref(bs_new_backing);
2650 static int img_resize(int argc, char **argv)
2652 int c, ret, relative;
2653 const char *filename, *fmt, *size;
2654 int64_t n, total_size;
2656 BlockDriverState *bs = NULL;
2658 static QemuOptsList resize_options = {
2659 .name = "resize_options",
2660 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
2663 .name = BLOCK_OPT_SIZE,
2664 .type = QEMU_OPT_SIZE,
2665 .help = "Virtual disk size"
2672 /* Remove size from argv manually so that negative numbers are not treated
2673 * as options by getopt. */
2675 error_exit("Not enough arguments");
2679 size = argv[--argc];
2681 /* Parse getopt arguments */
2684 c = getopt(argc, argv, "f:hq");
2701 if (optind != argc - 1) {
2702 error_exit("Expecting one image file name");
2704 filename = argv[optind++];
2706 /* Choose grow, shrink, or absolute resize mode */
2722 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
2723 if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
2724 /* Error message already printed when size parsing fails */
2726 qemu_opts_del(param);
2729 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
2730 qemu_opts_del(param);
2732 bs = bdrv_new_open("image", filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR,
2740 total_size = bdrv_getlength(bs) + n * relative;
2744 if (total_size <= 0) {
2745 error_report("New image size must be positive");
2750 ret = bdrv_truncate(bs, total_size);
2753 qprintf(quiet, "Image resized.\n");
2756 error_report("This image does not support resize");
2759 error_report("Image is read-only");
2762 error_report("Error resizing image (%d)", -ret);
2775 static int img_amend(int argc, char **argv)
2778 char *options = NULL;
2779 QemuOptsList *create_opts = NULL;
2780 QemuOpts *opts = NULL;
2781 const char *fmt = NULL, *filename, *cache;
2784 BlockDriverState *bs = NULL;
2786 cache = BDRV_DEFAULT_CACHE;
2788 c = getopt(argc, argv, "ho:f:t:q");
2799 if (!is_valid_option_list(optarg)) {
2800 error_report("Invalid option list: %s", optarg);
2805 options = g_strdup(optarg);
2807 char *old_options = options;
2808 options = g_strdup_printf("%s,%s", options, optarg);
2809 g_free(old_options);
2825 error_exit("Must specify options (-o)");
2828 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
2829 if (fmt && has_help_option(options)) {
2830 /* If a format is explicitly specified (and possibly no filename is
2831 * given), print option help here */
2832 ret = print_block_option_help(filename, fmt);
2836 if (optind != argc - 1) {
2837 error_exit("Expecting one image file name");
2840 flags = BDRV_O_FLAGS | BDRV_O_RDWR;
2841 ret = bdrv_parse_cache_flags(cache, &flags);
2843 error_report("Invalid cache option: %s", cache);
2847 bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
2849 error_report("Could not open image '%s'", filename);
2854 fmt = bs->drv->format_name;
2856 if (has_help_option(options)) {
2857 /* If the format was auto-detected, print option help here */
2858 ret = print_block_option_help(filename, fmt);
2862 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
2863 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2864 if (options && qemu_opts_do_parse(opts, options, NULL)) {
2865 error_report("Invalid options for file format '%s'", fmt);
2870 ret = bdrv_amend_options(bs, opts);
2872 error_report("Error while amending options: %s", strerror(-ret));
2880 qemu_opts_del(opts);
2881 qemu_opts_free(create_opts);
2890 static const img_cmd_t img_cmds[] = {
2891 #define DEF(option, callback, arg_string) \
2892 { option, callback },
2893 #include "qemu-img-cmds.h"
2899 int main(int argc, char **argv)
2901 const img_cmd_t *cmd;
2902 const char *cmdname;
2904 static const struct option long_options[] = {
2905 {"help", no_argument, 0, 'h'},
2906 {"version", no_argument, 0, 'v'},
2911 signal(SIGPIPE, SIG_IGN);
2914 error_set_progname(argv[0]);
2915 qemu_init_exec_dir(argv[0]);
2917 qemu_init_main_loop();
2920 error_exit("Not enough arguments");
2924 /* find the command */
2925 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
2926 if (!strcmp(cmdname, cmd->name)) {
2927 return cmd->handler(argc - 1, argv + 1);
2931 c = getopt_long(argc, argv, "h", long_options, NULL);
2937 printf(QEMU_IMG_VERSION);
2942 error_exit("Command not found: %s", cmdname);