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"
36 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION \
37 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
39 typedef struct img_cmd_t
{
41 int (*handler
)(int argc
, char **argv
);
46 OPTION_BACKING_CHAIN
= 257,
49 typedef enum OutputFormat
{
54 /* Default to cache=writeback as data integrity is not important for qemu-tcg. */
55 #define BDRV_O_FLAGS BDRV_O_CACHE_WB
56 #define BDRV_DEFAULT_CACHE "writeback"
58 static void format_print(void *opaque
, const char *name
)
63 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
67 error_printf("qemu-img: ");
70 error_vprintf(fmt
, ap
);
73 error_printf("\nTry 'qemu-img --help' for more information\n");
77 /* Please keep in synch with qemu-img.texi */
78 static void QEMU_NORETURN
help(void)
80 const char *help_msg
=
82 "usage: qemu-img command [command options]\n"
83 "QEMU disk image utility\n"
86 #define DEF(option, callback, arg_string) \
88 #include "qemu-img-cmds.h"
92 "Command parameters:\n"
93 " 'filename' is a disk image filename\n"
94 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
95 " 'cache' is the cache mode used to write the output disk image, the valid\n"
96 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
97 " 'directsync' and 'unsafe' (default for convert)\n"
98 " 'src_cache' in contrast is the cache mode used to read input disk images\n"
99 " 'size' is the disk image size in bytes. Optional suffixes\n"
100 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
101 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
102 " supported. 'b' is ignored.\n"
103 " 'output_filename' is the destination disk image filename\n"
104 " 'output_fmt' is the destination format\n"
105 " 'options' is a comma separated list of format specific options in a\n"
106 " name=value format. Use -o ? for an overview of the options supported by the\n"
108 " 'snapshot_param' is param used for internal snapshot, format\n"
109 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
111 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
113 " '-c' indicates that target image must be compressed (qcow format only)\n"
114 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
115 " match exactly. The image doesn't need a working backing file before\n"
116 " rebasing in this case (useful for renaming the backing file)\n"
117 " '-h' with or without a command shows this help and lists the supported formats\n"
118 " '-p' show progress of command (only certain commands)\n"
119 " '-q' use Quiet mode - do not print any output (except errors)\n"
120 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
121 " contain only zeros for qemu-img to create a sparse image during\n"
122 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
123 " unallocated or zero sectors, and the destination image will always be\n"
125 " '--output' takes the format in which the output must be done (human or json)\n"
126 " '-n' skips the target volume creation (useful if the volume is created\n"
127 " prior to running qemu-img)\n"
129 "Parameters to check subcommand:\n"
130 " '-r' tries to repair any inconsistencies that are found during the check.\n"
131 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
132 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
133 " hiding corruption that has already occurred.\n"
135 "Parameters to snapshot subcommand:\n"
136 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
137 " '-a' applies a snapshot (revert disk to saved state)\n"
138 " '-c' creates a snapshot\n"
139 " '-d' deletes a snapshot\n"
140 " '-l' lists all snapshots in the given image\n"
142 "Parameters to compare subcommand:\n"
143 " '-f' first image format\n"
144 " '-F' second image format\n"
145 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
147 printf("%s\nSupported formats:", help_msg
);
148 bdrv_iterate_format(format_print
, NULL
);
153 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
159 ret
= vprintf(fmt
, args
);
166 /* XXX: put correct support for win32 */
167 static int read_password(char *buf
, int buf_size
)
171 printf("Password: ");
179 } else if (c
== '\n') {
181 } else if (i
< (buf_size
- 1)) {
193 static struct termios oldtty
;
195 static void term_exit(void)
197 tcsetattr (0, TCSANOW
, &oldtty
);
200 static void term_init(void)
207 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
208 |INLCR
|IGNCR
|ICRNL
|IXON
);
209 tty
.c_oflag
|= OPOST
;
210 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
211 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
216 tcsetattr (0, TCSANOW
, &tty
);
221 static int read_password(char *buf
, int buf_size
)
226 printf("password: ");
231 ret
= read(0, &ch
, 1);
233 if (errno
== EAGAIN
|| errno
== EINTR
) {
238 } else if (ret
== 0) {
246 if (i
< (buf_size
- 1))
257 static int print_block_option_help(const char *filename
, const char *fmt
)
259 BlockDriver
*drv
, *proto_drv
;
260 QemuOptsList
*create_opts
= NULL
;
262 /* Find driver and parse its options */
263 drv
= bdrv_find_format(fmt
);
265 error_report("Unknown file format '%s'", fmt
);
269 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
271 proto_drv
= bdrv_find_protocol(filename
, true);
273 error_report("Unknown protocol '%s'", filename
);
274 qemu_opts_free(create_opts
);
277 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
280 qemu_opts_print_help(create_opts
);
281 qemu_opts_free(create_opts
);
285 static BlockDriverState
*bdrv_new_open(const char *id
,
286 const char *filename
,
292 BlockDriverState
*bs
;
295 Error
*local_err
= NULL
;
298 bs
= bdrv_new(id
, &error_abort
);
301 drv
= bdrv_find_format(fmt
);
303 error_report("Unknown file format '%s'", fmt
);
310 ret
= bdrv_open(&bs
, filename
, NULL
, NULL
, flags
, drv
, &local_err
);
312 error_report("Could not open '%s': %s", filename
,
313 error_get_pretty(local_err
));
314 error_free(local_err
);
318 if (bdrv_is_encrypted(bs
) && require_io
) {
319 qprintf(quiet
, "Disk image '%s' is encrypted.\n", filename
);
320 if (read_password(password
, sizeof(password
)) < 0) {
321 error_report("No password given");
324 if (bdrv_set_key(bs
, password
) < 0) {
325 error_report("invalid password");
335 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
336 const char *base_filename
,
337 const char *base_fmt
)
340 if (qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
)) {
341 error_report("Backing file not supported for file format '%s'",
347 if (qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
)) {
348 error_report("Backing file format not supported for file "
356 static int img_create(int argc
, char **argv
)
359 uint64_t img_size
= -1;
360 const char *fmt
= "raw";
361 const char *base_fmt
= NULL
;
362 const char *filename
;
363 const char *base_filename
= NULL
;
364 char *options
= NULL
;
365 Error
*local_err
= NULL
;
369 c
= getopt(argc
, argv
, "F:b:f:he6o:q");
382 base_filename
= optarg
;
388 error_report("option -e is deprecated, please use \'-o "
389 "encryption\' instead!");
392 error_report("option -6 is deprecated, please use \'-o "
393 "compat6\' instead!");
396 if (!is_valid_option_list(optarg
)) {
397 error_report("Invalid option list: %s", optarg
);
401 options
= g_strdup(optarg
);
403 char *old_options
= options
;
404 options
= g_strdup_printf("%s,%s", options
, optarg
);
414 /* Get the filename */
415 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
416 if (options
&& has_help_option(options
)) {
418 return print_block_option_help(filename
, fmt
);
421 if (optind
>= argc
) {
422 error_exit("Expecting image file name");
426 /* Get image size, if specified */
430 sval
= strtosz_suffix(argv
[optind
++], &end
, STRTOSZ_DEFSUFFIX_B
);
431 if (sval
< 0 || *end
) {
432 if (sval
== -ERANGE
) {
433 error_report("Image size must be less than 8 EiB!");
435 error_report("Invalid image size specified! You may use k, M, "
436 "G, T, P or E suffixes for ");
437 error_report("kilobytes, megabytes, gigabytes, terabytes, "
438 "petabytes and exabytes.");
442 img_size
= (uint64_t)sval
;
444 if (optind
!= argc
) {
445 error_exit("Unexpected argument: %s", argv
[optind
]);
448 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
449 options
, img_size
, BDRV_O_FLAGS
, &local_err
, quiet
);
451 error_report("%s: %s", filename
, error_get_pretty(local_err
));
452 error_free(local_err
);
464 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
466 Error
*local_err
= NULL
;
468 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
470 visit_type_ImageCheck(qmp_output_get_visitor(ov
),
471 &check
, NULL
, &local_err
);
472 obj
= qmp_output_get_qobject(ov
);
473 str
= qobject_to_json_pretty(obj
);
475 qprintf(quiet
, "%s\n", qstring_get_str(str
));
477 qmp_output_visitor_cleanup(ov
);
481 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
483 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
484 qprintf(quiet
, "No errors were found on the image.\n");
486 if (check
->corruptions
) {
487 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
488 "Data may be corrupted, or further writes to the image "
495 "\n%" PRId64
" leaked clusters were found on the image.\n"
496 "This means waste of disk space, but no harm to data.\n",
500 if (check
->check_errors
) {
503 " internal errors have occurred during the check.\n",
504 check
->check_errors
);
508 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
509 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
510 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
511 check
->allocated_clusters
, check
->total_clusters
,
512 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
513 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
514 check
->compressed_clusters
* 100.0 /
515 check
->allocated_clusters
);
518 if (check
->image_end_offset
) {
520 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
524 static int collect_image_check(BlockDriverState
*bs
,
526 const char *filename
,
531 BdrvCheckResult result
;
533 ret
= bdrv_check(bs
, &result
, fix
);
538 check
->filename
= g_strdup(filename
);
539 check
->format
= g_strdup(bdrv_get_format_name(bs
));
540 check
->check_errors
= result
.check_errors
;
541 check
->corruptions
= result
.corruptions
;
542 check
->has_corruptions
= result
.corruptions
!= 0;
543 check
->leaks
= result
.leaks
;
544 check
->has_leaks
= result
.leaks
!= 0;
545 check
->corruptions_fixed
= result
.corruptions_fixed
;
546 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
547 check
->leaks_fixed
= result
.leaks_fixed
;
548 check
->has_leaks_fixed
= result
.leaks
!= 0;
549 check
->image_end_offset
= result
.image_end_offset
;
550 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
551 check
->total_clusters
= result
.bfi
.total_clusters
;
552 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
553 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
554 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
555 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
556 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
557 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
558 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
564 * Checks an image for consistency. Exit codes:
566 * 0 - Check completed, image is good
567 * 1 - Check not completed because of internal errors
568 * 2 - Check completed, image is corrupted
569 * 3 - Check completed, image has leaked clusters, but is good otherwise
570 * 63 - Checks are not supported by the image format
572 static int img_check(int argc
, char **argv
)
575 OutputFormat output_format
= OFORMAT_HUMAN
;
576 const char *filename
, *fmt
, *output
, *cache
;
577 BlockDriverState
*bs
;
579 int flags
= BDRV_O_FLAGS
| BDRV_O_CHECK
;
585 cache
= BDRV_DEFAULT_CACHE
;
587 int option_index
= 0;
588 static const struct option long_options
[] = {
589 {"help", no_argument
, 0, 'h'},
590 {"format", required_argument
, 0, 'f'},
591 {"repair", required_argument
, 0, 'r'},
592 {"output", required_argument
, 0, OPTION_OUTPUT
},
595 c
= getopt_long(argc
, argv
, "hf:r:T:q",
596 long_options
, &option_index
);
609 flags
|= BDRV_O_RDWR
;
611 if (!strcmp(optarg
, "leaks")) {
612 fix
= BDRV_FIX_LEAKS
;
613 } else if (!strcmp(optarg
, "all")) {
614 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
616 error_exit("Unknown option value for -r "
617 "(expecting 'leaks' or 'all'): %s", optarg
);
631 if (optind
!= argc
- 1) {
632 error_exit("Expecting one image file name");
634 filename
= argv
[optind
++];
636 if (output
&& !strcmp(output
, "json")) {
637 output_format
= OFORMAT_JSON
;
638 } else if (output
&& !strcmp(output
, "human")) {
639 output_format
= OFORMAT_HUMAN
;
641 error_report("--output must be used with human or json as argument.");
645 ret
= bdrv_parse_cache_flags(cache
, &flags
);
647 error_report("Invalid source cache option: %s", cache
);
651 bs
= bdrv_new_open("image", filename
, fmt
, flags
, true, quiet
);
656 check
= g_new0(ImageCheck
, 1);
657 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
659 if (ret
== -ENOTSUP
) {
660 error_report("This image format does not support checks");
665 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
666 int corruptions_fixed
, leaks_fixed
;
668 leaks_fixed
= check
->leaks_fixed
;
669 corruptions_fixed
= check
->corruptions_fixed
;
671 if (output_format
== OFORMAT_HUMAN
) {
673 "The following inconsistencies were found and repaired:\n\n"
674 " %" PRId64
" leaked clusters\n"
675 " %" PRId64
" corruptions\n\n"
676 "Double checking the fixed image now...\n",
678 check
->corruptions_fixed
);
681 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
683 check
->leaks_fixed
= leaks_fixed
;
684 check
->corruptions_fixed
= corruptions_fixed
;
687 switch (output_format
) {
689 dump_human_image_check(check
, quiet
);
692 dump_json_image_check(check
, quiet
);
696 if (ret
|| check
->check_errors
) {
701 if (check
->corruptions
) {
703 } else if (check
->leaks
) {
710 qapi_free_ImageCheck(check
);
716 static int img_commit(int argc
, char **argv
)
719 const char *filename
, *fmt
, *cache
;
720 BlockDriverState
*bs
;
724 cache
= BDRV_DEFAULT_CACHE
;
726 c
= getopt(argc
, argv
, "f:ht:q");
746 if (optind
!= argc
- 1) {
747 error_exit("Expecting one image file name");
749 filename
= argv
[optind
++];
752 ret
= bdrv_parse_cache_flags(cache
, &flags
);
754 error_report("Invalid cache option: %s", cache
);
758 bs
= bdrv_new_open("image", filename
, fmt
, flags
, true, quiet
);
762 ret
= bdrv_commit(bs
);
765 qprintf(quiet
, "Image committed.\n");
768 error_report("No disk inserted");
771 error_report("Image is read-only");
774 error_report("Image is already committed");
777 error_report("Error while committing image");
789 * Returns true iff the first sector pointed to by 'buf' contains at least
792 * 'pnum' is set to the number of sectors (including and immediately following
793 * the first one) that are known to be in the same allocated/unallocated state.
795 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
)
804 is_zero
= buffer_is_zero(buf
, 512);
805 for(i
= 1; i
< n
; i
++) {
807 if (is_zero
!= buffer_is_zero(buf
, 512)) {
816 * Like is_allocated_sectors, but if the buffer starts with a used sector,
817 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
818 * breaking up write requests for only small sparse areas.
820 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
824 int num_checked
, num_used
;
830 ret
= is_allocated_sectors(buf
, n
, pnum
);
836 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
838 num_checked
= num_used
;
841 ret
= is_allocated_sectors(buf
, n
, pnum
);
843 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
845 num_checked
+= *pnum
;
847 num_used
= num_checked
;
848 } else if (*pnum
>= min
) {
858 * Compares two buffers sector by sector. Returns 0 if the first sector of both
859 * buffers matches, non-zero otherwise.
861 * pnum is set to the number of sectors (including and immediately following
862 * the first one) that are known to have the same comparison result
864 static int compare_sectors(const uint8_t *buf1
, const uint8_t *buf2
, int n
,
874 res
= !!memcmp(buf1
, buf2
, 512);
875 for(i
= 1; i
< n
; i
++) {
879 if (!!memcmp(buf1
, buf2
, 512) != res
) {
888 #define IO_BUF_SIZE (2 * 1024 * 1024)
890 static int64_t sectors_to_bytes(int64_t sectors
)
892 return sectors
<< BDRV_SECTOR_BITS
;
895 static int64_t sectors_to_process(int64_t total
, int64_t from
)
897 return MIN(total
- from
, IO_BUF_SIZE
>> BDRV_SECTOR_BITS
);
901 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
903 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
904 * data and negative value on error.
906 * @param bs: Driver used for accessing file
907 * @param sect_num: Number of first sector to check
908 * @param sect_count: Number of sectors to check
909 * @param filename: Name of disk file we are checking (logging purpose)
910 * @param buffer: Allocated buffer for storing read data
911 * @param quiet: Flag for quiet mode
913 static int check_empty_sectors(BlockDriverState
*bs
, int64_t sect_num
,
914 int sect_count
, const char *filename
,
915 uint8_t *buffer
, bool quiet
)
918 ret
= bdrv_read(bs
, sect_num
, buffer
, sect_count
);
920 error_report("Error while reading offset %" PRId64
" of %s: %s",
921 sectors_to_bytes(sect_num
), filename
, strerror(-ret
));
924 ret
= is_allocated_sectors(buffer
, sect_count
, &pnum
);
925 if (ret
|| pnum
!= sect_count
) {
926 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
927 sectors_to_bytes(ret
? sect_num
: sect_num
+ pnum
));
935 * Compares two images. Exit codes:
937 * 0 - Images are identical
939 * >1 - Error occurred
941 static int img_compare(int argc
, char **argv
)
943 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
944 BlockDriverState
*bs1
, *bs2
;
945 int64_t total_sectors1
, total_sectors2
;
946 uint8_t *buf1
= NULL
, *buf2
= NULL
;
948 int allocated1
, allocated2
;
949 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
950 bool progress
= false, quiet
= false, strict
= false;
952 int64_t total_sectors
;
953 int64_t sector_num
= 0;
956 uint64_t progress_base
;
958 cache
= BDRV_DEFAULT_CACHE
;
960 c
= getopt(argc
, argv
, "hf:F:T:pqs");
990 /* Progress is not shown in Quiet mode */
996 if (optind
!= argc
- 2) {
997 error_exit("Expecting two image file names");
999 filename1
= argv
[optind
++];
1000 filename2
= argv
[optind
++];
1002 flags
= BDRV_O_FLAGS
;
1003 ret
= bdrv_parse_cache_flags(cache
, &flags
);
1005 error_report("Invalid source cache option: %s", cache
);
1010 /* Initialize before goto out */
1011 qemu_progress_init(progress
, 2.0);
1013 bs1
= bdrv_new_open("image 1", filename1
, fmt1
, flags
, true, quiet
);
1015 error_report("Can't open file %s", filename1
);
1020 bs2
= bdrv_new_open("image 2", filename2
, fmt2
, flags
, true, quiet
);
1022 error_report("Can't open file %s", filename2
);
1027 buf1
= qemu_blockalign(bs1
, IO_BUF_SIZE
);
1028 buf2
= qemu_blockalign(bs2
, IO_BUF_SIZE
);
1029 total_sectors1
= bdrv_nb_sectors(bs1
);
1030 if (total_sectors1
< 0) {
1031 error_report("Can't get size of %s: %s",
1032 filename1
, strerror(-total_sectors1
));
1036 total_sectors2
= bdrv_nb_sectors(bs2
);
1037 if (total_sectors2
< 0) {
1038 error_report("Can't get size of %s: %s",
1039 filename2
, strerror(-total_sectors2
));
1043 total_sectors
= MIN(total_sectors1
, total_sectors2
);
1044 progress_base
= MAX(total_sectors1
, total_sectors2
);
1046 qemu_progress_print(0, 100);
1048 if (strict
&& total_sectors1
!= total_sectors2
) {
1050 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1055 nb_sectors
= sectors_to_process(total_sectors
, sector_num
);
1056 if (nb_sectors
<= 0) {
1059 allocated1
= bdrv_is_allocated_above(bs1
, NULL
, sector_num
, nb_sectors
,
1061 if (allocated1
< 0) {
1063 error_report("Sector allocation test failed for %s", filename1
);
1067 allocated2
= bdrv_is_allocated_above(bs2
, NULL
, sector_num
, nb_sectors
,
1069 if (allocated2
< 0) {
1071 error_report("Sector allocation test failed for %s", filename2
);
1074 nb_sectors
= MIN(pnum1
, pnum2
);
1076 if (allocated1
== allocated2
) {
1078 ret
= bdrv_read(bs1
, sector_num
, buf1
, nb_sectors
);
1080 error_report("Error while reading offset %" PRId64
" of %s:"
1081 " %s", sectors_to_bytes(sector_num
), filename1
,
1086 ret
= bdrv_read(bs2
, sector_num
, buf2
, nb_sectors
);
1088 error_report("Error while reading offset %" PRId64
1089 " of %s: %s", sectors_to_bytes(sector_num
),
1090 filename2
, strerror(-ret
));
1094 ret
= compare_sectors(buf1
, buf2
, nb_sectors
, &pnum
);
1095 if (ret
|| pnum
!= nb_sectors
) {
1096 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1098 ret
? sector_num
: sector_num
+ pnum
));
1106 qprintf(quiet
, "Strict mode: Offset %" PRId64
1107 " allocation mismatch!\n",
1108 sectors_to_bytes(sector_num
));
1113 ret
= check_empty_sectors(bs1
, sector_num
, nb_sectors
,
1114 filename1
, buf1
, quiet
);
1116 ret
= check_empty_sectors(bs2
, sector_num
, nb_sectors
,
1117 filename2
, buf1
, quiet
);
1121 error_report("Error while reading offset %" PRId64
": %s",
1122 sectors_to_bytes(sector_num
), strerror(-ret
));
1128 sector_num
+= nb_sectors
;
1129 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1132 if (total_sectors1
!= total_sectors2
) {
1133 BlockDriverState
*bs_over
;
1134 int64_t total_sectors_over
;
1135 const char *filename_over
;
1137 qprintf(quiet
, "Warning: Image size mismatch!\n");
1138 if (total_sectors1
> total_sectors2
) {
1139 total_sectors_over
= total_sectors1
;
1141 filename_over
= filename1
;
1143 total_sectors_over
= total_sectors2
;
1145 filename_over
= filename2
;
1149 nb_sectors
= sectors_to_process(total_sectors_over
, sector_num
);
1150 if (nb_sectors
<= 0) {
1153 ret
= bdrv_is_allocated_above(bs_over
, NULL
, sector_num
,
1157 error_report("Sector allocation test failed for %s",
1164 ret
= check_empty_sectors(bs_over
, sector_num
, nb_sectors
,
1165 filename_over
, buf1
, quiet
);
1168 error_report("Error while reading offset %" PRId64
1169 " of %s: %s", sectors_to_bytes(sector_num
),
1170 filename_over
, strerror(-ret
));
1176 sector_num
+= nb_sectors
;
1177 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1181 qprintf(quiet
, "Images are identical.\n");
1191 qemu_progress_end();
1195 static int img_convert(int argc
, char **argv
)
1197 int c
, n
, n1
, bs_n
, bs_i
, compress
, cluster_sectors
, skip_create
;
1199 int progress
= 0, flags
, src_flags
;
1200 const char *fmt
, *out_fmt
, *cache
, *src_cache
, *out_baseimg
, *out_filename
;
1201 BlockDriver
*drv
, *proto_drv
;
1202 BlockDriverState
**bs
= NULL
, *out_bs
= NULL
;
1203 int64_t total_sectors
, nb_sectors
, sector_num
, bs_offset
;
1204 int64_t *bs_sectors
= NULL
;
1205 uint8_t * buf
= NULL
;
1206 size_t bufsectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
;
1207 const uint8_t *buf1
;
1208 BlockDriverInfo bdi
;
1209 QemuOpts
*opts
= NULL
;
1210 QemuOptsList
*create_opts
= NULL
;
1211 const char *out_baseimg_param
;
1212 char *options
= NULL
;
1213 const char *snapshot_name
= NULL
;
1214 int min_sparse
= 8; /* Need at least 4k of zeros for sparse detection */
1216 Error
*local_err
= NULL
;
1217 QemuOpts
*sn_opts
= NULL
;
1222 src_cache
= BDRV_DEFAULT_CACHE
;
1227 c
= getopt(argc
, argv
, "hf:O:B:ce6o:s:l:S:pt:T:qn");
1243 out_baseimg
= optarg
;
1249 error_report("option -e is deprecated, please use \'-o "
1250 "encryption\' instead!");
1254 error_report("option -6 is deprecated, please use \'-o "
1255 "compat6\' instead!");
1259 if (!is_valid_option_list(optarg
)) {
1260 error_report("Invalid option list: %s", optarg
);
1265 options
= g_strdup(optarg
);
1267 char *old_options
= options
;
1268 options
= g_strdup_printf("%s,%s", options
, optarg
);
1269 g_free(old_options
);
1273 snapshot_name
= optarg
;
1276 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
1277 sn_opts
= qemu_opts_parse(&internal_snapshot_opts
, optarg
, 0);
1279 error_report("Failed in parsing snapshot param '%s'",
1285 snapshot_name
= optarg
;
1292 sval
= strtosz_suffix(optarg
, &end
, STRTOSZ_DEFSUFFIX_B
);
1293 if (sval
< 0 || *end
) {
1294 error_report("Invalid minimum zero buffer size for sparse output specified");
1299 min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
1320 /* Initialize before goto out */
1324 qemu_progress_init(progress
, 1.0);
1327 bs_n
= argc
- optind
- 1;
1328 out_filename
= bs_n
>= 1 ? argv
[argc
- 1] : NULL
;
1330 if (options
&& has_help_option(options
)) {
1331 ret
= print_block_option_help(out_filename
, out_fmt
);
1336 error_exit("Must specify image file name");
1340 if (bs_n
> 1 && out_baseimg
) {
1341 error_report("-B makes no sense when concatenating multiple input "
1347 src_flags
= BDRV_O_FLAGS
;
1348 ret
= bdrv_parse_cache_flags(src_cache
, &src_flags
);
1350 error_report("Invalid source cache option: %s", src_cache
);
1354 qemu_progress_print(0, 100);
1356 bs
= g_new0(BlockDriverState
*, bs_n
);
1357 bs_sectors
= g_new(int64_t, bs_n
);
1360 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
1361 char *id
= bs_n
> 1 ? g_strdup_printf("source %d", bs_i
)
1362 : g_strdup("source");
1363 bs
[bs_i
] = bdrv_new_open(id
, argv
[optind
+ bs_i
], fmt
, src_flags
,
1367 error_report("Could not open '%s'", argv
[optind
+ bs_i
]);
1371 bs_sectors
[bs_i
] = bdrv_nb_sectors(bs
[bs_i
]);
1372 if (bs_sectors
[bs_i
] < 0) {
1373 error_report("Could not get size of %s: %s",
1374 argv
[optind
+ bs_i
], strerror(-bs_sectors
[bs_i
]));
1378 total_sectors
+= bs_sectors
[bs_i
];
1382 ret
= bdrv_snapshot_load_tmp(bs
[0],
1383 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
1384 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
1386 } else if (snapshot_name
!= NULL
) {
1388 error_report("No support for concatenating multiple snapshot");
1393 bdrv_snapshot_load_tmp_by_id_or_name(bs
[0], snapshot_name
, &local_err
);
1396 error_report("Failed to load snapshot: %s",
1397 error_get_pretty(local_err
));
1398 error_free(local_err
);
1403 /* Find driver and parse its options */
1404 drv
= bdrv_find_format(out_fmt
);
1406 error_report("Unknown file format '%s'", out_fmt
);
1411 proto_drv
= bdrv_find_protocol(out_filename
, true);
1413 error_report("Unknown protocol '%s'", out_filename
);
1418 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
1419 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
1421 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
1422 if (options
&& qemu_opts_do_parse(opts
, options
, NULL
)) {
1423 error_report("Invalid options for file format '%s'", out_fmt
);
1428 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, total_sectors
* 512);
1429 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
1434 /* Get backing file name if -o backing_file was used */
1435 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
1436 if (out_baseimg_param
) {
1437 out_baseimg
= out_baseimg_param
;
1440 /* Check if compression is supported */
1443 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
1444 const char *preallocation
=
1445 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
1447 if (!drv
->bdrv_write_compressed
) {
1448 error_report("Compression not supported for this file format");
1454 error_report("Compression and encryption not supported at "
1461 && strcmp(preallocation
, "off"))
1463 error_report("Compression and preallocation not supported at "
1471 /* Create the new image */
1472 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
1474 error_report("%s: error while converting %s: %s",
1475 out_filename
, out_fmt
, error_get_pretty(local_err
));
1476 error_free(local_err
);
1481 flags
= min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
1482 ret
= bdrv_parse_cache_flags(cache
, &flags
);
1484 error_report("Invalid cache option: %s", cache
);
1488 out_bs
= bdrv_new_open("target", out_filename
, out_fmt
, flags
, true, quiet
);
1497 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
1498 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
1500 bufsectors
= MIN(32768,
1501 MAX(bufsectors
, MAX(out_bs
->bl
.opt_transfer_length
,
1502 out_bs
->bl
.discard_alignment
))
1505 buf
= qemu_blockalign(out_bs
, bufsectors
* BDRV_SECTOR_SIZE
);
1508 int64_t output_sectors
= bdrv_nb_sectors(out_bs
);
1509 if (output_sectors
< 0) {
1510 error_report("unable to get output image length: %s\n",
1511 strerror(-output_sectors
));
1514 } else if (output_sectors
< total_sectors
) {
1515 error_report("output file is smaller than input file");
1521 cluster_sectors
= 0;
1522 ret
= bdrv_get_info(out_bs
, &bdi
);
1525 error_report("could not get block driver info");
1529 compress
= compress
|| bdi
.needs_compressed_writes
;
1530 cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
1534 if (cluster_sectors
<= 0 || cluster_sectors
> bufsectors
) {
1535 error_report("invalid cluster size");
1541 nb_sectors
= total_sectors
;
1548 nb_sectors
= total_sectors
- sector_num
;
1549 if (nb_sectors
<= 0)
1551 if (nb_sectors
>= cluster_sectors
)
1552 n
= cluster_sectors
;
1556 bs_num
= sector_num
- bs_offset
;
1557 assert (bs_num
>= 0);
1560 while (remainder
> 0) {
1562 while (bs_num
== bs_sectors
[bs_i
]) {
1563 bs_offset
+= bs_sectors
[bs_i
];
1565 assert (bs_i
< bs_n
);
1567 /* printf("changing part: sector_num=%" PRId64 ", "
1568 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
1569 "\n", sector_num, bs_i, bs_offset, bs_sectors[bs_i]); */
1571 assert (bs_num
< bs_sectors
[bs_i
]);
1573 nlow
= remainder
> bs_sectors
[bs_i
] - bs_num
1574 ? bs_sectors
[bs_i
] - bs_num
: remainder
;
1576 ret
= bdrv_read(bs
[bs_i
], bs_num
, buf2
, nlow
);
1578 error_report("error while reading sector %" PRId64
": %s",
1579 bs_num
, strerror(-ret
));
1588 assert (remainder
== 0);
1590 if (!buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)) {
1591 ret
= bdrv_write_compressed(out_bs
, sector_num
, buf
, n
);
1593 error_report("error while compressing sector %" PRId64
1594 ": %s", sector_num
, strerror(-ret
));
1599 qemu_progress_print(100.0 * sector_num
/ total_sectors
, 0);
1601 /* signal EOF to align */
1602 bdrv_write_compressed(out_bs
, 0, NULL
, 0);
1604 int64_t sectors_to_read
, sectors_read
, sector_num_next_status
;
1605 bool count_allocated_sectors
;
1606 int has_zero_init
= min_sparse
? bdrv_has_zero_init(out_bs
) : 0;
1608 if (!has_zero_init
&& bdrv_can_write_zeroes_with_unmap(out_bs
)) {
1609 ret
= bdrv_make_zero(out_bs
, BDRV_REQ_MAY_UNMAP
);
1616 sectors_to_read
= total_sectors
;
1617 count_allocated_sectors
= progress
&& (out_baseimg
|| has_zero_init
);
1619 sector_num
= 0; // total number of sectors converted so far
1621 sector_num_next_status
= 0;
1624 nb_sectors
= total_sectors
- sector_num
;
1625 if (nb_sectors
<= 0) {
1626 if (count_allocated_sectors
) {
1627 sectors_to_read
= sectors_read
;
1628 count_allocated_sectors
= false;
1635 while (sector_num
- bs_offset
>= bs_sectors
[bs_i
]) {
1636 bs_offset
+= bs_sectors
[bs_i
];
1638 assert (bs_i
< bs_n
);
1639 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1640 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
1641 sector_num, bs_i, bs_offset, bs_sectors[bs_i]); */
1644 if ((out_baseimg
|| has_zero_init
) &&
1645 sector_num
>= sector_num_next_status
) {
1646 n
= nb_sectors
> INT_MAX
? INT_MAX
: nb_sectors
;
1647 ret
= bdrv_get_block_status(bs
[bs_i
], sector_num
- bs_offset
,
1650 error_report("error while reading block status of sector %"
1651 PRId64
": %s", sector_num
- bs_offset
,
1655 /* If the output image is zero initialized, we are not working
1656 * on a shared base and the input is zero we can skip the next
1658 if (has_zero_init
&& !out_baseimg
&& (ret
& BDRV_BLOCK_ZERO
)) {
1662 /* If the output image is being created as a copy on write
1663 * image, assume that sectors which are unallocated in the
1664 * input image are present in both the output's and input's
1665 * base images (no need to copy them). */
1667 if (!(ret
& BDRV_BLOCK_DATA
)) {
1671 /* The next 'n1' sectors are allocated in the input image.
1672 * Copy only those as they may be followed by unallocated
1676 /* avoid redundant callouts to get_block_status */
1677 sector_num_next_status
= sector_num
+ n1
;
1680 n
= MIN(nb_sectors
, bufsectors
);
1682 /* round down request length to an aligned sector, but
1683 * do not bother doing this on short requests. They happen
1684 * when we found an all-zero area, and the next sector to
1685 * write will not be sector_num + n. */
1686 if (cluster_sectors
> 0 && n
>= cluster_sectors
) {
1687 int64_t next_aligned_sector
= (sector_num
+ n
);
1688 next_aligned_sector
-= next_aligned_sector
% cluster_sectors
;
1689 if (sector_num
+ n
> next_aligned_sector
) {
1690 n
= next_aligned_sector
- sector_num
;
1694 n
= MIN(n
, bs_sectors
[bs_i
] - (sector_num
- bs_offset
));
1697 if (count_allocated_sectors
) {
1703 ret
= bdrv_read(bs
[bs_i
], sector_num
- bs_offset
, buf
, n
);
1705 error_report("error while reading sector %" PRId64
": %s",
1706 sector_num
- bs_offset
, strerror(-ret
));
1709 /* NOTE: at the same time we convert, we do not write zero
1710 sectors to have a chance to compress the image. Ideally, we
1711 should add a specific call to have the info to go faster */
1714 if (!has_zero_init
||
1715 is_allocated_sectors_min(buf1
, n
, &n1
, min_sparse
)) {
1716 ret
= bdrv_write(out_bs
, sector_num
, buf1
, n1
);
1718 error_report("error while writing sector %" PRId64
1719 ": %s", sector_num
, strerror(-ret
));
1727 qemu_progress_print(100.0 * sectors_read
/ sectors_to_read
, 0);
1732 qemu_progress_print(100, 0);
1734 qemu_progress_end();
1735 qemu_opts_del(opts
);
1736 qemu_opts_free(create_opts
);
1739 qemu_opts_del(sn_opts
);
1745 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
1747 bdrv_unref(bs
[bs_i
]);
1763 static void dump_snapshots(BlockDriverState
*bs
)
1765 QEMUSnapshotInfo
*sn_tab
, *sn
;
1768 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
1771 printf("Snapshot list:\n");
1772 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
1774 for(i
= 0; i
< nb_sns
; i
++) {
1776 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
1782 static void dump_json_image_info_list(ImageInfoList
*list
)
1784 Error
*local_err
= NULL
;
1786 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
1788 visit_type_ImageInfoList(qmp_output_get_visitor(ov
),
1789 &list
, NULL
, &local_err
);
1790 obj
= qmp_output_get_qobject(ov
);
1791 str
= qobject_to_json_pretty(obj
);
1792 assert(str
!= NULL
);
1793 printf("%s\n", qstring_get_str(str
));
1794 qobject_decref(obj
);
1795 qmp_output_visitor_cleanup(ov
);
1799 static void dump_json_image_info(ImageInfo
*info
)
1801 Error
*local_err
= NULL
;
1803 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
1805 visit_type_ImageInfo(qmp_output_get_visitor(ov
),
1806 &info
, NULL
, &local_err
);
1807 obj
= qmp_output_get_qobject(ov
);
1808 str
= qobject_to_json_pretty(obj
);
1809 assert(str
!= NULL
);
1810 printf("%s\n", qstring_get_str(str
));
1811 qobject_decref(obj
);
1812 qmp_output_visitor_cleanup(ov
);
1816 static void dump_human_image_info_list(ImageInfoList
*list
)
1818 ImageInfoList
*elem
;
1821 for (elem
= list
; elem
; elem
= elem
->next
) {
1827 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
1831 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
1833 return strcmp(a
, b
) == 0;
1837 * Open an image file chain and return an ImageInfoList
1839 * @filename: topmost image filename
1840 * @fmt: topmost image format (may be NULL to autodetect)
1841 * @chain: true - enumerate entire backing file chain
1842 * false - only topmost image file
1844 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1845 * image file. If there was an error a message will have been printed to
1848 static ImageInfoList
*collect_image_info_list(const char *filename
,
1852 ImageInfoList
*head
= NULL
;
1853 ImageInfoList
**last
= &head
;
1854 GHashTable
*filenames
;
1857 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
1860 BlockDriverState
*bs
;
1862 ImageInfoList
*elem
;
1864 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
1865 error_report("Backing file '%s' creates an infinite loop.",
1869 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
1871 bs
= bdrv_new_open("image", filename
, fmt
,
1872 BDRV_O_FLAGS
| BDRV_O_NO_BACKING
, false, false);
1877 bdrv_query_image_info(bs
, &info
, &err
);
1879 error_report("%s", error_get_pretty(err
));
1885 elem
= g_new0(ImageInfoList
, 1);
1892 filename
= fmt
= NULL
;
1894 if (info
->has_full_backing_filename
) {
1895 filename
= info
->full_backing_filename
;
1896 } else if (info
->has_backing_filename
) {
1897 filename
= info
->backing_filename
;
1899 if (info
->has_backing_filename_format
) {
1900 fmt
= info
->backing_filename_format
;
1904 g_hash_table_destroy(filenames
);
1908 qapi_free_ImageInfoList(head
);
1909 g_hash_table_destroy(filenames
);
1913 static int img_info(int argc
, char **argv
)
1916 OutputFormat output_format
= OFORMAT_HUMAN
;
1918 const char *filename
, *fmt
, *output
;
1919 ImageInfoList
*list
;
1924 int option_index
= 0;
1925 static const struct option long_options
[] = {
1926 {"help", no_argument
, 0, 'h'},
1927 {"format", required_argument
, 0, 'f'},
1928 {"output", required_argument
, 0, OPTION_OUTPUT
},
1929 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
1932 c
= getopt_long(argc
, argv
, "f:h",
1933 long_options
, &option_index
);
1948 case OPTION_BACKING_CHAIN
:
1953 if (optind
!= argc
- 1) {
1954 error_exit("Expecting one image file name");
1956 filename
= argv
[optind
++];
1958 if (output
&& !strcmp(output
, "json")) {
1959 output_format
= OFORMAT_JSON
;
1960 } else if (output
&& !strcmp(output
, "human")) {
1961 output_format
= OFORMAT_HUMAN
;
1962 } else if (output
) {
1963 error_report("--output must be used with human or json as argument.");
1967 list
= collect_image_info_list(filename
, fmt
, chain
);
1972 switch (output_format
) {
1974 dump_human_image_info_list(list
);
1978 dump_json_image_info_list(list
);
1980 dump_json_image_info(list
->value
);
1985 qapi_free_ImageInfoList(list
);
1990 typedef struct MapEntry
{
1996 BlockDriverState
*bs
;
1999 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2002 switch (output_format
) {
2004 if ((e
->flags
& BDRV_BLOCK_DATA
) &&
2005 !(e
->flags
& BDRV_BLOCK_OFFSET_VALID
)) {
2006 error_report("File contains external, encrypted or compressed clusters.");
2009 if ((e
->flags
& (BDRV_BLOCK_DATA
|BDRV_BLOCK_ZERO
)) == BDRV_BLOCK_DATA
) {
2010 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2011 e
->start
, e
->length
, e
->offset
, e
->bs
->filename
);
2013 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2014 * Modify the flags here to allow more coalescing.
2017 (next
->flags
& (BDRV_BLOCK_DATA
|BDRV_BLOCK_ZERO
)) != BDRV_BLOCK_DATA
) {
2018 next
->flags
&= ~BDRV_BLOCK_DATA
;
2019 next
->flags
|= BDRV_BLOCK_ZERO
;
2023 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
", \"depth\": %d,"
2024 " \"zero\": %s, \"data\": %s",
2025 (e
->start
== 0 ? "[" : ",\n"),
2026 e
->start
, e
->length
, e
->depth
,
2027 (e
->flags
& BDRV_BLOCK_ZERO
) ? "true" : "false",
2028 (e
->flags
& BDRV_BLOCK_DATA
) ? "true" : "false");
2029 if (e
->flags
& BDRV_BLOCK_OFFSET_VALID
) {
2030 printf(", \"offset\": %"PRId64
"", e
->offset
);
2041 static int get_block_status(BlockDriverState
*bs
, int64_t sector_num
,
2042 int nb_sectors
, MapEntry
*e
)
2047 /* As an optimization, we could cache the current range of unallocated
2048 * clusters in each file of the chain, and avoid querying the same
2054 ret
= bdrv_get_block_status(bs
, sector_num
, nb_sectors
, &nb_sectors
);
2059 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2062 bs
= bs
->backing_hd
;
2071 e
->start
= sector_num
* BDRV_SECTOR_SIZE
;
2072 e
->length
= nb_sectors
* BDRV_SECTOR_SIZE
;
2073 e
->flags
= ret
& ~BDRV_BLOCK_OFFSET_MASK
;
2074 e
->offset
= ret
& BDRV_BLOCK_OFFSET_MASK
;
2080 static int img_map(int argc
, char **argv
)
2083 OutputFormat output_format
= OFORMAT_HUMAN
;
2084 BlockDriverState
*bs
;
2085 const char *filename
, *fmt
, *output
;
2087 MapEntry curr
= { .length
= 0 }, next
;
2093 int option_index
= 0;
2094 static const struct option long_options
[] = {
2095 {"help", no_argument
, 0, 'h'},
2096 {"format", required_argument
, 0, 'f'},
2097 {"output", required_argument
, 0, OPTION_OUTPUT
},
2100 c
= getopt_long(argc
, argv
, "f:h",
2101 long_options
, &option_index
);
2118 if (optind
!= argc
- 1) {
2119 error_exit("Expecting one image file name");
2121 filename
= argv
[optind
];
2123 if (output
&& !strcmp(output
, "json")) {
2124 output_format
= OFORMAT_JSON
;
2125 } else if (output
&& !strcmp(output
, "human")) {
2126 output_format
= OFORMAT_HUMAN
;
2127 } else if (output
) {
2128 error_report("--output must be used with human or json as argument.");
2132 bs
= bdrv_new_open("image", filename
, fmt
, BDRV_O_FLAGS
, true, false);
2137 if (output_format
== OFORMAT_HUMAN
) {
2138 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2141 length
= bdrv_getlength(bs
);
2142 while (curr
.start
+ curr
.length
< length
) {
2143 int64_t nsectors_left
;
2147 sector_num
= (curr
.start
+ curr
.length
) >> BDRV_SECTOR_BITS
;
2149 /* Probe up to 1 GiB at a time. */
2150 nsectors_left
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
) - sector_num
;
2151 n
= MIN(1 << (30 - BDRV_SECTOR_BITS
), nsectors_left
);
2152 ret
= get_block_status(bs
, sector_num
, n
, &next
);
2155 error_report("Could not read file metadata: %s", strerror(-ret
));
2159 if (curr
.length
!= 0 && curr
.flags
== next
.flags
&&
2160 curr
.depth
== next
.depth
&&
2161 ((curr
.flags
& BDRV_BLOCK_OFFSET_VALID
) == 0 ||
2162 curr
.offset
+ curr
.length
== next
.offset
)) {
2163 curr
.length
+= next
.length
;
2167 if (curr
.length
> 0) {
2168 dump_map_entry(output_format
, &curr
, &next
);
2173 dump_map_entry(output_format
, &curr
, NULL
);
2180 #define SNAPSHOT_LIST 1
2181 #define SNAPSHOT_CREATE 2
2182 #define SNAPSHOT_APPLY 3
2183 #define SNAPSHOT_DELETE 4
2185 static int img_snapshot(int argc
, char **argv
)
2187 BlockDriverState
*bs
;
2188 QEMUSnapshotInfo sn
;
2189 char *filename
, *snapshot_name
= NULL
;
2190 int c
, ret
= 0, bdrv_oflags
;
2196 bdrv_oflags
= BDRV_O_FLAGS
| BDRV_O_RDWR
;
2197 /* Parse commandline parameters */
2199 c
= getopt(argc
, argv
, "la:c:d:hq");
2210 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2213 action
= SNAPSHOT_LIST
;
2214 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
2218 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2221 action
= SNAPSHOT_APPLY
;
2222 snapshot_name
= optarg
;
2226 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2229 action
= SNAPSHOT_CREATE
;
2230 snapshot_name
= optarg
;
2234 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2237 action
= SNAPSHOT_DELETE
;
2238 snapshot_name
= optarg
;
2246 if (optind
!= argc
- 1) {
2247 error_exit("Expecting one image file name");
2249 filename
= argv
[optind
++];
2251 /* Open the image */
2252 bs
= bdrv_new_open("image", filename
, NULL
, bdrv_oflags
, true, quiet
);
2257 /* Perform the requested action */
2263 case SNAPSHOT_CREATE
:
2264 memset(&sn
, 0, sizeof(sn
));
2265 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
2267 qemu_gettimeofday(&tv
);
2268 sn
.date_sec
= tv
.tv_sec
;
2269 sn
.date_nsec
= tv
.tv_usec
* 1000;
2271 ret
= bdrv_snapshot_create(bs
, &sn
);
2273 error_report("Could not create snapshot '%s': %d (%s)",
2274 snapshot_name
, ret
, strerror(-ret
));
2278 case SNAPSHOT_APPLY
:
2279 ret
= bdrv_snapshot_goto(bs
, snapshot_name
);
2281 error_report("Could not apply snapshot '%s': %d (%s)",
2282 snapshot_name
, ret
, strerror(-ret
));
2286 case SNAPSHOT_DELETE
:
2287 bdrv_snapshot_delete_by_id_or_name(bs
, snapshot_name
, &err
);
2289 error_report("Could not delete snapshot '%s': (%s)",
2290 snapshot_name
, error_get_pretty(err
));
2305 static int img_rebase(int argc
, char **argv
)
2307 BlockDriverState
*bs
, *bs_old_backing
= NULL
, *bs_new_backing
= NULL
;
2308 BlockDriver
*old_backing_drv
, *new_backing_drv
;
2310 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
2311 int c
, flags
, src_flags
, ret
;
2315 Error
*local_err
= NULL
;
2317 /* Parse commandline parameters */
2319 cache
= BDRV_DEFAULT_CACHE
;
2320 src_cache
= BDRV_DEFAULT_CACHE
;
2324 c
= getopt(argc
, argv
, "hf:F:b:upt:T:q");
2337 out_basefmt
= optarg
;
2340 out_baseimg
= optarg
;
2364 if (optind
!= argc
- 1) {
2365 error_exit("Expecting one image file name");
2367 if (!unsafe
&& !out_baseimg
) {
2368 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
2370 filename
= argv
[optind
++];
2372 qemu_progress_init(progress
, 2.0);
2373 qemu_progress_print(0, 100);
2375 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
2376 ret
= bdrv_parse_cache_flags(cache
, &flags
);
2378 error_report("Invalid cache option: %s", cache
);
2382 src_flags
= BDRV_O_FLAGS
;
2383 ret
= bdrv_parse_cache_flags(src_cache
, &src_flags
);
2385 error_report("Invalid source cache option: %s", src_cache
);
2392 * Ignore the old backing file for unsafe rebase in case we want to correct
2393 * the reference to a renamed or moved backing file.
2395 bs
= bdrv_new_open("image", filename
, fmt
, flags
, true, quiet
);
2400 /* Find the right drivers for the backing files */
2401 old_backing_drv
= NULL
;
2402 new_backing_drv
= NULL
;
2404 if (!unsafe
&& bs
->backing_format
[0] != '\0') {
2405 old_backing_drv
= bdrv_find_format(bs
->backing_format
);
2406 if (old_backing_drv
== NULL
) {
2407 error_report("Invalid format name: '%s'", bs
->backing_format
);
2413 if (out_basefmt
!= NULL
) {
2414 new_backing_drv
= bdrv_find_format(out_basefmt
);
2415 if (new_backing_drv
== NULL
) {
2416 error_report("Invalid format name: '%s'", out_basefmt
);
2422 /* For safe rebasing we need to compare old and new backing file */
2424 /* Make the compiler happy */
2425 bs_old_backing
= NULL
;
2426 bs_new_backing
= NULL
;
2428 char backing_name
[1024];
2430 bs_old_backing
= bdrv_new("old_backing", &error_abort
);
2431 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
2432 ret
= bdrv_open(&bs_old_backing
, backing_name
, NULL
, NULL
, src_flags
,
2433 old_backing_drv
, &local_err
);
2435 error_report("Could not open old backing file '%s': %s",
2436 backing_name
, error_get_pretty(local_err
));
2437 error_free(local_err
);
2440 if (out_baseimg
[0]) {
2441 bs_new_backing
= bdrv_new("new_backing", &error_abort
);
2442 ret
= bdrv_open(&bs_new_backing
, out_baseimg
, NULL
, NULL
, src_flags
,
2443 new_backing_drv
, &local_err
);
2445 error_report("Could not open new backing file '%s': %s",
2446 out_baseimg
, error_get_pretty(local_err
));
2447 error_free(local_err
);
2454 * Check each unallocated cluster in the COW file. If it is unallocated,
2455 * accesses go to the backing file. We must therefore compare this cluster
2456 * in the old and new backing file, and if they differ we need to copy it
2457 * from the old backing file into the COW file.
2459 * If qemu-img crashes during this step, no harm is done. The content of
2460 * the image is the same as the original one at any time.
2463 int64_t num_sectors
;
2464 int64_t old_backing_num_sectors
;
2465 int64_t new_backing_num_sectors
= 0;
2470 float local_progress
= 0;
2472 buf_old
= qemu_blockalign(bs
, IO_BUF_SIZE
);
2473 buf_new
= qemu_blockalign(bs
, IO_BUF_SIZE
);
2475 num_sectors
= bdrv_nb_sectors(bs
);
2476 if (num_sectors
< 0) {
2477 error_report("Could not get size of '%s': %s",
2478 filename
, strerror(-num_sectors
));
2482 old_backing_num_sectors
= bdrv_nb_sectors(bs_old_backing
);
2483 if (old_backing_num_sectors
< 0) {
2484 char backing_name
[1024];
2486 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
2487 error_report("Could not get size of '%s': %s",
2488 backing_name
, strerror(-old_backing_num_sectors
));
2492 if (bs_new_backing
) {
2493 new_backing_num_sectors
= bdrv_nb_sectors(bs_new_backing
);
2494 if (new_backing_num_sectors
< 0) {
2495 error_report("Could not get size of '%s': %s",
2496 out_baseimg
, strerror(-new_backing_num_sectors
));
2502 if (num_sectors
!= 0) {
2503 local_progress
= (float)100 /
2504 (num_sectors
/ MIN(num_sectors
, IO_BUF_SIZE
/ 512));
2507 for (sector
= 0; sector
< num_sectors
; sector
+= n
) {
2509 /* How many sectors can we handle with the next read? */
2510 if (sector
+ (IO_BUF_SIZE
/ 512) <= num_sectors
) {
2511 n
= (IO_BUF_SIZE
/ 512);
2513 n
= num_sectors
- sector
;
2516 /* If the cluster is allocated, we don't need to take action */
2517 ret
= bdrv_is_allocated(bs
, sector
, n
, &n
);
2519 error_report("error while reading image metadata: %s",
2528 * Read old and new backing file and take into consideration that
2529 * backing files may be smaller than the COW image.
2531 if (sector
>= old_backing_num_sectors
) {
2532 memset(buf_old
, 0, n
* BDRV_SECTOR_SIZE
);
2534 if (sector
+ n
> old_backing_num_sectors
) {
2535 n
= old_backing_num_sectors
- sector
;
2538 ret
= bdrv_read(bs_old_backing
, sector
, buf_old
, n
);
2540 error_report("error while reading from old backing file");
2545 if (sector
>= new_backing_num_sectors
|| !bs_new_backing
) {
2546 memset(buf_new
, 0, n
* BDRV_SECTOR_SIZE
);
2548 if (sector
+ n
> new_backing_num_sectors
) {
2549 n
= new_backing_num_sectors
- sector
;
2552 ret
= bdrv_read(bs_new_backing
, sector
, buf_new
, n
);
2554 error_report("error while reading from new backing file");
2559 /* If they differ, we need to write to the COW file */
2560 uint64_t written
= 0;
2562 while (written
< n
) {
2565 if (compare_sectors(buf_old
+ written
* 512,
2566 buf_new
+ written
* 512, n
- written
, &pnum
))
2568 ret
= bdrv_write(bs
, sector
+ written
,
2569 buf_old
+ written
* 512, pnum
);
2571 error_report("Error while writing to COW image: %s",
2579 qemu_progress_print(local_progress
, 100);
2582 qemu_vfree(buf_old
);
2583 qemu_vfree(buf_new
);
2587 * Change the backing file. All clusters that are different from the old
2588 * backing file are overwritten in the COW file now, so the visible content
2589 * doesn't change when we switch the backing file.
2591 if (out_baseimg
&& *out_baseimg
) {
2592 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
2594 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
2597 if (ret
== -ENOSPC
) {
2598 error_report("Could not change the backing file to '%s': No "
2599 "space left in the file header", out_baseimg
);
2600 } else if (ret
< 0) {
2601 error_report("Could not change the backing file to '%s': %s",
2602 out_baseimg
, strerror(-ret
));
2605 qemu_progress_print(100, 0);
2607 * TODO At this point it is possible to check if any clusters that are
2608 * allocated in the COW file are the same in the backing file. If so, they
2609 * could be dropped from the COW file. Don't do this before switching the
2610 * backing file, in case of a crash this would lead to corruption.
2613 qemu_progress_end();
2616 if (bs_old_backing
!= NULL
) {
2617 bdrv_unref(bs_old_backing
);
2619 if (bs_new_backing
!= NULL
) {
2620 bdrv_unref(bs_new_backing
);
2631 static int img_resize(int argc
, char **argv
)
2633 int c
, ret
, relative
;
2634 const char *filename
, *fmt
, *size
;
2635 int64_t n
, total_size
;
2637 BlockDriverState
*bs
= NULL
;
2639 static QemuOptsList resize_options
= {
2640 .name
= "resize_options",
2641 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
2644 .name
= BLOCK_OPT_SIZE
,
2645 .type
= QEMU_OPT_SIZE
,
2646 .help
= "Virtual disk size"
2653 /* Remove size from argv manually so that negative numbers are not treated
2654 * as options by getopt. */
2656 error_exit("Not enough arguments");
2660 size
= argv
[--argc
];
2662 /* Parse getopt arguments */
2665 c
= getopt(argc
, argv
, "f:hq");
2682 if (optind
!= argc
- 1) {
2683 error_exit("Expecting one image file name");
2685 filename
= argv
[optind
++];
2687 /* Choose grow, shrink, or absolute resize mode */
2703 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
2704 if (qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
)) {
2705 /* Error message already printed when size parsing fails */
2707 qemu_opts_del(param
);
2710 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
2711 qemu_opts_del(param
);
2713 bs
= bdrv_new_open("image", filename
, fmt
, BDRV_O_FLAGS
| BDRV_O_RDWR
,
2721 total_size
= bdrv_getlength(bs
) + n
* relative
;
2725 if (total_size
<= 0) {
2726 error_report("New image size must be positive");
2731 ret
= bdrv_truncate(bs
, total_size
);
2734 qprintf(quiet
, "Image resized.\n");
2737 error_report("This image does not support resize");
2740 error_report("Image is read-only");
2743 error_report("Error resizing image (%d)", -ret
);
2756 static int img_amend(int argc
, char **argv
)
2759 char *options
= NULL
;
2760 QemuOptsList
*create_opts
= NULL
;
2761 QemuOpts
*opts
= NULL
;
2762 const char *fmt
= NULL
, *filename
, *cache
;
2765 BlockDriverState
*bs
= NULL
;
2767 cache
= BDRV_DEFAULT_CACHE
;
2769 c
= getopt(argc
, argv
, "ho:f:t:q");
2780 if (!is_valid_option_list(optarg
)) {
2781 error_report("Invalid option list: %s", optarg
);
2786 options
= g_strdup(optarg
);
2788 char *old_options
= options
;
2789 options
= g_strdup_printf("%s,%s", options
, optarg
);
2790 g_free(old_options
);
2806 error_exit("Must specify options (-o)");
2809 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
2810 if (fmt
&& has_help_option(options
)) {
2811 /* If a format is explicitly specified (and possibly no filename is
2812 * given), print option help here */
2813 ret
= print_block_option_help(filename
, fmt
);
2817 if (optind
!= argc
- 1) {
2818 error_exit("Expecting one image file name");
2821 flags
= BDRV_O_FLAGS
| BDRV_O_RDWR
;
2822 ret
= bdrv_parse_cache_flags(cache
, &flags
);
2824 error_report("Invalid cache option: %s", cache
);
2828 bs
= bdrv_new_open("image", filename
, fmt
, flags
, true, quiet
);
2830 error_report("Could not open image '%s'", filename
);
2835 fmt
= bs
->drv
->format_name
;
2837 if (has_help_option(options
)) {
2838 /* If the format was auto-detected, print option help here */
2839 ret
= print_block_option_help(filename
, fmt
);
2843 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
2844 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2845 if (options
&& qemu_opts_do_parse(opts
, options
, NULL
)) {
2846 error_report("Invalid options for file format '%s'", fmt
);
2851 ret
= bdrv_amend_options(bs
, opts
);
2853 error_report("Error while amending options: %s", strerror(-ret
));
2861 qemu_opts_del(opts
);
2862 qemu_opts_free(create_opts
);
2871 static const img_cmd_t img_cmds
[] = {
2872 #define DEF(option, callback, arg_string) \
2873 { option, callback },
2874 #include "qemu-img-cmds.h"
2880 int main(int argc
, char **argv
)
2882 const img_cmd_t
*cmd
;
2883 const char *cmdname
;
2885 static const struct option long_options
[] = {
2886 {"help", no_argument
, 0, 'h'},
2887 {"version", no_argument
, 0, 'v'},
2892 signal(SIGPIPE
, SIG_IGN
);
2895 error_set_progname(argv
[0]);
2896 qemu_init_exec_dir(argv
[0]);
2898 qemu_init_main_loop();
2901 error_exit("Not enough arguments");
2905 /* find the command */
2906 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
2907 if (!strcmp(cmdname
, cmd
->name
)) {
2908 return cmd
->handler(argc
- 1, argv
+ 1);
2912 c
= getopt_long(argc
, argv
, "h", long_options
, NULL
);
2918 printf(QEMU_IMG_VERSION
);
2923 error_exit("Command not found: %s", cmdname
);