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 " and T (terabyte, 1024G) are supported. 'b' is ignored.\n"
90 " 'output_filename' is the destination disk image filename\n"
91 " 'output_fmt' is the destination format\n"
92 " 'options' is a comma separated list of format specific options in a\n"
93 " name=value format. Use -o ? for an overview of the options supported by the\n"
95 " '-c' indicates that target image must be compressed (qcow format only)\n"
96 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
97 " match exactly. The image doesn't need a working backing file before\n"
98 " rebasing in this case (useful for renaming the backing file)\n"
99 " '-h' with or without a command shows this help and lists the supported formats\n"
100 " '-p' show progress of command (only certain commands)\n"
101 " '-q' use Quiet mode - do not print any output (except errors)\n"
102 " '-S' indicates the consecutive number of bytes that must contain only zeros\n"
103 " for qemu-img to create a sparse image during conversion\n"
104 " '--output' takes the format in which the output must be done (human or json)\n"
106 "Parameters to check subcommand:\n"
107 " '-r' tries to repair any inconsistencies that are found during the check.\n"
108 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
109 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
110 " hiding corruption that has already occurred.\n"
112 "Parameters to snapshot subcommand:\n"
113 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
114 " '-a' applies a snapshot (revert disk to saved state)\n"
115 " '-c' creates a snapshot\n"
116 " '-d' deletes a snapshot\n"
117 " '-l' lists all snapshots in the given image\n"
119 "Parameters to compare subcommand:\n"
120 " '-f' first image format\n"
121 " '-F' second image format\n"
122 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
124 printf("%s\nSupported formats:", help_msg
);
125 bdrv_iterate_format(format_print
, NULL
);
130 static int qprintf(bool quiet
, const char *fmt
, ...)
136 ret
= vprintf(fmt
, args
);
143 /* XXX: put correct support for win32 */
144 static int read_password(char *buf
, int buf_size
)
147 printf("Password: ");
154 if (i
< (buf_size
- 1))
165 static struct termios oldtty
;
167 static void term_exit(void)
169 tcsetattr (0, TCSANOW
, &oldtty
);
172 static void term_init(void)
179 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
180 |INLCR
|IGNCR
|ICRNL
|IXON
);
181 tty
.c_oflag
|= OPOST
;
182 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
183 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
188 tcsetattr (0, TCSANOW
, &tty
);
193 static int read_password(char *buf
, int buf_size
)
198 printf("password: ");
203 ret
= read(0, &ch
, 1);
205 if (errno
== EAGAIN
|| errno
== EINTR
) {
211 } else if (ret
== 0) {
219 if (i
< (buf_size
- 1))
230 static int print_block_option_help(const char *filename
, const char *fmt
)
232 BlockDriver
*drv
, *proto_drv
;
233 QEMUOptionParameter
*create_options
= NULL
;
235 /* Find driver and parse its options */
236 drv
= bdrv_find_format(fmt
);
238 error_report("Unknown file format '%s'", fmt
);
242 proto_drv
= bdrv_find_protocol(filename
);
244 error_report("Unknown protocol '%s'", filename
);
248 create_options
= append_option_parameters(create_options
,
249 drv
->create_options
);
250 create_options
= append_option_parameters(create_options
,
251 proto_drv
->create_options
);
252 print_option_help(create_options
);
253 free_option_parameters(create_options
);
257 static BlockDriverState
*bdrv_new_open(const char *filename
,
263 BlockDriverState
*bs
;
268 bs
= bdrv_new("image");
271 drv
= bdrv_find_format(fmt
);
273 error_report("Unknown file format '%s'", fmt
);
280 ret
= bdrv_open(bs
, filename
, NULL
, flags
, drv
);
282 error_report("Could not open '%s': %s", filename
, strerror(-ret
));
286 if (bdrv_is_encrypted(bs
) && require_io
) {
287 qprintf(quiet
, "Disk image '%s' is encrypted.\n", filename
);
288 if (read_password(password
, sizeof(password
)) < 0) {
289 error_report("No password given");
292 if (bdrv_set_key(bs
, password
) < 0) {
293 error_report("invalid password");
305 static int add_old_style_options(const char *fmt
, QEMUOptionParameter
*list
,
306 const char *base_filename
,
307 const char *base_fmt
)
310 if (set_option_parameter(list
, BLOCK_OPT_BACKING_FILE
, base_filename
)) {
311 error_report("Backing file not supported for file format '%s'",
317 if (set_option_parameter(list
, BLOCK_OPT_BACKING_FMT
, base_fmt
)) {
318 error_report("Backing file format not supported for file "
326 static int img_create(int argc
, char **argv
)
329 uint64_t img_size
= -1;
330 const char *fmt
= "raw";
331 const char *base_fmt
= NULL
;
332 const char *filename
;
333 const char *base_filename
= NULL
;
334 char *options
= NULL
;
335 Error
*local_err
= NULL
;
339 c
= getopt(argc
, argv
, "F:b:f:he6o:q");
352 base_filename
= optarg
;
358 error_report("option -e is deprecated, please use \'-o "
359 "encryption\' instead!");
362 error_report("option -6 is deprecated, please use \'-o "
363 "compat6\' instead!");
374 /* Get the filename */
375 if (optind
>= argc
) {
378 filename
= argv
[optind
++];
380 /* Get image size, if specified */
384 sval
= strtosz_suffix(argv
[optind
++], &end
, STRTOSZ_DEFSUFFIX_B
);
385 if (sval
< 0 || *end
) {
386 if (sval
== -ERANGE
) {
387 error_report("Image size must be less than 8 EiB!");
389 error_report("Invalid image size specified! You may use k, M, "
390 "G or T suffixes for ");
391 error_report("kilobytes, megabytes, gigabytes and terabytes.");
395 img_size
= (uint64_t)sval
;
398 if (options
&& is_help_option(options
)) {
399 return print_block_option_help(filename
, fmt
);
402 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
403 options
, img_size
, BDRV_O_FLAGS
, &local_err
, quiet
);
404 if (error_is_set(&local_err
)) {
405 error_report("%s", error_get_pretty(local_err
));
406 error_free(local_err
);
413 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
417 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
419 visit_type_ImageCheck(qmp_output_get_visitor(ov
),
420 &check
, NULL
, &errp
);
421 obj
= qmp_output_get_qobject(ov
);
422 str
= qobject_to_json_pretty(obj
);
424 qprintf(quiet
, "%s\n", qstring_get_str(str
));
426 qmp_output_visitor_cleanup(ov
);
430 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
432 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
433 qprintf(quiet
, "No errors were found on the image.\n");
435 if (check
->corruptions
) {
436 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
437 "Data may be corrupted, or further writes to the image "
444 "\n%" PRId64
" leaked clusters were found on the image.\n"
445 "This means waste of disk space, but no harm to data.\n",
449 if (check
->check_errors
) {
452 " internal errors have occurred during the check.\n",
453 check
->check_errors
);
457 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
458 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
459 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
460 check
->allocated_clusters
, check
->total_clusters
,
461 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
462 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
463 check
->compressed_clusters
* 100.0 /
464 check
->allocated_clusters
);
467 if (check
->image_end_offset
) {
469 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
473 static int collect_image_check(BlockDriverState
*bs
,
475 const char *filename
,
480 BdrvCheckResult result
;
482 ret
= bdrv_check(bs
, &result
, fix
);
487 check
->filename
= g_strdup(filename
);
488 check
->format
= g_strdup(bdrv_get_format_name(bs
));
489 check
->check_errors
= result
.check_errors
;
490 check
->corruptions
= result
.corruptions
;
491 check
->has_corruptions
= result
.corruptions
!= 0;
492 check
->leaks
= result
.leaks
;
493 check
->has_leaks
= result
.leaks
!= 0;
494 check
->corruptions_fixed
= result
.corruptions_fixed
;
495 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
496 check
->leaks_fixed
= result
.leaks_fixed
;
497 check
->has_leaks_fixed
= result
.leaks
!= 0;
498 check
->image_end_offset
= result
.image_end_offset
;
499 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
500 check
->total_clusters
= result
.bfi
.total_clusters
;
501 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
502 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
503 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
504 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
505 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
506 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
507 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
513 * Checks an image for consistency. Exit codes:
515 * 0 - Check completed, image is good
516 * 1 - Check not completed because of internal errors
517 * 2 - Check completed, image is corrupted
518 * 3 - Check completed, image has leaked clusters, but is good otherwise
520 static int img_check(int argc
, char **argv
)
523 OutputFormat output_format
= OFORMAT_HUMAN
;
524 const char *filename
, *fmt
, *output
;
525 BlockDriverState
*bs
;
527 int flags
= BDRV_O_FLAGS
| BDRV_O_CHECK
;
534 int option_index
= 0;
535 static const struct option long_options
[] = {
536 {"help", no_argument
, 0, 'h'},
537 {"format", required_argument
, 0, 'f'},
538 {"repair", no_argument
, 0, 'r'},
539 {"output", required_argument
, 0, OPTION_OUTPUT
},
542 c
= getopt_long(argc
, argv
, "f:hr:q",
543 long_options
, &option_index
);
556 flags
|= BDRV_O_RDWR
;
558 if (!strcmp(optarg
, "leaks")) {
559 fix
= BDRV_FIX_LEAKS
;
560 } else if (!strcmp(optarg
, "all")) {
561 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
574 if (optind
>= argc
) {
577 filename
= argv
[optind
++];
579 if (output
&& !strcmp(output
, "json")) {
580 output_format
= OFORMAT_JSON
;
581 } else if (output
&& !strcmp(output
, "human")) {
582 output_format
= OFORMAT_HUMAN
;
584 error_report("--output must be used with human or json as argument.");
588 bs
= bdrv_new_open(filename
, fmt
, flags
, true, quiet
);
593 check
= g_new0(ImageCheck
, 1);
594 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
596 if (ret
== -ENOTSUP
) {
597 if (output_format
== OFORMAT_HUMAN
) {
598 error_report("This image format does not support checks");
604 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
605 int corruptions_fixed
, leaks_fixed
;
607 leaks_fixed
= check
->leaks_fixed
;
608 corruptions_fixed
= check
->corruptions_fixed
;
610 if (output_format
== OFORMAT_HUMAN
) {
612 "The following inconsistencies were found and repaired:\n\n"
613 " %" PRId64
" leaked clusters\n"
614 " %" PRId64
" corruptions\n\n"
615 "Double checking the fixed image now...\n",
617 check
->corruptions_fixed
);
620 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
622 check
->leaks_fixed
= leaks_fixed
;
623 check
->corruptions_fixed
= corruptions_fixed
;
626 switch (output_format
) {
628 dump_human_image_check(check
, quiet
);
631 dump_json_image_check(check
, quiet
);
635 if (ret
|| check
->check_errors
) {
640 if (check
->corruptions
) {
642 } else if (check
->leaks
) {
649 qapi_free_ImageCheck(check
);
655 static int img_commit(int argc
, char **argv
)
658 const char *filename
, *fmt
, *cache
;
659 BlockDriverState
*bs
;
663 cache
= BDRV_DEFAULT_CACHE
;
665 c
= getopt(argc
, argv
, "f:ht:q");
685 if (optind
>= argc
) {
688 filename
= argv
[optind
++];
691 ret
= bdrv_parse_cache_flags(cache
, &flags
);
693 error_report("Invalid cache option: %s", cache
);
697 bs
= bdrv_new_open(filename
, fmt
, flags
, true, quiet
);
701 ret
= bdrv_commit(bs
);
704 qprintf(quiet
, "Image committed.\n");
707 error_report("No disk inserted");
710 error_report("Image is read-only");
713 error_report("Image is already committed");
716 error_report("Error while committing image");
728 * Returns true iff the first sector pointed to by 'buf' contains at least
731 * 'pnum' is set to the number of sectors (including and immediately following
732 * the first one) that are known to be in the same allocated/unallocated state.
734 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
)
743 is_zero
= buffer_is_zero(buf
, 512);
744 for(i
= 1; i
< n
; i
++) {
746 if (is_zero
!= buffer_is_zero(buf
, 512)) {
755 * Like is_allocated_sectors, but if the buffer starts with a used sector,
756 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
757 * breaking up write requests for only small sparse areas.
759 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
763 int num_checked
, num_used
;
769 ret
= is_allocated_sectors(buf
, n
, pnum
);
775 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
777 num_checked
= num_used
;
780 ret
= is_allocated_sectors(buf
, n
, pnum
);
782 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
784 num_checked
+= *pnum
;
786 num_used
= num_checked
;
787 } else if (*pnum
>= min
) {
797 * Compares two buffers sector by sector. Returns 0 if the first sector of both
798 * buffers matches, non-zero otherwise.
800 * pnum is set to the number of sectors (including and immediately following
801 * the first one) that are known to have the same comparison result
803 static int compare_sectors(const uint8_t *buf1
, const uint8_t *buf2
, int n
,
813 res
= !!memcmp(buf1
, buf2
, 512);
814 for(i
= 1; i
< n
; i
++) {
818 if (!!memcmp(buf1
, buf2
, 512) != res
) {
827 #define IO_BUF_SIZE (2 * 1024 * 1024)
829 static int64_t sectors_to_bytes(int64_t sectors
)
831 return sectors
<< BDRV_SECTOR_BITS
;
834 static int64_t sectors_to_process(int64_t total
, int64_t from
)
836 return MIN(total
- from
, IO_BUF_SIZE
>> BDRV_SECTOR_BITS
);
840 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
842 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
843 * data and negative value on error.
845 * @param bs: Driver used for accessing file
846 * @param sect_num: Number of first sector to check
847 * @param sect_count: Number of sectors to check
848 * @param filename: Name of disk file we are checking (logging purpose)
849 * @param buffer: Allocated buffer for storing read data
850 * @param quiet: Flag for quiet mode
852 static int check_empty_sectors(BlockDriverState
*bs
, int64_t sect_num
,
853 int sect_count
, const char *filename
,
854 uint8_t *buffer
, bool quiet
)
857 ret
= bdrv_read(bs
, sect_num
, buffer
, sect_count
);
859 error_report("Error while reading offset %" PRId64
" of %s: %s",
860 sectors_to_bytes(sect_num
), filename
, strerror(-ret
));
863 ret
= is_allocated_sectors(buffer
, sect_count
, &pnum
);
864 if (ret
|| pnum
!= sect_count
) {
865 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
866 sectors_to_bytes(ret
? sect_num
: sect_num
+ pnum
));
874 * Compares two images. Exit codes:
876 * 0 - Images are identical
878 * >1 - Error occurred
880 static int img_compare(int argc
, char **argv
)
882 const char *fmt1
= NULL
, *fmt2
= NULL
, *filename1
, *filename2
;
883 BlockDriverState
*bs1
, *bs2
;
884 int64_t total_sectors1
, total_sectors2
;
885 uint8_t *buf1
= NULL
, *buf2
= NULL
;
887 int allocated1
, allocated2
;
888 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
889 bool progress
= false, quiet
= false, strict
= false;
890 int64_t total_sectors
;
891 int64_t sector_num
= 0;
895 uint64_t progress_base
;
898 c
= getopt(argc
, argv
, "hpf:F:sq");
925 /* Progress is not shown in Quiet mode */
931 if (optind
> argc
- 2) {
934 filename1
= argv
[optind
++];
935 filename2
= argv
[optind
++];
937 /* Initialize before goto out */
938 qemu_progress_init(progress
, 2.0);
940 bs1
= bdrv_new_open(filename1
, fmt1
, BDRV_O_FLAGS
, true, quiet
);
942 error_report("Can't open file %s", filename1
);
947 bs2
= bdrv_new_open(filename2
, fmt2
, BDRV_O_FLAGS
, true, quiet
);
949 error_report("Can't open file %s", filename2
);
954 buf1
= qemu_blockalign(bs1
, IO_BUF_SIZE
);
955 buf2
= qemu_blockalign(bs2
, IO_BUF_SIZE
);
956 bdrv_get_geometry(bs1
, &bs_sectors
);
957 total_sectors1
= bs_sectors
;
958 bdrv_get_geometry(bs2
, &bs_sectors
);
959 total_sectors2
= bs_sectors
;
960 total_sectors
= MIN(total_sectors1
, total_sectors2
);
961 progress_base
= MAX(total_sectors1
, total_sectors2
);
963 qemu_progress_print(0, 100);
965 if (strict
&& total_sectors1
!= total_sectors2
) {
967 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
972 nb_sectors
= sectors_to_process(total_sectors
, sector_num
);
973 if (nb_sectors
<= 0) {
976 allocated1
= bdrv_is_allocated_above(bs1
, NULL
, sector_num
, nb_sectors
,
978 if (allocated1
< 0) {
980 error_report("Sector allocation test failed for %s", filename1
);
984 allocated2
= bdrv_is_allocated_above(bs2
, NULL
, sector_num
, nb_sectors
,
986 if (allocated2
< 0) {
988 error_report("Sector allocation test failed for %s", filename2
);
991 nb_sectors
= MIN(pnum1
, pnum2
);
993 if (allocated1
== allocated2
) {
995 ret
= bdrv_read(bs1
, sector_num
, buf1
, nb_sectors
);
997 error_report("Error while reading offset %" PRId64
" of %s:"
998 " %s", sectors_to_bytes(sector_num
), filename1
,
1003 ret
= bdrv_read(bs2
, sector_num
, buf2
, nb_sectors
);
1005 error_report("Error while reading offset %" PRId64
1006 " of %s: %s", sectors_to_bytes(sector_num
),
1007 filename2
, strerror(-ret
));
1011 ret
= compare_sectors(buf1
, buf2
, nb_sectors
, &pnum
);
1012 if (ret
|| pnum
!= nb_sectors
) {
1014 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1016 ret
? sector_num
: sector_num
+ pnum
));
1023 qprintf(quiet
, "Strict mode: Offset %" PRId64
1024 " allocation mismatch!\n",
1025 sectors_to_bytes(sector_num
));
1030 ret
= check_empty_sectors(bs1
, sector_num
, nb_sectors
,
1031 filename1
, buf1
, quiet
);
1033 ret
= check_empty_sectors(bs2
, sector_num
, nb_sectors
,
1034 filename2
, buf1
, quiet
);
1039 error_report("Error while reading offset %" PRId64
": %s",
1040 sectors_to_bytes(sector_num
), strerror(-ret
));
1045 sector_num
+= nb_sectors
;
1046 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1049 if (total_sectors1
!= total_sectors2
) {
1050 BlockDriverState
*bs_over
;
1051 int64_t total_sectors_over
;
1052 const char *filename_over
;
1054 qprintf(quiet
, "Warning: Image size mismatch!\n");
1055 if (total_sectors1
> total_sectors2
) {
1056 total_sectors_over
= total_sectors1
;
1058 filename_over
= filename1
;
1060 total_sectors_over
= total_sectors2
;
1062 filename_over
= filename2
;
1066 nb_sectors
= sectors_to_process(total_sectors_over
, sector_num
);
1067 if (nb_sectors
<= 0) {
1070 ret
= bdrv_is_allocated_above(bs_over
, NULL
, sector_num
,
1074 error_report("Sector allocation test failed for %s",
1081 ret
= check_empty_sectors(bs_over
, sector_num
, nb_sectors
,
1082 filename_over
, buf1
, quiet
);
1086 error_report("Error while reading offset %" PRId64
1087 " of %s: %s", sectors_to_bytes(sector_num
),
1088 filename_over
, strerror(-ret
));
1093 sector_num
+= nb_sectors
;
1094 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1098 qprintf(quiet
, "Images are identical.\n");
1108 qemu_progress_end();
1112 static int img_convert(int argc
, char **argv
)
1114 int c
, ret
= 0, n
, n1
, bs_n
, bs_i
, compress
, cluster_size
, cluster_sectors
;
1115 int progress
= 0, flags
;
1116 const char *fmt
, *out_fmt
, *cache
, *out_baseimg
, *out_filename
;
1117 BlockDriver
*drv
, *proto_drv
;
1118 BlockDriverState
**bs
= NULL
, *out_bs
= NULL
;
1119 int64_t total_sectors
, nb_sectors
, sector_num
, bs_offset
;
1120 uint64_t bs_sectors
;
1121 uint8_t * buf
= NULL
;
1122 const uint8_t *buf1
;
1123 BlockDriverInfo bdi
;
1124 QEMUOptionParameter
*param
= NULL
, *create_options
= NULL
;
1125 QEMUOptionParameter
*out_baseimg_param
;
1126 char *options
= NULL
;
1127 const char *snapshot_name
= NULL
;
1128 float local_progress
= 0;
1129 int min_sparse
= 8; /* Need at least 4k of zeros for sparse detection */
1138 c
= getopt(argc
, argv
, "f:O:B:s:hce6o:pS:t:q");
1154 out_baseimg
= optarg
;
1160 error_report("option -e is deprecated, please use \'-o "
1161 "encryption\' instead!");
1164 error_report("option -6 is deprecated, please use \'-o "
1165 "compat6\' instead!");
1171 snapshot_name
= optarg
;
1177 sval
= strtosz_suffix(optarg
, &end
, STRTOSZ_DEFSUFFIX_B
);
1178 if (sval
< 0 || *end
) {
1179 error_report("Invalid minimum zero buffer size for sparse output specified");
1183 min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
1202 bs_n
= argc
- optind
- 1;
1207 out_filename
= argv
[argc
- 1];
1209 /* Initialize before goto out */
1210 qemu_progress_init(progress
, 2.0);
1212 if (options
&& is_help_option(options
)) {
1213 ret
= print_block_option_help(out_filename
, out_fmt
);
1217 if (bs_n
> 1 && out_baseimg
) {
1218 error_report("-B makes no sense when concatenating multiple input "
1224 qemu_progress_print(0, 100);
1226 bs
= g_malloc0(bs_n
* sizeof(BlockDriverState
*));
1229 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
1230 bs
[bs_i
] = bdrv_new_open(argv
[optind
+ bs_i
], fmt
, BDRV_O_FLAGS
, true,
1233 error_report("Could not open '%s'", argv
[optind
+ bs_i
]);
1237 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1238 total_sectors
+= bs_sectors
;
1241 if (snapshot_name
!= NULL
) {
1243 error_report("No support for concatenating multiple snapshot");
1247 if (bdrv_snapshot_load_tmp(bs
[0], snapshot_name
) < 0) {
1248 error_report("Failed to load snapshot");
1254 /* Find driver and parse its options */
1255 drv
= bdrv_find_format(out_fmt
);
1257 error_report("Unknown file format '%s'", out_fmt
);
1262 proto_drv
= bdrv_find_protocol(out_filename
);
1264 error_report("Unknown protocol '%s'", out_filename
);
1269 create_options
= append_option_parameters(create_options
,
1270 drv
->create_options
);
1271 create_options
= append_option_parameters(create_options
,
1272 proto_drv
->create_options
);
1275 param
= parse_option_parameters(options
, create_options
, param
);
1276 if (param
== NULL
) {
1277 error_report("Invalid options for file format '%s'.", out_fmt
);
1282 param
= parse_option_parameters("", create_options
, param
);
1285 set_option_parameter_int(param
, BLOCK_OPT_SIZE
, total_sectors
* 512);
1286 ret
= add_old_style_options(out_fmt
, param
, out_baseimg
, NULL
);
1291 /* Get backing file name if -o backing_file was used */
1292 out_baseimg_param
= get_option_parameter(param
, BLOCK_OPT_BACKING_FILE
);
1293 if (out_baseimg_param
) {
1294 out_baseimg
= out_baseimg_param
->value
.s
;
1297 /* Check if compression is supported */
1299 QEMUOptionParameter
*encryption
=
1300 get_option_parameter(param
, BLOCK_OPT_ENCRYPT
);
1301 QEMUOptionParameter
*preallocation
=
1302 get_option_parameter(param
, BLOCK_OPT_PREALLOC
);
1304 if (!drv
->bdrv_write_compressed
) {
1305 error_report("Compression not supported for this file format");
1310 if (encryption
&& encryption
->value
.n
) {
1311 error_report("Compression and encryption not supported at "
1317 if (preallocation
&& preallocation
->value
.s
1318 && strcmp(preallocation
->value
.s
, "off"))
1320 error_report("Compression and preallocation not supported at "
1327 /* Create the new image */
1328 ret
= bdrv_create(drv
, out_filename
, param
);
1330 if (ret
== -ENOTSUP
) {
1331 error_report("Formatting not supported for file format '%s'",
1333 } else if (ret
== -EFBIG
) {
1334 error_report("The image size is too large for file format '%s'",
1337 error_report("%s: error while converting %s: %s",
1338 out_filename
, out_fmt
, strerror(-ret
));
1343 flags
= BDRV_O_RDWR
;
1344 ret
= bdrv_parse_cache_flags(cache
, &flags
);
1346 error_report("Invalid cache option: %s", cache
);
1350 out_bs
= bdrv_new_open(out_filename
, out_fmt
, flags
, true, quiet
);
1358 bdrv_get_geometry(bs
[0], &bs_sectors
);
1359 buf
= qemu_blockalign(out_bs
, IO_BUF_SIZE
);
1362 ret
= bdrv_get_info(out_bs
, &bdi
);
1364 error_report("could not get block driver info");
1367 cluster_size
= bdi
.cluster_size
;
1368 if (cluster_size
<= 0 || cluster_size
> IO_BUF_SIZE
) {
1369 error_report("invalid cluster size");
1373 cluster_sectors
= cluster_size
>> 9;
1376 nb_sectors
= total_sectors
;
1377 if (nb_sectors
!= 0) {
1378 local_progress
= (float)100 /
1379 (nb_sectors
/ MIN(nb_sectors
, cluster_sectors
));
1387 nb_sectors
= total_sectors
- sector_num
;
1388 if (nb_sectors
<= 0)
1390 if (nb_sectors
>= cluster_sectors
)
1391 n
= cluster_sectors
;
1395 bs_num
= sector_num
- bs_offset
;
1396 assert (bs_num
>= 0);
1399 while (remainder
> 0) {
1401 while (bs_num
== bs_sectors
) {
1403 assert (bs_i
< bs_n
);
1404 bs_offset
+= bs_sectors
;
1405 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1407 /* printf("changing part: sector_num=%" PRId64 ", "
1408 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
1409 "\n", sector_num, bs_i, bs_offset, bs_sectors); */
1411 assert (bs_num
< bs_sectors
);
1413 nlow
= (remainder
> bs_sectors
- bs_num
) ? bs_sectors
- bs_num
: remainder
;
1415 ret
= bdrv_read(bs
[bs_i
], bs_num
, buf2
, nlow
);
1417 error_report("error while reading sector %" PRId64
": %s",
1418 bs_num
, strerror(-ret
));
1427 assert (remainder
== 0);
1429 if (!buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)) {
1430 ret
= bdrv_write_compressed(out_bs
, sector_num
, buf
, n
);
1432 error_report("error while compressing sector %" PRId64
1433 ": %s", sector_num
, strerror(-ret
));
1438 qemu_progress_print(local_progress
, 100);
1440 /* signal EOF to align */
1441 bdrv_write_compressed(out_bs
, 0, NULL
, 0);
1443 int has_zero_init
= bdrv_has_zero_init(out_bs
);
1445 sector_num
= 0; // total number of sectors converted so far
1446 nb_sectors
= total_sectors
- sector_num
;
1447 if (nb_sectors
!= 0) {
1448 local_progress
= (float)100 /
1449 (nb_sectors
/ MIN(nb_sectors
, IO_BUF_SIZE
/ 512));
1453 nb_sectors
= total_sectors
- sector_num
;
1454 if (nb_sectors
<= 0) {
1457 if (nb_sectors
>= (IO_BUF_SIZE
/ 512)) {
1458 n
= (IO_BUF_SIZE
/ 512);
1463 while (sector_num
- bs_offset
>= bs_sectors
) {
1465 assert (bs_i
< bs_n
);
1466 bs_offset
+= bs_sectors
;
1467 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1468 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1469 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
1470 sector_num, bs_i, bs_offset, bs_sectors); */
1473 if (n
> bs_offset
+ bs_sectors
- sector_num
) {
1474 n
= bs_offset
+ bs_sectors
- sector_num
;
1477 if (has_zero_init
) {
1478 /* If the output image is being created as a copy on write image,
1479 assume that sectors which are unallocated in the input image
1480 are present in both the output's and input's base images (no
1481 need to copy them). */
1483 if (!bdrv_is_allocated(bs
[bs_i
], sector_num
- bs_offset
,
1488 /* The next 'n1' sectors are allocated in the input image. Copy
1489 only those as they may be followed by unallocated sectors. */
1496 ret
= bdrv_read(bs
[bs_i
], sector_num
- bs_offset
, buf
, n
);
1498 error_report("error while reading sector %" PRId64
": %s",
1499 sector_num
- bs_offset
, strerror(-ret
));
1502 /* NOTE: at the same time we convert, we do not write zero
1503 sectors to have a chance to compress the image. Ideally, we
1504 should add a specific call to have the info to go faster */
1507 /* If the output image is being created as a copy on write image,
1508 copy all sectors even the ones containing only NUL bytes,
1509 because they may differ from the sectors in the base image.
1511 If the output is to a host device, we also write out
1512 sectors that are entirely 0, since whatever data was
1513 already there is garbage, not 0s. */
1514 if (!has_zero_init
|| out_baseimg
||
1515 is_allocated_sectors_min(buf1
, n
, &n1
, min_sparse
)) {
1516 ret
= bdrv_write(out_bs
, sector_num
, buf1
, n1
);
1518 error_report("error while writing sector %" PRId64
1519 ": %s", sector_num
, strerror(-ret
));
1527 qemu_progress_print(local_progress
, 100);
1531 qemu_progress_end();
1532 free_option_parameters(create_options
);
1533 free_option_parameters(param
);
1536 bdrv_delete(out_bs
);
1539 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
1541 bdrv_delete(bs
[bs_i
]);
1553 static void dump_snapshots(BlockDriverState
*bs
)
1555 QEMUSnapshotInfo
*sn_tab
, *sn
;
1559 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
1562 printf("Snapshot list:\n");
1563 printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
1564 for(i
= 0; i
< nb_sns
; i
++) {
1566 printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
1571 static void dump_json_image_info_list(ImageInfoList
*list
)
1575 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
1577 visit_type_ImageInfoList(qmp_output_get_visitor(ov
),
1578 &list
, NULL
, &errp
);
1579 obj
= qmp_output_get_qobject(ov
);
1580 str
= qobject_to_json_pretty(obj
);
1581 assert(str
!= NULL
);
1582 printf("%s\n", qstring_get_str(str
));
1583 qobject_decref(obj
);
1584 qmp_output_visitor_cleanup(ov
);
1588 static void dump_json_image_info(ImageInfo
*info
)
1592 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
1594 visit_type_ImageInfo(qmp_output_get_visitor(ov
),
1595 &info
, NULL
, &errp
);
1596 obj
= qmp_output_get_qobject(ov
);
1597 str
= qobject_to_json_pretty(obj
);
1598 assert(str
!= NULL
);
1599 printf("%s\n", qstring_get_str(str
));
1600 qobject_decref(obj
);
1601 qmp_output_visitor_cleanup(ov
);
1605 static void dump_human_image_info_list(ImageInfoList
*list
)
1607 ImageInfoList
*elem
;
1610 for (elem
= list
; elem
; elem
= elem
->next
) {
1616 bdrv_image_info_dump(elem
->value
);
1620 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
1622 return strcmp(a
, b
) == 0;
1626 * Open an image file chain and return an ImageInfoList
1628 * @filename: topmost image filename
1629 * @fmt: topmost image format (may be NULL to autodetect)
1630 * @chain: true - enumerate entire backing file chain
1631 * false - only topmost image file
1633 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1634 * image file. If there was an error a message will have been printed to
1637 static ImageInfoList
*collect_image_info_list(const char *filename
,
1641 ImageInfoList
*head
= NULL
;
1642 ImageInfoList
**last
= &head
;
1643 GHashTable
*filenames
;
1645 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
1648 BlockDriverState
*bs
;
1650 ImageInfoList
*elem
;
1652 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
1653 error_report("Backing file '%s' creates an infinite loop.",
1657 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
1659 bs
= bdrv_new_open(filename
, fmt
, BDRV_O_FLAGS
| BDRV_O_NO_BACKING
,
1665 info
= g_new0(ImageInfo
, 1);
1666 bdrv_collect_image_info(bs
, info
, filename
);
1667 bdrv_collect_snapshots(bs
, info
);
1669 elem
= g_new0(ImageInfoList
, 1);
1676 filename
= fmt
= NULL
;
1678 if (info
->has_full_backing_filename
) {
1679 filename
= info
->full_backing_filename
;
1680 } else if (info
->has_backing_filename
) {
1681 filename
= info
->backing_filename
;
1683 if (info
->has_backing_filename_format
) {
1684 fmt
= info
->backing_filename_format
;
1688 g_hash_table_destroy(filenames
);
1692 qapi_free_ImageInfoList(head
);
1693 g_hash_table_destroy(filenames
);
1697 static int img_info(int argc
, char **argv
)
1700 OutputFormat output_format
= OFORMAT_HUMAN
;
1702 const char *filename
, *fmt
, *output
;
1703 ImageInfoList
*list
;
1708 int option_index
= 0;
1709 static const struct option long_options
[] = {
1710 {"help", no_argument
, 0, 'h'},
1711 {"format", required_argument
, 0, 'f'},
1712 {"output", required_argument
, 0, OPTION_OUTPUT
},
1713 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
1716 c
= getopt_long(argc
, argv
, "f:h",
1717 long_options
, &option_index
);
1732 case OPTION_BACKING_CHAIN
:
1737 if (optind
>= argc
) {
1740 filename
= argv
[optind
++];
1742 if (output
&& !strcmp(output
, "json")) {
1743 output_format
= OFORMAT_JSON
;
1744 } else if (output
&& !strcmp(output
, "human")) {
1745 output_format
= OFORMAT_HUMAN
;
1746 } else if (output
) {
1747 error_report("--output must be used with human or json as argument.");
1751 list
= collect_image_info_list(filename
, fmt
, chain
);
1756 switch (output_format
) {
1758 dump_human_image_info_list(list
);
1762 dump_json_image_info_list(list
);
1764 dump_json_image_info(list
->value
);
1769 qapi_free_ImageInfoList(list
);
1773 #define SNAPSHOT_LIST 1
1774 #define SNAPSHOT_CREATE 2
1775 #define SNAPSHOT_APPLY 3
1776 #define SNAPSHOT_DELETE 4
1778 static int img_snapshot(int argc
, char **argv
)
1780 BlockDriverState
*bs
;
1781 QEMUSnapshotInfo sn
;
1782 char *filename
, *snapshot_name
= NULL
;
1783 int c
, ret
= 0, bdrv_oflags
;
1788 bdrv_oflags
= BDRV_O_FLAGS
| BDRV_O_RDWR
;
1789 /* Parse commandline parameters */
1791 c
= getopt(argc
, argv
, "la:c:d:hq");
1805 action
= SNAPSHOT_LIST
;
1806 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
1813 action
= SNAPSHOT_APPLY
;
1814 snapshot_name
= optarg
;
1821 action
= SNAPSHOT_CREATE
;
1822 snapshot_name
= optarg
;
1829 action
= SNAPSHOT_DELETE
;
1830 snapshot_name
= optarg
;
1838 if (optind
>= argc
) {
1841 filename
= argv
[optind
++];
1843 /* Open the image */
1844 bs
= bdrv_new_open(filename
, NULL
, bdrv_oflags
, true, quiet
);
1849 /* Perform the requested action */
1855 case SNAPSHOT_CREATE
:
1856 memset(&sn
, 0, sizeof(sn
));
1857 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
1859 qemu_gettimeofday(&tv
);
1860 sn
.date_sec
= tv
.tv_sec
;
1861 sn
.date_nsec
= tv
.tv_usec
* 1000;
1863 ret
= bdrv_snapshot_create(bs
, &sn
);
1865 error_report("Could not create snapshot '%s': %d (%s)",
1866 snapshot_name
, ret
, strerror(-ret
));
1870 case SNAPSHOT_APPLY
:
1871 ret
= bdrv_snapshot_goto(bs
, snapshot_name
);
1873 error_report("Could not apply snapshot '%s': %d (%s)",
1874 snapshot_name
, ret
, strerror(-ret
));
1878 case SNAPSHOT_DELETE
:
1879 ret
= bdrv_snapshot_delete(bs
, snapshot_name
);
1881 error_report("Could not delete snapshot '%s': %d (%s)",
1882 snapshot_name
, ret
, strerror(-ret
));
1895 static int img_rebase(int argc
, char **argv
)
1897 BlockDriverState
*bs
, *bs_old_backing
= NULL
, *bs_new_backing
= NULL
;
1898 BlockDriver
*old_backing_drv
, *new_backing_drv
;
1900 const char *fmt
, *cache
, *out_basefmt
, *out_baseimg
;
1906 /* Parse commandline parameters */
1908 cache
= BDRV_DEFAULT_CACHE
;
1912 c
= getopt(argc
, argv
, "uhf:F:b:pt:q");
1925 out_basefmt
= optarg
;
1928 out_baseimg
= optarg
;
1949 if ((optind
>= argc
) || (!unsafe
&& !out_baseimg
)) {
1952 filename
= argv
[optind
++];
1954 qemu_progress_init(progress
, 2.0);
1955 qemu_progress_print(0, 100);
1957 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
1958 ret
= bdrv_parse_cache_flags(cache
, &flags
);
1960 error_report("Invalid cache option: %s", cache
);
1967 * Ignore the old backing file for unsafe rebase in case we want to correct
1968 * the reference to a renamed or moved backing file.
1970 bs
= bdrv_new_open(filename
, fmt
, flags
, true, quiet
);
1975 /* Find the right drivers for the backing files */
1976 old_backing_drv
= NULL
;
1977 new_backing_drv
= NULL
;
1979 if (!unsafe
&& bs
->backing_format
[0] != '\0') {
1980 old_backing_drv
= bdrv_find_format(bs
->backing_format
);
1981 if (old_backing_drv
== NULL
) {
1982 error_report("Invalid format name: '%s'", bs
->backing_format
);
1988 if (out_basefmt
!= NULL
) {
1989 new_backing_drv
= bdrv_find_format(out_basefmt
);
1990 if (new_backing_drv
== NULL
) {
1991 error_report("Invalid format name: '%s'", out_basefmt
);
1997 /* For safe rebasing we need to compare old and new backing file */
1999 /* Make the compiler happy */
2000 bs_old_backing
= NULL
;
2001 bs_new_backing
= NULL
;
2003 char backing_name
[1024];
2005 bs_old_backing
= bdrv_new("old_backing");
2006 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
2007 ret
= bdrv_open(bs_old_backing
, backing_name
, NULL
, BDRV_O_FLAGS
,
2010 error_report("Could not open old backing file '%s'", backing_name
);
2013 if (out_baseimg
[0]) {
2014 bs_new_backing
= bdrv_new("new_backing");
2015 ret
= bdrv_open(bs_new_backing
, out_baseimg
, NULL
, BDRV_O_FLAGS
,
2018 error_report("Could not open new backing file '%s'",
2026 * Check each unallocated cluster in the COW file. If it is unallocated,
2027 * accesses go to the backing file. We must therefore compare this cluster
2028 * in the old and new backing file, and if they differ we need to copy it
2029 * from the old backing file into the COW file.
2031 * If qemu-img crashes during this step, no harm is done. The content of
2032 * the image is the same as the original one at any time.
2035 uint64_t num_sectors
;
2036 uint64_t old_backing_num_sectors
;
2037 uint64_t new_backing_num_sectors
= 0;
2042 float local_progress
= 0;
2044 buf_old
= qemu_blockalign(bs
, IO_BUF_SIZE
);
2045 buf_new
= qemu_blockalign(bs
, IO_BUF_SIZE
);
2047 bdrv_get_geometry(bs
, &num_sectors
);
2048 bdrv_get_geometry(bs_old_backing
, &old_backing_num_sectors
);
2049 if (bs_new_backing
) {
2050 bdrv_get_geometry(bs_new_backing
, &new_backing_num_sectors
);
2053 if (num_sectors
!= 0) {
2054 local_progress
= (float)100 /
2055 (num_sectors
/ MIN(num_sectors
, IO_BUF_SIZE
/ 512));
2058 for (sector
= 0; sector
< num_sectors
; sector
+= n
) {
2060 /* How many sectors can we handle with the next read? */
2061 if (sector
+ (IO_BUF_SIZE
/ 512) <= num_sectors
) {
2062 n
= (IO_BUF_SIZE
/ 512);
2064 n
= num_sectors
- sector
;
2067 /* If the cluster is allocated, we don't need to take action */
2068 ret
= bdrv_is_allocated(bs
, sector
, n
, &n
);
2074 * Read old and new backing file and take into consideration that
2075 * backing files may be smaller than the COW image.
2077 if (sector
>= old_backing_num_sectors
) {
2078 memset(buf_old
, 0, n
* BDRV_SECTOR_SIZE
);
2080 if (sector
+ n
> old_backing_num_sectors
) {
2081 n
= old_backing_num_sectors
- sector
;
2084 ret
= bdrv_read(bs_old_backing
, sector
, buf_old
, n
);
2086 error_report("error while reading from old backing file");
2091 if (sector
>= new_backing_num_sectors
|| !bs_new_backing
) {
2092 memset(buf_new
, 0, n
* BDRV_SECTOR_SIZE
);
2094 if (sector
+ n
> new_backing_num_sectors
) {
2095 n
= new_backing_num_sectors
- sector
;
2098 ret
= bdrv_read(bs_new_backing
, sector
, buf_new
, n
);
2100 error_report("error while reading from new backing file");
2105 /* If they differ, we need to write to the COW file */
2106 uint64_t written
= 0;
2108 while (written
< n
) {
2111 if (compare_sectors(buf_old
+ written
* 512,
2112 buf_new
+ written
* 512, n
- written
, &pnum
))
2114 ret
= bdrv_write(bs
, sector
+ written
,
2115 buf_old
+ written
* 512, pnum
);
2117 error_report("Error while writing to COW image: %s",
2125 qemu_progress_print(local_progress
, 100);
2128 qemu_vfree(buf_old
);
2129 qemu_vfree(buf_new
);
2133 * Change the backing file. All clusters that are different from the old
2134 * backing file are overwritten in the COW file now, so the visible content
2135 * doesn't change when we switch the backing file.
2137 if (out_baseimg
&& *out_baseimg
) {
2138 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
2140 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
2143 if (ret
== -ENOSPC
) {
2144 error_report("Could not change the backing file to '%s': No "
2145 "space left in the file header", out_baseimg
);
2146 } else if (ret
< 0) {
2147 error_report("Could not change the backing file to '%s': %s",
2148 out_baseimg
, strerror(-ret
));
2151 qemu_progress_print(100, 0);
2153 * TODO At this point it is possible to check if any clusters that are
2154 * allocated in the COW file are the same in the backing file. If so, they
2155 * could be dropped from the COW file. Don't do this before switching the
2156 * backing file, in case of a crash this would lead to corruption.
2159 qemu_progress_end();
2162 if (bs_old_backing
!= NULL
) {
2163 bdrv_delete(bs_old_backing
);
2165 if (bs_new_backing
!= NULL
) {
2166 bdrv_delete(bs_new_backing
);
2177 static int img_resize(int argc
, char **argv
)
2179 int c
, ret
, relative
;
2180 const char *filename
, *fmt
, *size
;
2181 int64_t n
, total_size
;
2183 BlockDriverState
*bs
= NULL
;
2185 static QemuOptsList resize_options
= {
2186 .name
= "resize_options",
2187 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
2190 .name
= BLOCK_OPT_SIZE
,
2191 .type
= QEMU_OPT_SIZE
,
2192 .help
= "Virtual disk size"
2199 /* Remove size from argv manually so that negative numbers are not treated
2200 * as options by getopt. */
2206 size
= argv
[--argc
];
2208 /* Parse getopt arguments */
2211 c
= getopt(argc
, argv
, "f:hq");
2228 if (optind
>= argc
) {
2231 filename
= argv
[optind
++];
2233 /* Choose grow, shrink, or absolute resize mode */
2249 param
= qemu_opts_create_nofail(&resize_options
);
2250 if (qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
)) {
2251 /* Error message already printed when size parsing fails */
2253 qemu_opts_del(param
);
2256 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
2257 qemu_opts_del(param
);
2259 bs
= bdrv_new_open(filename
, fmt
, BDRV_O_FLAGS
| BDRV_O_RDWR
, true, quiet
);
2266 total_size
= bdrv_getlength(bs
) + n
* relative
;
2270 if (total_size
<= 0) {
2271 error_report("New image size must be positive");
2276 ret
= bdrv_truncate(bs
, total_size
);
2279 qprintf(quiet
, "Image resized.\n");
2282 error_report("This image does not support resize");
2285 error_report("Image is read-only");
2288 error_report("Error resizing image (%d)", -ret
);
2301 static const img_cmd_t img_cmds
[] = {
2302 #define DEF(option, callback, arg_string) \
2303 { option, callback },
2304 #include "qemu-img-cmds.h"
2310 int main(int argc
, char **argv
)
2312 const img_cmd_t
*cmd
;
2313 const char *cmdname
;
2315 error_set_progname(argv
[0]);
2317 qemu_init_main_loop();
2324 /* find the command */
2325 for(cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
2326 if (!strcmp(cmdname
, cmd
->name
)) {
2327 return cmd
->handler(argc
, argv
);