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"
107 "Parameters to check subcommand:\n"
108 " '-r' tries to repair any inconsistencies that are found during the check.\n"
109 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
110 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
111 " hiding corruption that has already occurred.\n"
113 "Parameters to snapshot subcommand:\n"
114 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
115 " '-a' applies a snapshot (revert disk to saved state)\n"
116 " '-c' creates a snapshot\n"
117 " '-d' deletes a snapshot\n"
118 " '-l' lists all snapshots in the given image\n"
120 "Parameters to compare subcommand:\n"
121 " '-f' first image format\n"
122 " '-F' second image format\n"
123 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
125 printf("%s\nSupported formats:", help_msg
);
126 bdrv_iterate_format(format_print
, NULL
);
131 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
137 ret
= vprintf(fmt
, args
);
144 /* XXX: put correct support for win32 */
145 static int read_password(char *buf
, int buf_size
)
148 printf("Password: ");
155 if (i
< (buf_size
- 1))
166 static struct termios oldtty
;
168 static void term_exit(void)
170 tcsetattr (0, TCSANOW
, &oldtty
);
173 static void term_init(void)
180 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
181 |INLCR
|IGNCR
|ICRNL
|IXON
);
182 tty
.c_oflag
|= OPOST
;
183 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
184 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
189 tcsetattr (0, TCSANOW
, &tty
);
194 static int read_password(char *buf
, int buf_size
)
199 printf("password: ");
204 ret
= read(0, &ch
, 1);
206 if (errno
== EAGAIN
|| errno
== EINTR
) {
212 } else if (ret
== 0) {
220 if (i
< (buf_size
- 1))
231 static int print_block_option_help(const char *filename
, const char *fmt
)
233 BlockDriver
*drv
, *proto_drv
;
234 QEMUOptionParameter
*create_options
= NULL
;
236 /* Find driver and parse its options */
237 drv
= bdrv_find_format(fmt
);
239 error_report("Unknown file format '%s'", fmt
);
243 proto_drv
= bdrv_find_protocol(filename
, true);
245 error_report("Unknown protocol '%s'", filename
);
249 create_options
= append_option_parameters(create_options
,
250 drv
->create_options
);
251 create_options
= append_option_parameters(create_options
,
252 proto_drv
->create_options
);
253 print_option_help(create_options
);
254 free_option_parameters(create_options
);
258 static BlockDriverState
*bdrv_new_open(const char *filename
,
264 BlockDriverState
*bs
;
269 bs
= bdrv_new("image");
272 drv
= bdrv_find_format(fmt
);
274 error_report("Unknown file format '%s'", fmt
);
281 ret
= bdrv_open(bs
, filename
, NULL
, flags
, drv
);
283 error_report("Could not open '%s': %s", filename
, strerror(-ret
));
287 if (bdrv_is_encrypted(bs
) && require_io
) {
288 qprintf(quiet
, "Disk image '%s' is encrypted.\n", filename
);
289 if (read_password(password
, sizeof(password
)) < 0) {
290 error_report("No password given");
293 if (bdrv_set_key(bs
, password
) < 0) {
294 error_report("invalid password");
306 static int add_old_style_options(const char *fmt
, QEMUOptionParameter
*list
,
307 const char *base_filename
,
308 const char *base_fmt
)
311 if (set_option_parameter(list
, BLOCK_OPT_BACKING_FILE
, base_filename
)) {
312 error_report("Backing file not supported for file format '%s'",
318 if (set_option_parameter(list
, BLOCK_OPT_BACKING_FMT
, base_fmt
)) {
319 error_report("Backing file format not supported for file "
327 static int img_create(int argc
, char **argv
)
330 uint64_t img_size
= -1;
331 const char *fmt
= "raw";
332 const char *base_fmt
= NULL
;
333 const char *filename
;
334 const char *base_filename
= NULL
;
335 char *options
= NULL
;
336 Error
*local_err
= NULL
;
340 c
= getopt(argc
, argv
, "F:b:f:he6o:q");
353 base_filename
= optarg
;
359 error_report("option -e is deprecated, please use \'-o "
360 "encryption\' instead!");
363 error_report("option -6 is deprecated, please use \'-o "
364 "compat6\' instead!");
375 /* Get the filename */
376 if (optind
>= argc
) {
379 filename
= argv
[optind
++];
381 /* Get image size, if specified */
385 sval
= strtosz_suffix(argv
[optind
++], &end
, STRTOSZ_DEFSUFFIX_B
);
386 if (sval
< 0 || *end
) {
387 if (sval
== -ERANGE
) {
388 error_report("Image size must be less than 8 EiB!");
390 error_report("Invalid image size specified! You may use k, M, "
391 "G, T, P or E suffixes for ");
392 error_report("kilobytes, megabytes, gigabytes, terabytes, "
393 "petabytes and exabytes.");
397 img_size
= (uint64_t)sval
;
399 if (optind
!= argc
) {
403 if (options
&& is_help_option(options
)) {
404 return print_block_option_help(filename
, fmt
);
407 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
408 options
, img_size
, BDRV_O_FLAGS
, &local_err
, quiet
);
409 if (error_is_set(&local_err
)) {
410 error_report("%s", error_get_pretty(local_err
));
411 error_free(local_err
);
418 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
422 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
424 visit_type_ImageCheck(qmp_output_get_visitor(ov
),
425 &check
, NULL
, &errp
);
426 obj
= qmp_output_get_qobject(ov
);
427 str
= qobject_to_json_pretty(obj
);
429 qprintf(quiet
, "%s\n", qstring_get_str(str
));
431 qmp_output_visitor_cleanup(ov
);
435 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
437 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
438 qprintf(quiet
, "No errors were found on the image.\n");
440 if (check
->corruptions
) {
441 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
442 "Data may be corrupted, or further writes to the image "
449 "\n%" PRId64
" leaked clusters were found on the image.\n"
450 "This means waste of disk space, but no harm to data.\n",
454 if (check
->check_errors
) {
457 " internal errors have occurred during the check.\n",
458 check
->check_errors
);
462 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
463 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
464 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
465 check
->allocated_clusters
, check
->total_clusters
,
466 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
467 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
468 check
->compressed_clusters
* 100.0 /
469 check
->allocated_clusters
);
472 if (check
->image_end_offset
) {
474 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
478 static int collect_image_check(BlockDriverState
*bs
,
480 const char *filename
,
485 BdrvCheckResult result
;
487 ret
= bdrv_check(bs
, &result
, fix
);
492 check
->filename
= g_strdup(filename
);
493 check
->format
= g_strdup(bdrv_get_format_name(bs
));
494 check
->check_errors
= result
.check_errors
;
495 check
->corruptions
= result
.corruptions
;
496 check
->has_corruptions
= result
.corruptions
!= 0;
497 check
->leaks
= result
.leaks
;
498 check
->has_leaks
= result
.leaks
!= 0;
499 check
->corruptions_fixed
= result
.corruptions_fixed
;
500 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
501 check
->leaks_fixed
= result
.leaks_fixed
;
502 check
->has_leaks_fixed
= result
.leaks
!= 0;
503 check
->image_end_offset
= result
.image_end_offset
;
504 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
505 check
->total_clusters
= result
.bfi
.total_clusters
;
506 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
507 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
508 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
509 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
510 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
511 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
512 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
518 * Checks an image for consistency. Exit codes:
520 * 0 - Check completed, image is good
521 * 1 - Check not completed because of internal errors
522 * 2 - Check completed, image is corrupted
523 * 3 - Check completed, image has leaked clusters, but is good otherwise
525 static int img_check(int argc
, char **argv
)
528 OutputFormat output_format
= OFORMAT_HUMAN
;
529 const char *filename
, *fmt
, *output
;
530 BlockDriverState
*bs
;
532 int flags
= BDRV_O_FLAGS
| BDRV_O_CHECK
;
539 int option_index
= 0;
540 static const struct option long_options
[] = {
541 {"help", no_argument
, 0, 'h'},
542 {"format", required_argument
, 0, 'f'},
543 {"repair", no_argument
, 0, 'r'},
544 {"output", required_argument
, 0, OPTION_OUTPUT
},
547 c
= getopt_long(argc
, argv
, "f:hr:q",
548 long_options
, &option_index
);
561 flags
|= BDRV_O_RDWR
;
563 if (!strcmp(optarg
, "leaks")) {
564 fix
= BDRV_FIX_LEAKS
;
565 } else if (!strcmp(optarg
, "all")) {
566 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
579 if (optind
!= argc
- 1) {
582 filename
= argv
[optind
++];
584 if (output
&& !strcmp(output
, "json")) {
585 output_format
= OFORMAT_JSON
;
586 } else if (output
&& !strcmp(output
, "human")) {
587 output_format
= OFORMAT_HUMAN
;
589 error_report("--output must be used with human or json as argument.");
593 bs
= bdrv_new_open(filename
, fmt
, flags
, true, quiet
);
598 check
= g_new0(ImageCheck
, 1);
599 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
601 if (ret
== -ENOTSUP
) {
602 if (output_format
== OFORMAT_HUMAN
) {
603 error_report("This image format does not support checks");
609 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
610 int corruptions_fixed
, leaks_fixed
;
612 leaks_fixed
= check
->leaks_fixed
;
613 corruptions_fixed
= check
->corruptions_fixed
;
615 if (output_format
== OFORMAT_HUMAN
) {
617 "The following inconsistencies were found and repaired:\n\n"
618 " %" PRId64
" leaked clusters\n"
619 " %" PRId64
" corruptions\n\n"
620 "Double checking the fixed image now...\n",
622 check
->corruptions_fixed
);
625 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
627 check
->leaks_fixed
= leaks_fixed
;
628 check
->corruptions_fixed
= corruptions_fixed
;
631 switch (output_format
) {
633 dump_human_image_check(check
, quiet
);
636 dump_json_image_check(check
, quiet
);
640 if (ret
|| check
->check_errors
) {
645 if (check
->corruptions
) {
647 } else if (check
->leaks
) {
654 qapi_free_ImageCheck(check
);
660 static int img_commit(int argc
, char **argv
)
663 const char *filename
, *fmt
, *cache
;
664 BlockDriverState
*bs
;
668 cache
= BDRV_DEFAULT_CACHE
;
670 c
= getopt(argc
, argv
, "f:ht:q");
690 if (optind
!= argc
- 1) {
693 filename
= argv
[optind
++];
696 ret
= bdrv_parse_cache_flags(cache
, &flags
);
698 error_report("Invalid cache option: %s", cache
);
702 bs
= bdrv_new_open(filename
, fmt
, flags
, true, quiet
);
706 ret
= bdrv_commit(bs
);
709 qprintf(quiet
, "Image committed.\n");
712 error_report("No disk inserted");
715 error_report("Image is read-only");
718 error_report("Image is already committed");
721 error_report("Error while committing image");
733 * Returns true iff the first sector pointed to by 'buf' contains at least
736 * 'pnum' is set to the number of sectors (including and immediately following
737 * the first one) that are known to be in the same allocated/unallocated state.
739 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
)
748 is_zero
= buffer_is_zero(buf
, 512);
749 for(i
= 1; i
< n
; i
++) {
751 if (is_zero
!= buffer_is_zero(buf
, 512)) {
760 * Like is_allocated_sectors, but if the buffer starts with a used sector,
761 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
762 * breaking up write requests for only small sparse areas.
764 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
768 int num_checked
, num_used
;
774 ret
= is_allocated_sectors(buf
, n
, pnum
);
780 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
782 num_checked
= num_used
;
785 ret
= is_allocated_sectors(buf
, n
, pnum
);
787 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
789 num_checked
+= *pnum
;
791 num_used
= num_checked
;
792 } else if (*pnum
>= min
) {
802 * Compares two buffers sector by sector. Returns 0 if the first sector of both
803 * buffers matches, non-zero otherwise.
805 * pnum is set to the number of sectors (including and immediately following
806 * the first one) that are known to have the same comparison result
808 static int compare_sectors(const uint8_t *buf1
, const uint8_t *buf2
, int n
,
818 res
= !!memcmp(buf1
, buf2
, 512);
819 for(i
= 1; i
< n
; i
++) {
823 if (!!memcmp(buf1
, buf2
, 512) != res
) {
832 #define IO_BUF_SIZE (2 * 1024 * 1024)
834 static int64_t sectors_to_bytes(int64_t sectors
)
836 return sectors
<< BDRV_SECTOR_BITS
;
839 static int64_t sectors_to_process(int64_t total
, int64_t from
)
841 return MIN(total
- from
, IO_BUF_SIZE
>> BDRV_SECTOR_BITS
);
845 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
847 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
848 * data and negative value on error.
850 * @param bs: Driver used for accessing file
851 * @param sect_num: Number of first sector to check
852 * @param sect_count: Number of sectors to check
853 * @param filename: Name of disk file we are checking (logging purpose)
854 * @param buffer: Allocated buffer for storing read data
855 * @param quiet: Flag for quiet mode
857 static int check_empty_sectors(BlockDriverState
*bs
, int64_t sect_num
,
858 int sect_count
, const char *filename
,
859 uint8_t *buffer
, bool quiet
)
862 ret
= bdrv_read(bs
, sect_num
, buffer
, sect_count
);
864 error_report("Error while reading offset %" PRId64
" of %s: %s",
865 sectors_to_bytes(sect_num
), filename
, strerror(-ret
));
868 ret
= is_allocated_sectors(buffer
, sect_count
, &pnum
);
869 if (ret
|| pnum
!= sect_count
) {
870 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
871 sectors_to_bytes(ret
? sect_num
: sect_num
+ pnum
));
879 * Compares two images. Exit codes:
881 * 0 - Images are identical
883 * >1 - Error occurred
885 static int img_compare(int argc
, char **argv
)
887 const char *fmt1
= NULL
, *fmt2
= NULL
, *filename1
, *filename2
;
888 BlockDriverState
*bs1
, *bs2
;
889 int64_t total_sectors1
, total_sectors2
;
890 uint8_t *buf1
= NULL
, *buf2
= NULL
;
892 int allocated1
, allocated2
;
893 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
894 bool progress
= false, quiet
= false, strict
= false;
895 int64_t total_sectors
;
896 int64_t sector_num
= 0;
900 uint64_t progress_base
;
903 c
= getopt(argc
, argv
, "hpf:F:sq");
930 /* Progress is not shown in Quiet mode */
936 if (optind
!= argc
- 2) {
939 filename1
= argv
[optind
++];
940 filename2
= argv
[optind
++];
942 /* Initialize before goto out */
943 qemu_progress_init(progress
, 2.0);
945 bs1
= bdrv_new_open(filename1
, fmt1
, BDRV_O_FLAGS
, true, quiet
);
947 error_report("Can't open file %s", filename1
);
952 bs2
= bdrv_new_open(filename2
, fmt2
, BDRV_O_FLAGS
, true, quiet
);
954 error_report("Can't open file %s", filename2
);
959 buf1
= qemu_blockalign(bs1
, IO_BUF_SIZE
);
960 buf2
= qemu_blockalign(bs2
, IO_BUF_SIZE
);
961 bdrv_get_geometry(bs1
, &bs_sectors
);
962 total_sectors1
= bs_sectors
;
963 bdrv_get_geometry(bs2
, &bs_sectors
);
964 total_sectors2
= bs_sectors
;
965 total_sectors
= MIN(total_sectors1
, total_sectors2
);
966 progress_base
= MAX(total_sectors1
, total_sectors2
);
968 qemu_progress_print(0, 100);
970 if (strict
&& total_sectors1
!= total_sectors2
) {
972 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
977 nb_sectors
= sectors_to_process(total_sectors
, sector_num
);
978 if (nb_sectors
<= 0) {
981 allocated1
= bdrv_is_allocated_above(bs1
, NULL
, sector_num
, nb_sectors
,
983 if (allocated1
< 0) {
985 error_report("Sector allocation test failed for %s", filename1
);
989 allocated2
= bdrv_is_allocated_above(bs2
, NULL
, sector_num
, nb_sectors
,
991 if (allocated2
< 0) {
993 error_report("Sector allocation test failed for %s", filename2
);
996 nb_sectors
= MIN(pnum1
, pnum2
);
998 if (allocated1
== allocated2
) {
1000 ret
= bdrv_read(bs1
, sector_num
, buf1
, nb_sectors
);
1002 error_report("Error while reading offset %" PRId64
" of %s:"
1003 " %s", sectors_to_bytes(sector_num
), filename1
,
1008 ret
= bdrv_read(bs2
, sector_num
, buf2
, nb_sectors
);
1010 error_report("Error while reading offset %" PRId64
1011 " of %s: %s", sectors_to_bytes(sector_num
),
1012 filename2
, strerror(-ret
));
1016 ret
= compare_sectors(buf1
, buf2
, nb_sectors
, &pnum
);
1017 if (ret
|| pnum
!= nb_sectors
) {
1019 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1021 ret
? sector_num
: sector_num
+ pnum
));
1028 qprintf(quiet
, "Strict mode: Offset %" PRId64
1029 " allocation mismatch!\n",
1030 sectors_to_bytes(sector_num
));
1035 ret
= check_empty_sectors(bs1
, sector_num
, nb_sectors
,
1036 filename1
, buf1
, quiet
);
1038 ret
= check_empty_sectors(bs2
, sector_num
, nb_sectors
,
1039 filename2
, buf1
, quiet
);
1044 error_report("Error while reading offset %" PRId64
": %s",
1045 sectors_to_bytes(sector_num
), strerror(-ret
));
1050 sector_num
+= nb_sectors
;
1051 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1054 if (total_sectors1
!= total_sectors2
) {
1055 BlockDriverState
*bs_over
;
1056 int64_t total_sectors_over
;
1057 const char *filename_over
;
1059 qprintf(quiet
, "Warning: Image size mismatch!\n");
1060 if (total_sectors1
> total_sectors2
) {
1061 total_sectors_over
= total_sectors1
;
1063 filename_over
= filename1
;
1065 total_sectors_over
= total_sectors2
;
1067 filename_over
= filename2
;
1071 nb_sectors
= sectors_to_process(total_sectors_over
, sector_num
);
1072 if (nb_sectors
<= 0) {
1075 ret
= bdrv_is_allocated_above(bs_over
, NULL
, sector_num
,
1079 error_report("Sector allocation test failed for %s",
1086 ret
= check_empty_sectors(bs_over
, sector_num
, nb_sectors
,
1087 filename_over
, buf1
, quiet
);
1091 error_report("Error while reading offset %" PRId64
1092 " of %s: %s", sectors_to_bytes(sector_num
),
1093 filename_over
, strerror(-ret
));
1098 sector_num
+= nb_sectors
;
1099 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1103 qprintf(quiet
, "Images are identical.\n");
1113 qemu_progress_end();
1117 static int img_convert(int argc
, char **argv
)
1119 int c
, ret
= 0, n
, n1
, bs_n
, bs_i
, compress
, cluster_size
, cluster_sectors
;
1120 int progress
= 0, flags
;
1121 const char *fmt
, *out_fmt
, *cache
, *out_baseimg
, *out_filename
;
1122 BlockDriver
*drv
, *proto_drv
;
1123 BlockDriverState
**bs
= NULL
, *out_bs
= NULL
;
1124 int64_t total_sectors
, nb_sectors
, sector_num
, bs_offset
;
1125 uint64_t bs_sectors
;
1126 uint8_t * buf
= NULL
;
1127 const uint8_t *buf1
;
1128 BlockDriverInfo bdi
;
1129 QEMUOptionParameter
*param
= NULL
, *create_options
= NULL
;
1130 QEMUOptionParameter
*out_baseimg_param
;
1131 char *options
= NULL
;
1132 const char *snapshot_name
= NULL
;
1133 float local_progress
= 0;
1134 int min_sparse
= 8; /* Need at least 4k of zeros for sparse detection */
1143 c
= getopt(argc
, argv
, "f:O:B:s:hce6o:pS:t:q");
1159 out_baseimg
= optarg
;
1165 error_report("option -e is deprecated, please use \'-o "
1166 "encryption\' instead!");
1169 error_report("option -6 is deprecated, please use \'-o "
1170 "compat6\' instead!");
1176 snapshot_name
= optarg
;
1182 sval
= strtosz_suffix(optarg
, &end
, STRTOSZ_DEFSUFFIX_B
);
1183 if (sval
< 0 || *end
) {
1184 error_report("Invalid minimum zero buffer size for sparse output specified");
1188 min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
1207 bs_n
= argc
- optind
- 1;
1212 out_filename
= argv
[argc
- 1];
1214 /* Initialize before goto out */
1215 qemu_progress_init(progress
, 2.0);
1217 if (options
&& is_help_option(options
)) {
1218 ret
= print_block_option_help(out_filename
, out_fmt
);
1222 if (bs_n
> 1 && out_baseimg
) {
1223 error_report("-B makes no sense when concatenating multiple input "
1229 qemu_progress_print(0, 100);
1231 bs
= g_malloc0(bs_n
* sizeof(BlockDriverState
*));
1234 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
1235 bs
[bs_i
] = bdrv_new_open(argv
[optind
+ bs_i
], fmt
, BDRV_O_FLAGS
, true,
1238 error_report("Could not open '%s'", argv
[optind
+ bs_i
]);
1242 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1243 total_sectors
+= bs_sectors
;
1246 if (snapshot_name
!= NULL
) {
1248 error_report("No support for concatenating multiple snapshot");
1252 if (bdrv_snapshot_load_tmp(bs
[0], snapshot_name
) < 0) {
1253 error_report("Failed to load snapshot");
1259 /* Find driver and parse its options */
1260 drv
= bdrv_find_format(out_fmt
);
1262 error_report("Unknown file format '%s'", out_fmt
);
1267 proto_drv
= bdrv_find_protocol(out_filename
, true);
1269 error_report("Unknown protocol '%s'", out_filename
);
1274 create_options
= append_option_parameters(create_options
,
1275 drv
->create_options
);
1276 create_options
= append_option_parameters(create_options
,
1277 proto_drv
->create_options
);
1280 param
= parse_option_parameters(options
, create_options
, param
);
1281 if (param
== NULL
) {
1282 error_report("Invalid options for file format '%s'.", out_fmt
);
1287 param
= parse_option_parameters("", create_options
, param
);
1290 set_option_parameter_int(param
, BLOCK_OPT_SIZE
, total_sectors
* 512);
1291 ret
= add_old_style_options(out_fmt
, param
, out_baseimg
, NULL
);
1296 /* Get backing file name if -o backing_file was used */
1297 out_baseimg_param
= get_option_parameter(param
, BLOCK_OPT_BACKING_FILE
);
1298 if (out_baseimg_param
) {
1299 out_baseimg
= out_baseimg_param
->value
.s
;
1302 /* Check if compression is supported */
1304 QEMUOptionParameter
*encryption
=
1305 get_option_parameter(param
, BLOCK_OPT_ENCRYPT
);
1306 QEMUOptionParameter
*preallocation
=
1307 get_option_parameter(param
, BLOCK_OPT_PREALLOC
);
1309 if (!drv
->bdrv_write_compressed
) {
1310 error_report("Compression not supported for this file format");
1315 if (encryption
&& encryption
->value
.n
) {
1316 error_report("Compression and encryption not supported at "
1322 if (preallocation
&& preallocation
->value
.s
1323 && strcmp(preallocation
->value
.s
, "off"))
1325 error_report("Compression and preallocation not supported at "
1332 /* Create the new image */
1333 ret
= bdrv_create(drv
, out_filename
, param
);
1335 if (ret
== -ENOTSUP
) {
1336 error_report("Formatting not supported for file format '%s'",
1338 } else if (ret
== -EFBIG
) {
1339 error_report("The image size is too large for file format '%s'",
1342 error_report("%s: error while converting %s: %s",
1343 out_filename
, out_fmt
, strerror(-ret
));
1348 flags
= BDRV_O_RDWR
;
1349 ret
= bdrv_parse_cache_flags(cache
, &flags
);
1351 error_report("Invalid cache option: %s", cache
);
1355 out_bs
= bdrv_new_open(out_filename
, out_fmt
, flags
, true, quiet
);
1363 bdrv_get_geometry(bs
[0], &bs_sectors
);
1364 buf
= qemu_blockalign(out_bs
, IO_BUF_SIZE
);
1367 ret
= bdrv_get_info(out_bs
, &bdi
);
1369 error_report("could not get block driver info");
1372 cluster_size
= bdi
.cluster_size
;
1373 if (cluster_size
<= 0 || cluster_size
> IO_BUF_SIZE
) {
1374 error_report("invalid cluster size");
1378 cluster_sectors
= cluster_size
>> 9;
1381 nb_sectors
= total_sectors
;
1382 if (nb_sectors
!= 0) {
1383 local_progress
= (float)100 /
1384 (nb_sectors
/ MIN(nb_sectors
, cluster_sectors
));
1392 nb_sectors
= total_sectors
- sector_num
;
1393 if (nb_sectors
<= 0)
1395 if (nb_sectors
>= cluster_sectors
)
1396 n
= cluster_sectors
;
1400 bs_num
= sector_num
- bs_offset
;
1401 assert (bs_num
>= 0);
1404 while (remainder
> 0) {
1406 while (bs_num
== bs_sectors
) {
1408 assert (bs_i
< bs_n
);
1409 bs_offset
+= bs_sectors
;
1410 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1412 /* printf("changing part: sector_num=%" PRId64 ", "
1413 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
1414 "\n", sector_num, bs_i, bs_offset, bs_sectors); */
1416 assert (bs_num
< bs_sectors
);
1418 nlow
= (remainder
> bs_sectors
- bs_num
) ? bs_sectors
- bs_num
: remainder
;
1420 ret
= bdrv_read(bs
[bs_i
], bs_num
, buf2
, nlow
);
1422 error_report("error while reading sector %" PRId64
": %s",
1423 bs_num
, strerror(-ret
));
1432 assert (remainder
== 0);
1434 if (!buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)) {
1435 ret
= bdrv_write_compressed(out_bs
, sector_num
, buf
, n
);
1437 error_report("error while compressing sector %" PRId64
1438 ": %s", sector_num
, strerror(-ret
));
1443 qemu_progress_print(local_progress
, 100);
1445 /* signal EOF to align */
1446 bdrv_write_compressed(out_bs
, 0, NULL
, 0);
1448 int has_zero_init
= bdrv_has_zero_init(out_bs
);
1450 sector_num
= 0; // total number of sectors converted so far
1451 nb_sectors
= total_sectors
- sector_num
;
1452 if (nb_sectors
!= 0) {
1453 local_progress
= (float)100 /
1454 (nb_sectors
/ MIN(nb_sectors
, IO_BUF_SIZE
/ 512));
1458 nb_sectors
= total_sectors
- sector_num
;
1459 if (nb_sectors
<= 0) {
1462 if (nb_sectors
>= (IO_BUF_SIZE
/ 512)) {
1463 n
= (IO_BUF_SIZE
/ 512);
1468 while (sector_num
- bs_offset
>= bs_sectors
) {
1470 assert (bs_i
< bs_n
);
1471 bs_offset
+= bs_sectors
;
1472 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1473 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1474 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
1475 sector_num, bs_i, bs_offset, bs_sectors); */
1478 if (n
> bs_offset
+ bs_sectors
- sector_num
) {
1479 n
= bs_offset
+ bs_sectors
- sector_num
;
1482 if (has_zero_init
) {
1483 /* If the output image is being created as a copy on write image,
1484 assume that sectors which are unallocated in the input image
1485 are present in both the output's and input's base images (no
1486 need to copy them). */
1488 if (!bdrv_is_allocated(bs
[bs_i
], sector_num
- bs_offset
,
1493 /* The next 'n1' sectors are allocated in the input image. Copy
1494 only those as they may be followed by unallocated sectors. */
1501 ret
= bdrv_read(bs
[bs_i
], sector_num
- bs_offset
, buf
, n
);
1503 error_report("error while reading sector %" PRId64
": %s",
1504 sector_num
- bs_offset
, strerror(-ret
));
1507 /* NOTE: at the same time we convert, we do not write zero
1508 sectors to have a chance to compress the image. Ideally, we
1509 should add a specific call to have the info to go faster */
1512 /* If the output image is being created as a copy on write image,
1513 copy all sectors even the ones containing only NUL bytes,
1514 because they may differ from the sectors in the base image.
1516 If the output is to a host device, we also write out
1517 sectors that are entirely 0, since whatever data was
1518 already there is garbage, not 0s. */
1519 if (!has_zero_init
|| out_baseimg
||
1520 is_allocated_sectors_min(buf1
, n
, &n1
, min_sparse
)) {
1521 ret
= bdrv_write(out_bs
, sector_num
, buf1
, n1
);
1523 error_report("error while writing sector %" PRId64
1524 ": %s", sector_num
, strerror(-ret
));
1532 qemu_progress_print(local_progress
, 100);
1536 qemu_progress_end();
1537 free_option_parameters(create_options
);
1538 free_option_parameters(param
);
1541 bdrv_delete(out_bs
);
1544 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
1546 bdrv_delete(bs
[bs_i
]);
1558 static void dump_snapshots(BlockDriverState
*bs
)
1560 QEMUSnapshotInfo
*sn_tab
, *sn
;
1563 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
1566 printf("Snapshot list:\n");
1567 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
1569 for(i
= 0; i
< nb_sns
; i
++) {
1571 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
1577 static void dump_json_image_info_list(ImageInfoList
*list
)
1581 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
1583 visit_type_ImageInfoList(qmp_output_get_visitor(ov
),
1584 &list
, NULL
, &errp
);
1585 obj
= qmp_output_get_qobject(ov
);
1586 str
= qobject_to_json_pretty(obj
);
1587 assert(str
!= NULL
);
1588 printf("%s\n", qstring_get_str(str
));
1589 qobject_decref(obj
);
1590 qmp_output_visitor_cleanup(ov
);
1594 static void dump_json_image_info(ImageInfo
*info
)
1598 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
1600 visit_type_ImageInfo(qmp_output_get_visitor(ov
),
1601 &info
, NULL
, &errp
);
1602 obj
= qmp_output_get_qobject(ov
);
1603 str
= qobject_to_json_pretty(obj
);
1604 assert(str
!= NULL
);
1605 printf("%s\n", qstring_get_str(str
));
1606 qobject_decref(obj
);
1607 qmp_output_visitor_cleanup(ov
);
1611 static void dump_human_image_info_list(ImageInfoList
*list
)
1613 ImageInfoList
*elem
;
1616 for (elem
= list
; elem
; elem
= elem
->next
) {
1622 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
1626 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
1628 return strcmp(a
, b
) == 0;
1632 * Open an image file chain and return an ImageInfoList
1634 * @filename: topmost image filename
1635 * @fmt: topmost image format (may be NULL to autodetect)
1636 * @chain: true - enumerate entire backing file chain
1637 * false - only topmost image file
1639 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1640 * image file. If there was an error a message will have been printed to
1643 static ImageInfoList
*collect_image_info_list(const char *filename
,
1647 ImageInfoList
*head
= NULL
;
1648 ImageInfoList
**last
= &head
;
1649 GHashTable
*filenames
;
1652 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
1655 BlockDriverState
*bs
;
1657 ImageInfoList
*elem
;
1659 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
1660 error_report("Backing file '%s' creates an infinite loop.",
1664 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
1666 bs
= bdrv_new_open(filename
, fmt
, BDRV_O_FLAGS
| BDRV_O_NO_BACKING
,
1672 bdrv_query_image_info(bs
, &info
, &err
);
1673 if (error_is_set(&err
)) {
1674 error_report("%s", error_get_pretty(err
));
1679 elem
= g_new0(ImageInfoList
, 1);
1686 filename
= fmt
= NULL
;
1688 if (info
->has_full_backing_filename
) {
1689 filename
= info
->full_backing_filename
;
1690 } else if (info
->has_backing_filename
) {
1691 filename
= info
->backing_filename
;
1693 if (info
->has_backing_filename_format
) {
1694 fmt
= info
->backing_filename_format
;
1698 g_hash_table_destroy(filenames
);
1702 qapi_free_ImageInfoList(head
);
1703 g_hash_table_destroy(filenames
);
1707 static int img_info(int argc
, char **argv
)
1710 OutputFormat output_format
= OFORMAT_HUMAN
;
1712 const char *filename
, *fmt
, *output
;
1713 ImageInfoList
*list
;
1718 int option_index
= 0;
1719 static const struct option long_options
[] = {
1720 {"help", no_argument
, 0, 'h'},
1721 {"format", required_argument
, 0, 'f'},
1722 {"output", required_argument
, 0, OPTION_OUTPUT
},
1723 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
1726 c
= getopt_long(argc
, argv
, "f:h",
1727 long_options
, &option_index
);
1742 case OPTION_BACKING_CHAIN
:
1747 if (optind
!= argc
- 1) {
1750 filename
= argv
[optind
++];
1752 if (output
&& !strcmp(output
, "json")) {
1753 output_format
= OFORMAT_JSON
;
1754 } else if (output
&& !strcmp(output
, "human")) {
1755 output_format
= OFORMAT_HUMAN
;
1756 } else if (output
) {
1757 error_report("--output must be used with human or json as argument.");
1761 list
= collect_image_info_list(filename
, fmt
, chain
);
1766 switch (output_format
) {
1768 dump_human_image_info_list(list
);
1772 dump_json_image_info_list(list
);
1774 dump_json_image_info(list
->value
);
1779 qapi_free_ImageInfoList(list
);
1783 #define SNAPSHOT_LIST 1
1784 #define SNAPSHOT_CREATE 2
1785 #define SNAPSHOT_APPLY 3
1786 #define SNAPSHOT_DELETE 4
1788 static int img_snapshot(int argc
, char **argv
)
1790 BlockDriverState
*bs
;
1791 QEMUSnapshotInfo sn
;
1792 char *filename
, *snapshot_name
= NULL
;
1793 int c
, ret
= 0, bdrv_oflags
;
1798 bdrv_oflags
= BDRV_O_FLAGS
| BDRV_O_RDWR
;
1799 /* Parse commandline parameters */
1801 c
= getopt(argc
, argv
, "la:c:d:hq");
1815 action
= SNAPSHOT_LIST
;
1816 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
1823 action
= SNAPSHOT_APPLY
;
1824 snapshot_name
= optarg
;
1831 action
= SNAPSHOT_CREATE
;
1832 snapshot_name
= optarg
;
1839 action
= SNAPSHOT_DELETE
;
1840 snapshot_name
= optarg
;
1848 if (optind
!= argc
- 1) {
1851 filename
= argv
[optind
++];
1853 /* Open the image */
1854 bs
= bdrv_new_open(filename
, NULL
, bdrv_oflags
, true, quiet
);
1859 /* Perform the requested action */
1865 case SNAPSHOT_CREATE
:
1866 memset(&sn
, 0, sizeof(sn
));
1867 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
1869 qemu_gettimeofday(&tv
);
1870 sn
.date_sec
= tv
.tv_sec
;
1871 sn
.date_nsec
= tv
.tv_usec
* 1000;
1873 ret
= bdrv_snapshot_create(bs
, &sn
);
1875 error_report("Could not create snapshot '%s': %d (%s)",
1876 snapshot_name
, ret
, strerror(-ret
));
1880 case SNAPSHOT_APPLY
:
1881 ret
= bdrv_snapshot_goto(bs
, snapshot_name
);
1883 error_report("Could not apply snapshot '%s': %d (%s)",
1884 snapshot_name
, ret
, strerror(-ret
));
1888 case SNAPSHOT_DELETE
:
1889 ret
= bdrv_snapshot_delete(bs
, snapshot_name
);
1891 error_report("Could not delete snapshot '%s': %d (%s)",
1892 snapshot_name
, ret
, strerror(-ret
));
1905 static int img_rebase(int argc
, char **argv
)
1907 BlockDriverState
*bs
, *bs_old_backing
= NULL
, *bs_new_backing
= NULL
;
1908 BlockDriver
*old_backing_drv
, *new_backing_drv
;
1910 const char *fmt
, *cache
, *out_basefmt
, *out_baseimg
;
1916 /* Parse commandline parameters */
1918 cache
= BDRV_DEFAULT_CACHE
;
1922 c
= getopt(argc
, argv
, "uhf:F:b:pt:q");
1935 out_basefmt
= optarg
;
1938 out_baseimg
= optarg
;
1959 if ((optind
!= argc
- 1) || (!unsafe
&& !out_baseimg
)) {
1962 filename
= argv
[optind
++];
1964 qemu_progress_init(progress
, 2.0);
1965 qemu_progress_print(0, 100);
1967 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
1968 ret
= bdrv_parse_cache_flags(cache
, &flags
);
1970 error_report("Invalid cache option: %s", cache
);
1977 * Ignore the old backing file for unsafe rebase in case we want to correct
1978 * the reference to a renamed or moved backing file.
1980 bs
= bdrv_new_open(filename
, fmt
, flags
, true, quiet
);
1985 /* Find the right drivers for the backing files */
1986 old_backing_drv
= NULL
;
1987 new_backing_drv
= NULL
;
1989 if (!unsafe
&& bs
->backing_format
[0] != '\0') {
1990 old_backing_drv
= bdrv_find_format(bs
->backing_format
);
1991 if (old_backing_drv
== NULL
) {
1992 error_report("Invalid format name: '%s'", bs
->backing_format
);
1998 if (out_basefmt
!= NULL
) {
1999 new_backing_drv
= bdrv_find_format(out_basefmt
);
2000 if (new_backing_drv
== NULL
) {
2001 error_report("Invalid format name: '%s'", out_basefmt
);
2007 /* For safe rebasing we need to compare old and new backing file */
2009 /* Make the compiler happy */
2010 bs_old_backing
= NULL
;
2011 bs_new_backing
= NULL
;
2013 char backing_name
[1024];
2015 bs_old_backing
= bdrv_new("old_backing");
2016 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
2017 ret
= bdrv_open(bs_old_backing
, backing_name
, NULL
, BDRV_O_FLAGS
,
2020 error_report("Could not open old backing file '%s'", backing_name
);
2023 if (out_baseimg
[0]) {
2024 bs_new_backing
= bdrv_new("new_backing");
2025 ret
= bdrv_open(bs_new_backing
, out_baseimg
, NULL
, BDRV_O_FLAGS
,
2028 error_report("Could not open new backing file '%s'",
2036 * Check each unallocated cluster in the COW file. If it is unallocated,
2037 * accesses go to the backing file. We must therefore compare this cluster
2038 * in the old and new backing file, and if they differ we need to copy it
2039 * from the old backing file into the COW file.
2041 * If qemu-img crashes during this step, no harm is done. The content of
2042 * the image is the same as the original one at any time.
2045 uint64_t num_sectors
;
2046 uint64_t old_backing_num_sectors
;
2047 uint64_t new_backing_num_sectors
= 0;
2052 float local_progress
= 0;
2054 buf_old
= qemu_blockalign(bs
, IO_BUF_SIZE
);
2055 buf_new
= qemu_blockalign(bs
, IO_BUF_SIZE
);
2057 bdrv_get_geometry(bs
, &num_sectors
);
2058 bdrv_get_geometry(bs_old_backing
, &old_backing_num_sectors
);
2059 if (bs_new_backing
) {
2060 bdrv_get_geometry(bs_new_backing
, &new_backing_num_sectors
);
2063 if (num_sectors
!= 0) {
2064 local_progress
= (float)100 /
2065 (num_sectors
/ MIN(num_sectors
, IO_BUF_SIZE
/ 512));
2068 for (sector
= 0; sector
< num_sectors
; sector
+= n
) {
2070 /* How many sectors can we handle with the next read? */
2071 if (sector
+ (IO_BUF_SIZE
/ 512) <= num_sectors
) {
2072 n
= (IO_BUF_SIZE
/ 512);
2074 n
= num_sectors
- sector
;
2077 /* If the cluster is allocated, we don't need to take action */
2078 ret
= bdrv_is_allocated(bs
, sector
, n
, &n
);
2084 * Read old and new backing file and take into consideration that
2085 * backing files may be smaller than the COW image.
2087 if (sector
>= old_backing_num_sectors
) {
2088 memset(buf_old
, 0, n
* BDRV_SECTOR_SIZE
);
2090 if (sector
+ n
> old_backing_num_sectors
) {
2091 n
= old_backing_num_sectors
- sector
;
2094 ret
= bdrv_read(bs_old_backing
, sector
, buf_old
, n
);
2096 error_report("error while reading from old backing file");
2101 if (sector
>= new_backing_num_sectors
|| !bs_new_backing
) {
2102 memset(buf_new
, 0, n
* BDRV_SECTOR_SIZE
);
2104 if (sector
+ n
> new_backing_num_sectors
) {
2105 n
= new_backing_num_sectors
- sector
;
2108 ret
= bdrv_read(bs_new_backing
, sector
, buf_new
, n
);
2110 error_report("error while reading from new backing file");
2115 /* If they differ, we need to write to the COW file */
2116 uint64_t written
= 0;
2118 while (written
< n
) {
2121 if (compare_sectors(buf_old
+ written
* 512,
2122 buf_new
+ written
* 512, n
- written
, &pnum
))
2124 ret
= bdrv_write(bs
, sector
+ written
,
2125 buf_old
+ written
* 512, pnum
);
2127 error_report("Error while writing to COW image: %s",
2135 qemu_progress_print(local_progress
, 100);
2138 qemu_vfree(buf_old
);
2139 qemu_vfree(buf_new
);
2143 * Change the backing file. All clusters that are different from the old
2144 * backing file are overwritten in the COW file now, so the visible content
2145 * doesn't change when we switch the backing file.
2147 if (out_baseimg
&& *out_baseimg
) {
2148 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
2150 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
2153 if (ret
== -ENOSPC
) {
2154 error_report("Could not change the backing file to '%s': No "
2155 "space left in the file header", out_baseimg
);
2156 } else if (ret
< 0) {
2157 error_report("Could not change the backing file to '%s': %s",
2158 out_baseimg
, strerror(-ret
));
2161 qemu_progress_print(100, 0);
2163 * TODO At this point it is possible to check if any clusters that are
2164 * allocated in the COW file are the same in the backing file. If so, they
2165 * could be dropped from the COW file. Don't do this before switching the
2166 * backing file, in case of a crash this would lead to corruption.
2169 qemu_progress_end();
2172 if (bs_old_backing
!= NULL
) {
2173 bdrv_delete(bs_old_backing
);
2175 if (bs_new_backing
!= NULL
) {
2176 bdrv_delete(bs_new_backing
);
2187 static int img_resize(int argc
, char **argv
)
2189 int c
, ret
, relative
;
2190 const char *filename
, *fmt
, *size
;
2191 int64_t n
, total_size
;
2193 BlockDriverState
*bs
= NULL
;
2195 static QemuOptsList resize_options
= {
2196 .name
= "resize_options",
2197 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
2200 .name
= BLOCK_OPT_SIZE
,
2201 .type
= QEMU_OPT_SIZE
,
2202 .help
= "Virtual disk size"
2209 /* Remove size from argv manually so that negative numbers are not treated
2210 * as options by getopt. */
2216 size
= argv
[--argc
];
2218 /* Parse getopt arguments */
2221 c
= getopt(argc
, argv
, "f:hq");
2238 if (optind
!= argc
- 1) {
2241 filename
= argv
[optind
++];
2243 /* Choose grow, shrink, or absolute resize mode */
2259 param
= qemu_opts_create_nofail(&resize_options
);
2260 if (qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
)) {
2261 /* Error message already printed when size parsing fails */
2263 qemu_opts_del(param
);
2266 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
2267 qemu_opts_del(param
);
2269 bs
= bdrv_new_open(filename
, fmt
, BDRV_O_FLAGS
| BDRV_O_RDWR
, true, quiet
);
2276 total_size
= bdrv_getlength(bs
) + n
* relative
;
2280 if (total_size
<= 0) {
2281 error_report("New image size must be positive");
2286 ret
= bdrv_truncate(bs
, total_size
);
2289 qprintf(quiet
, "Image resized.\n");
2292 error_report("This image does not support resize");
2295 error_report("Image is read-only");
2298 error_report("Error resizing image (%d)", -ret
);
2311 static const img_cmd_t img_cmds
[] = {
2312 #define DEF(option, callback, arg_string) \
2313 { option, callback },
2314 #include "qemu-img-cmds.h"
2320 int main(int argc
, char **argv
)
2322 const img_cmd_t
*cmd
;
2323 const char *cmdname
;
2326 signal(SIGPIPE
, SIG_IGN
);
2329 error_set_progname(argv
[0]);
2331 qemu_init_main_loop();
2338 /* find the command */
2339 for(cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
2340 if (!strcmp(cmdname
, cmd
->name
)) {
2341 return cmd
->handler(argc
, argv
);