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 " 'size' is the disk image size in bytes. Optional suffixes\n"
99 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
100 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
101 " supported. 'b' is ignored.\n"
102 " 'output_filename' is the destination disk image filename\n"
103 " 'output_fmt' is the destination format\n"
104 " 'options' is a comma separated list of format specific options in a\n"
105 " name=value format. Use -o ? for an overview of the options supported by the\n"
107 " 'snapshot_param' is param used for internal snapshot, format\n"
108 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
110 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
112 " '-c' indicates that target image must be compressed (qcow format only)\n"
113 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
114 " match exactly. The image doesn't need a working backing file before\n"
115 " rebasing in this case (useful for renaming the backing file)\n"
116 " '-h' with or without a command shows this help and lists the supported formats\n"
117 " '-p' show progress of command (only certain commands)\n"
118 " '-q' use Quiet mode - do not print any output (except errors)\n"
119 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
120 " contain only zeros for qemu-img to create a sparse image during\n"
121 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
122 " unallocated or zero sectors, and the destination image will always be\n"
124 " '--output' takes the format in which the output must be done (human or json)\n"
125 " '-n' skips the target volume creation (useful if the volume is created\n"
126 " prior to running qemu-img)\n"
128 "Parameters to check subcommand:\n"
129 " '-r' tries to repair any inconsistencies that are found during the check.\n"
130 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
131 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
132 " hiding corruption that has already occurred.\n"
134 "Parameters to snapshot subcommand:\n"
135 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
136 " '-a' applies a snapshot (revert disk to saved state)\n"
137 " '-c' creates a snapshot\n"
138 " '-d' deletes a snapshot\n"
139 " '-l' lists all snapshots in the given image\n"
141 "Parameters to compare subcommand:\n"
142 " '-f' first image format\n"
143 " '-F' second image format\n"
144 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
146 printf("%s\nSupported formats:", help_msg
);
147 bdrv_iterate_format(format_print
, NULL
);
152 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
158 ret
= vprintf(fmt
, args
);
165 /* XXX: put correct support for win32 */
166 static int read_password(char *buf
, int buf_size
)
169 printf("Password: ");
176 if (i
< (buf_size
- 1))
187 static struct termios oldtty
;
189 static void term_exit(void)
191 tcsetattr (0, TCSANOW
, &oldtty
);
194 static void term_init(void)
201 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
202 |INLCR
|IGNCR
|ICRNL
|IXON
);
203 tty
.c_oflag
|= OPOST
;
204 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
205 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
210 tcsetattr (0, TCSANOW
, &tty
);
215 static int read_password(char *buf
, int buf_size
)
220 printf("password: ");
225 ret
= read(0, &ch
, 1);
227 if (errno
== EAGAIN
|| errno
== EINTR
) {
233 } else if (ret
== 0) {
241 if (i
< (buf_size
- 1))
252 static int print_block_option_help(const char *filename
, const char *fmt
)
254 BlockDriver
*drv
, *proto_drv
;
255 QEMUOptionParameter
*create_options
= NULL
;
257 /* Find driver and parse its options */
258 drv
= bdrv_find_format(fmt
);
260 error_report("Unknown file format '%s'", fmt
);
264 create_options
= append_option_parameters(create_options
,
265 drv
->create_options
);
268 proto_drv
= bdrv_find_protocol(filename
, true);
270 error_report("Unknown protocol '%s'", filename
);
273 create_options
= append_option_parameters(create_options
,
274 proto_drv
->create_options
);
277 print_option_help(create_options
);
278 free_option_parameters(create_options
);
282 static BlockDriverState
*bdrv_new_open(const char *id
,
283 const char *filename
,
289 BlockDriverState
*bs
;
292 Error
*local_err
= NULL
;
295 bs
= bdrv_new(id
, &error_abort
);
298 drv
= bdrv_find_format(fmt
);
300 error_report("Unknown file format '%s'", fmt
);
307 ret
= bdrv_open(&bs
, filename
, NULL
, NULL
, flags
, drv
, &local_err
);
309 error_report("Could not open '%s': %s", filename
,
310 error_get_pretty(local_err
));
311 error_free(local_err
);
315 if (bdrv_is_encrypted(bs
) && require_io
) {
316 qprintf(quiet
, "Disk image '%s' is encrypted.\n", filename
);
317 if (read_password(password
, sizeof(password
)) < 0) {
318 error_report("No password given");
321 if (bdrv_set_key(bs
, password
) < 0) {
322 error_report("invalid password");
332 static int add_old_style_options(const char *fmt
, QEMUOptionParameter
*list
,
333 const char *base_filename
,
334 const char *base_fmt
)
337 if (set_option_parameter(list
, BLOCK_OPT_BACKING_FILE
, base_filename
)) {
338 error_report("Backing file not supported for file format '%s'",
344 if (set_option_parameter(list
, BLOCK_OPT_BACKING_FMT
, base_fmt
)) {
345 error_report("Backing file format not supported for file "
353 static int img_create(int argc
, char **argv
)
356 uint64_t img_size
= -1;
357 const char *fmt
= "raw";
358 const char *base_fmt
= NULL
;
359 const char *filename
;
360 const char *base_filename
= NULL
;
361 char *options
= NULL
;
362 Error
*local_err
= NULL
;
366 c
= getopt(argc
, argv
, "F:b:f:he6o:q");
379 base_filename
= optarg
;
385 error_report("option -e is deprecated, please use \'-o "
386 "encryption\' instead!");
389 error_report("option -6 is deprecated, please use \'-o "
390 "compat6\' instead!");
393 if (!is_valid_option_list(optarg
)) {
394 error_report("Invalid option list: %s", optarg
);
398 options
= g_strdup(optarg
);
400 char *old_options
= options
;
401 options
= g_strdup_printf("%s,%s", options
, optarg
);
411 /* Get the filename */
412 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
413 if (options
&& has_help_option(options
)) {
415 return print_block_option_help(filename
, fmt
);
418 if (optind
>= argc
) {
419 error_exit("Expecting image file name");
423 /* Get image size, if specified */
427 sval
= strtosz_suffix(argv
[optind
++], &end
, STRTOSZ_DEFSUFFIX_B
);
428 if (sval
< 0 || *end
) {
429 if (sval
== -ERANGE
) {
430 error_report("Image size must be less than 8 EiB!");
432 error_report("Invalid image size specified! You may use k, M, "
433 "G, T, P or E suffixes for ");
434 error_report("kilobytes, megabytes, gigabytes, terabytes, "
435 "petabytes and exabytes.");
439 img_size
= (uint64_t)sval
;
441 if (optind
!= argc
) {
442 error_exit("Unexpected argument: %s", argv
[optind
]);
445 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
446 options
, img_size
, BDRV_O_FLAGS
, &local_err
, quiet
);
448 error_report("%s: %s", filename
, error_get_pretty(local_err
));
449 error_free(local_err
);
461 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
463 Error
*local_err
= NULL
;
465 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
467 visit_type_ImageCheck(qmp_output_get_visitor(ov
),
468 &check
, NULL
, &local_err
);
469 obj
= qmp_output_get_qobject(ov
);
470 str
= qobject_to_json_pretty(obj
);
472 qprintf(quiet
, "%s\n", qstring_get_str(str
));
474 qmp_output_visitor_cleanup(ov
);
478 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
480 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
481 qprintf(quiet
, "No errors were found on the image.\n");
483 if (check
->corruptions
) {
484 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
485 "Data may be corrupted, or further writes to the image "
492 "\n%" PRId64
" leaked clusters were found on the image.\n"
493 "This means waste of disk space, but no harm to data.\n",
497 if (check
->check_errors
) {
500 " internal errors have occurred during the check.\n",
501 check
->check_errors
);
505 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
506 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
507 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
508 check
->allocated_clusters
, check
->total_clusters
,
509 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
510 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
511 check
->compressed_clusters
* 100.0 /
512 check
->allocated_clusters
);
515 if (check
->image_end_offset
) {
517 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
521 static int collect_image_check(BlockDriverState
*bs
,
523 const char *filename
,
528 BdrvCheckResult result
;
530 ret
= bdrv_check(bs
, &result
, fix
);
535 check
->filename
= g_strdup(filename
);
536 check
->format
= g_strdup(bdrv_get_format_name(bs
));
537 check
->check_errors
= result
.check_errors
;
538 check
->corruptions
= result
.corruptions
;
539 check
->has_corruptions
= result
.corruptions
!= 0;
540 check
->leaks
= result
.leaks
;
541 check
->has_leaks
= result
.leaks
!= 0;
542 check
->corruptions_fixed
= result
.corruptions_fixed
;
543 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
544 check
->leaks_fixed
= result
.leaks_fixed
;
545 check
->has_leaks_fixed
= result
.leaks
!= 0;
546 check
->image_end_offset
= result
.image_end_offset
;
547 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
548 check
->total_clusters
= result
.bfi
.total_clusters
;
549 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
550 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
551 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
552 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
553 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
554 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
555 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
561 * Checks an image for consistency. Exit codes:
563 * 0 - Check completed, image is good
564 * 1 - Check not completed because of internal errors
565 * 2 - Check completed, image is corrupted
566 * 3 - Check completed, image has leaked clusters, but is good otherwise
568 static int img_check(int argc
, char **argv
)
571 OutputFormat output_format
= OFORMAT_HUMAN
;
572 const char *filename
, *fmt
, *output
;
573 BlockDriverState
*bs
;
575 int flags
= BDRV_O_FLAGS
| BDRV_O_CHECK
;
582 int option_index
= 0;
583 static const struct option long_options
[] = {
584 {"help", no_argument
, 0, 'h'},
585 {"format", required_argument
, 0, 'f'},
586 {"repair", required_argument
, 0, 'r'},
587 {"output", required_argument
, 0, OPTION_OUTPUT
},
590 c
= getopt_long(argc
, argv
, "f:hr:q",
591 long_options
, &option_index
);
604 flags
|= BDRV_O_RDWR
;
606 if (!strcmp(optarg
, "leaks")) {
607 fix
= BDRV_FIX_LEAKS
;
608 } else if (!strcmp(optarg
, "all")) {
609 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
611 error_exit("Unknown option value for -r "
612 "(expecting 'leaks' or 'all'): %s", optarg
);
623 if (optind
!= argc
- 1) {
624 error_exit("Expecting one image file name");
626 filename
= argv
[optind
++];
628 if (output
&& !strcmp(output
, "json")) {
629 output_format
= OFORMAT_JSON
;
630 } else if (output
&& !strcmp(output
, "human")) {
631 output_format
= OFORMAT_HUMAN
;
633 error_report("--output must be used with human or json as argument.");
637 bs
= bdrv_new_open("image", filename
, fmt
, flags
, true, quiet
);
642 check
= g_new0(ImageCheck
, 1);
643 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
645 if (ret
== -ENOTSUP
) {
646 if (output_format
== OFORMAT_HUMAN
) {
647 error_report("This image format does not support checks");
653 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
654 int corruptions_fixed
, leaks_fixed
;
656 leaks_fixed
= check
->leaks_fixed
;
657 corruptions_fixed
= check
->corruptions_fixed
;
659 if (output_format
== OFORMAT_HUMAN
) {
661 "The following inconsistencies were found and repaired:\n\n"
662 " %" PRId64
" leaked clusters\n"
663 " %" PRId64
" corruptions\n\n"
664 "Double checking the fixed image now...\n",
666 check
->corruptions_fixed
);
669 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
671 check
->leaks_fixed
= leaks_fixed
;
672 check
->corruptions_fixed
= corruptions_fixed
;
675 switch (output_format
) {
677 dump_human_image_check(check
, quiet
);
680 dump_json_image_check(check
, quiet
);
684 if (ret
|| check
->check_errors
) {
689 if (check
->corruptions
) {
691 } else if (check
->leaks
) {
698 qapi_free_ImageCheck(check
);
704 static int img_commit(int argc
, char **argv
)
707 const char *filename
, *fmt
, *cache
;
708 BlockDriverState
*bs
;
712 cache
= BDRV_DEFAULT_CACHE
;
714 c
= getopt(argc
, argv
, "f:ht:q");
734 if (optind
!= argc
- 1) {
735 error_exit("Expecting one image file name");
737 filename
= argv
[optind
++];
740 ret
= bdrv_parse_cache_flags(cache
, &flags
);
742 error_report("Invalid cache option: %s", cache
);
746 bs
= bdrv_new_open("image", filename
, fmt
, flags
, true, quiet
);
750 ret
= bdrv_commit(bs
);
753 qprintf(quiet
, "Image committed.\n");
756 error_report("No disk inserted");
759 error_report("Image is read-only");
762 error_report("Image is already committed");
765 error_report("Error while committing image");
777 * Returns true iff the first sector pointed to by 'buf' contains at least
780 * 'pnum' is set to the number of sectors (including and immediately following
781 * the first one) that are known to be in the same allocated/unallocated state.
783 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
)
792 is_zero
= buffer_is_zero(buf
, 512);
793 for(i
= 1; i
< n
; i
++) {
795 if (is_zero
!= buffer_is_zero(buf
, 512)) {
804 * Like is_allocated_sectors, but if the buffer starts with a used sector,
805 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
806 * breaking up write requests for only small sparse areas.
808 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
812 int num_checked
, num_used
;
818 ret
= is_allocated_sectors(buf
, n
, pnum
);
824 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
826 num_checked
= num_used
;
829 ret
= is_allocated_sectors(buf
, n
, pnum
);
831 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
833 num_checked
+= *pnum
;
835 num_used
= num_checked
;
836 } else if (*pnum
>= min
) {
846 * Compares two buffers sector by sector. Returns 0 if the first sector of both
847 * buffers matches, non-zero otherwise.
849 * pnum is set to the number of sectors (including and immediately following
850 * the first one) that are known to have the same comparison result
852 static int compare_sectors(const uint8_t *buf1
, const uint8_t *buf2
, int n
,
862 res
= !!memcmp(buf1
, buf2
, 512);
863 for(i
= 1; i
< n
; i
++) {
867 if (!!memcmp(buf1
, buf2
, 512) != res
) {
876 #define IO_BUF_SIZE (2 * 1024 * 1024)
878 static int64_t sectors_to_bytes(int64_t sectors
)
880 return sectors
<< BDRV_SECTOR_BITS
;
883 static int64_t sectors_to_process(int64_t total
, int64_t from
)
885 return MIN(total
- from
, IO_BUF_SIZE
>> BDRV_SECTOR_BITS
);
889 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
891 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
892 * data and negative value on error.
894 * @param bs: Driver used for accessing file
895 * @param sect_num: Number of first sector to check
896 * @param sect_count: Number of sectors to check
897 * @param filename: Name of disk file we are checking (logging purpose)
898 * @param buffer: Allocated buffer for storing read data
899 * @param quiet: Flag for quiet mode
901 static int check_empty_sectors(BlockDriverState
*bs
, int64_t sect_num
,
902 int sect_count
, const char *filename
,
903 uint8_t *buffer
, bool quiet
)
906 ret
= bdrv_read(bs
, sect_num
, buffer
, sect_count
);
908 error_report("Error while reading offset %" PRId64
" of %s: %s",
909 sectors_to_bytes(sect_num
), filename
, strerror(-ret
));
912 ret
= is_allocated_sectors(buffer
, sect_count
, &pnum
);
913 if (ret
|| pnum
!= sect_count
) {
914 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
915 sectors_to_bytes(ret
? sect_num
: sect_num
+ pnum
));
923 * Compares two images. Exit codes:
925 * 0 - Images are identical
927 * >1 - Error occurred
929 static int img_compare(int argc
, char **argv
)
931 const char *fmt1
= NULL
, *fmt2
= NULL
, *filename1
, *filename2
;
932 BlockDriverState
*bs1
, *bs2
;
933 int64_t total_sectors1
, total_sectors2
;
934 uint8_t *buf1
= NULL
, *buf2
= NULL
;
936 int allocated1
, allocated2
;
937 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
938 bool progress
= false, quiet
= false, strict
= false;
939 int64_t total_sectors
;
940 int64_t sector_num
= 0;
944 uint64_t progress_base
;
947 c
= getopt(argc
, argv
, "hpf:F:sq");
974 /* Progress is not shown in Quiet mode */
980 if (optind
!= argc
- 2) {
981 error_exit("Expecting two image file names");
983 filename1
= argv
[optind
++];
984 filename2
= argv
[optind
++];
986 /* Initialize before goto out */
987 qemu_progress_init(progress
, 2.0);
989 bs1
= bdrv_new_open("image 1", filename1
, fmt1
, BDRV_O_FLAGS
, true, quiet
);
991 error_report("Can't open file %s", filename1
);
996 bs2
= bdrv_new_open("image 2", filename2
, fmt2
, BDRV_O_FLAGS
, true, quiet
);
998 error_report("Can't open file %s", filename2
);
1003 buf1
= qemu_blockalign(bs1
, IO_BUF_SIZE
);
1004 buf2
= qemu_blockalign(bs2
, IO_BUF_SIZE
);
1005 bdrv_get_geometry(bs1
, &bs_sectors
);
1006 total_sectors1
= bs_sectors
;
1007 bdrv_get_geometry(bs2
, &bs_sectors
);
1008 total_sectors2
= bs_sectors
;
1009 total_sectors
= MIN(total_sectors1
, total_sectors2
);
1010 progress_base
= MAX(total_sectors1
, total_sectors2
);
1012 qemu_progress_print(0, 100);
1014 if (strict
&& total_sectors1
!= total_sectors2
) {
1016 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1021 nb_sectors
= sectors_to_process(total_sectors
, sector_num
);
1022 if (nb_sectors
<= 0) {
1025 allocated1
= bdrv_is_allocated_above(bs1
, NULL
, sector_num
, nb_sectors
,
1027 if (allocated1
< 0) {
1029 error_report("Sector allocation test failed for %s", filename1
);
1033 allocated2
= bdrv_is_allocated_above(bs2
, NULL
, sector_num
, nb_sectors
,
1035 if (allocated2
< 0) {
1037 error_report("Sector allocation test failed for %s", filename2
);
1040 nb_sectors
= MIN(pnum1
, pnum2
);
1042 if (allocated1
== allocated2
) {
1044 ret
= bdrv_read(bs1
, sector_num
, buf1
, nb_sectors
);
1046 error_report("Error while reading offset %" PRId64
" of %s:"
1047 " %s", sectors_to_bytes(sector_num
), filename1
,
1052 ret
= bdrv_read(bs2
, sector_num
, buf2
, nb_sectors
);
1054 error_report("Error while reading offset %" PRId64
1055 " of %s: %s", sectors_to_bytes(sector_num
),
1056 filename2
, strerror(-ret
));
1060 ret
= compare_sectors(buf1
, buf2
, nb_sectors
, &pnum
);
1061 if (ret
|| pnum
!= nb_sectors
) {
1062 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1064 ret
? sector_num
: sector_num
+ pnum
));
1072 qprintf(quiet
, "Strict mode: Offset %" PRId64
1073 " allocation mismatch!\n",
1074 sectors_to_bytes(sector_num
));
1079 ret
= check_empty_sectors(bs1
, sector_num
, nb_sectors
,
1080 filename1
, buf1
, quiet
);
1082 ret
= check_empty_sectors(bs2
, sector_num
, nb_sectors
,
1083 filename2
, buf1
, quiet
);
1087 error_report("Error while reading offset %" PRId64
": %s",
1088 sectors_to_bytes(sector_num
), strerror(-ret
));
1094 sector_num
+= nb_sectors
;
1095 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1098 if (total_sectors1
!= total_sectors2
) {
1099 BlockDriverState
*bs_over
;
1100 int64_t total_sectors_over
;
1101 const char *filename_over
;
1103 qprintf(quiet
, "Warning: Image size mismatch!\n");
1104 if (total_sectors1
> total_sectors2
) {
1105 total_sectors_over
= total_sectors1
;
1107 filename_over
= filename1
;
1109 total_sectors_over
= total_sectors2
;
1111 filename_over
= filename2
;
1115 nb_sectors
= sectors_to_process(total_sectors_over
, sector_num
);
1116 if (nb_sectors
<= 0) {
1119 ret
= bdrv_is_allocated_above(bs_over
, NULL
, sector_num
,
1123 error_report("Sector allocation test failed for %s",
1130 ret
= check_empty_sectors(bs_over
, sector_num
, nb_sectors
,
1131 filename_over
, buf1
, quiet
);
1134 error_report("Error while reading offset %" PRId64
1135 " of %s: %s", sectors_to_bytes(sector_num
),
1136 filename_over
, strerror(-ret
));
1142 sector_num
+= nb_sectors
;
1143 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1147 qprintf(quiet
, "Images are identical.\n");
1157 qemu_progress_end();
1161 static int img_convert(int argc
, char **argv
)
1163 int c
, n
, n1
, bs_n
, bs_i
, compress
, cluster_sectors
, skip_create
;
1165 int progress
= 0, flags
;
1166 const char *fmt
, *out_fmt
, *cache
, *out_baseimg
, *out_filename
;
1167 BlockDriver
*drv
, *proto_drv
;
1168 BlockDriverState
**bs
= NULL
, *out_bs
= NULL
;
1169 int64_t total_sectors
, nb_sectors
, sector_num
, bs_offset
;
1170 uint64_t bs_sectors
;
1171 uint8_t * buf
= NULL
;
1172 size_t bufsectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
;
1173 const uint8_t *buf1
;
1174 BlockDriverInfo bdi
;
1175 QEMUOptionParameter
*param
= NULL
, *create_options
= NULL
;
1176 QEMUOptionParameter
*out_baseimg_param
;
1177 char *options
= NULL
;
1178 const char *snapshot_name
= NULL
;
1179 int min_sparse
= 8; /* Need at least 4k of zeros for sparse detection */
1181 Error
*local_err
= NULL
;
1182 QemuOpts
*sn_opts
= NULL
;
1191 c
= getopt(argc
, argv
, "f:O:B:s:hce6o:pS:t:qnl:");
1207 out_baseimg
= optarg
;
1213 error_report("option -e is deprecated, please use \'-o "
1214 "encryption\' instead!");
1218 error_report("option -6 is deprecated, please use \'-o "
1219 "compat6\' instead!");
1223 if (!is_valid_option_list(optarg
)) {
1224 error_report("Invalid option list: %s", optarg
);
1229 options
= g_strdup(optarg
);
1231 char *old_options
= options
;
1232 options
= g_strdup_printf("%s,%s", options
, optarg
);
1233 g_free(old_options
);
1237 snapshot_name
= optarg
;
1240 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
1241 sn_opts
= qemu_opts_parse(&internal_snapshot_opts
, optarg
, 0);
1243 error_report("Failed in parsing snapshot param '%s'",
1249 snapshot_name
= optarg
;
1256 sval
= strtosz_suffix(optarg
, &end
, STRTOSZ_DEFSUFFIX_B
);
1257 if (sval
< 0 || *end
) {
1258 error_report("Invalid minimum zero buffer size for sparse output specified");
1263 min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
1281 /* Initialize before goto out */
1285 qemu_progress_init(progress
, 1.0);
1288 bs_n
= argc
- optind
- 1;
1289 out_filename
= bs_n
>= 1 ? argv
[argc
- 1] : NULL
;
1291 if (options
&& has_help_option(options
)) {
1292 ret
= print_block_option_help(out_filename
, out_fmt
);
1297 error_exit("Must specify image file name");
1301 if (bs_n
> 1 && out_baseimg
) {
1302 error_report("-B makes no sense when concatenating multiple input "
1308 qemu_progress_print(0, 100);
1310 bs
= g_malloc0(bs_n
* sizeof(BlockDriverState
*));
1313 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
1314 char *id
= bs_n
> 1 ? g_strdup_printf("source %d", bs_i
)
1315 : g_strdup("source");
1316 bs
[bs_i
] = bdrv_new_open(id
, argv
[optind
+ bs_i
], fmt
, BDRV_O_FLAGS
,
1320 error_report("Could not open '%s'", argv
[optind
+ bs_i
]);
1324 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1325 total_sectors
+= bs_sectors
;
1329 ret
= bdrv_snapshot_load_tmp(bs
[0],
1330 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
1331 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
1333 } else if (snapshot_name
!= NULL
) {
1335 error_report("No support for concatenating multiple snapshot");
1340 bdrv_snapshot_load_tmp_by_id_or_name(bs
[0], snapshot_name
, &local_err
);
1343 error_report("Failed to load snapshot: %s",
1344 error_get_pretty(local_err
));
1345 error_free(local_err
);
1350 /* Find driver and parse its options */
1351 drv
= bdrv_find_format(out_fmt
);
1353 error_report("Unknown file format '%s'", out_fmt
);
1358 proto_drv
= bdrv_find_protocol(out_filename
, true);
1360 error_report("Unknown protocol '%s'", out_filename
);
1365 create_options
= append_option_parameters(create_options
,
1366 drv
->create_options
);
1367 create_options
= append_option_parameters(create_options
,
1368 proto_drv
->create_options
);
1371 param
= parse_option_parameters(options
, create_options
, param
);
1372 if (param
== NULL
) {
1373 error_report("Invalid options for file format '%s'.", out_fmt
);
1378 param
= parse_option_parameters("", create_options
, param
);
1381 set_option_parameter_int(param
, BLOCK_OPT_SIZE
, total_sectors
* 512);
1382 ret
= add_old_style_options(out_fmt
, param
, out_baseimg
, NULL
);
1387 /* Get backing file name if -o backing_file was used */
1388 out_baseimg_param
= get_option_parameter(param
, BLOCK_OPT_BACKING_FILE
);
1389 if (out_baseimg_param
) {
1390 out_baseimg
= out_baseimg_param
->value
.s
;
1393 /* Check if compression is supported */
1395 QEMUOptionParameter
*encryption
=
1396 get_option_parameter(param
, BLOCK_OPT_ENCRYPT
);
1397 QEMUOptionParameter
*preallocation
=
1398 get_option_parameter(param
, BLOCK_OPT_PREALLOC
);
1400 if (!drv
->bdrv_write_compressed
) {
1401 error_report("Compression not supported for this file format");
1406 if (encryption
&& encryption
->value
.n
) {
1407 error_report("Compression and encryption not supported at "
1413 if (preallocation
&& preallocation
->value
.s
1414 && strcmp(preallocation
->value
.s
, "off"))
1416 error_report("Compression and preallocation not supported at "
1424 /* Create the new image */
1425 ret
= bdrv_create(drv
, out_filename
, param
, &local_err
);
1427 error_report("%s: error while converting %s: %s",
1428 out_filename
, out_fmt
, error_get_pretty(local_err
));
1429 error_free(local_err
);
1434 flags
= min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
1435 ret
= bdrv_parse_cache_flags(cache
, &flags
);
1437 error_report("Invalid cache option: %s", cache
);
1441 out_bs
= bdrv_new_open("target", out_filename
, out_fmt
, flags
, true, quiet
);
1449 bdrv_get_geometry(bs
[0], &bs_sectors
);
1451 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
1452 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
1454 bufsectors
= MIN(32768,
1455 MAX(bufsectors
, MAX(out_bs
->bl
.opt_transfer_length
,
1456 out_bs
->bl
.discard_alignment
))
1459 buf
= qemu_blockalign(out_bs
, bufsectors
* BDRV_SECTOR_SIZE
);
1462 int64_t output_length
= bdrv_getlength(out_bs
);
1463 if (output_length
< 0) {
1464 error_report("unable to get output image length: %s\n",
1465 strerror(-output_length
));
1468 } else if (output_length
< total_sectors
<< BDRV_SECTOR_BITS
) {
1469 error_report("output file is smaller than input file");
1475 cluster_sectors
= 0;
1476 ret
= bdrv_get_info(out_bs
, &bdi
);
1479 error_report("could not get block driver info");
1483 cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
1487 if (cluster_sectors
<= 0 || cluster_sectors
> bufsectors
) {
1488 error_report("invalid cluster size");
1494 nb_sectors
= total_sectors
;
1501 nb_sectors
= total_sectors
- sector_num
;
1502 if (nb_sectors
<= 0)
1504 if (nb_sectors
>= cluster_sectors
)
1505 n
= cluster_sectors
;
1509 bs_num
= sector_num
- bs_offset
;
1510 assert (bs_num
>= 0);
1513 while (remainder
> 0) {
1515 while (bs_num
== bs_sectors
) {
1517 assert (bs_i
< bs_n
);
1518 bs_offset
+= bs_sectors
;
1519 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1521 /* printf("changing part: sector_num=%" PRId64 ", "
1522 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
1523 "\n", sector_num, bs_i, bs_offset, bs_sectors); */
1525 assert (bs_num
< bs_sectors
);
1527 nlow
= (remainder
> bs_sectors
- bs_num
) ? bs_sectors
- bs_num
: remainder
;
1529 ret
= bdrv_read(bs
[bs_i
], bs_num
, buf2
, nlow
);
1531 error_report("error while reading sector %" PRId64
": %s",
1532 bs_num
, strerror(-ret
));
1541 assert (remainder
== 0);
1543 if (!buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)) {
1544 ret
= bdrv_write_compressed(out_bs
, sector_num
, buf
, n
);
1546 error_report("error while compressing sector %" PRId64
1547 ": %s", sector_num
, strerror(-ret
));
1552 qemu_progress_print(100.0 * sector_num
/ total_sectors
, 0);
1554 /* signal EOF to align */
1555 bdrv_write_compressed(out_bs
, 0, NULL
, 0);
1557 int64_t sectors_to_read
, sectors_read
, sector_num_next_status
;
1558 bool count_allocated_sectors
;
1559 int has_zero_init
= min_sparse
? bdrv_has_zero_init(out_bs
) : 0;
1561 if (!has_zero_init
&& bdrv_can_write_zeroes_with_unmap(out_bs
)) {
1562 ret
= bdrv_make_zero(out_bs
, BDRV_REQ_MAY_UNMAP
);
1569 sectors_to_read
= total_sectors
;
1570 count_allocated_sectors
= progress
&& (out_baseimg
|| has_zero_init
);
1572 sector_num
= 0; // total number of sectors converted so far
1574 sector_num_next_status
= 0;
1577 nb_sectors
= total_sectors
- sector_num
;
1578 if (nb_sectors
<= 0) {
1579 if (count_allocated_sectors
) {
1580 sectors_to_read
= sectors_read
;
1581 count_allocated_sectors
= false;
1588 while (sector_num
- bs_offset
>= bs_sectors
) {
1590 assert (bs_i
< bs_n
);
1591 bs_offset
+= bs_sectors
;
1592 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1593 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1594 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
1595 sector_num, bs_i, bs_offset, bs_sectors); */
1598 if ((out_baseimg
|| has_zero_init
) &&
1599 sector_num
>= sector_num_next_status
) {
1600 n
= nb_sectors
> INT_MAX
? INT_MAX
: nb_sectors
;
1601 ret
= bdrv_get_block_status(bs
[bs_i
], sector_num
- bs_offset
,
1604 error_report("error while reading block status of sector %"
1605 PRId64
": %s", sector_num
- bs_offset
,
1609 /* If the output image is zero initialized, we are not working
1610 * on a shared base and the input is zero we can skip the next
1612 if (has_zero_init
&& !out_baseimg
&& (ret
& BDRV_BLOCK_ZERO
)) {
1616 /* If the output image is being created as a copy on write
1617 * image, assume that sectors which are unallocated in the
1618 * input image are present in both the output's and input's
1619 * base images (no need to copy them). */
1621 if (!(ret
& BDRV_BLOCK_DATA
)) {
1625 /* The next 'n1' sectors are allocated in the input image.
1626 * Copy only those as they may be followed by unallocated
1630 /* avoid redundant callouts to get_block_status */
1631 sector_num_next_status
= sector_num
+ n1
;
1634 n
= MIN(nb_sectors
, bufsectors
);
1636 /* round down request length to an aligned sector, but
1637 * do not bother doing this on short requests. They happen
1638 * when we found an all-zero area, and the next sector to
1639 * write will not be sector_num + n. */
1640 if (cluster_sectors
> 0 && n
>= cluster_sectors
) {
1641 int64_t next_aligned_sector
= (sector_num
+ n
);
1642 next_aligned_sector
-= next_aligned_sector
% cluster_sectors
;
1643 if (sector_num
+ n
> next_aligned_sector
) {
1644 n
= next_aligned_sector
- sector_num
;
1648 n
= MIN(n
, bs_sectors
- (sector_num
- bs_offset
));
1651 if (count_allocated_sectors
) {
1657 ret
= bdrv_read(bs
[bs_i
], sector_num
- bs_offset
, buf
, n
);
1659 error_report("error while reading sector %" PRId64
": %s",
1660 sector_num
- bs_offset
, strerror(-ret
));
1663 /* NOTE: at the same time we convert, we do not write zero
1664 sectors to have a chance to compress the image. Ideally, we
1665 should add a specific call to have the info to go faster */
1668 if (!has_zero_init
||
1669 is_allocated_sectors_min(buf1
, n
, &n1
, min_sparse
)) {
1670 ret
= bdrv_write(out_bs
, sector_num
, buf1
, n1
);
1672 error_report("error while writing sector %" PRId64
1673 ": %s", sector_num
, strerror(-ret
));
1681 qemu_progress_print(100.0 * sectors_read
/ sectors_to_read
, 0);
1686 qemu_progress_print(100, 0);
1688 qemu_progress_end();
1689 free_option_parameters(create_options
);
1690 free_option_parameters(param
);
1693 qemu_opts_del(sn_opts
);
1699 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
1701 bdrv_unref(bs
[bs_i
]);
1716 static void dump_snapshots(BlockDriverState
*bs
)
1718 QEMUSnapshotInfo
*sn_tab
, *sn
;
1721 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
1724 printf("Snapshot list:\n");
1725 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
1727 for(i
= 0; i
< nb_sns
; i
++) {
1729 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
1735 static void dump_json_image_info_list(ImageInfoList
*list
)
1737 Error
*local_err
= NULL
;
1739 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
1741 visit_type_ImageInfoList(qmp_output_get_visitor(ov
),
1742 &list
, NULL
, &local_err
);
1743 obj
= qmp_output_get_qobject(ov
);
1744 str
= qobject_to_json_pretty(obj
);
1745 assert(str
!= NULL
);
1746 printf("%s\n", qstring_get_str(str
));
1747 qobject_decref(obj
);
1748 qmp_output_visitor_cleanup(ov
);
1752 static void dump_json_image_info(ImageInfo
*info
)
1754 Error
*local_err
= NULL
;
1756 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
1758 visit_type_ImageInfo(qmp_output_get_visitor(ov
),
1759 &info
, NULL
, &local_err
);
1760 obj
= qmp_output_get_qobject(ov
);
1761 str
= qobject_to_json_pretty(obj
);
1762 assert(str
!= NULL
);
1763 printf("%s\n", qstring_get_str(str
));
1764 qobject_decref(obj
);
1765 qmp_output_visitor_cleanup(ov
);
1769 static void dump_human_image_info_list(ImageInfoList
*list
)
1771 ImageInfoList
*elem
;
1774 for (elem
= list
; elem
; elem
= elem
->next
) {
1780 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
1784 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
1786 return strcmp(a
, b
) == 0;
1790 * Open an image file chain and return an ImageInfoList
1792 * @filename: topmost image filename
1793 * @fmt: topmost image format (may be NULL to autodetect)
1794 * @chain: true - enumerate entire backing file chain
1795 * false - only topmost image file
1797 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1798 * image file. If there was an error a message will have been printed to
1801 static ImageInfoList
*collect_image_info_list(const char *filename
,
1805 ImageInfoList
*head
= NULL
;
1806 ImageInfoList
**last
= &head
;
1807 GHashTable
*filenames
;
1810 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
1813 BlockDriverState
*bs
;
1815 ImageInfoList
*elem
;
1817 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
1818 error_report("Backing file '%s' creates an infinite loop.",
1822 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
1824 bs
= bdrv_new_open("image", filename
, fmt
,
1825 BDRV_O_FLAGS
| BDRV_O_NO_BACKING
, false, false);
1830 bdrv_query_image_info(bs
, &info
, &err
);
1832 error_report("%s", error_get_pretty(err
));
1838 elem
= g_new0(ImageInfoList
, 1);
1845 filename
= fmt
= NULL
;
1847 if (info
->has_full_backing_filename
) {
1848 filename
= info
->full_backing_filename
;
1849 } else if (info
->has_backing_filename
) {
1850 filename
= info
->backing_filename
;
1852 if (info
->has_backing_filename_format
) {
1853 fmt
= info
->backing_filename_format
;
1857 g_hash_table_destroy(filenames
);
1861 qapi_free_ImageInfoList(head
);
1862 g_hash_table_destroy(filenames
);
1866 static int img_info(int argc
, char **argv
)
1869 OutputFormat output_format
= OFORMAT_HUMAN
;
1871 const char *filename
, *fmt
, *output
;
1872 ImageInfoList
*list
;
1877 int option_index
= 0;
1878 static const struct option long_options
[] = {
1879 {"help", no_argument
, 0, 'h'},
1880 {"format", required_argument
, 0, 'f'},
1881 {"output", required_argument
, 0, OPTION_OUTPUT
},
1882 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
1885 c
= getopt_long(argc
, argv
, "f:h",
1886 long_options
, &option_index
);
1901 case OPTION_BACKING_CHAIN
:
1906 if (optind
!= argc
- 1) {
1907 error_exit("Expecting one image file name");
1909 filename
= argv
[optind
++];
1911 if (output
&& !strcmp(output
, "json")) {
1912 output_format
= OFORMAT_JSON
;
1913 } else if (output
&& !strcmp(output
, "human")) {
1914 output_format
= OFORMAT_HUMAN
;
1915 } else if (output
) {
1916 error_report("--output must be used with human or json as argument.");
1920 list
= collect_image_info_list(filename
, fmt
, chain
);
1925 switch (output_format
) {
1927 dump_human_image_info_list(list
);
1931 dump_json_image_info_list(list
);
1933 dump_json_image_info(list
->value
);
1938 qapi_free_ImageInfoList(list
);
1943 typedef struct MapEntry
{
1949 BlockDriverState
*bs
;
1952 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
1955 switch (output_format
) {
1957 if ((e
->flags
& BDRV_BLOCK_DATA
) &&
1958 !(e
->flags
& BDRV_BLOCK_OFFSET_VALID
)) {
1959 error_report("File contains external, encrypted or compressed clusters.");
1962 if ((e
->flags
& (BDRV_BLOCK_DATA
|BDRV_BLOCK_ZERO
)) == BDRV_BLOCK_DATA
) {
1963 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
1964 e
->start
, e
->length
, e
->offset
, e
->bs
->filename
);
1966 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
1967 * Modify the flags here to allow more coalescing.
1970 (next
->flags
& (BDRV_BLOCK_DATA
|BDRV_BLOCK_ZERO
)) != BDRV_BLOCK_DATA
) {
1971 next
->flags
&= ~BDRV_BLOCK_DATA
;
1972 next
->flags
|= BDRV_BLOCK_ZERO
;
1976 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
", \"depth\": %d,"
1977 " \"zero\": %s, \"data\": %s",
1978 (e
->start
== 0 ? "[" : ",\n"),
1979 e
->start
, e
->length
, e
->depth
,
1980 (e
->flags
& BDRV_BLOCK_ZERO
) ? "true" : "false",
1981 (e
->flags
& BDRV_BLOCK_DATA
) ? "true" : "false");
1982 if (e
->flags
& BDRV_BLOCK_OFFSET_VALID
) {
1983 printf(", \"offset\": %"PRId64
"", e
->offset
);
1994 static int get_block_status(BlockDriverState
*bs
, int64_t sector_num
,
1995 int nb_sectors
, MapEntry
*e
)
2000 /* As an optimization, we could cache the current range of unallocated
2001 * clusters in each file of the chain, and avoid querying the same
2007 ret
= bdrv_get_block_status(bs
, sector_num
, nb_sectors
, &nb_sectors
);
2012 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2015 bs
= bs
->backing_hd
;
2024 e
->start
= sector_num
* BDRV_SECTOR_SIZE
;
2025 e
->length
= nb_sectors
* BDRV_SECTOR_SIZE
;
2026 e
->flags
= ret
& ~BDRV_BLOCK_OFFSET_MASK
;
2027 e
->offset
= ret
& BDRV_BLOCK_OFFSET_MASK
;
2033 static int img_map(int argc
, char **argv
)
2036 OutputFormat output_format
= OFORMAT_HUMAN
;
2037 BlockDriverState
*bs
;
2038 const char *filename
, *fmt
, *output
;
2040 MapEntry curr
= { .length
= 0 }, next
;
2046 int option_index
= 0;
2047 static const struct option long_options
[] = {
2048 {"help", no_argument
, 0, 'h'},
2049 {"format", required_argument
, 0, 'f'},
2050 {"output", required_argument
, 0, OPTION_OUTPUT
},
2053 c
= getopt_long(argc
, argv
, "f:h",
2054 long_options
, &option_index
);
2071 if (optind
!= argc
- 1) {
2072 error_exit("Expecting one image file name");
2074 filename
= argv
[optind
];
2076 if (output
&& !strcmp(output
, "json")) {
2077 output_format
= OFORMAT_JSON
;
2078 } else if (output
&& !strcmp(output
, "human")) {
2079 output_format
= OFORMAT_HUMAN
;
2080 } else if (output
) {
2081 error_report("--output must be used with human or json as argument.");
2085 bs
= bdrv_new_open("image", filename
, fmt
, BDRV_O_FLAGS
, true, false);
2090 if (output_format
== OFORMAT_HUMAN
) {
2091 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2094 length
= bdrv_getlength(bs
);
2095 while (curr
.start
+ curr
.length
< length
) {
2096 int64_t nsectors_left
;
2100 sector_num
= (curr
.start
+ curr
.length
) >> BDRV_SECTOR_BITS
;
2102 /* Probe up to 1 GiB at a time. */
2103 nsectors_left
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
) - sector_num
;
2104 n
= MIN(1 << (30 - BDRV_SECTOR_BITS
), nsectors_left
);
2105 ret
= get_block_status(bs
, sector_num
, n
, &next
);
2108 error_report("Could not read file metadata: %s", strerror(-ret
));
2112 if (curr
.length
!= 0 && curr
.flags
== next
.flags
&&
2113 curr
.depth
== next
.depth
&&
2114 ((curr
.flags
& BDRV_BLOCK_OFFSET_VALID
) == 0 ||
2115 curr
.offset
+ curr
.length
== next
.offset
)) {
2116 curr
.length
+= next
.length
;
2120 if (curr
.length
> 0) {
2121 dump_map_entry(output_format
, &curr
, &next
);
2126 dump_map_entry(output_format
, &curr
, NULL
);
2133 #define SNAPSHOT_LIST 1
2134 #define SNAPSHOT_CREATE 2
2135 #define SNAPSHOT_APPLY 3
2136 #define SNAPSHOT_DELETE 4
2138 static int img_snapshot(int argc
, char **argv
)
2140 BlockDriverState
*bs
;
2141 QEMUSnapshotInfo sn
;
2142 char *filename
, *snapshot_name
= NULL
;
2143 int c
, ret
= 0, bdrv_oflags
;
2149 bdrv_oflags
= BDRV_O_FLAGS
| BDRV_O_RDWR
;
2150 /* Parse commandline parameters */
2152 c
= getopt(argc
, argv
, "la:c:d:hq");
2163 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2166 action
= SNAPSHOT_LIST
;
2167 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
2171 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2174 action
= SNAPSHOT_APPLY
;
2175 snapshot_name
= optarg
;
2179 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2182 action
= SNAPSHOT_CREATE
;
2183 snapshot_name
= optarg
;
2187 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2190 action
= SNAPSHOT_DELETE
;
2191 snapshot_name
= optarg
;
2199 if (optind
!= argc
- 1) {
2200 error_exit("Expecting one image file name");
2202 filename
= argv
[optind
++];
2204 /* Open the image */
2205 bs
= bdrv_new_open("image", filename
, NULL
, bdrv_oflags
, true, quiet
);
2210 /* Perform the requested action */
2216 case SNAPSHOT_CREATE
:
2217 memset(&sn
, 0, sizeof(sn
));
2218 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
2220 qemu_gettimeofday(&tv
);
2221 sn
.date_sec
= tv
.tv_sec
;
2222 sn
.date_nsec
= tv
.tv_usec
* 1000;
2224 ret
= bdrv_snapshot_create(bs
, &sn
);
2226 error_report("Could not create snapshot '%s': %d (%s)",
2227 snapshot_name
, ret
, strerror(-ret
));
2231 case SNAPSHOT_APPLY
:
2232 ret
= bdrv_snapshot_goto(bs
, snapshot_name
);
2234 error_report("Could not apply snapshot '%s': %d (%s)",
2235 snapshot_name
, ret
, strerror(-ret
));
2239 case SNAPSHOT_DELETE
:
2240 bdrv_snapshot_delete_by_id_or_name(bs
, snapshot_name
, &err
);
2242 error_report("Could not delete snapshot '%s': (%s)",
2243 snapshot_name
, error_get_pretty(err
));
2258 static int img_rebase(int argc
, char **argv
)
2260 BlockDriverState
*bs
, *bs_old_backing
= NULL
, *bs_new_backing
= NULL
;
2261 BlockDriver
*old_backing_drv
, *new_backing_drv
;
2263 const char *fmt
, *cache
, *out_basefmt
, *out_baseimg
;
2268 Error
*local_err
= NULL
;
2270 /* Parse commandline parameters */
2272 cache
= BDRV_DEFAULT_CACHE
;
2276 c
= getopt(argc
, argv
, "uhf:F:b:pt:q");
2289 out_basefmt
= optarg
;
2292 out_baseimg
= optarg
;
2313 if (optind
!= argc
- 1) {
2314 error_exit("Expecting one image file name");
2316 if (!unsafe
&& !out_baseimg
) {
2317 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
2319 filename
= argv
[optind
++];
2321 qemu_progress_init(progress
, 2.0);
2322 qemu_progress_print(0, 100);
2324 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
2325 ret
= bdrv_parse_cache_flags(cache
, &flags
);
2327 error_report("Invalid cache option: %s", cache
);
2334 * Ignore the old backing file for unsafe rebase in case we want to correct
2335 * the reference to a renamed or moved backing file.
2337 bs
= bdrv_new_open("image", filename
, fmt
, flags
, true, quiet
);
2342 /* Find the right drivers for the backing files */
2343 old_backing_drv
= NULL
;
2344 new_backing_drv
= NULL
;
2346 if (!unsafe
&& bs
->backing_format
[0] != '\0') {
2347 old_backing_drv
= bdrv_find_format(bs
->backing_format
);
2348 if (old_backing_drv
== NULL
) {
2349 error_report("Invalid format name: '%s'", bs
->backing_format
);
2355 if (out_basefmt
!= NULL
) {
2356 new_backing_drv
= bdrv_find_format(out_basefmt
);
2357 if (new_backing_drv
== NULL
) {
2358 error_report("Invalid format name: '%s'", out_basefmt
);
2364 /* For safe rebasing we need to compare old and new backing file */
2366 /* Make the compiler happy */
2367 bs_old_backing
= NULL
;
2368 bs_new_backing
= NULL
;
2370 char backing_name
[1024];
2372 bs_old_backing
= bdrv_new("old_backing", &error_abort
);
2373 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
2374 ret
= bdrv_open(&bs_old_backing
, backing_name
, NULL
, NULL
, BDRV_O_FLAGS
,
2375 old_backing_drv
, &local_err
);
2377 error_report("Could not open old backing file '%s': %s",
2378 backing_name
, error_get_pretty(local_err
));
2379 error_free(local_err
);
2382 if (out_baseimg
[0]) {
2383 bs_new_backing
= bdrv_new("new_backing", &error_abort
);
2384 ret
= bdrv_open(&bs_new_backing
, out_baseimg
, NULL
, NULL
,
2385 BDRV_O_FLAGS
, new_backing_drv
, &local_err
);
2387 error_report("Could not open new backing file '%s': %s",
2388 out_baseimg
, error_get_pretty(local_err
));
2389 error_free(local_err
);
2396 * Check each unallocated cluster in the COW file. If it is unallocated,
2397 * accesses go to the backing file. We must therefore compare this cluster
2398 * in the old and new backing file, and if they differ we need to copy it
2399 * from the old backing file into the COW file.
2401 * If qemu-img crashes during this step, no harm is done. The content of
2402 * the image is the same as the original one at any time.
2405 uint64_t num_sectors
;
2406 uint64_t old_backing_num_sectors
;
2407 uint64_t new_backing_num_sectors
= 0;
2412 float local_progress
= 0;
2414 buf_old
= qemu_blockalign(bs
, IO_BUF_SIZE
);
2415 buf_new
= qemu_blockalign(bs
, IO_BUF_SIZE
);
2417 bdrv_get_geometry(bs
, &num_sectors
);
2418 bdrv_get_geometry(bs_old_backing
, &old_backing_num_sectors
);
2419 if (bs_new_backing
) {
2420 bdrv_get_geometry(bs_new_backing
, &new_backing_num_sectors
);
2423 if (num_sectors
!= 0) {
2424 local_progress
= (float)100 /
2425 (num_sectors
/ MIN(num_sectors
, IO_BUF_SIZE
/ 512));
2428 for (sector
= 0; sector
< num_sectors
; sector
+= n
) {
2430 /* How many sectors can we handle with the next read? */
2431 if (sector
+ (IO_BUF_SIZE
/ 512) <= num_sectors
) {
2432 n
= (IO_BUF_SIZE
/ 512);
2434 n
= num_sectors
- sector
;
2437 /* If the cluster is allocated, we don't need to take action */
2438 ret
= bdrv_is_allocated(bs
, sector
, n
, &n
);
2440 error_report("error while reading image metadata: %s",
2449 * Read old and new backing file and take into consideration that
2450 * backing files may be smaller than the COW image.
2452 if (sector
>= old_backing_num_sectors
) {
2453 memset(buf_old
, 0, n
* BDRV_SECTOR_SIZE
);
2455 if (sector
+ n
> old_backing_num_sectors
) {
2456 n
= old_backing_num_sectors
- sector
;
2459 ret
= bdrv_read(bs_old_backing
, sector
, buf_old
, n
);
2461 error_report("error while reading from old backing file");
2466 if (sector
>= new_backing_num_sectors
|| !bs_new_backing
) {
2467 memset(buf_new
, 0, n
* BDRV_SECTOR_SIZE
);
2469 if (sector
+ n
> new_backing_num_sectors
) {
2470 n
= new_backing_num_sectors
- sector
;
2473 ret
= bdrv_read(bs_new_backing
, sector
, buf_new
, n
);
2475 error_report("error while reading from new backing file");
2480 /* If they differ, we need to write to the COW file */
2481 uint64_t written
= 0;
2483 while (written
< n
) {
2486 if (compare_sectors(buf_old
+ written
* 512,
2487 buf_new
+ written
* 512, n
- written
, &pnum
))
2489 ret
= bdrv_write(bs
, sector
+ written
,
2490 buf_old
+ written
* 512, pnum
);
2492 error_report("Error while writing to COW image: %s",
2500 qemu_progress_print(local_progress
, 100);
2503 qemu_vfree(buf_old
);
2504 qemu_vfree(buf_new
);
2508 * Change the backing file. All clusters that are different from the old
2509 * backing file are overwritten in the COW file now, so the visible content
2510 * doesn't change when we switch the backing file.
2512 if (out_baseimg
&& *out_baseimg
) {
2513 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
2515 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
2518 if (ret
== -ENOSPC
) {
2519 error_report("Could not change the backing file to '%s': No "
2520 "space left in the file header", out_baseimg
);
2521 } else if (ret
< 0) {
2522 error_report("Could not change the backing file to '%s': %s",
2523 out_baseimg
, strerror(-ret
));
2526 qemu_progress_print(100, 0);
2528 * TODO At this point it is possible to check if any clusters that are
2529 * allocated in the COW file are the same in the backing file. If so, they
2530 * could be dropped from the COW file. Don't do this before switching the
2531 * backing file, in case of a crash this would lead to corruption.
2534 qemu_progress_end();
2537 if (bs_old_backing
!= NULL
) {
2538 bdrv_unref(bs_old_backing
);
2540 if (bs_new_backing
!= NULL
) {
2541 bdrv_unref(bs_new_backing
);
2552 static int img_resize(int argc
, char **argv
)
2554 int c
, ret
, relative
;
2555 const char *filename
, *fmt
, *size
;
2556 int64_t n
, total_size
;
2558 BlockDriverState
*bs
= NULL
;
2560 static QemuOptsList resize_options
= {
2561 .name
= "resize_options",
2562 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
2565 .name
= BLOCK_OPT_SIZE
,
2566 .type
= QEMU_OPT_SIZE
,
2567 .help
= "Virtual disk size"
2574 /* Remove size from argv manually so that negative numbers are not treated
2575 * as options by getopt. */
2577 error_exit("Not enough arguments");
2581 size
= argv
[--argc
];
2583 /* Parse getopt arguments */
2586 c
= getopt(argc
, argv
, "f:hq");
2603 if (optind
!= argc
- 1) {
2604 error_exit("Expecting one image file name");
2606 filename
= argv
[optind
++];
2608 /* Choose grow, shrink, or absolute resize mode */
2624 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
2625 if (qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
)) {
2626 /* Error message already printed when size parsing fails */
2628 qemu_opts_del(param
);
2631 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
2632 qemu_opts_del(param
);
2634 bs
= bdrv_new_open("image", filename
, fmt
, BDRV_O_FLAGS
| BDRV_O_RDWR
,
2642 total_size
= bdrv_getlength(bs
) + n
* relative
;
2646 if (total_size
<= 0) {
2647 error_report("New image size must be positive");
2652 ret
= bdrv_truncate(bs
, total_size
);
2655 qprintf(quiet
, "Image resized.\n");
2658 error_report("This image does not support resize");
2661 error_report("Image is read-only");
2664 error_report("Error resizing image (%d)", -ret
);
2677 static int img_amend(int argc
, char **argv
)
2680 char *options
= NULL
;
2681 QEMUOptionParameter
*create_options
= NULL
, *options_param
= NULL
;
2682 const char *fmt
= NULL
, *filename
;
2684 BlockDriverState
*bs
= NULL
;
2687 c
= getopt(argc
, argv
, "hqf:o:");
2698 if (!is_valid_option_list(optarg
)) {
2699 error_report("Invalid option list: %s", optarg
);
2704 options
= g_strdup(optarg
);
2706 char *old_options
= options
;
2707 options
= g_strdup_printf("%s,%s", options
, optarg
);
2708 g_free(old_options
);
2721 error_exit("Must specify options (-o)");
2724 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
2725 if (fmt
&& has_help_option(options
)) {
2726 /* If a format is explicitly specified (and possibly no filename is
2727 * given), print option help here */
2728 ret
= print_block_option_help(filename
, fmt
);
2732 if (optind
!= argc
- 1) {
2733 error_exit("Expecting one image file name");
2736 bs
= bdrv_new_open("image", filename
, fmt
,
2737 BDRV_O_FLAGS
| BDRV_O_RDWR
, true, quiet
);
2739 error_report("Could not open image '%s'", filename
);
2744 fmt
= bs
->drv
->format_name
;
2746 if (has_help_option(options
)) {
2747 /* If the format was auto-detected, print option help here */
2748 ret
= print_block_option_help(filename
, fmt
);
2752 create_options
= append_option_parameters(create_options
,
2753 bs
->drv
->create_options
);
2754 options_param
= parse_option_parameters(options
, create_options
,
2756 if (options_param
== NULL
) {
2757 error_report("Invalid options for file format '%s'", fmt
);
2762 ret
= bdrv_amend_options(bs
, options_param
);
2764 error_report("Error while amending options: %s", strerror(-ret
));
2772 free_option_parameters(create_options
);
2773 free_option_parameters(options_param
);
2782 static const img_cmd_t img_cmds
[] = {
2783 #define DEF(option, callback, arg_string) \
2784 { option, callback },
2785 #include "qemu-img-cmds.h"
2791 int main(int argc
, char **argv
)
2793 const img_cmd_t
*cmd
;
2794 const char *cmdname
;
2796 static const struct option long_options
[] = {
2797 {"help", no_argument
, 0, 'h'},
2798 {"version", no_argument
, 0, 'v'},
2803 signal(SIGPIPE
, SIG_IGN
);
2806 error_set_progname(argv
[0]);
2807 qemu_init_exec_dir(argv
[0]);
2809 qemu_init_main_loop();
2812 error_exit("Not enough arguments");
2816 /* find the command */
2817 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
2818 if (!strcmp(cmdname
, cmd
->name
)) {
2819 return cmd
->handler(argc
- 1, argv
+ 1);
2823 c
= getopt_long(argc
, argv
, "h", long_options
, NULL
);
2829 printf(QEMU_IMG_VERSION
);
2834 error_exit("Command not found: %s", cmdname
);