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"
42 typedef struct img_cmd_t
{
44 int (*handler
)(int argc
, char **argv
);
49 OPTION_BACKING_CHAIN
= 257,
52 typedef enum OutputFormat
{
57 /* Default to cache=writeback as data integrity is not important for qemu-tcg. */
58 #define BDRV_O_FLAGS BDRV_O_CACHE_WB
59 #define BDRV_DEFAULT_CACHE "writeback"
61 static void format_print(void *opaque
, const char *name
)
66 /* Please keep in synch with qemu-img.texi */
67 static void help(void)
69 const char *help_msg
=
70 "qemu-img version " QEMU_VERSION
", Copyright (c) 2004-2008 Fabrice Bellard\n"
71 "usage: qemu-img command [command options]\n"
72 "QEMU disk image utility\n"
75 #define DEF(option, callback, arg_string) \
77 #include "qemu-img-cmds.h"
81 "Command parameters:\n"
82 " 'filename' is a disk image filename\n"
83 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
84 " 'cache' is the cache mode used to write the output disk image, the valid\n"
85 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
86 " 'directsync' and 'unsafe' (default for convert)\n"
87 " 'size' is the disk image size in bytes. Optional suffixes\n"
88 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
89 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
90 " supported. 'b' is ignored.\n"
91 " 'output_filename' is the destination disk image filename\n"
92 " 'output_fmt' is the destination format\n"
93 " 'options' is a comma separated list of format specific options in a\n"
94 " name=value format. Use -o ? for an overview of the options supported by the\n"
96 " 'snapshot_param' is param used for internal snapshot, format\n"
97 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
99 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
101 " '-c' indicates that target image must be compressed (qcow format only)\n"
102 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
103 " match exactly. The image doesn't need a working backing file before\n"
104 " rebasing in this case (useful for renaming the backing file)\n"
105 " '-h' with or without a command shows this help and lists the supported formats\n"
106 " '-p' show progress of command (only certain commands)\n"
107 " '-q' use Quiet mode - do not print any output (except errors)\n"
108 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
109 " contain only zeros for qemu-img to create a sparse image during\n"
110 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
111 " unallocated or zero sectors, and the destination image will always be\n"
113 " '--output' takes the format in which the output must be done (human or json)\n"
114 " '-n' skips the target volume creation (useful if the volume is created\n"
115 " prior to running qemu-img)\n"
117 "Parameters to check subcommand:\n"
118 " '-r' tries to repair any inconsistencies that are found during the check.\n"
119 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
120 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
121 " hiding corruption that has already occurred.\n"
123 "Parameters to snapshot subcommand:\n"
124 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
125 " '-a' applies a snapshot (revert disk to saved state)\n"
126 " '-c' creates a snapshot\n"
127 " '-d' deletes a snapshot\n"
128 " '-l' lists all snapshots in the given image\n"
130 "Parameters to compare subcommand:\n"
131 " '-f' first image format\n"
132 " '-F' second image format\n"
133 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
135 printf("%s\nSupported formats:", help_msg
);
136 bdrv_iterate_format(format_print
, NULL
);
141 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
147 ret
= vprintf(fmt
, args
);
154 /* XXX: put correct support for win32 */
155 static int read_password(char *buf
, int buf_size
)
158 printf("Password: ");
165 if (i
< (buf_size
- 1))
176 static struct termios oldtty
;
178 static void term_exit(void)
180 tcsetattr (0, TCSANOW
, &oldtty
);
183 static void term_init(void)
190 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
191 |INLCR
|IGNCR
|ICRNL
|IXON
);
192 tty
.c_oflag
|= OPOST
;
193 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
194 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
199 tcsetattr (0, TCSANOW
, &tty
);
204 static int read_password(char *buf
, int buf_size
)
209 printf("password: ");
214 ret
= read(0, &ch
, 1);
216 if (errno
== EAGAIN
|| errno
== EINTR
) {
222 } else if (ret
== 0) {
230 if (i
< (buf_size
- 1))
241 static int print_block_option_help(const char *filename
, const char *fmt
)
243 BlockDriver
*drv
, *proto_drv
;
244 QEMUOptionParameter
*create_options
= NULL
;
246 /* Find driver and parse its options */
247 drv
= bdrv_find_format(fmt
);
249 error_report("Unknown file format '%s'", fmt
);
253 proto_drv
= bdrv_find_protocol(filename
, true);
255 error_report("Unknown protocol '%s'", filename
);
259 create_options
= append_option_parameters(create_options
,
260 drv
->create_options
);
261 create_options
= append_option_parameters(create_options
,
262 proto_drv
->create_options
);
263 print_option_help(create_options
);
264 free_option_parameters(create_options
);
268 static BlockDriverState
*bdrv_new_open(const char *filename
,
274 BlockDriverState
*bs
;
277 Error
*local_err
= NULL
;
280 bs
= bdrv_new("image");
283 drv
= bdrv_find_format(fmt
);
285 error_report("Unknown file format '%s'", fmt
);
292 ret
= bdrv_open(&bs
, filename
, NULL
, NULL
, flags
, drv
, &local_err
);
294 error_report("Could not open '%s': %s", filename
,
295 error_get_pretty(local_err
));
296 error_free(local_err
);
300 if (bdrv_is_encrypted(bs
) && require_io
) {
301 qprintf(quiet
, "Disk image '%s' is encrypted.\n", filename
);
302 if (read_password(password
, sizeof(password
)) < 0) {
303 error_report("No password given");
306 if (bdrv_set_key(bs
, password
) < 0) {
307 error_report("invalid password");
317 static int add_old_style_options(const char *fmt
, QEMUOptionParameter
*list
,
318 const char *base_filename
,
319 const char *base_fmt
)
322 if (set_option_parameter(list
, BLOCK_OPT_BACKING_FILE
, base_filename
)) {
323 error_report("Backing file not supported for file format '%s'",
329 if (set_option_parameter(list
, BLOCK_OPT_BACKING_FMT
, base_fmt
)) {
330 error_report("Backing file format not supported for file "
338 static int img_create(int argc
, char **argv
)
341 uint64_t img_size
= -1;
342 const char *fmt
= "raw";
343 const char *base_fmt
= NULL
;
344 const char *filename
;
345 const char *base_filename
= NULL
;
346 char *options
= NULL
;
347 Error
*local_err
= NULL
;
351 c
= getopt(argc
, argv
, "F:b:f:he6o:q");
364 base_filename
= optarg
;
370 error_report("option -e is deprecated, please use \'-o "
371 "encryption\' instead!");
374 error_report("option -6 is deprecated, please use \'-o "
375 "compat6\' instead!");
386 /* Get the filename */
387 if (optind
>= argc
) {
390 filename
= argv
[optind
++];
392 /* Get image size, if specified */
396 sval
= strtosz_suffix(argv
[optind
++], &end
, STRTOSZ_DEFSUFFIX_B
);
397 if (sval
< 0 || *end
) {
398 if (sval
== -ERANGE
) {
399 error_report("Image size must be less than 8 EiB!");
401 error_report("Invalid image size specified! You may use k, M, "
402 "G, T, P or E suffixes for ");
403 error_report("kilobytes, megabytes, gigabytes, terabytes, "
404 "petabytes and exabytes.");
408 img_size
= (uint64_t)sval
;
410 if (optind
!= argc
) {
414 if (options
&& is_help_option(options
)) {
415 return print_block_option_help(filename
, fmt
);
418 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
419 options
, img_size
, BDRV_O_FLAGS
, &local_err
, quiet
);
421 error_report("%s: %s", filename
, error_get_pretty(local_err
));
422 error_free(local_err
);
429 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
433 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
435 visit_type_ImageCheck(qmp_output_get_visitor(ov
),
436 &check
, NULL
, &errp
);
437 obj
= qmp_output_get_qobject(ov
);
438 str
= qobject_to_json_pretty(obj
);
440 qprintf(quiet
, "%s\n", qstring_get_str(str
));
442 qmp_output_visitor_cleanup(ov
);
446 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
448 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
449 qprintf(quiet
, "No errors were found on the image.\n");
451 if (check
->corruptions
) {
452 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
453 "Data may be corrupted, or further writes to the image "
460 "\n%" PRId64
" leaked clusters were found on the image.\n"
461 "This means waste of disk space, but no harm to data.\n",
465 if (check
->check_errors
) {
468 " internal errors have occurred during the check.\n",
469 check
->check_errors
);
473 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
474 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
475 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
476 check
->allocated_clusters
, check
->total_clusters
,
477 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
478 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
479 check
->compressed_clusters
* 100.0 /
480 check
->allocated_clusters
);
483 if (check
->image_end_offset
) {
485 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
489 static int collect_image_check(BlockDriverState
*bs
,
491 const char *filename
,
496 BdrvCheckResult result
;
498 ret
= bdrv_check(bs
, &result
, fix
);
503 check
->filename
= g_strdup(filename
);
504 check
->format
= g_strdup(bdrv_get_format_name(bs
));
505 check
->check_errors
= result
.check_errors
;
506 check
->corruptions
= result
.corruptions
;
507 check
->has_corruptions
= result
.corruptions
!= 0;
508 check
->leaks
= result
.leaks
;
509 check
->has_leaks
= result
.leaks
!= 0;
510 check
->corruptions_fixed
= result
.corruptions_fixed
;
511 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
512 check
->leaks_fixed
= result
.leaks_fixed
;
513 check
->has_leaks_fixed
= result
.leaks
!= 0;
514 check
->image_end_offset
= result
.image_end_offset
;
515 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
516 check
->total_clusters
= result
.bfi
.total_clusters
;
517 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
518 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
519 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
520 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
521 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
522 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
523 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
529 * Checks an image for consistency. Exit codes:
531 * 0 - Check completed, image is good
532 * 1 - Check not completed because of internal errors
533 * 2 - Check completed, image is corrupted
534 * 3 - Check completed, image has leaked clusters, but is good otherwise
536 static int img_check(int argc
, char **argv
)
539 OutputFormat output_format
= OFORMAT_HUMAN
;
540 const char *filename
, *fmt
, *output
;
541 BlockDriverState
*bs
;
543 int flags
= BDRV_O_FLAGS
| BDRV_O_CHECK
;
550 int option_index
= 0;
551 static const struct option long_options
[] = {
552 {"help", no_argument
, 0, 'h'},
553 {"format", required_argument
, 0, 'f'},
554 {"repair", no_argument
, 0, 'r'},
555 {"output", required_argument
, 0, OPTION_OUTPUT
},
558 c
= getopt_long(argc
, argv
, "f:hr:q",
559 long_options
, &option_index
);
572 flags
|= BDRV_O_RDWR
;
574 if (!strcmp(optarg
, "leaks")) {
575 fix
= BDRV_FIX_LEAKS
;
576 } else if (!strcmp(optarg
, "all")) {
577 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
590 if (optind
!= argc
- 1) {
593 filename
= argv
[optind
++];
595 if (output
&& !strcmp(output
, "json")) {
596 output_format
= OFORMAT_JSON
;
597 } else if (output
&& !strcmp(output
, "human")) {
598 output_format
= OFORMAT_HUMAN
;
600 error_report("--output must be used with human or json as argument.");
604 bs
= bdrv_new_open(filename
, fmt
, flags
, true, quiet
);
609 check
= g_new0(ImageCheck
, 1);
610 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
612 if (ret
== -ENOTSUP
) {
613 if (output_format
== OFORMAT_HUMAN
) {
614 error_report("This image format does not support checks");
620 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
621 int corruptions_fixed
, leaks_fixed
;
623 leaks_fixed
= check
->leaks_fixed
;
624 corruptions_fixed
= check
->corruptions_fixed
;
626 if (output_format
== OFORMAT_HUMAN
) {
628 "The following inconsistencies were found and repaired:\n\n"
629 " %" PRId64
" leaked clusters\n"
630 " %" PRId64
" corruptions\n\n"
631 "Double checking the fixed image now...\n",
633 check
->corruptions_fixed
);
636 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
638 check
->leaks_fixed
= leaks_fixed
;
639 check
->corruptions_fixed
= corruptions_fixed
;
642 switch (output_format
) {
644 dump_human_image_check(check
, quiet
);
647 dump_json_image_check(check
, quiet
);
651 if (ret
|| check
->check_errors
) {
656 if (check
->corruptions
) {
658 } else if (check
->leaks
) {
665 qapi_free_ImageCheck(check
);
671 static int img_commit(int argc
, char **argv
)
674 const char *filename
, *fmt
, *cache
;
675 BlockDriverState
*bs
;
679 cache
= BDRV_DEFAULT_CACHE
;
681 c
= getopt(argc
, argv
, "f:ht:q");
701 if (optind
!= argc
- 1) {
704 filename
= argv
[optind
++];
707 ret
= bdrv_parse_cache_flags(cache
, &flags
);
709 error_report("Invalid cache option: %s", cache
);
713 bs
= bdrv_new_open(filename
, fmt
, flags
, true, quiet
);
717 ret
= bdrv_commit(bs
);
720 qprintf(quiet
, "Image committed.\n");
723 error_report("No disk inserted");
726 error_report("Image is read-only");
729 error_report("Image is already committed");
732 error_report("Error while committing image");
744 * Returns true iff the first sector pointed to by 'buf' contains at least
747 * 'pnum' is set to the number of sectors (including and immediately following
748 * the first one) that are known to be in the same allocated/unallocated state.
750 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
)
759 is_zero
= buffer_is_zero(buf
, 512);
760 for(i
= 1; i
< n
; i
++) {
762 if (is_zero
!= buffer_is_zero(buf
, 512)) {
771 * Like is_allocated_sectors, but if the buffer starts with a used sector,
772 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
773 * breaking up write requests for only small sparse areas.
775 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
779 int num_checked
, num_used
;
785 ret
= is_allocated_sectors(buf
, n
, pnum
);
791 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
793 num_checked
= num_used
;
796 ret
= is_allocated_sectors(buf
, n
, pnum
);
798 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
800 num_checked
+= *pnum
;
802 num_used
= num_checked
;
803 } else if (*pnum
>= min
) {
813 * Compares two buffers sector by sector. Returns 0 if the first sector of both
814 * buffers matches, non-zero otherwise.
816 * pnum is set to the number of sectors (including and immediately following
817 * the first one) that are known to have the same comparison result
819 static int compare_sectors(const uint8_t *buf1
, const uint8_t *buf2
, int n
,
829 res
= !!memcmp(buf1
, buf2
, 512);
830 for(i
= 1; i
< n
; i
++) {
834 if (!!memcmp(buf1
, buf2
, 512) != res
) {
843 #define IO_BUF_SIZE (2 * 1024 * 1024)
845 static int64_t sectors_to_bytes(int64_t sectors
)
847 return sectors
<< BDRV_SECTOR_BITS
;
850 static int64_t sectors_to_process(int64_t total
, int64_t from
)
852 return MIN(total
- from
, IO_BUF_SIZE
>> BDRV_SECTOR_BITS
);
856 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
858 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
859 * data and negative value on error.
861 * @param bs: Driver used for accessing file
862 * @param sect_num: Number of first sector to check
863 * @param sect_count: Number of sectors to check
864 * @param filename: Name of disk file we are checking (logging purpose)
865 * @param buffer: Allocated buffer for storing read data
866 * @param quiet: Flag for quiet mode
868 static int check_empty_sectors(BlockDriverState
*bs
, int64_t sect_num
,
869 int sect_count
, const char *filename
,
870 uint8_t *buffer
, bool quiet
)
873 ret
= bdrv_read(bs
, sect_num
, buffer
, sect_count
);
875 error_report("Error while reading offset %" PRId64
" of %s: %s",
876 sectors_to_bytes(sect_num
), filename
, strerror(-ret
));
879 ret
= is_allocated_sectors(buffer
, sect_count
, &pnum
);
880 if (ret
|| pnum
!= sect_count
) {
881 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
882 sectors_to_bytes(ret
? sect_num
: sect_num
+ pnum
));
890 * Compares two images. Exit codes:
892 * 0 - Images are identical
894 * >1 - Error occurred
896 static int img_compare(int argc
, char **argv
)
898 const char *fmt1
= NULL
, *fmt2
= NULL
, *filename1
, *filename2
;
899 BlockDriverState
*bs1
, *bs2
;
900 int64_t total_sectors1
, total_sectors2
;
901 uint8_t *buf1
= NULL
, *buf2
= NULL
;
903 int allocated1
, allocated2
;
904 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
905 bool progress
= false, quiet
= false, strict
= false;
906 int64_t total_sectors
;
907 int64_t sector_num
= 0;
911 uint64_t progress_base
;
914 c
= getopt(argc
, argv
, "hpf:F:sq");
941 /* Progress is not shown in Quiet mode */
947 if (optind
!= argc
- 2) {
950 filename1
= argv
[optind
++];
951 filename2
= argv
[optind
++];
953 /* Initialize before goto out */
954 qemu_progress_init(progress
, 2.0);
956 bs1
= bdrv_new_open(filename1
, fmt1
, BDRV_O_FLAGS
, true, quiet
);
958 error_report("Can't open file %s", filename1
);
963 bs2
= bdrv_new_open(filename2
, fmt2
, BDRV_O_FLAGS
, true, quiet
);
965 error_report("Can't open file %s", filename2
);
970 buf1
= qemu_blockalign(bs1
, IO_BUF_SIZE
);
971 buf2
= qemu_blockalign(bs2
, IO_BUF_SIZE
);
972 bdrv_get_geometry(bs1
, &bs_sectors
);
973 total_sectors1
= bs_sectors
;
974 bdrv_get_geometry(bs2
, &bs_sectors
);
975 total_sectors2
= bs_sectors
;
976 total_sectors
= MIN(total_sectors1
, total_sectors2
);
977 progress_base
= MAX(total_sectors1
, total_sectors2
);
979 qemu_progress_print(0, 100);
981 if (strict
&& total_sectors1
!= total_sectors2
) {
983 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
988 nb_sectors
= sectors_to_process(total_sectors
, sector_num
);
989 if (nb_sectors
<= 0) {
992 allocated1
= bdrv_is_allocated_above(bs1
, NULL
, sector_num
, nb_sectors
,
994 if (allocated1
< 0) {
996 error_report("Sector allocation test failed for %s", filename1
);
1000 allocated2
= bdrv_is_allocated_above(bs2
, NULL
, sector_num
, nb_sectors
,
1002 if (allocated2
< 0) {
1004 error_report("Sector allocation test failed for %s", filename2
);
1007 nb_sectors
= MIN(pnum1
, pnum2
);
1009 if (allocated1
== allocated2
) {
1011 ret
= bdrv_read(bs1
, sector_num
, buf1
, nb_sectors
);
1013 error_report("Error while reading offset %" PRId64
" of %s:"
1014 " %s", sectors_to_bytes(sector_num
), filename1
,
1019 ret
= bdrv_read(bs2
, sector_num
, buf2
, nb_sectors
);
1021 error_report("Error while reading offset %" PRId64
1022 " of %s: %s", sectors_to_bytes(sector_num
),
1023 filename2
, strerror(-ret
));
1027 ret
= compare_sectors(buf1
, buf2
, nb_sectors
, &pnum
);
1028 if (ret
|| pnum
!= nb_sectors
) {
1029 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1031 ret
? sector_num
: sector_num
+ pnum
));
1039 qprintf(quiet
, "Strict mode: Offset %" PRId64
1040 " allocation mismatch!\n",
1041 sectors_to_bytes(sector_num
));
1046 ret
= check_empty_sectors(bs1
, sector_num
, nb_sectors
,
1047 filename1
, buf1
, quiet
);
1049 ret
= check_empty_sectors(bs2
, sector_num
, nb_sectors
,
1050 filename2
, buf1
, quiet
);
1054 error_report("Error while reading offset %" PRId64
": %s",
1055 sectors_to_bytes(sector_num
), strerror(-ret
));
1061 sector_num
+= nb_sectors
;
1062 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1065 if (total_sectors1
!= total_sectors2
) {
1066 BlockDriverState
*bs_over
;
1067 int64_t total_sectors_over
;
1068 const char *filename_over
;
1070 qprintf(quiet
, "Warning: Image size mismatch!\n");
1071 if (total_sectors1
> total_sectors2
) {
1072 total_sectors_over
= total_sectors1
;
1074 filename_over
= filename1
;
1076 total_sectors_over
= total_sectors2
;
1078 filename_over
= filename2
;
1082 nb_sectors
= sectors_to_process(total_sectors_over
, sector_num
);
1083 if (nb_sectors
<= 0) {
1086 ret
= bdrv_is_allocated_above(bs_over
, NULL
, sector_num
,
1090 error_report("Sector allocation test failed for %s",
1097 ret
= check_empty_sectors(bs_over
, sector_num
, nb_sectors
,
1098 filename_over
, buf1
, quiet
);
1101 error_report("Error while reading offset %" PRId64
1102 " of %s: %s", sectors_to_bytes(sector_num
),
1103 filename_over
, strerror(-ret
));
1109 sector_num
+= nb_sectors
;
1110 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1114 qprintf(quiet
, "Images are identical.\n");
1124 qemu_progress_end();
1128 static int img_convert(int argc
, char **argv
)
1130 int c
, n
, n1
, bs_n
, bs_i
, compress
, cluster_sectors
, skip_create
;
1132 int progress
= 0, flags
;
1133 const char *fmt
, *out_fmt
, *cache
, *out_baseimg
, *out_filename
;
1134 BlockDriver
*drv
, *proto_drv
;
1135 BlockDriverState
**bs
= NULL
, *out_bs
= NULL
;
1136 int64_t total_sectors
, nb_sectors
, sector_num
, bs_offset
;
1137 uint64_t bs_sectors
;
1138 uint8_t * buf
= NULL
;
1139 size_t bufsectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
;
1140 const uint8_t *buf1
;
1141 BlockDriverInfo bdi
;
1142 QEMUOptionParameter
*param
= NULL
, *create_options
= NULL
;
1143 QEMUOptionParameter
*out_baseimg_param
;
1144 char *options
= NULL
;
1145 const char *snapshot_name
= NULL
;
1146 int min_sparse
= 8; /* Need at least 4k of zeros for sparse detection */
1148 Error
*local_err
= NULL
;
1149 QemuOpts
*sn_opts
= NULL
;
1158 c
= getopt(argc
, argv
, "f:O:B:s:hce6o:pS:t:qnl:");
1174 out_baseimg
= optarg
;
1180 error_report("option -e is deprecated, please use \'-o "
1181 "encryption\' instead!");
1184 error_report("option -6 is deprecated, please use \'-o "
1185 "compat6\' instead!");
1191 snapshot_name
= optarg
;
1194 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
1195 sn_opts
= qemu_opts_parse(&internal_snapshot_opts
, optarg
, 0);
1197 error_report("Failed in parsing snapshot param '%s'",
1202 snapshot_name
= optarg
;
1209 sval
= strtosz_suffix(optarg
, &end
, STRTOSZ_DEFSUFFIX_B
);
1210 if (sval
< 0 || *end
) {
1211 error_report("Invalid minimum zero buffer size for sparse output specified");
1215 min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
1237 bs_n
= argc
- optind
- 1;
1242 out_filename
= argv
[argc
- 1];
1244 /* Initialize before goto out */
1245 qemu_progress_init(progress
, 1.0);
1247 if (options
&& is_help_option(options
)) {
1248 ret
= print_block_option_help(out_filename
, out_fmt
);
1252 if (bs_n
> 1 && out_baseimg
) {
1253 error_report("-B makes no sense when concatenating multiple input "
1259 qemu_progress_print(0, 100);
1261 bs
= g_malloc0(bs_n
* sizeof(BlockDriverState
*));
1264 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
1265 bs
[bs_i
] = bdrv_new_open(argv
[optind
+ bs_i
], fmt
, BDRV_O_FLAGS
, true,
1268 error_report("Could not open '%s'", argv
[optind
+ bs_i
]);
1272 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1273 total_sectors
+= bs_sectors
;
1277 ret
= bdrv_snapshot_load_tmp(bs
[0],
1278 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
1279 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
1281 } else if (snapshot_name
!= NULL
) {
1283 error_report("No support for concatenating multiple snapshot");
1288 bdrv_snapshot_load_tmp_by_id_or_name(bs
[0], snapshot_name
, &local_err
);
1291 error_report("Failed to load snapshot: %s",
1292 error_get_pretty(local_err
));
1293 error_free(local_err
);
1298 /* Find driver and parse its options */
1299 drv
= bdrv_find_format(out_fmt
);
1301 error_report("Unknown file format '%s'", out_fmt
);
1306 proto_drv
= bdrv_find_protocol(out_filename
, true);
1308 error_report("Unknown protocol '%s'", out_filename
);
1313 create_options
= append_option_parameters(create_options
,
1314 drv
->create_options
);
1315 create_options
= append_option_parameters(create_options
,
1316 proto_drv
->create_options
);
1319 param
= parse_option_parameters(options
, create_options
, param
);
1320 if (param
== NULL
) {
1321 error_report("Invalid options for file format '%s'.", out_fmt
);
1326 param
= parse_option_parameters("", create_options
, param
);
1329 set_option_parameter_int(param
, BLOCK_OPT_SIZE
, total_sectors
* 512);
1330 ret
= add_old_style_options(out_fmt
, param
, out_baseimg
, NULL
);
1335 /* Get backing file name if -o backing_file was used */
1336 out_baseimg_param
= get_option_parameter(param
, BLOCK_OPT_BACKING_FILE
);
1337 if (out_baseimg_param
) {
1338 out_baseimg
= out_baseimg_param
->value
.s
;
1341 /* Check if compression is supported */
1343 QEMUOptionParameter
*encryption
=
1344 get_option_parameter(param
, BLOCK_OPT_ENCRYPT
);
1345 QEMUOptionParameter
*preallocation
=
1346 get_option_parameter(param
, BLOCK_OPT_PREALLOC
);
1348 if (!drv
->bdrv_write_compressed
) {
1349 error_report("Compression not supported for this file format");
1354 if (encryption
&& encryption
->value
.n
) {
1355 error_report("Compression and encryption not supported at "
1361 if (preallocation
&& preallocation
->value
.s
1362 && strcmp(preallocation
->value
.s
, "off"))
1364 error_report("Compression and preallocation not supported at "
1372 /* Create the new image */
1373 ret
= bdrv_create(drv
, out_filename
, param
, &local_err
);
1375 error_report("%s: error while converting %s: %s",
1376 out_filename
, out_fmt
, error_get_pretty(local_err
));
1377 error_free(local_err
);
1382 flags
= min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
1383 ret
= bdrv_parse_cache_flags(cache
, &flags
);
1385 error_report("Invalid cache option: %s", cache
);
1389 out_bs
= bdrv_new_open(out_filename
, out_fmt
, flags
, true, quiet
);
1397 bdrv_get_geometry(bs
[0], &bs_sectors
);
1399 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
1400 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
1402 bufsectors
= MIN(32768,
1403 MAX(bufsectors
, MAX(out_bs
->bl
.opt_transfer_length
,
1404 out_bs
->bl
.discard_alignment
))
1407 buf
= qemu_blockalign(out_bs
, bufsectors
* BDRV_SECTOR_SIZE
);
1410 int64_t output_length
= bdrv_getlength(out_bs
);
1411 if (output_length
< 0) {
1412 error_report("unable to get output image length: %s\n",
1413 strerror(-output_length
));
1416 } else if (output_length
< total_sectors
<< BDRV_SECTOR_BITS
) {
1417 error_report("output file is smaller than input file");
1423 cluster_sectors
= 0;
1424 ret
= bdrv_get_info(out_bs
, &bdi
);
1427 error_report("could not get block driver info");
1431 cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
1435 if (cluster_sectors
<= 0 || cluster_sectors
> bufsectors
) {
1436 error_report("invalid cluster size");
1442 nb_sectors
= total_sectors
;
1449 nb_sectors
= total_sectors
- sector_num
;
1450 if (nb_sectors
<= 0)
1452 if (nb_sectors
>= cluster_sectors
)
1453 n
= cluster_sectors
;
1457 bs_num
= sector_num
- bs_offset
;
1458 assert (bs_num
>= 0);
1461 while (remainder
> 0) {
1463 while (bs_num
== bs_sectors
) {
1465 assert (bs_i
< bs_n
);
1466 bs_offset
+= bs_sectors
;
1467 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1469 /* printf("changing part: sector_num=%" PRId64 ", "
1470 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
1471 "\n", sector_num, bs_i, bs_offset, bs_sectors); */
1473 assert (bs_num
< bs_sectors
);
1475 nlow
= (remainder
> bs_sectors
- bs_num
) ? bs_sectors
- bs_num
: remainder
;
1477 ret
= bdrv_read(bs
[bs_i
], bs_num
, buf2
, nlow
);
1479 error_report("error while reading sector %" PRId64
": %s",
1480 bs_num
, strerror(-ret
));
1489 assert (remainder
== 0);
1491 if (!buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)) {
1492 ret
= bdrv_write_compressed(out_bs
, sector_num
, buf
, n
);
1494 error_report("error while compressing sector %" PRId64
1495 ": %s", sector_num
, strerror(-ret
));
1500 qemu_progress_print(100.0 * sector_num
/ total_sectors
, 0);
1502 /* signal EOF to align */
1503 bdrv_write_compressed(out_bs
, 0, NULL
, 0);
1505 int64_t sectors_to_read
, sectors_read
, sector_num_next_status
;
1506 bool count_allocated_sectors
;
1507 int has_zero_init
= min_sparse
? bdrv_has_zero_init(out_bs
) : 0;
1509 if (!has_zero_init
&& bdrv_can_write_zeroes_with_unmap(out_bs
)) {
1510 ret
= bdrv_make_zero(out_bs
, BDRV_REQ_MAY_UNMAP
);
1517 sectors_to_read
= total_sectors
;
1518 count_allocated_sectors
= progress
&& (out_baseimg
|| has_zero_init
);
1520 sector_num
= 0; // total number of sectors converted so far
1522 sector_num_next_status
= 0;
1525 nb_sectors
= total_sectors
- sector_num
;
1526 if (nb_sectors
<= 0) {
1527 if (count_allocated_sectors
) {
1528 sectors_to_read
= sectors_read
;
1529 count_allocated_sectors
= false;
1536 while (sector_num
- bs_offset
>= bs_sectors
) {
1538 assert (bs_i
< bs_n
);
1539 bs_offset
+= bs_sectors
;
1540 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1541 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1542 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
1543 sector_num, bs_i, bs_offset, bs_sectors); */
1546 if ((out_baseimg
|| has_zero_init
) &&
1547 sector_num
>= sector_num_next_status
) {
1548 n
= nb_sectors
> INT_MAX
? INT_MAX
: nb_sectors
;
1549 ret
= bdrv_get_block_status(bs
[bs_i
], sector_num
- bs_offset
,
1552 error_report("error while reading block status of sector %"
1553 PRId64
": %s", sector_num
- bs_offset
,
1557 /* If the output image is zero initialized, we are not working
1558 * on a shared base and the input is zero we can skip the next
1560 if (has_zero_init
&& !out_baseimg
&& (ret
& BDRV_BLOCK_ZERO
)) {
1564 /* If the output image is being created as a copy on write
1565 * image, assume that sectors which are unallocated in the
1566 * input image are present in both the output's and input's
1567 * base images (no need to copy them). */
1569 if (!(ret
& BDRV_BLOCK_DATA
)) {
1573 /* The next 'n1' sectors are allocated in the input image.
1574 * Copy only those as they may be followed by unallocated
1578 /* avoid redundant callouts to get_block_status */
1579 sector_num_next_status
= sector_num
+ n1
;
1582 n
= MIN(nb_sectors
, bufsectors
);
1584 /* round down request length to an aligned sector, but
1585 * do not bother doing this on short requests. They happen
1586 * when we found an all-zero area, and the next sector to
1587 * write will not be sector_num + n. */
1588 if (cluster_sectors
> 0 && n
>= cluster_sectors
) {
1589 int64_t next_aligned_sector
= (sector_num
+ n
);
1590 next_aligned_sector
-= next_aligned_sector
% cluster_sectors
;
1591 if (sector_num
+ n
> next_aligned_sector
) {
1592 n
= next_aligned_sector
- sector_num
;
1596 n
= MIN(n
, bs_sectors
- (sector_num
- bs_offset
));
1599 if (count_allocated_sectors
) {
1605 ret
= bdrv_read(bs
[bs_i
], sector_num
- bs_offset
, buf
, n
);
1607 error_report("error while reading sector %" PRId64
": %s",
1608 sector_num
- bs_offset
, strerror(-ret
));
1611 /* NOTE: at the same time we convert, we do not write zero
1612 sectors to have a chance to compress the image. Ideally, we
1613 should add a specific call to have the info to go faster */
1616 if (!has_zero_init
||
1617 is_allocated_sectors_min(buf1
, n
, &n1
, min_sparse
)) {
1618 ret
= bdrv_write(out_bs
, sector_num
, buf1
, n1
);
1620 error_report("error while writing sector %" PRId64
1621 ": %s", sector_num
, strerror(-ret
));
1629 qemu_progress_print(100.0 * sectors_read
/ sectors_to_read
, 0);
1634 qemu_progress_print(100, 0);
1636 qemu_progress_end();
1637 free_option_parameters(create_options
);
1638 free_option_parameters(param
);
1641 qemu_opts_del(sn_opts
);
1647 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
1649 bdrv_unref(bs
[bs_i
]);
1661 static void dump_snapshots(BlockDriverState
*bs
)
1663 QEMUSnapshotInfo
*sn_tab
, *sn
;
1666 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
1669 printf("Snapshot list:\n");
1670 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
1672 for(i
= 0; i
< nb_sns
; i
++) {
1674 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
1680 static void dump_json_image_info_list(ImageInfoList
*list
)
1684 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
1686 visit_type_ImageInfoList(qmp_output_get_visitor(ov
),
1687 &list
, NULL
, &errp
);
1688 obj
= qmp_output_get_qobject(ov
);
1689 str
= qobject_to_json_pretty(obj
);
1690 assert(str
!= NULL
);
1691 printf("%s\n", qstring_get_str(str
));
1692 qobject_decref(obj
);
1693 qmp_output_visitor_cleanup(ov
);
1697 static void dump_json_image_info(ImageInfo
*info
)
1701 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
1703 visit_type_ImageInfo(qmp_output_get_visitor(ov
),
1704 &info
, NULL
, &errp
);
1705 obj
= qmp_output_get_qobject(ov
);
1706 str
= qobject_to_json_pretty(obj
);
1707 assert(str
!= NULL
);
1708 printf("%s\n", qstring_get_str(str
));
1709 qobject_decref(obj
);
1710 qmp_output_visitor_cleanup(ov
);
1714 static void dump_human_image_info_list(ImageInfoList
*list
)
1716 ImageInfoList
*elem
;
1719 for (elem
= list
; elem
; elem
= elem
->next
) {
1725 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
1729 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
1731 return strcmp(a
, b
) == 0;
1735 * Open an image file chain and return an ImageInfoList
1737 * @filename: topmost image filename
1738 * @fmt: topmost image format (may be NULL to autodetect)
1739 * @chain: true - enumerate entire backing file chain
1740 * false - only topmost image file
1742 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1743 * image file. If there was an error a message will have been printed to
1746 static ImageInfoList
*collect_image_info_list(const char *filename
,
1750 ImageInfoList
*head
= NULL
;
1751 ImageInfoList
**last
= &head
;
1752 GHashTable
*filenames
;
1755 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
1758 BlockDriverState
*bs
;
1760 ImageInfoList
*elem
;
1762 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
1763 error_report("Backing file '%s' creates an infinite loop.",
1767 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
1769 bs
= bdrv_new_open(filename
, fmt
, BDRV_O_FLAGS
| BDRV_O_NO_BACKING
,
1775 bdrv_query_image_info(bs
, &info
, &err
);
1777 error_report("%s", error_get_pretty(err
));
1782 elem
= g_new0(ImageInfoList
, 1);
1789 filename
= fmt
= NULL
;
1791 if (info
->has_full_backing_filename
) {
1792 filename
= info
->full_backing_filename
;
1793 } else if (info
->has_backing_filename
) {
1794 filename
= info
->backing_filename
;
1796 if (info
->has_backing_filename_format
) {
1797 fmt
= info
->backing_filename_format
;
1801 g_hash_table_destroy(filenames
);
1805 qapi_free_ImageInfoList(head
);
1806 g_hash_table_destroy(filenames
);
1810 static int img_info(int argc
, char **argv
)
1813 OutputFormat output_format
= OFORMAT_HUMAN
;
1815 const char *filename
, *fmt
, *output
;
1816 ImageInfoList
*list
;
1821 int option_index
= 0;
1822 static const struct option long_options
[] = {
1823 {"help", no_argument
, 0, 'h'},
1824 {"format", required_argument
, 0, 'f'},
1825 {"output", required_argument
, 0, OPTION_OUTPUT
},
1826 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
1829 c
= getopt_long(argc
, argv
, "f:h",
1830 long_options
, &option_index
);
1845 case OPTION_BACKING_CHAIN
:
1850 if (optind
!= argc
- 1) {
1853 filename
= argv
[optind
++];
1855 if (output
&& !strcmp(output
, "json")) {
1856 output_format
= OFORMAT_JSON
;
1857 } else if (output
&& !strcmp(output
, "human")) {
1858 output_format
= OFORMAT_HUMAN
;
1859 } else if (output
) {
1860 error_report("--output must be used with human or json as argument.");
1864 list
= collect_image_info_list(filename
, fmt
, chain
);
1869 switch (output_format
) {
1871 dump_human_image_info_list(list
);
1875 dump_json_image_info_list(list
);
1877 dump_json_image_info(list
->value
);
1882 qapi_free_ImageInfoList(list
);
1887 typedef struct MapEntry
{
1893 BlockDriverState
*bs
;
1896 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
1899 switch (output_format
) {
1901 if ((e
->flags
& BDRV_BLOCK_DATA
) &&
1902 !(e
->flags
& BDRV_BLOCK_OFFSET_VALID
)) {
1903 error_report("File contains external, encrypted or compressed clusters.");
1906 if ((e
->flags
& (BDRV_BLOCK_DATA
|BDRV_BLOCK_ZERO
)) == BDRV_BLOCK_DATA
) {
1907 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
1908 e
->start
, e
->length
, e
->offset
, e
->bs
->filename
);
1910 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
1911 * Modify the flags here to allow more coalescing.
1914 (next
->flags
& (BDRV_BLOCK_DATA
|BDRV_BLOCK_ZERO
)) != BDRV_BLOCK_DATA
) {
1915 next
->flags
&= ~BDRV_BLOCK_DATA
;
1916 next
->flags
|= BDRV_BLOCK_ZERO
;
1920 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
", \"depth\": %d,"
1921 " \"zero\": %s, \"data\": %s",
1922 (e
->start
== 0 ? "[" : ",\n"),
1923 e
->start
, e
->length
, e
->depth
,
1924 (e
->flags
& BDRV_BLOCK_ZERO
) ? "true" : "false",
1925 (e
->flags
& BDRV_BLOCK_DATA
) ? "true" : "false");
1926 if (e
->flags
& BDRV_BLOCK_OFFSET_VALID
) {
1927 printf(", \"offset\": %"PRId64
"", e
->offset
);
1938 static int get_block_status(BlockDriverState
*bs
, int64_t sector_num
,
1939 int nb_sectors
, MapEntry
*e
)
1944 /* As an optimization, we could cache the current range of unallocated
1945 * clusters in each file of the chain, and avoid querying the same
1951 ret
= bdrv_get_block_status(bs
, sector_num
, nb_sectors
, &nb_sectors
);
1956 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
1959 bs
= bs
->backing_hd
;
1968 e
->start
= sector_num
* BDRV_SECTOR_SIZE
;
1969 e
->length
= nb_sectors
* BDRV_SECTOR_SIZE
;
1970 e
->flags
= ret
& ~BDRV_BLOCK_OFFSET_MASK
;
1971 e
->offset
= ret
& BDRV_BLOCK_OFFSET_MASK
;
1977 static int img_map(int argc
, char **argv
)
1980 OutputFormat output_format
= OFORMAT_HUMAN
;
1981 BlockDriverState
*bs
;
1982 const char *filename
, *fmt
, *output
;
1984 MapEntry curr
= { .length
= 0 }, next
;
1990 int option_index
= 0;
1991 static const struct option long_options
[] = {
1992 {"help", no_argument
, 0, 'h'},
1993 {"format", required_argument
, 0, 'f'},
1994 {"output", required_argument
, 0, OPTION_OUTPUT
},
1997 c
= getopt_long(argc
, argv
, "f:h",
1998 long_options
, &option_index
);
2015 if (optind
>= argc
) {
2018 filename
= argv
[optind
++];
2020 if (output
&& !strcmp(output
, "json")) {
2021 output_format
= OFORMAT_JSON
;
2022 } else if (output
&& !strcmp(output
, "human")) {
2023 output_format
= OFORMAT_HUMAN
;
2024 } else if (output
) {
2025 error_report("--output must be used with human or json as argument.");
2029 bs
= bdrv_new_open(filename
, fmt
, BDRV_O_FLAGS
, true, false);
2034 if (output_format
== OFORMAT_HUMAN
) {
2035 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2038 length
= bdrv_getlength(bs
);
2039 while (curr
.start
+ curr
.length
< length
) {
2040 int64_t nsectors_left
;
2044 sector_num
= (curr
.start
+ curr
.length
) >> BDRV_SECTOR_BITS
;
2046 /* Probe up to 1 GiB at a time. */
2047 nsectors_left
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
) - sector_num
;
2048 n
= MIN(1 << (30 - BDRV_SECTOR_BITS
), nsectors_left
);
2049 ret
= get_block_status(bs
, sector_num
, n
, &next
);
2052 error_report("Could not read file metadata: %s", strerror(-ret
));
2056 if (curr
.length
!= 0 && curr
.flags
== next
.flags
&&
2057 curr
.depth
== next
.depth
&&
2058 ((curr
.flags
& BDRV_BLOCK_OFFSET_VALID
) == 0 ||
2059 curr
.offset
+ curr
.length
== next
.offset
)) {
2060 curr
.length
+= next
.length
;
2064 if (curr
.length
> 0) {
2065 dump_map_entry(output_format
, &curr
, &next
);
2070 dump_map_entry(output_format
, &curr
, NULL
);
2077 #define SNAPSHOT_LIST 1
2078 #define SNAPSHOT_CREATE 2
2079 #define SNAPSHOT_APPLY 3
2080 #define SNAPSHOT_DELETE 4
2082 static int img_snapshot(int argc
, char **argv
)
2084 BlockDriverState
*bs
;
2085 QEMUSnapshotInfo sn
;
2086 char *filename
, *snapshot_name
= NULL
;
2087 int c
, ret
= 0, bdrv_oflags
;
2093 bdrv_oflags
= BDRV_O_FLAGS
| BDRV_O_RDWR
;
2094 /* Parse commandline parameters */
2096 c
= getopt(argc
, argv
, "la:c:d:hq");
2110 action
= SNAPSHOT_LIST
;
2111 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
2118 action
= SNAPSHOT_APPLY
;
2119 snapshot_name
= optarg
;
2126 action
= SNAPSHOT_CREATE
;
2127 snapshot_name
= optarg
;
2134 action
= SNAPSHOT_DELETE
;
2135 snapshot_name
= optarg
;
2143 if (optind
!= argc
- 1) {
2146 filename
= argv
[optind
++];
2148 /* Open the image */
2149 bs
= bdrv_new_open(filename
, NULL
, bdrv_oflags
, true, quiet
);
2154 /* Perform the requested action */
2160 case SNAPSHOT_CREATE
:
2161 memset(&sn
, 0, sizeof(sn
));
2162 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
2164 qemu_gettimeofday(&tv
);
2165 sn
.date_sec
= tv
.tv_sec
;
2166 sn
.date_nsec
= tv
.tv_usec
* 1000;
2168 ret
= bdrv_snapshot_create(bs
, &sn
);
2170 error_report("Could not create snapshot '%s': %d (%s)",
2171 snapshot_name
, ret
, strerror(-ret
));
2175 case SNAPSHOT_APPLY
:
2176 ret
= bdrv_snapshot_goto(bs
, snapshot_name
);
2178 error_report("Could not apply snapshot '%s': %d (%s)",
2179 snapshot_name
, ret
, strerror(-ret
));
2183 case SNAPSHOT_DELETE
:
2184 bdrv_snapshot_delete_by_id_or_name(bs
, snapshot_name
, &err
);
2186 error_report("Could not delete snapshot '%s': (%s)",
2187 snapshot_name
, error_get_pretty(err
));
2202 static int img_rebase(int argc
, char **argv
)
2204 BlockDriverState
*bs
, *bs_old_backing
= NULL
, *bs_new_backing
= NULL
;
2205 BlockDriver
*old_backing_drv
, *new_backing_drv
;
2207 const char *fmt
, *cache
, *out_basefmt
, *out_baseimg
;
2212 Error
*local_err
= NULL
;
2214 /* Parse commandline parameters */
2216 cache
= BDRV_DEFAULT_CACHE
;
2220 c
= getopt(argc
, argv
, "uhf:F:b:pt:q");
2233 out_basefmt
= optarg
;
2236 out_baseimg
= optarg
;
2257 if ((optind
!= argc
- 1) || (!unsafe
&& !out_baseimg
)) {
2260 filename
= argv
[optind
++];
2262 qemu_progress_init(progress
, 2.0);
2263 qemu_progress_print(0, 100);
2265 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
2266 ret
= bdrv_parse_cache_flags(cache
, &flags
);
2268 error_report("Invalid cache option: %s", cache
);
2275 * Ignore the old backing file for unsafe rebase in case we want to correct
2276 * the reference to a renamed or moved backing file.
2278 bs
= bdrv_new_open(filename
, fmt
, flags
, true, quiet
);
2283 /* Find the right drivers for the backing files */
2284 old_backing_drv
= NULL
;
2285 new_backing_drv
= NULL
;
2287 if (!unsafe
&& bs
->backing_format
[0] != '\0') {
2288 old_backing_drv
= bdrv_find_format(bs
->backing_format
);
2289 if (old_backing_drv
== NULL
) {
2290 error_report("Invalid format name: '%s'", bs
->backing_format
);
2296 if (out_basefmt
!= NULL
) {
2297 new_backing_drv
= bdrv_find_format(out_basefmt
);
2298 if (new_backing_drv
== NULL
) {
2299 error_report("Invalid format name: '%s'", out_basefmt
);
2305 /* For safe rebasing we need to compare old and new backing file */
2307 /* Make the compiler happy */
2308 bs_old_backing
= NULL
;
2309 bs_new_backing
= NULL
;
2311 char backing_name
[1024];
2313 bs_old_backing
= bdrv_new("old_backing");
2314 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
2315 ret
= bdrv_open(&bs_old_backing
, backing_name
, NULL
, NULL
, BDRV_O_FLAGS
,
2316 old_backing_drv
, &local_err
);
2318 error_report("Could not open old backing file '%s': %s",
2319 backing_name
, error_get_pretty(local_err
));
2320 error_free(local_err
);
2323 if (out_baseimg
[0]) {
2324 bs_new_backing
= bdrv_new("new_backing");
2325 ret
= bdrv_open(&bs_new_backing
, out_baseimg
, NULL
, NULL
,
2326 BDRV_O_FLAGS
, new_backing_drv
, &local_err
);
2328 error_report("Could not open new backing file '%s': %s",
2329 out_baseimg
, error_get_pretty(local_err
));
2330 error_free(local_err
);
2337 * Check each unallocated cluster in the COW file. If it is unallocated,
2338 * accesses go to the backing file. We must therefore compare this cluster
2339 * in the old and new backing file, and if they differ we need to copy it
2340 * from the old backing file into the COW file.
2342 * If qemu-img crashes during this step, no harm is done. The content of
2343 * the image is the same as the original one at any time.
2346 uint64_t num_sectors
;
2347 uint64_t old_backing_num_sectors
;
2348 uint64_t new_backing_num_sectors
= 0;
2353 float local_progress
= 0;
2355 buf_old
= qemu_blockalign(bs
, IO_BUF_SIZE
);
2356 buf_new
= qemu_blockalign(bs
, IO_BUF_SIZE
);
2358 bdrv_get_geometry(bs
, &num_sectors
);
2359 bdrv_get_geometry(bs_old_backing
, &old_backing_num_sectors
);
2360 if (bs_new_backing
) {
2361 bdrv_get_geometry(bs_new_backing
, &new_backing_num_sectors
);
2364 if (num_sectors
!= 0) {
2365 local_progress
= (float)100 /
2366 (num_sectors
/ MIN(num_sectors
, IO_BUF_SIZE
/ 512));
2369 for (sector
= 0; sector
< num_sectors
; sector
+= n
) {
2371 /* How many sectors can we handle with the next read? */
2372 if (sector
+ (IO_BUF_SIZE
/ 512) <= num_sectors
) {
2373 n
= (IO_BUF_SIZE
/ 512);
2375 n
= num_sectors
- sector
;
2378 /* If the cluster is allocated, we don't need to take action */
2379 ret
= bdrv_is_allocated(bs
, sector
, n
, &n
);
2381 error_report("error while reading image metadata: %s",
2390 * Read old and new backing file and take into consideration that
2391 * backing files may be smaller than the COW image.
2393 if (sector
>= old_backing_num_sectors
) {
2394 memset(buf_old
, 0, n
* BDRV_SECTOR_SIZE
);
2396 if (sector
+ n
> old_backing_num_sectors
) {
2397 n
= old_backing_num_sectors
- sector
;
2400 ret
= bdrv_read(bs_old_backing
, sector
, buf_old
, n
);
2402 error_report("error while reading from old backing file");
2407 if (sector
>= new_backing_num_sectors
|| !bs_new_backing
) {
2408 memset(buf_new
, 0, n
* BDRV_SECTOR_SIZE
);
2410 if (sector
+ n
> new_backing_num_sectors
) {
2411 n
= new_backing_num_sectors
- sector
;
2414 ret
= bdrv_read(bs_new_backing
, sector
, buf_new
, n
);
2416 error_report("error while reading from new backing file");
2421 /* If they differ, we need to write to the COW file */
2422 uint64_t written
= 0;
2424 while (written
< n
) {
2427 if (compare_sectors(buf_old
+ written
* 512,
2428 buf_new
+ written
* 512, n
- written
, &pnum
))
2430 ret
= bdrv_write(bs
, sector
+ written
,
2431 buf_old
+ written
* 512, pnum
);
2433 error_report("Error while writing to COW image: %s",
2441 qemu_progress_print(local_progress
, 100);
2444 qemu_vfree(buf_old
);
2445 qemu_vfree(buf_new
);
2449 * Change the backing file. All clusters that are different from the old
2450 * backing file are overwritten in the COW file now, so the visible content
2451 * doesn't change when we switch the backing file.
2453 if (out_baseimg
&& *out_baseimg
) {
2454 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
2456 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
2459 if (ret
== -ENOSPC
) {
2460 error_report("Could not change the backing file to '%s': No "
2461 "space left in the file header", out_baseimg
);
2462 } else if (ret
< 0) {
2463 error_report("Could not change the backing file to '%s': %s",
2464 out_baseimg
, strerror(-ret
));
2467 qemu_progress_print(100, 0);
2469 * TODO At this point it is possible to check if any clusters that are
2470 * allocated in the COW file are the same in the backing file. If so, they
2471 * could be dropped from the COW file. Don't do this before switching the
2472 * backing file, in case of a crash this would lead to corruption.
2475 qemu_progress_end();
2478 if (bs_old_backing
!= NULL
) {
2479 bdrv_unref(bs_old_backing
);
2481 if (bs_new_backing
!= NULL
) {
2482 bdrv_unref(bs_new_backing
);
2493 static int img_resize(int argc
, char **argv
)
2495 int c
, ret
, relative
;
2496 const char *filename
, *fmt
, *size
;
2497 int64_t n
, total_size
;
2499 BlockDriverState
*bs
= NULL
;
2501 static QemuOptsList resize_options
= {
2502 .name
= "resize_options",
2503 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
2506 .name
= BLOCK_OPT_SIZE
,
2507 .type
= QEMU_OPT_SIZE
,
2508 .help
= "Virtual disk size"
2515 /* Remove size from argv manually so that negative numbers are not treated
2516 * as options by getopt. */
2522 size
= argv
[--argc
];
2524 /* Parse getopt arguments */
2527 c
= getopt(argc
, argv
, "f:hq");
2544 if (optind
!= argc
- 1) {
2547 filename
= argv
[optind
++];
2549 /* Choose grow, shrink, or absolute resize mode */
2565 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
2566 if (qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
)) {
2567 /* Error message already printed when size parsing fails */
2569 qemu_opts_del(param
);
2572 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
2573 qemu_opts_del(param
);
2575 bs
= bdrv_new_open(filename
, fmt
, BDRV_O_FLAGS
| BDRV_O_RDWR
, true, quiet
);
2582 total_size
= bdrv_getlength(bs
) + n
* relative
;
2586 if (total_size
<= 0) {
2587 error_report("New image size must be positive");
2592 ret
= bdrv_truncate(bs
, total_size
);
2595 qprintf(quiet
, "Image resized.\n");
2598 error_report("This image does not support resize");
2601 error_report("Image is read-only");
2604 error_report("Error resizing image (%d)", -ret
);
2617 static int img_amend(int argc
, char **argv
)
2620 char *options
= NULL
;
2621 QEMUOptionParameter
*create_options
= NULL
, *options_param
= NULL
;
2622 const char *fmt
= NULL
, *filename
;
2624 BlockDriverState
*bs
= NULL
;
2627 c
= getopt(argc
, argv
, "hqf:o:");
2649 if (optind
!= argc
- 1) {
2657 filename
= argv
[argc
- 1];
2659 bs
= bdrv_new_open(filename
, fmt
, BDRV_O_FLAGS
| BDRV_O_RDWR
, true, quiet
);
2661 error_report("Could not open image '%s'", filename
);
2666 fmt
= bs
->drv
->format_name
;
2668 if (is_help_option(options
)) {
2669 ret
= print_block_option_help(filename
, fmt
);
2673 create_options
= append_option_parameters(create_options
,
2674 bs
->drv
->create_options
);
2675 options_param
= parse_option_parameters(options
, create_options
,
2677 if (options_param
== NULL
) {
2678 error_report("Invalid options for file format '%s'", fmt
);
2683 ret
= bdrv_amend_options(bs
, options_param
);
2685 error_report("Error while amending options: %s", strerror(-ret
));
2693 free_option_parameters(create_options
);
2694 free_option_parameters(options_param
);
2701 static const img_cmd_t img_cmds
[] = {
2702 #define DEF(option, callback, arg_string) \
2703 { option, callback },
2704 #include "qemu-img-cmds.h"
2710 int main(int argc
, char **argv
)
2712 const img_cmd_t
*cmd
;
2713 const char *cmdname
;
2716 signal(SIGPIPE
, SIG_IGN
);
2719 error_set_progname(argv
[0]);
2721 qemu_init_main_loop();
2728 /* find the command */
2729 for(cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
2730 if (!strcmp(cmdname
, cmd
->name
)) {
2731 return cmd
->handler(argc
, argv
);