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 " '-c' indicates that target image must be compressed (qcow format only)\n"
97 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
98 " match exactly. The image doesn't need a working backing file before\n"
99 " rebasing in this case (useful for renaming the backing file)\n"
100 " '-h' with or without a command shows this help and lists the supported formats\n"
101 " '-p' show progress of command (only certain commands)\n"
102 " '-q' use Quiet mode - do not print any output (except errors)\n"
103 " '-S' indicates the consecutive number of bytes that must contain only zeros\n"
104 " for qemu-img to create a sparse image during conversion\n"
105 " '--output' takes the format in which the output must be done (human or json)\n"
106 " '-n' skips the target volume creation (useful if the volume is created\n"
107 " prior to running qemu-img)\n"
109 "Parameters to check subcommand:\n"
110 " '-r' tries to repair any inconsistencies that are found during the check.\n"
111 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
112 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
113 " hiding corruption that has already occurred.\n"
115 "Parameters to snapshot subcommand:\n"
116 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
117 " '-a' applies a snapshot (revert disk to saved state)\n"
118 " '-c' creates a snapshot\n"
119 " '-d' deletes a snapshot\n"
120 " '-l' lists all snapshots in the given image\n"
122 "Parameters to compare subcommand:\n"
123 " '-f' first image format\n"
124 " '-F' second image format\n"
125 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
127 printf("%s\nSupported formats:", help_msg
);
128 bdrv_iterate_format(format_print
, NULL
);
133 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
139 ret
= vprintf(fmt
, args
);
146 /* XXX: put correct support for win32 */
147 static int read_password(char *buf
, int buf_size
)
150 printf("Password: ");
157 if (i
< (buf_size
- 1))
168 static struct termios oldtty
;
170 static void term_exit(void)
172 tcsetattr (0, TCSANOW
, &oldtty
);
175 static void term_init(void)
182 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
183 |INLCR
|IGNCR
|ICRNL
|IXON
);
184 tty
.c_oflag
|= OPOST
;
185 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
186 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
191 tcsetattr (0, TCSANOW
, &tty
);
196 static int read_password(char *buf
, int buf_size
)
201 printf("password: ");
206 ret
= read(0, &ch
, 1);
208 if (errno
== EAGAIN
|| errno
== EINTR
) {
214 } else if (ret
== 0) {
222 if (i
< (buf_size
- 1))
233 static int print_block_option_help(const char *filename
, const char *fmt
)
235 BlockDriver
*drv
, *proto_drv
;
236 QEMUOptionParameter
*create_options
= NULL
;
238 /* Find driver and parse its options */
239 drv
= bdrv_find_format(fmt
);
241 error_report("Unknown file format '%s'", fmt
);
245 proto_drv
= bdrv_find_protocol(filename
, true);
247 error_report("Unknown protocol '%s'", filename
);
251 create_options
= append_option_parameters(create_options
,
252 drv
->create_options
);
253 create_options
= append_option_parameters(create_options
,
254 proto_drv
->create_options
);
255 print_option_help(create_options
);
256 free_option_parameters(create_options
);
260 static BlockDriverState
*bdrv_new_open(const char *filename
,
266 BlockDriverState
*bs
;
271 bs
= bdrv_new("image");
274 drv
= bdrv_find_format(fmt
);
276 error_report("Unknown file format '%s'", fmt
);
283 ret
= bdrv_open(bs
, filename
, NULL
, flags
, drv
);
285 error_report("Could not open '%s': %s", filename
, strerror(-ret
));
289 if (bdrv_is_encrypted(bs
) && require_io
) {
290 qprintf(quiet
, "Disk image '%s' is encrypted.\n", filename
);
291 if (read_password(password
, sizeof(password
)) < 0) {
292 error_report("No password given");
295 if (bdrv_set_key(bs
, password
) < 0) {
296 error_report("invalid password");
308 static int add_old_style_options(const char *fmt
, QEMUOptionParameter
*list
,
309 const char *base_filename
,
310 const char *base_fmt
)
313 if (set_option_parameter(list
, BLOCK_OPT_BACKING_FILE
, base_filename
)) {
314 error_report("Backing file not supported for file format '%s'",
320 if (set_option_parameter(list
, BLOCK_OPT_BACKING_FMT
, base_fmt
)) {
321 error_report("Backing file format not supported for file "
329 static int img_create(int argc
, char **argv
)
332 uint64_t img_size
= -1;
333 const char *fmt
= "raw";
334 const char *base_fmt
= NULL
;
335 const char *filename
;
336 const char *base_filename
= NULL
;
337 char *options
= NULL
;
338 Error
*local_err
= NULL
;
342 c
= getopt(argc
, argv
, "F:b:f:he6o:q");
355 base_filename
= optarg
;
361 error_report("option -e is deprecated, please use \'-o "
362 "encryption\' instead!");
365 error_report("option -6 is deprecated, please use \'-o "
366 "compat6\' instead!");
377 /* Get the filename */
378 if (optind
>= argc
) {
381 filename
= argv
[optind
++];
383 /* Get image size, if specified */
387 sval
= strtosz_suffix(argv
[optind
++], &end
, STRTOSZ_DEFSUFFIX_B
);
388 if (sval
< 0 || *end
) {
389 if (sval
== -ERANGE
) {
390 error_report("Image size must be less than 8 EiB!");
392 error_report("Invalid image size specified! You may use k, M, "
393 "G, T, P or E suffixes for ");
394 error_report("kilobytes, megabytes, gigabytes, terabytes, "
395 "petabytes and exabytes.");
399 img_size
= (uint64_t)sval
;
401 if (optind
!= argc
) {
405 if (options
&& is_help_option(options
)) {
406 return print_block_option_help(filename
, fmt
);
409 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
410 options
, img_size
, BDRV_O_FLAGS
, &local_err
, quiet
);
411 if (error_is_set(&local_err
)) {
412 error_report("%s", error_get_pretty(local_err
));
413 error_free(local_err
);
420 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
424 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
426 visit_type_ImageCheck(qmp_output_get_visitor(ov
),
427 &check
, NULL
, &errp
);
428 obj
= qmp_output_get_qobject(ov
);
429 str
= qobject_to_json_pretty(obj
);
431 qprintf(quiet
, "%s\n", qstring_get_str(str
));
433 qmp_output_visitor_cleanup(ov
);
437 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
439 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
440 qprintf(quiet
, "No errors were found on the image.\n");
442 if (check
->corruptions
) {
443 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
444 "Data may be corrupted, or further writes to the image "
451 "\n%" PRId64
" leaked clusters were found on the image.\n"
452 "This means waste of disk space, but no harm to data.\n",
456 if (check
->check_errors
) {
459 " internal errors have occurred during the check.\n",
460 check
->check_errors
);
464 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
465 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
466 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
467 check
->allocated_clusters
, check
->total_clusters
,
468 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
469 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
470 check
->compressed_clusters
* 100.0 /
471 check
->allocated_clusters
);
474 if (check
->image_end_offset
) {
476 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
480 static int collect_image_check(BlockDriverState
*bs
,
482 const char *filename
,
487 BdrvCheckResult result
;
489 ret
= bdrv_check(bs
, &result
, fix
);
494 check
->filename
= g_strdup(filename
);
495 check
->format
= g_strdup(bdrv_get_format_name(bs
));
496 check
->check_errors
= result
.check_errors
;
497 check
->corruptions
= result
.corruptions
;
498 check
->has_corruptions
= result
.corruptions
!= 0;
499 check
->leaks
= result
.leaks
;
500 check
->has_leaks
= result
.leaks
!= 0;
501 check
->corruptions_fixed
= result
.corruptions_fixed
;
502 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
503 check
->leaks_fixed
= result
.leaks_fixed
;
504 check
->has_leaks_fixed
= result
.leaks
!= 0;
505 check
->image_end_offset
= result
.image_end_offset
;
506 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
507 check
->total_clusters
= result
.bfi
.total_clusters
;
508 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
509 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
510 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
511 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
512 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
513 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
514 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
520 * Checks an image for consistency. Exit codes:
522 * 0 - Check completed, image is good
523 * 1 - Check not completed because of internal errors
524 * 2 - Check completed, image is corrupted
525 * 3 - Check completed, image has leaked clusters, but is good otherwise
527 static int img_check(int argc
, char **argv
)
530 OutputFormat output_format
= OFORMAT_HUMAN
;
531 const char *filename
, *fmt
, *output
;
532 BlockDriverState
*bs
;
534 int flags
= BDRV_O_FLAGS
| BDRV_O_CHECK
;
541 int option_index
= 0;
542 static const struct option long_options
[] = {
543 {"help", no_argument
, 0, 'h'},
544 {"format", required_argument
, 0, 'f'},
545 {"repair", no_argument
, 0, 'r'},
546 {"output", required_argument
, 0, OPTION_OUTPUT
},
549 c
= getopt_long(argc
, argv
, "f:hr:q",
550 long_options
, &option_index
);
563 flags
|= BDRV_O_RDWR
;
565 if (!strcmp(optarg
, "leaks")) {
566 fix
= BDRV_FIX_LEAKS
;
567 } else if (!strcmp(optarg
, "all")) {
568 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
581 if (optind
!= argc
- 1) {
584 filename
= argv
[optind
++];
586 if (output
&& !strcmp(output
, "json")) {
587 output_format
= OFORMAT_JSON
;
588 } else if (output
&& !strcmp(output
, "human")) {
589 output_format
= OFORMAT_HUMAN
;
591 error_report("--output must be used with human or json as argument.");
595 bs
= bdrv_new_open(filename
, fmt
, flags
, true, quiet
);
600 check
= g_new0(ImageCheck
, 1);
601 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
603 if (ret
== -ENOTSUP
) {
604 if (output_format
== OFORMAT_HUMAN
) {
605 error_report("This image format does not support checks");
611 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
612 int corruptions_fixed
, leaks_fixed
;
614 leaks_fixed
= check
->leaks_fixed
;
615 corruptions_fixed
= check
->corruptions_fixed
;
617 if (output_format
== OFORMAT_HUMAN
) {
619 "The following inconsistencies were found and repaired:\n\n"
620 " %" PRId64
" leaked clusters\n"
621 " %" PRId64
" corruptions\n\n"
622 "Double checking the fixed image now...\n",
624 check
->corruptions_fixed
);
627 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
629 check
->leaks_fixed
= leaks_fixed
;
630 check
->corruptions_fixed
= corruptions_fixed
;
633 switch (output_format
) {
635 dump_human_image_check(check
, quiet
);
638 dump_json_image_check(check
, quiet
);
642 if (ret
|| check
->check_errors
) {
647 if (check
->corruptions
) {
649 } else if (check
->leaks
) {
656 qapi_free_ImageCheck(check
);
662 static int img_commit(int argc
, char **argv
)
665 const char *filename
, *fmt
, *cache
;
666 BlockDriverState
*bs
;
670 cache
= BDRV_DEFAULT_CACHE
;
672 c
= getopt(argc
, argv
, "f:ht:q");
692 if (optind
!= argc
- 1) {
695 filename
= argv
[optind
++];
698 ret
= bdrv_parse_cache_flags(cache
, &flags
);
700 error_report("Invalid cache option: %s", cache
);
704 bs
= bdrv_new_open(filename
, fmt
, flags
, true, quiet
);
708 ret
= bdrv_commit(bs
);
711 qprintf(quiet
, "Image committed.\n");
714 error_report("No disk inserted");
717 error_report("Image is read-only");
720 error_report("Image is already committed");
723 error_report("Error while committing image");
735 * Returns true iff the first sector pointed to by 'buf' contains at least
738 * 'pnum' is set to the number of sectors (including and immediately following
739 * the first one) that are known to be in the same allocated/unallocated state.
741 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
)
750 is_zero
= buffer_is_zero(buf
, 512);
751 for(i
= 1; i
< n
; i
++) {
753 if (is_zero
!= buffer_is_zero(buf
, 512)) {
762 * Like is_allocated_sectors, but if the buffer starts with a used sector,
763 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
764 * breaking up write requests for only small sparse areas.
766 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
770 int num_checked
, num_used
;
776 ret
= is_allocated_sectors(buf
, n
, pnum
);
782 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
784 num_checked
= num_used
;
787 ret
= is_allocated_sectors(buf
, n
, pnum
);
789 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
791 num_checked
+= *pnum
;
793 num_used
= num_checked
;
794 } else if (*pnum
>= min
) {
804 * Compares two buffers sector by sector. Returns 0 if the first sector of both
805 * buffers matches, non-zero otherwise.
807 * pnum is set to the number of sectors (including and immediately following
808 * the first one) that are known to have the same comparison result
810 static int compare_sectors(const uint8_t *buf1
, const uint8_t *buf2
, int n
,
820 res
= !!memcmp(buf1
, buf2
, 512);
821 for(i
= 1; i
< n
; i
++) {
825 if (!!memcmp(buf1
, buf2
, 512) != res
) {
834 #define IO_BUF_SIZE (2 * 1024 * 1024)
836 static int64_t sectors_to_bytes(int64_t sectors
)
838 return sectors
<< BDRV_SECTOR_BITS
;
841 static int64_t sectors_to_process(int64_t total
, int64_t from
)
843 return MIN(total
- from
, IO_BUF_SIZE
>> BDRV_SECTOR_BITS
);
847 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
849 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
850 * data and negative value on error.
852 * @param bs: Driver used for accessing file
853 * @param sect_num: Number of first sector to check
854 * @param sect_count: Number of sectors to check
855 * @param filename: Name of disk file we are checking (logging purpose)
856 * @param buffer: Allocated buffer for storing read data
857 * @param quiet: Flag for quiet mode
859 static int check_empty_sectors(BlockDriverState
*bs
, int64_t sect_num
,
860 int sect_count
, const char *filename
,
861 uint8_t *buffer
, bool quiet
)
864 ret
= bdrv_read(bs
, sect_num
, buffer
, sect_count
);
866 error_report("Error while reading offset %" PRId64
" of %s: %s",
867 sectors_to_bytes(sect_num
), filename
, strerror(-ret
));
870 ret
= is_allocated_sectors(buffer
, sect_count
, &pnum
);
871 if (ret
|| pnum
!= sect_count
) {
872 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
873 sectors_to_bytes(ret
? sect_num
: sect_num
+ pnum
));
881 * Compares two images. Exit codes:
883 * 0 - Images are identical
885 * >1 - Error occurred
887 static int img_compare(int argc
, char **argv
)
889 const char *fmt1
= NULL
, *fmt2
= NULL
, *filename1
, *filename2
;
890 BlockDriverState
*bs1
, *bs2
;
891 int64_t total_sectors1
, total_sectors2
;
892 uint8_t *buf1
= NULL
, *buf2
= NULL
;
894 int allocated1
, allocated2
;
895 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
896 bool progress
= false, quiet
= false, strict
= false;
897 int64_t total_sectors
;
898 int64_t sector_num
= 0;
902 uint64_t progress_base
;
905 c
= getopt(argc
, argv
, "hpf:F:sq");
932 /* Progress is not shown in Quiet mode */
938 if (optind
!= argc
- 2) {
941 filename1
= argv
[optind
++];
942 filename2
= argv
[optind
++];
944 /* Initialize before goto out */
945 qemu_progress_init(progress
, 2.0);
947 bs1
= bdrv_new_open(filename1
, fmt1
, BDRV_O_FLAGS
, true, quiet
);
949 error_report("Can't open file %s", filename1
);
954 bs2
= bdrv_new_open(filename2
, fmt2
, BDRV_O_FLAGS
, true, quiet
);
956 error_report("Can't open file %s", filename2
);
961 buf1
= qemu_blockalign(bs1
, IO_BUF_SIZE
);
962 buf2
= qemu_blockalign(bs2
, IO_BUF_SIZE
);
963 bdrv_get_geometry(bs1
, &bs_sectors
);
964 total_sectors1
= bs_sectors
;
965 bdrv_get_geometry(bs2
, &bs_sectors
);
966 total_sectors2
= bs_sectors
;
967 total_sectors
= MIN(total_sectors1
, total_sectors2
);
968 progress_base
= MAX(total_sectors1
, total_sectors2
);
970 qemu_progress_print(0, 100);
972 if (strict
&& total_sectors1
!= total_sectors2
) {
974 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
979 nb_sectors
= sectors_to_process(total_sectors
, sector_num
);
980 if (nb_sectors
<= 0) {
983 allocated1
= bdrv_is_allocated_above(bs1
, NULL
, sector_num
, nb_sectors
,
985 if (allocated1
< 0) {
987 error_report("Sector allocation test failed for %s", filename1
);
991 allocated2
= bdrv_is_allocated_above(bs2
, NULL
, sector_num
, nb_sectors
,
993 if (allocated2
< 0) {
995 error_report("Sector allocation test failed for %s", filename2
);
998 nb_sectors
= MIN(pnum1
, pnum2
);
1000 if (allocated1
== allocated2
) {
1002 ret
= bdrv_read(bs1
, sector_num
, buf1
, nb_sectors
);
1004 error_report("Error while reading offset %" PRId64
" of %s:"
1005 " %s", sectors_to_bytes(sector_num
), filename1
,
1010 ret
= bdrv_read(bs2
, sector_num
, buf2
, nb_sectors
);
1012 error_report("Error while reading offset %" PRId64
1013 " of %s: %s", sectors_to_bytes(sector_num
),
1014 filename2
, strerror(-ret
));
1018 ret
= compare_sectors(buf1
, buf2
, nb_sectors
, &pnum
);
1019 if (ret
|| pnum
!= nb_sectors
) {
1021 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1023 ret
? sector_num
: sector_num
+ pnum
));
1030 qprintf(quiet
, "Strict mode: Offset %" PRId64
1031 " allocation mismatch!\n",
1032 sectors_to_bytes(sector_num
));
1037 ret
= check_empty_sectors(bs1
, sector_num
, nb_sectors
,
1038 filename1
, buf1
, quiet
);
1040 ret
= check_empty_sectors(bs2
, sector_num
, nb_sectors
,
1041 filename2
, buf1
, quiet
);
1046 error_report("Error while reading offset %" PRId64
": %s",
1047 sectors_to_bytes(sector_num
), strerror(-ret
));
1052 sector_num
+= nb_sectors
;
1053 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1056 if (total_sectors1
!= total_sectors2
) {
1057 BlockDriverState
*bs_over
;
1058 int64_t total_sectors_over
;
1059 const char *filename_over
;
1061 qprintf(quiet
, "Warning: Image size mismatch!\n");
1062 if (total_sectors1
> total_sectors2
) {
1063 total_sectors_over
= total_sectors1
;
1065 filename_over
= filename1
;
1067 total_sectors_over
= total_sectors2
;
1069 filename_over
= filename2
;
1073 nb_sectors
= sectors_to_process(total_sectors_over
, sector_num
);
1074 if (nb_sectors
<= 0) {
1077 ret
= bdrv_is_allocated_above(bs_over
, NULL
, sector_num
,
1081 error_report("Sector allocation test failed for %s",
1088 ret
= check_empty_sectors(bs_over
, sector_num
, nb_sectors
,
1089 filename_over
, buf1
, quiet
);
1093 error_report("Error while reading offset %" PRId64
1094 " of %s: %s", sectors_to_bytes(sector_num
),
1095 filename_over
, strerror(-ret
));
1100 sector_num
+= nb_sectors
;
1101 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1105 qprintf(quiet
, "Images are identical.\n");
1115 qemu_progress_end();
1119 static int img_convert(int argc
, char **argv
)
1121 int c
, ret
= 0, n
, n1
, bs_n
, bs_i
, compress
, cluster_size
,
1122 cluster_sectors
, skip_create
;
1123 int progress
= 0, flags
;
1124 const char *fmt
, *out_fmt
, *cache
, *out_baseimg
, *out_filename
;
1125 BlockDriver
*drv
, *proto_drv
;
1126 BlockDriverState
**bs
= NULL
, *out_bs
= NULL
;
1127 int64_t total_sectors
, nb_sectors
, sector_num
, bs_offset
;
1128 uint64_t bs_sectors
;
1129 uint8_t * buf
= NULL
;
1130 const uint8_t *buf1
;
1131 BlockDriverInfo bdi
;
1132 QEMUOptionParameter
*param
= NULL
, *create_options
= NULL
;
1133 QEMUOptionParameter
*out_baseimg_param
;
1134 char *options
= NULL
;
1135 const char *snapshot_name
= NULL
;
1136 float local_progress
= 0;
1137 int min_sparse
= 8; /* Need at least 4k of zeros for sparse detection */
1147 c
= getopt(argc
, argv
, "f:O:B:s:hce6o:pS:t:qn");
1163 out_baseimg
= optarg
;
1169 error_report("option -e is deprecated, please use \'-o "
1170 "encryption\' instead!");
1173 error_report("option -6 is deprecated, please use \'-o "
1174 "compat6\' instead!");
1180 snapshot_name
= optarg
;
1186 sval
= strtosz_suffix(optarg
, &end
, STRTOSZ_DEFSUFFIX_B
);
1187 if (sval
< 0 || *end
) {
1188 error_report("Invalid minimum zero buffer size for sparse output specified");
1192 min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
1214 bs_n
= argc
- optind
- 1;
1219 out_filename
= argv
[argc
- 1];
1221 /* Initialize before goto out */
1222 qemu_progress_init(progress
, 2.0);
1224 if (options
&& is_help_option(options
)) {
1225 ret
= print_block_option_help(out_filename
, out_fmt
);
1229 if (bs_n
> 1 && out_baseimg
) {
1230 error_report("-B makes no sense when concatenating multiple input "
1236 qemu_progress_print(0, 100);
1238 bs
= g_malloc0(bs_n
* sizeof(BlockDriverState
*));
1241 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
1242 bs
[bs_i
] = bdrv_new_open(argv
[optind
+ bs_i
], fmt
, BDRV_O_FLAGS
, true,
1245 error_report("Could not open '%s'", argv
[optind
+ bs_i
]);
1249 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1250 total_sectors
+= bs_sectors
;
1253 if (snapshot_name
!= NULL
) {
1255 error_report("No support for concatenating multiple snapshot");
1259 if (bdrv_snapshot_load_tmp(bs
[0], snapshot_name
) < 0) {
1260 error_report("Failed to load snapshot");
1266 /* Find driver and parse its options */
1267 drv
= bdrv_find_format(out_fmt
);
1269 error_report("Unknown file format '%s'", out_fmt
);
1274 proto_drv
= bdrv_find_protocol(out_filename
, true);
1276 error_report("Unknown protocol '%s'", out_filename
);
1281 create_options
= append_option_parameters(create_options
,
1282 drv
->create_options
);
1283 create_options
= append_option_parameters(create_options
,
1284 proto_drv
->create_options
);
1287 param
= parse_option_parameters(options
, create_options
, param
);
1288 if (param
== NULL
) {
1289 error_report("Invalid options for file format '%s'.", out_fmt
);
1294 param
= parse_option_parameters("", create_options
, param
);
1297 set_option_parameter_int(param
, BLOCK_OPT_SIZE
, total_sectors
* 512);
1298 ret
= add_old_style_options(out_fmt
, param
, out_baseimg
, NULL
);
1303 /* Get backing file name if -o backing_file was used */
1304 out_baseimg_param
= get_option_parameter(param
, BLOCK_OPT_BACKING_FILE
);
1305 if (out_baseimg_param
) {
1306 out_baseimg
= out_baseimg_param
->value
.s
;
1309 /* Check if compression is supported */
1311 QEMUOptionParameter
*encryption
=
1312 get_option_parameter(param
, BLOCK_OPT_ENCRYPT
);
1313 QEMUOptionParameter
*preallocation
=
1314 get_option_parameter(param
, BLOCK_OPT_PREALLOC
);
1316 if (!drv
->bdrv_write_compressed
) {
1317 error_report("Compression not supported for this file format");
1322 if (encryption
&& encryption
->value
.n
) {
1323 error_report("Compression and encryption not supported at "
1329 if (preallocation
&& preallocation
->value
.s
1330 && strcmp(preallocation
->value
.s
, "off"))
1332 error_report("Compression and preallocation not supported at "
1340 /* Create the new image */
1341 ret
= bdrv_create(drv
, out_filename
, param
);
1343 if (ret
== -ENOTSUP
) {
1344 error_report("Formatting not supported for file format '%s'",
1346 } else if (ret
== -EFBIG
) {
1347 error_report("The image size is too large for file format '%s'",
1350 error_report("%s: error while converting %s: %s",
1351 out_filename
, out_fmt
, strerror(-ret
));
1357 flags
= BDRV_O_RDWR
;
1358 ret
= bdrv_parse_cache_flags(cache
, &flags
);
1360 error_report("Invalid cache option: %s", cache
);
1364 out_bs
= bdrv_new_open(out_filename
, out_fmt
, flags
, true, quiet
);
1372 bdrv_get_geometry(bs
[0], &bs_sectors
);
1373 buf
= qemu_blockalign(out_bs
, IO_BUF_SIZE
);
1376 int64_t output_length
= bdrv_getlength(out_bs
);
1377 if (output_length
< 0) {
1378 error_report("unable to get output image length: %s\n",
1379 strerror(-output_length
));
1382 } else if (output_length
< total_sectors
<< BDRV_SECTOR_BITS
) {
1383 error_report("output file is smaller than input file");
1390 ret
= bdrv_get_info(out_bs
, &bdi
);
1392 error_report("could not get block driver info");
1395 cluster_size
= bdi
.cluster_size
;
1396 if (cluster_size
<= 0 || cluster_size
> IO_BUF_SIZE
) {
1397 error_report("invalid cluster size");
1401 cluster_sectors
= cluster_size
>> 9;
1404 nb_sectors
= total_sectors
;
1405 if (nb_sectors
!= 0) {
1406 local_progress
= (float)100 /
1407 (nb_sectors
/ MIN(nb_sectors
, cluster_sectors
));
1415 nb_sectors
= total_sectors
- sector_num
;
1416 if (nb_sectors
<= 0)
1418 if (nb_sectors
>= cluster_sectors
)
1419 n
= cluster_sectors
;
1423 bs_num
= sector_num
- bs_offset
;
1424 assert (bs_num
>= 0);
1427 while (remainder
> 0) {
1429 while (bs_num
== bs_sectors
) {
1431 assert (bs_i
< bs_n
);
1432 bs_offset
+= bs_sectors
;
1433 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1435 /* printf("changing part: sector_num=%" PRId64 ", "
1436 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
1437 "\n", sector_num, bs_i, bs_offset, bs_sectors); */
1439 assert (bs_num
< bs_sectors
);
1441 nlow
= (remainder
> bs_sectors
- bs_num
) ? bs_sectors
- bs_num
: remainder
;
1443 ret
= bdrv_read(bs
[bs_i
], bs_num
, buf2
, nlow
);
1445 error_report("error while reading sector %" PRId64
": %s",
1446 bs_num
, strerror(-ret
));
1455 assert (remainder
== 0);
1457 if (!buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)) {
1458 ret
= bdrv_write_compressed(out_bs
, sector_num
, buf
, n
);
1460 error_report("error while compressing sector %" PRId64
1461 ": %s", sector_num
, strerror(-ret
));
1466 qemu_progress_print(local_progress
, 100);
1468 /* signal EOF to align */
1469 bdrv_write_compressed(out_bs
, 0, NULL
, 0);
1471 int has_zero_init
= bdrv_has_zero_init(out_bs
);
1473 sector_num
= 0; // total number of sectors converted so far
1474 nb_sectors
= total_sectors
- sector_num
;
1475 if (nb_sectors
!= 0) {
1476 local_progress
= (float)100 /
1477 (nb_sectors
/ MIN(nb_sectors
, IO_BUF_SIZE
/ 512));
1481 nb_sectors
= total_sectors
- sector_num
;
1482 if (nb_sectors
<= 0) {
1485 if (nb_sectors
>= (IO_BUF_SIZE
/ 512)) {
1486 n
= (IO_BUF_SIZE
/ 512);
1491 while (sector_num
- bs_offset
>= bs_sectors
) {
1493 assert (bs_i
< bs_n
);
1494 bs_offset
+= bs_sectors
;
1495 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1496 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1497 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
1498 sector_num, bs_i, bs_offset, bs_sectors); */
1501 if (n
> bs_offset
+ bs_sectors
- sector_num
) {
1502 n
= bs_offset
+ bs_sectors
- sector_num
;
1505 /* If the output image is being created as a copy on write image,
1506 assume that sectors which are unallocated in the input image
1507 are present in both the output's and input's base images (no
1508 need to copy them). */
1510 ret
= bdrv_is_allocated(bs
[bs_i
], sector_num
- bs_offset
,
1513 error_report("error while reading metadata for sector "
1515 sector_num
- bs_offset
, strerror(-ret
));
1522 /* The next 'n1' sectors are allocated in the input image. Copy
1523 only those as they may be followed by unallocated sectors. */
1529 ret
= bdrv_read(bs
[bs_i
], sector_num
- bs_offset
, buf
, n
);
1531 error_report("error while reading sector %" PRId64
": %s",
1532 sector_num
- bs_offset
, strerror(-ret
));
1535 /* NOTE: at the same time we convert, we do not write zero
1536 sectors to have a chance to compress the image. Ideally, we
1537 should add a specific call to have the info to go faster */
1540 if (!has_zero_init
||
1541 is_allocated_sectors_min(buf1
, n
, &n1
, min_sparse
)) {
1542 ret
= bdrv_write(out_bs
, sector_num
, buf1
, n1
);
1544 error_report("error while writing sector %" PRId64
1545 ": %s", sector_num
, strerror(-ret
));
1553 qemu_progress_print(local_progress
, 100);
1557 qemu_progress_end();
1558 free_option_parameters(create_options
);
1559 free_option_parameters(param
);
1565 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
1567 bdrv_unref(bs
[bs_i
]);
1579 static void dump_snapshots(BlockDriverState
*bs
)
1581 QEMUSnapshotInfo
*sn_tab
, *sn
;
1584 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
1587 printf("Snapshot list:\n");
1588 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
1590 for(i
= 0; i
< nb_sns
; i
++) {
1592 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
1598 static void dump_json_image_info_list(ImageInfoList
*list
)
1602 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
1604 visit_type_ImageInfoList(qmp_output_get_visitor(ov
),
1605 &list
, NULL
, &errp
);
1606 obj
= qmp_output_get_qobject(ov
);
1607 str
= qobject_to_json_pretty(obj
);
1608 assert(str
!= NULL
);
1609 printf("%s\n", qstring_get_str(str
));
1610 qobject_decref(obj
);
1611 qmp_output_visitor_cleanup(ov
);
1615 static void dump_json_image_info(ImageInfo
*info
)
1619 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
1621 visit_type_ImageInfo(qmp_output_get_visitor(ov
),
1622 &info
, NULL
, &errp
);
1623 obj
= qmp_output_get_qobject(ov
);
1624 str
= qobject_to_json_pretty(obj
);
1625 assert(str
!= NULL
);
1626 printf("%s\n", qstring_get_str(str
));
1627 qobject_decref(obj
);
1628 qmp_output_visitor_cleanup(ov
);
1632 static void dump_human_image_info_list(ImageInfoList
*list
)
1634 ImageInfoList
*elem
;
1637 for (elem
= list
; elem
; elem
= elem
->next
) {
1643 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
1647 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
1649 return strcmp(a
, b
) == 0;
1653 * Open an image file chain and return an ImageInfoList
1655 * @filename: topmost image filename
1656 * @fmt: topmost image format (may be NULL to autodetect)
1657 * @chain: true - enumerate entire backing file chain
1658 * false - only topmost image file
1660 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1661 * image file. If there was an error a message will have been printed to
1664 static ImageInfoList
*collect_image_info_list(const char *filename
,
1668 ImageInfoList
*head
= NULL
;
1669 ImageInfoList
**last
= &head
;
1670 GHashTable
*filenames
;
1673 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
1676 BlockDriverState
*bs
;
1678 ImageInfoList
*elem
;
1680 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
1681 error_report("Backing file '%s' creates an infinite loop.",
1685 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
1687 bs
= bdrv_new_open(filename
, fmt
, BDRV_O_FLAGS
| BDRV_O_NO_BACKING
,
1693 bdrv_query_image_info(bs
, &info
, &err
);
1694 if (error_is_set(&err
)) {
1695 error_report("%s", error_get_pretty(err
));
1700 elem
= g_new0(ImageInfoList
, 1);
1707 filename
= fmt
= NULL
;
1709 if (info
->has_full_backing_filename
) {
1710 filename
= info
->full_backing_filename
;
1711 } else if (info
->has_backing_filename
) {
1712 filename
= info
->backing_filename
;
1714 if (info
->has_backing_filename_format
) {
1715 fmt
= info
->backing_filename_format
;
1719 g_hash_table_destroy(filenames
);
1723 qapi_free_ImageInfoList(head
);
1724 g_hash_table_destroy(filenames
);
1728 static int img_info(int argc
, char **argv
)
1731 OutputFormat output_format
= OFORMAT_HUMAN
;
1733 const char *filename
, *fmt
, *output
;
1734 ImageInfoList
*list
;
1739 int option_index
= 0;
1740 static const struct option long_options
[] = {
1741 {"help", no_argument
, 0, 'h'},
1742 {"format", required_argument
, 0, 'f'},
1743 {"output", required_argument
, 0, OPTION_OUTPUT
},
1744 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
1747 c
= getopt_long(argc
, argv
, "f:h",
1748 long_options
, &option_index
);
1763 case OPTION_BACKING_CHAIN
:
1768 if (optind
!= argc
- 1) {
1771 filename
= argv
[optind
++];
1773 if (output
&& !strcmp(output
, "json")) {
1774 output_format
= OFORMAT_JSON
;
1775 } else if (output
&& !strcmp(output
, "human")) {
1776 output_format
= OFORMAT_HUMAN
;
1777 } else if (output
) {
1778 error_report("--output must be used with human or json as argument.");
1782 list
= collect_image_info_list(filename
, fmt
, chain
);
1787 switch (output_format
) {
1789 dump_human_image_info_list(list
);
1793 dump_json_image_info_list(list
);
1795 dump_json_image_info(list
->value
);
1800 qapi_free_ImageInfoList(list
);
1805 typedef struct MapEntry
{
1811 BlockDriverState
*bs
;
1814 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
1817 switch (output_format
) {
1819 if ((e
->flags
& BDRV_BLOCK_DATA
) &&
1820 !(e
->flags
& BDRV_BLOCK_OFFSET_VALID
)) {
1821 error_report("File contains external, encrypted or compressed clusters.");
1824 if ((e
->flags
& (BDRV_BLOCK_DATA
|BDRV_BLOCK_ZERO
)) == BDRV_BLOCK_DATA
) {
1825 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
1826 e
->start
, e
->length
, e
->offset
, e
->bs
->filename
);
1828 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
1829 * Modify the flags here to allow more coalescing.
1832 (next
->flags
& (BDRV_BLOCK_DATA
|BDRV_BLOCK_ZERO
)) != BDRV_BLOCK_DATA
) {
1833 next
->flags
&= ~BDRV_BLOCK_DATA
;
1834 next
->flags
|= BDRV_BLOCK_ZERO
;
1838 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
", \"depth\": %d,"
1839 " \"zero\": %s, \"data\": %s",
1840 (e
->start
== 0 ? "[" : ",\n"),
1841 e
->start
, e
->length
, e
->depth
,
1842 (e
->flags
& BDRV_BLOCK_ZERO
) ? "true" : "false",
1843 (e
->flags
& BDRV_BLOCK_DATA
) ? "true" : "false");
1844 if (e
->flags
& BDRV_BLOCK_OFFSET_VALID
) {
1845 printf(", 'offset': %"PRId64
"", e
->offset
);
1856 static int get_block_status(BlockDriverState
*bs
, int64_t sector_num
,
1857 int nb_sectors
, MapEntry
*e
)
1862 /* As an optimization, we could cache the current range of unallocated
1863 * clusters in each file of the chain, and avoid querying the same
1869 ret
= bdrv_get_block_status(bs
, sector_num
, nb_sectors
, &nb_sectors
);
1874 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
1877 bs
= bs
->backing_hd
;
1886 e
->start
= sector_num
* BDRV_SECTOR_SIZE
;
1887 e
->length
= nb_sectors
* BDRV_SECTOR_SIZE
;
1888 e
->flags
= ret
& ~BDRV_BLOCK_OFFSET_MASK
;
1889 e
->offset
= ret
& BDRV_BLOCK_OFFSET_MASK
;
1895 static int img_map(int argc
, char **argv
)
1898 OutputFormat output_format
= OFORMAT_HUMAN
;
1899 BlockDriverState
*bs
;
1900 const char *filename
, *fmt
, *output
;
1902 MapEntry curr
= { .length
= 0 }, next
;
1908 int option_index
= 0;
1909 static const struct option long_options
[] = {
1910 {"help", no_argument
, 0, 'h'},
1911 {"format", required_argument
, 0, 'f'},
1912 {"output", required_argument
, 0, OPTION_OUTPUT
},
1915 c
= getopt_long(argc
, argv
, "f:h",
1916 long_options
, &option_index
);
1933 if (optind
>= argc
) {
1936 filename
= argv
[optind
++];
1938 if (output
&& !strcmp(output
, "json")) {
1939 output_format
= OFORMAT_JSON
;
1940 } else if (output
&& !strcmp(output
, "human")) {
1941 output_format
= OFORMAT_HUMAN
;
1942 } else if (output
) {
1943 error_report("--output must be used with human or json as argument.");
1947 bs
= bdrv_new_open(filename
, fmt
, BDRV_O_FLAGS
, true, false);
1952 if (output_format
== OFORMAT_HUMAN
) {
1953 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
1956 length
= bdrv_getlength(bs
);
1957 while (curr
.start
+ curr
.length
< length
) {
1958 int64_t nsectors_left
;
1962 sector_num
= (curr
.start
+ curr
.length
) >> BDRV_SECTOR_BITS
;
1964 /* Probe up to 1 GiB at a time. */
1965 nsectors_left
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
) - sector_num
;
1966 n
= MIN(1 << (30 - BDRV_SECTOR_BITS
), nsectors_left
);
1967 ret
= get_block_status(bs
, sector_num
, n
, &next
);
1970 error_report("Could not read file metadata: %s", strerror(-ret
));
1974 if (curr
.length
!= 0 && curr
.flags
== next
.flags
&&
1975 curr
.depth
== next
.depth
&&
1976 ((curr
.flags
& BDRV_BLOCK_OFFSET_VALID
) == 0 ||
1977 curr
.offset
+ curr
.length
== next
.offset
)) {
1978 curr
.length
+= next
.length
;
1982 if (curr
.length
> 0) {
1983 dump_map_entry(output_format
, &curr
, &next
);
1988 dump_map_entry(output_format
, &curr
, NULL
);
1995 #define SNAPSHOT_LIST 1
1996 #define SNAPSHOT_CREATE 2
1997 #define SNAPSHOT_APPLY 3
1998 #define SNAPSHOT_DELETE 4
2000 static int img_snapshot(int argc
, char **argv
)
2002 BlockDriverState
*bs
;
2003 QEMUSnapshotInfo sn
;
2004 char *filename
, *snapshot_name
= NULL
;
2005 int c
, ret
= 0, bdrv_oflags
;
2011 bdrv_oflags
= BDRV_O_FLAGS
| BDRV_O_RDWR
;
2012 /* Parse commandline parameters */
2014 c
= getopt(argc
, argv
, "la:c:d:hq");
2028 action
= SNAPSHOT_LIST
;
2029 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
2036 action
= SNAPSHOT_APPLY
;
2037 snapshot_name
= optarg
;
2044 action
= SNAPSHOT_CREATE
;
2045 snapshot_name
= optarg
;
2052 action
= SNAPSHOT_DELETE
;
2053 snapshot_name
= optarg
;
2061 if (optind
!= argc
- 1) {
2064 filename
= argv
[optind
++];
2066 /* Open the image */
2067 bs
= bdrv_new_open(filename
, NULL
, bdrv_oflags
, true, quiet
);
2072 /* Perform the requested action */
2078 case SNAPSHOT_CREATE
:
2079 memset(&sn
, 0, sizeof(sn
));
2080 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
2082 qemu_gettimeofday(&tv
);
2083 sn
.date_sec
= tv
.tv_sec
;
2084 sn
.date_nsec
= tv
.tv_usec
* 1000;
2086 ret
= bdrv_snapshot_create(bs
, &sn
);
2088 error_report("Could not create snapshot '%s': %d (%s)",
2089 snapshot_name
, ret
, strerror(-ret
));
2093 case SNAPSHOT_APPLY
:
2094 ret
= bdrv_snapshot_goto(bs
, snapshot_name
);
2096 error_report("Could not apply snapshot '%s': %d (%s)",
2097 snapshot_name
, ret
, strerror(-ret
));
2101 case SNAPSHOT_DELETE
:
2102 bdrv_snapshot_delete_by_id_or_name(bs
, snapshot_name
, &err
);
2103 if (error_is_set(&err
)) {
2104 error_report("Could not delete snapshot '%s': (%s)",
2105 snapshot_name
, error_get_pretty(err
));
2120 static int img_rebase(int argc
, char **argv
)
2122 BlockDriverState
*bs
, *bs_old_backing
= NULL
, *bs_new_backing
= NULL
;
2123 BlockDriver
*old_backing_drv
, *new_backing_drv
;
2125 const char *fmt
, *cache
, *out_basefmt
, *out_baseimg
;
2131 /* Parse commandline parameters */
2133 cache
= BDRV_DEFAULT_CACHE
;
2137 c
= getopt(argc
, argv
, "uhf:F:b:pt:q");
2150 out_basefmt
= optarg
;
2153 out_baseimg
= optarg
;
2174 if ((optind
!= argc
- 1) || (!unsafe
&& !out_baseimg
)) {
2177 filename
= argv
[optind
++];
2179 qemu_progress_init(progress
, 2.0);
2180 qemu_progress_print(0, 100);
2182 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
2183 ret
= bdrv_parse_cache_flags(cache
, &flags
);
2185 error_report("Invalid cache option: %s", cache
);
2192 * Ignore the old backing file for unsafe rebase in case we want to correct
2193 * the reference to a renamed or moved backing file.
2195 bs
= bdrv_new_open(filename
, fmt
, flags
, true, quiet
);
2200 /* Find the right drivers for the backing files */
2201 old_backing_drv
= NULL
;
2202 new_backing_drv
= NULL
;
2204 if (!unsafe
&& bs
->backing_format
[0] != '\0') {
2205 old_backing_drv
= bdrv_find_format(bs
->backing_format
);
2206 if (old_backing_drv
== NULL
) {
2207 error_report("Invalid format name: '%s'", bs
->backing_format
);
2213 if (out_basefmt
!= NULL
) {
2214 new_backing_drv
= bdrv_find_format(out_basefmt
);
2215 if (new_backing_drv
== NULL
) {
2216 error_report("Invalid format name: '%s'", out_basefmt
);
2222 /* For safe rebasing we need to compare old and new backing file */
2224 /* Make the compiler happy */
2225 bs_old_backing
= NULL
;
2226 bs_new_backing
= NULL
;
2228 char backing_name
[1024];
2230 bs_old_backing
= bdrv_new("old_backing");
2231 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
2232 ret
= bdrv_open(bs_old_backing
, backing_name
, NULL
, BDRV_O_FLAGS
,
2235 error_report("Could not open old backing file '%s'", backing_name
);
2238 if (out_baseimg
[0]) {
2239 bs_new_backing
= bdrv_new("new_backing");
2240 ret
= bdrv_open(bs_new_backing
, out_baseimg
, NULL
, BDRV_O_FLAGS
,
2243 error_report("Could not open new backing file '%s'",
2251 * Check each unallocated cluster in the COW file. If it is unallocated,
2252 * accesses go to the backing file. We must therefore compare this cluster
2253 * in the old and new backing file, and if they differ we need to copy it
2254 * from the old backing file into the COW file.
2256 * If qemu-img crashes during this step, no harm is done. The content of
2257 * the image is the same as the original one at any time.
2260 uint64_t num_sectors
;
2261 uint64_t old_backing_num_sectors
;
2262 uint64_t new_backing_num_sectors
= 0;
2267 float local_progress
= 0;
2269 buf_old
= qemu_blockalign(bs
, IO_BUF_SIZE
);
2270 buf_new
= qemu_blockalign(bs
, IO_BUF_SIZE
);
2272 bdrv_get_geometry(bs
, &num_sectors
);
2273 bdrv_get_geometry(bs_old_backing
, &old_backing_num_sectors
);
2274 if (bs_new_backing
) {
2275 bdrv_get_geometry(bs_new_backing
, &new_backing_num_sectors
);
2278 if (num_sectors
!= 0) {
2279 local_progress
= (float)100 /
2280 (num_sectors
/ MIN(num_sectors
, IO_BUF_SIZE
/ 512));
2283 for (sector
= 0; sector
< num_sectors
; sector
+= n
) {
2285 /* How many sectors can we handle with the next read? */
2286 if (sector
+ (IO_BUF_SIZE
/ 512) <= num_sectors
) {
2287 n
= (IO_BUF_SIZE
/ 512);
2289 n
= num_sectors
- sector
;
2292 /* If the cluster is allocated, we don't need to take action */
2293 ret
= bdrv_is_allocated(bs
, sector
, n
, &n
);
2295 error_report("error while reading image metadata: %s",
2304 * Read old and new backing file and take into consideration that
2305 * backing files may be smaller than the COW image.
2307 if (sector
>= old_backing_num_sectors
) {
2308 memset(buf_old
, 0, n
* BDRV_SECTOR_SIZE
);
2310 if (sector
+ n
> old_backing_num_sectors
) {
2311 n
= old_backing_num_sectors
- sector
;
2314 ret
= bdrv_read(bs_old_backing
, sector
, buf_old
, n
);
2316 error_report("error while reading from old backing file");
2321 if (sector
>= new_backing_num_sectors
|| !bs_new_backing
) {
2322 memset(buf_new
, 0, n
* BDRV_SECTOR_SIZE
);
2324 if (sector
+ n
> new_backing_num_sectors
) {
2325 n
= new_backing_num_sectors
- sector
;
2328 ret
= bdrv_read(bs_new_backing
, sector
, buf_new
, n
);
2330 error_report("error while reading from new backing file");
2335 /* If they differ, we need to write to the COW file */
2336 uint64_t written
= 0;
2338 while (written
< n
) {
2341 if (compare_sectors(buf_old
+ written
* 512,
2342 buf_new
+ written
* 512, n
- written
, &pnum
))
2344 ret
= bdrv_write(bs
, sector
+ written
,
2345 buf_old
+ written
* 512, pnum
);
2347 error_report("Error while writing to COW image: %s",
2355 qemu_progress_print(local_progress
, 100);
2358 qemu_vfree(buf_old
);
2359 qemu_vfree(buf_new
);
2363 * Change the backing file. All clusters that are different from the old
2364 * backing file are overwritten in the COW file now, so the visible content
2365 * doesn't change when we switch the backing file.
2367 if (out_baseimg
&& *out_baseimg
) {
2368 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
2370 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
2373 if (ret
== -ENOSPC
) {
2374 error_report("Could not change the backing file to '%s': No "
2375 "space left in the file header", out_baseimg
);
2376 } else if (ret
< 0) {
2377 error_report("Could not change the backing file to '%s': %s",
2378 out_baseimg
, strerror(-ret
));
2381 qemu_progress_print(100, 0);
2383 * TODO At this point it is possible to check if any clusters that are
2384 * allocated in the COW file are the same in the backing file. If so, they
2385 * could be dropped from the COW file. Don't do this before switching the
2386 * backing file, in case of a crash this would lead to corruption.
2389 qemu_progress_end();
2392 if (bs_old_backing
!= NULL
) {
2393 bdrv_unref(bs_old_backing
);
2395 if (bs_new_backing
!= NULL
) {
2396 bdrv_unref(bs_new_backing
);
2407 static int img_resize(int argc
, char **argv
)
2409 int c
, ret
, relative
;
2410 const char *filename
, *fmt
, *size
;
2411 int64_t n
, total_size
;
2413 BlockDriverState
*bs
= NULL
;
2415 static QemuOptsList resize_options
= {
2416 .name
= "resize_options",
2417 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
2420 .name
= BLOCK_OPT_SIZE
,
2421 .type
= QEMU_OPT_SIZE
,
2422 .help
= "Virtual disk size"
2429 /* Remove size from argv manually so that negative numbers are not treated
2430 * as options by getopt. */
2436 size
= argv
[--argc
];
2438 /* Parse getopt arguments */
2441 c
= getopt(argc
, argv
, "f:hq");
2458 if (optind
!= argc
- 1) {
2461 filename
= argv
[optind
++];
2463 /* Choose grow, shrink, or absolute resize mode */
2479 param
= qemu_opts_create_nofail(&resize_options
);
2480 if (qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
)) {
2481 /* Error message already printed when size parsing fails */
2483 qemu_opts_del(param
);
2486 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
2487 qemu_opts_del(param
);
2489 bs
= bdrv_new_open(filename
, fmt
, BDRV_O_FLAGS
| BDRV_O_RDWR
, true, quiet
);
2496 total_size
= bdrv_getlength(bs
) + n
* relative
;
2500 if (total_size
<= 0) {
2501 error_report("New image size must be positive");
2506 ret
= bdrv_truncate(bs
, total_size
);
2509 qprintf(quiet
, "Image resized.\n");
2512 error_report("This image does not support resize");
2515 error_report("Image is read-only");
2518 error_report("Error resizing image (%d)", -ret
);
2531 static int img_amend(int argc
, char **argv
)
2534 char *options
= NULL
;
2535 QEMUOptionParameter
*create_options
= NULL
, *options_param
= NULL
;
2536 const char *fmt
= NULL
, *filename
;
2538 BlockDriverState
*bs
= NULL
;
2541 c
= getopt(argc
, argv
, "hqf:o:");
2563 if (optind
!= argc
- 1) {
2571 filename
= argv
[argc
- 1];
2573 bs
= bdrv_new_open(filename
, fmt
, BDRV_O_FLAGS
| BDRV_O_RDWR
, true, quiet
);
2575 error_report("Could not open image '%s'", filename
);
2580 fmt
= bs
->drv
->format_name
;
2582 if (is_help_option(options
)) {
2583 ret
= print_block_option_help(filename
, fmt
);
2587 create_options
= append_option_parameters(create_options
,
2588 bs
->drv
->create_options
);
2589 options_param
= parse_option_parameters(options
, create_options
,
2591 if (options_param
== NULL
) {
2592 error_report("Invalid options for file format '%s'", fmt
);
2597 ret
= bdrv_amend_options(bs
, options_param
);
2599 error_report("Error while amending options: %s", strerror(-ret
));
2607 free_option_parameters(create_options
);
2608 free_option_parameters(options_param
);
2615 static const img_cmd_t img_cmds
[] = {
2616 #define DEF(option, callback, arg_string) \
2617 { option, callback },
2618 #include "qemu-img-cmds.h"
2624 int main(int argc
, char **argv
)
2626 const img_cmd_t
*cmd
;
2627 const char *cmdname
;
2630 signal(SIGPIPE
, SIG_IGN
);
2633 error_set_progname(argv
[0]);
2635 qemu_init_main_loop();
2642 /* find the command */
2643 for(cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
2644 if (!strcmp(cmdname
, cmd
->name
)) {
2645 return cmd
->handler(argc
, argv
);