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"
41 typedef struct img_cmd_t
{
43 int (*handler
)(int argc
, char **argv
);
48 OPTION_BACKING_CHAIN
= 257,
51 typedef enum OutputFormat
{
56 /* Default to cache=writeback as data integrity is not important for qemu-tcg. */
57 #define BDRV_O_FLAGS BDRV_O_CACHE_WB
58 #define BDRV_DEFAULT_CACHE "writeback"
60 static void format_print(void *opaque
, const char *name
)
65 /* Please keep in synch with qemu-img.texi */
66 static void help(void)
68 const char *help_msg
=
69 "qemu-img version " QEMU_VERSION
", Copyright (c) 2004-2008 Fabrice Bellard\n"
70 "usage: qemu-img command [command options]\n"
71 "QEMU disk image utility\n"
74 #define DEF(option, callback, arg_string) \
76 #include "qemu-img-cmds.h"
80 "Command parameters:\n"
81 " 'filename' is a disk image filename\n"
82 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
83 " 'cache' is the cache mode used to write the output disk image, the valid\n"
84 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
85 " 'directsync' and 'unsafe' (default for convert)\n"
86 " 'size' is the disk image size in bytes. Optional suffixes\n"
87 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M)\n"
88 " and T (terabyte, 1024G) are supported. 'b' is ignored.\n"
89 " 'output_filename' is the destination disk image filename\n"
90 " 'output_fmt' is the destination format\n"
91 " 'options' is a comma separated list of format specific options in a\n"
92 " name=value format. Use -o ? for an overview of the options supported by the\n"
94 " '-c' indicates that target image must be compressed (qcow format only)\n"
95 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
96 " match exactly. The image doesn't need a working backing file before\n"
97 " rebasing in this case (useful for renaming the backing file)\n"
98 " '-h' with or without a command shows this help and lists the supported formats\n"
99 " '-p' show progress of command (only certain commands)\n"
100 " '-q' use Quiet mode - do not print any output (except errors)\n"
101 " '-S' indicates the consecutive number of bytes that must contain only zeros\n"
102 " for qemu-img to create a sparse image during conversion\n"
103 " '--output' takes the format in which the output must be done (human or json)\n"
105 "Parameters to check subcommand:\n"
106 " '-r' tries to repair any inconsistencies that are found during the check.\n"
107 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
108 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
109 " hiding corruption that has already occurred.\n"
111 "Parameters to snapshot subcommand:\n"
112 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
113 " '-a' applies a snapshot (revert disk to saved state)\n"
114 " '-c' creates a snapshot\n"
115 " '-d' deletes a snapshot\n"
116 " '-l' lists all snapshots in the given image\n"
118 "Parameters to compare subcommand:\n"
119 " '-f' first image format\n"
120 " '-F' second image format\n"
121 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
123 printf("%s\nSupported formats:", help_msg
);
124 bdrv_iterate_format(format_print
, NULL
);
129 static int qprintf(bool quiet
, const char *fmt
, ...)
135 ret
= vprintf(fmt
, args
);
142 /* XXX: put correct support for win32 */
143 static int read_password(char *buf
, int buf_size
)
146 printf("Password: ");
153 if (i
< (buf_size
- 1))
164 static struct termios oldtty
;
166 static void term_exit(void)
168 tcsetattr (0, TCSANOW
, &oldtty
);
171 static void term_init(void)
178 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
179 |INLCR
|IGNCR
|ICRNL
|IXON
);
180 tty
.c_oflag
|= OPOST
;
181 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
182 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
187 tcsetattr (0, TCSANOW
, &tty
);
192 static int read_password(char *buf
, int buf_size
)
197 printf("password: ");
202 ret
= read(0, &ch
, 1);
204 if (errno
== EAGAIN
|| errno
== EINTR
) {
210 } else if (ret
== 0) {
218 if (i
< (buf_size
- 1))
229 static int print_block_option_help(const char *filename
, const char *fmt
)
231 BlockDriver
*drv
, *proto_drv
;
232 QEMUOptionParameter
*create_options
= NULL
;
234 /* Find driver and parse its options */
235 drv
= bdrv_find_format(fmt
);
237 error_report("Unknown file format '%s'", fmt
);
241 proto_drv
= bdrv_find_protocol(filename
);
243 error_report("Unknown protocol '%s'", filename
);
247 create_options
= append_option_parameters(create_options
,
248 drv
->create_options
);
249 create_options
= append_option_parameters(create_options
,
250 proto_drv
->create_options
);
251 print_option_help(create_options
);
252 free_option_parameters(create_options
);
256 static BlockDriverState
*bdrv_new_open(const char *filename
,
262 BlockDriverState
*bs
;
267 bs
= bdrv_new("image");
270 drv
= bdrv_find_format(fmt
);
272 error_report("Unknown file format '%s'", fmt
);
279 ret
= bdrv_open(bs
, filename
, NULL
, flags
, drv
);
281 error_report("Could not open '%s': %s", filename
, strerror(-ret
));
285 if (bdrv_is_encrypted(bs
) && require_io
) {
286 qprintf(quiet
, "Disk image '%s' is encrypted.\n", filename
);
287 if (read_password(password
, sizeof(password
)) < 0) {
288 error_report("No password given");
291 if (bdrv_set_key(bs
, password
) < 0) {
292 error_report("invalid password");
304 static int add_old_style_options(const char *fmt
, QEMUOptionParameter
*list
,
305 const char *base_filename
,
306 const char *base_fmt
)
309 if (set_option_parameter(list
, BLOCK_OPT_BACKING_FILE
, base_filename
)) {
310 error_report("Backing file not supported for file format '%s'",
316 if (set_option_parameter(list
, BLOCK_OPT_BACKING_FMT
, base_fmt
)) {
317 error_report("Backing file format not supported for file "
325 static int img_create(int argc
, char **argv
)
328 uint64_t img_size
= -1;
329 const char *fmt
= "raw";
330 const char *base_fmt
= NULL
;
331 const char *filename
;
332 const char *base_filename
= NULL
;
333 char *options
= NULL
;
334 Error
*local_err
= NULL
;
338 c
= getopt(argc
, argv
, "F:b:f:he6o:q");
351 base_filename
= optarg
;
357 error_report("option -e is deprecated, please use \'-o "
358 "encryption\' instead!");
361 error_report("option -6 is deprecated, please use \'-o "
362 "compat6\' instead!");
373 /* Get the filename */
374 if (optind
>= argc
) {
377 filename
= argv
[optind
++];
379 /* Get image size, if specified */
383 sval
= strtosz_suffix(argv
[optind
++], &end
, STRTOSZ_DEFSUFFIX_B
);
384 if (sval
< 0 || *end
) {
385 if (sval
== -ERANGE
) {
386 error_report("Image size must be less than 8 EiB!");
388 error_report("Invalid image size specified! You may use k, M, "
389 "G or T suffixes for ");
390 error_report("kilobytes, megabytes, gigabytes and terabytes.");
394 img_size
= (uint64_t)sval
;
397 if (options
&& is_help_option(options
)) {
398 return print_block_option_help(filename
, fmt
);
401 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
402 options
, img_size
, BDRV_O_FLAGS
, &local_err
, quiet
);
403 if (error_is_set(&local_err
)) {
404 error_report("%s", error_get_pretty(local_err
));
405 error_free(local_err
);
412 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
416 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
418 visit_type_ImageCheck(qmp_output_get_visitor(ov
),
419 &check
, NULL
, &errp
);
420 obj
= qmp_output_get_qobject(ov
);
421 str
= qobject_to_json_pretty(obj
);
423 qprintf(quiet
, "%s\n", qstring_get_str(str
));
425 qmp_output_visitor_cleanup(ov
);
429 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
431 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
432 qprintf(quiet
, "No errors were found on the image.\n");
434 if (check
->corruptions
) {
435 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
436 "Data may be corrupted, or further writes to the image "
443 "\n%" PRId64
" leaked clusters were found on the image.\n"
444 "This means waste of disk space, but no harm to data.\n",
448 if (check
->check_errors
) {
451 " internal errors have occurred during the check.\n",
452 check
->check_errors
);
456 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
457 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
458 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
459 check
->allocated_clusters
, check
->total_clusters
,
460 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
461 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
462 check
->compressed_clusters
* 100.0 /
463 check
->allocated_clusters
);
466 if (check
->image_end_offset
) {
468 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
472 static int collect_image_check(BlockDriverState
*bs
,
474 const char *filename
,
479 BdrvCheckResult result
;
481 ret
= bdrv_check(bs
, &result
, fix
);
486 check
->filename
= g_strdup(filename
);
487 check
->format
= g_strdup(bdrv_get_format_name(bs
));
488 check
->check_errors
= result
.check_errors
;
489 check
->corruptions
= result
.corruptions
;
490 check
->has_corruptions
= result
.corruptions
!= 0;
491 check
->leaks
= result
.leaks
;
492 check
->has_leaks
= result
.leaks
!= 0;
493 check
->corruptions_fixed
= result
.corruptions_fixed
;
494 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
495 check
->leaks_fixed
= result
.leaks_fixed
;
496 check
->has_leaks_fixed
= result
.leaks
!= 0;
497 check
->image_end_offset
= result
.image_end_offset
;
498 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
499 check
->total_clusters
= result
.bfi
.total_clusters
;
500 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
501 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
502 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
503 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
504 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
505 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
506 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
512 * Checks an image for consistency. Exit codes:
514 * 0 - Check completed, image is good
515 * 1 - Check not completed because of internal errors
516 * 2 - Check completed, image is corrupted
517 * 3 - Check completed, image has leaked clusters, but is good otherwise
519 static int img_check(int argc
, char **argv
)
522 OutputFormat output_format
= OFORMAT_HUMAN
;
523 const char *filename
, *fmt
, *output
;
524 BlockDriverState
*bs
;
526 int flags
= BDRV_O_FLAGS
| BDRV_O_CHECK
;
533 int option_index
= 0;
534 static const struct option long_options
[] = {
535 {"help", no_argument
, 0, 'h'},
536 {"format", required_argument
, 0, 'f'},
537 {"repair", no_argument
, 0, 'r'},
538 {"output", required_argument
, 0, OPTION_OUTPUT
},
541 c
= getopt_long(argc
, argv
, "f:hr:q",
542 long_options
, &option_index
);
555 flags
|= BDRV_O_RDWR
;
557 if (!strcmp(optarg
, "leaks")) {
558 fix
= BDRV_FIX_LEAKS
;
559 } else if (!strcmp(optarg
, "all")) {
560 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
573 if (optind
>= argc
) {
576 filename
= argv
[optind
++];
578 if (output
&& !strcmp(output
, "json")) {
579 output_format
= OFORMAT_JSON
;
580 } else if (output
&& !strcmp(output
, "human")) {
581 output_format
= OFORMAT_HUMAN
;
583 error_report("--output must be used with human or json as argument.");
587 bs
= bdrv_new_open(filename
, fmt
, flags
, true, quiet
);
592 check
= g_new0(ImageCheck
, 1);
593 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
595 if (ret
== -ENOTSUP
) {
596 if (output_format
== OFORMAT_HUMAN
) {
597 error_report("This image format does not support checks");
603 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
604 int corruptions_fixed
, leaks_fixed
;
606 leaks_fixed
= check
->leaks_fixed
;
607 corruptions_fixed
= check
->corruptions_fixed
;
609 if (output_format
== OFORMAT_HUMAN
) {
611 "The following inconsistencies were found and repaired:\n\n"
612 " %" PRId64
" leaked clusters\n"
613 " %" PRId64
" corruptions\n\n"
614 "Double checking the fixed image now...\n",
616 check
->corruptions_fixed
);
619 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
621 check
->leaks_fixed
= leaks_fixed
;
622 check
->corruptions_fixed
= corruptions_fixed
;
625 switch (output_format
) {
627 dump_human_image_check(check
, quiet
);
630 dump_json_image_check(check
, quiet
);
634 if (ret
|| check
->check_errors
) {
639 if (check
->corruptions
) {
641 } else if (check
->leaks
) {
648 qapi_free_ImageCheck(check
);
654 static int img_commit(int argc
, char **argv
)
657 const char *filename
, *fmt
, *cache
;
658 BlockDriverState
*bs
;
662 cache
= BDRV_DEFAULT_CACHE
;
664 c
= getopt(argc
, argv
, "f:ht:q");
684 if (optind
>= argc
) {
687 filename
= argv
[optind
++];
690 ret
= bdrv_parse_cache_flags(cache
, &flags
);
692 error_report("Invalid cache option: %s", cache
);
696 bs
= bdrv_new_open(filename
, fmt
, flags
, true, quiet
);
700 ret
= bdrv_commit(bs
);
703 qprintf(quiet
, "Image committed.\n");
706 error_report("No disk inserted");
709 error_report("Image is read-only");
712 error_report("Image is already committed");
715 error_report("Error while committing image");
727 * Returns true iff the first sector pointed to by 'buf' contains at least
730 * 'pnum' is set to the number of sectors (including and immediately following
731 * the first one) that are known to be in the same allocated/unallocated state.
733 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
)
742 is_zero
= buffer_is_zero(buf
, 512);
743 for(i
= 1; i
< n
; i
++) {
745 if (is_zero
!= buffer_is_zero(buf
, 512)) {
754 * Like is_allocated_sectors, but if the buffer starts with a used sector,
755 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
756 * breaking up write requests for only small sparse areas.
758 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
762 int num_checked
, num_used
;
768 ret
= is_allocated_sectors(buf
, n
, pnum
);
774 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
776 num_checked
= num_used
;
779 ret
= is_allocated_sectors(buf
, n
, pnum
);
781 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
783 num_checked
+= *pnum
;
785 num_used
= num_checked
;
786 } else if (*pnum
>= min
) {
796 * Compares two buffers sector by sector. Returns 0 if the first sector of both
797 * buffers matches, non-zero otherwise.
799 * pnum is set to the number of sectors (including and immediately following
800 * the first one) that are known to have the same comparison result
802 static int compare_sectors(const uint8_t *buf1
, const uint8_t *buf2
, int n
,
812 res
= !!memcmp(buf1
, buf2
, 512);
813 for(i
= 1; i
< n
; i
++) {
817 if (!!memcmp(buf1
, buf2
, 512) != res
) {
826 #define IO_BUF_SIZE (2 * 1024 * 1024)
828 static int64_t sectors_to_bytes(int64_t sectors
)
830 return sectors
<< BDRV_SECTOR_BITS
;
833 static int64_t sectors_to_process(int64_t total
, int64_t from
)
835 return MIN(total
- from
, IO_BUF_SIZE
>> BDRV_SECTOR_BITS
);
839 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
841 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
842 * data and negative value on error.
844 * @param bs: Driver used for accessing file
845 * @param sect_num: Number of first sector to check
846 * @param sect_count: Number of sectors to check
847 * @param filename: Name of disk file we are checking (logging purpose)
848 * @param buffer: Allocated buffer for storing read data
849 * @param quiet: Flag for quiet mode
851 static int check_empty_sectors(BlockDriverState
*bs
, int64_t sect_num
,
852 int sect_count
, const char *filename
,
853 uint8_t *buffer
, bool quiet
)
856 ret
= bdrv_read(bs
, sect_num
, buffer
, sect_count
);
858 error_report("Error while reading offset %" PRId64
" of %s: %s",
859 sectors_to_bytes(sect_num
), filename
, strerror(-ret
));
862 ret
= is_allocated_sectors(buffer
, sect_count
, &pnum
);
863 if (ret
|| pnum
!= sect_count
) {
864 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
865 sectors_to_bytes(ret
? sect_num
: sect_num
+ pnum
));
873 * Compares two images. Exit codes:
875 * 0 - Images are identical
877 * >1 - Error occurred
879 static int img_compare(int argc
, char **argv
)
881 const char *fmt1
= NULL
, *fmt2
= NULL
, *filename1
, *filename2
;
882 BlockDriverState
*bs1
, *bs2
;
883 int64_t total_sectors1
, total_sectors2
;
884 uint8_t *buf1
= NULL
, *buf2
= NULL
;
886 int allocated1
, allocated2
;
887 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
888 bool progress
= false, quiet
= false, strict
= false;
889 int64_t total_sectors
;
890 int64_t sector_num
= 0;
894 uint64_t progress_base
;
897 c
= getopt(argc
, argv
, "hpf:F:sq");
924 /* Progress is not shown in Quiet mode */
930 if (optind
> argc
- 2) {
933 filename1
= argv
[optind
++];
934 filename2
= argv
[optind
++];
936 /* Initialize before goto out */
937 qemu_progress_init(progress
, 2.0);
939 bs1
= bdrv_new_open(filename1
, fmt1
, BDRV_O_FLAGS
, true, quiet
);
941 error_report("Can't open file %s", filename1
);
946 bs2
= bdrv_new_open(filename2
, fmt2
, BDRV_O_FLAGS
, true, quiet
);
948 error_report("Can't open file %s", filename2
);
953 buf1
= qemu_blockalign(bs1
, IO_BUF_SIZE
);
954 buf2
= qemu_blockalign(bs2
, IO_BUF_SIZE
);
955 bdrv_get_geometry(bs1
, &bs_sectors
);
956 total_sectors1
= bs_sectors
;
957 bdrv_get_geometry(bs2
, &bs_sectors
);
958 total_sectors2
= bs_sectors
;
959 total_sectors
= MIN(total_sectors1
, total_sectors2
);
960 progress_base
= MAX(total_sectors1
, total_sectors2
);
962 qemu_progress_print(0, 100);
964 if (strict
&& total_sectors1
!= total_sectors2
) {
966 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
971 nb_sectors
= sectors_to_process(total_sectors
, sector_num
);
972 if (nb_sectors
<= 0) {
975 allocated1
= bdrv_is_allocated_above(bs1
, NULL
, sector_num
, nb_sectors
,
977 if (allocated1
< 0) {
979 error_report("Sector allocation test failed for %s", filename1
);
983 allocated2
= bdrv_is_allocated_above(bs2
, NULL
, sector_num
, nb_sectors
,
985 if (allocated2
< 0) {
987 error_report("Sector allocation test failed for %s", filename2
);
990 nb_sectors
= MIN(pnum1
, pnum2
);
992 if (allocated1
== allocated2
) {
994 ret
= bdrv_read(bs1
, sector_num
, buf1
, nb_sectors
);
996 error_report("Error while reading offset %" PRId64
" of %s:"
997 " %s", sectors_to_bytes(sector_num
), filename1
,
1002 ret
= bdrv_read(bs2
, sector_num
, buf2
, nb_sectors
);
1004 error_report("Error while reading offset %" PRId64
1005 " of %s: %s", sectors_to_bytes(sector_num
),
1006 filename2
, strerror(-ret
));
1010 ret
= compare_sectors(buf1
, buf2
, nb_sectors
, &pnum
);
1011 if (ret
|| pnum
!= nb_sectors
) {
1013 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1015 ret
? sector_num
: sector_num
+ pnum
));
1022 qprintf(quiet
, "Strict mode: Offset %" PRId64
1023 " allocation mismatch!\n",
1024 sectors_to_bytes(sector_num
));
1029 ret
= check_empty_sectors(bs1
, sector_num
, nb_sectors
,
1030 filename1
, buf1
, quiet
);
1032 ret
= check_empty_sectors(bs2
, sector_num
, nb_sectors
,
1033 filename2
, buf1
, quiet
);
1038 error_report("Error while reading offset %" PRId64
": %s",
1039 sectors_to_bytes(sector_num
), strerror(-ret
));
1044 sector_num
+= nb_sectors
;
1045 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1048 if (total_sectors1
!= total_sectors2
) {
1049 BlockDriverState
*bs_over
;
1050 int64_t total_sectors_over
;
1051 const char *filename_over
;
1053 qprintf(quiet
, "Warning: Image size mismatch!\n");
1054 if (total_sectors1
> total_sectors2
) {
1055 total_sectors_over
= total_sectors1
;
1057 filename_over
= filename1
;
1059 total_sectors_over
= total_sectors2
;
1061 filename_over
= filename2
;
1065 nb_sectors
= sectors_to_process(total_sectors_over
, sector_num
);
1066 if (nb_sectors
<= 0) {
1069 ret
= bdrv_is_allocated_above(bs_over
, NULL
, sector_num
,
1073 error_report("Sector allocation test failed for %s",
1080 ret
= check_empty_sectors(bs_over
, sector_num
, nb_sectors
,
1081 filename_over
, buf1
, quiet
);
1085 error_report("Error while reading offset %" PRId64
1086 " of %s: %s", sectors_to_bytes(sector_num
),
1087 filename_over
, strerror(-ret
));
1092 sector_num
+= nb_sectors
;
1093 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1097 qprintf(quiet
, "Images are identical.\n");
1107 qemu_progress_end();
1111 static int img_convert(int argc
, char **argv
)
1113 int c
, ret
= 0, n
, n1
, bs_n
, bs_i
, compress
, cluster_size
, cluster_sectors
;
1114 int progress
= 0, flags
;
1115 const char *fmt
, *out_fmt
, *cache
, *out_baseimg
, *out_filename
;
1116 BlockDriver
*drv
, *proto_drv
;
1117 BlockDriverState
**bs
= NULL
, *out_bs
= NULL
;
1118 int64_t total_sectors
, nb_sectors
, sector_num
, bs_offset
;
1119 uint64_t bs_sectors
;
1120 uint8_t * buf
= NULL
;
1121 const uint8_t *buf1
;
1122 BlockDriverInfo bdi
;
1123 QEMUOptionParameter
*param
= NULL
, *create_options
= NULL
;
1124 QEMUOptionParameter
*out_baseimg_param
;
1125 char *options
= NULL
;
1126 const char *snapshot_name
= NULL
;
1127 float local_progress
= 0;
1128 int min_sparse
= 8; /* Need at least 4k of zeros for sparse detection */
1137 c
= getopt(argc
, argv
, "f:O:B:s:hce6o:pS:t:q");
1153 out_baseimg
= optarg
;
1159 error_report("option -e is deprecated, please use \'-o "
1160 "encryption\' instead!");
1163 error_report("option -6 is deprecated, please use \'-o "
1164 "compat6\' instead!");
1170 snapshot_name
= optarg
;
1176 sval
= strtosz_suffix(optarg
, &end
, STRTOSZ_DEFSUFFIX_B
);
1177 if (sval
< 0 || *end
) {
1178 error_report("Invalid minimum zero buffer size for sparse output specified");
1182 min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
1201 bs_n
= argc
- optind
- 1;
1206 out_filename
= argv
[argc
- 1];
1208 /* Initialize before goto out */
1209 qemu_progress_init(progress
, 2.0);
1211 if (options
&& is_help_option(options
)) {
1212 ret
= print_block_option_help(out_filename
, out_fmt
);
1216 if (bs_n
> 1 && out_baseimg
) {
1217 error_report("-B makes no sense when concatenating multiple input "
1223 qemu_progress_print(0, 100);
1225 bs
= g_malloc0(bs_n
* sizeof(BlockDriverState
*));
1228 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
1229 bs
[bs_i
] = bdrv_new_open(argv
[optind
+ bs_i
], fmt
, BDRV_O_FLAGS
, true,
1232 error_report("Could not open '%s'", argv
[optind
+ bs_i
]);
1236 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1237 total_sectors
+= bs_sectors
;
1240 if (snapshot_name
!= NULL
) {
1242 error_report("No support for concatenating multiple snapshot");
1246 if (bdrv_snapshot_load_tmp(bs
[0], snapshot_name
) < 0) {
1247 error_report("Failed to load snapshot");
1253 /* Find driver and parse its options */
1254 drv
= bdrv_find_format(out_fmt
);
1256 error_report("Unknown file format '%s'", out_fmt
);
1261 proto_drv
= bdrv_find_protocol(out_filename
);
1263 error_report("Unknown protocol '%s'", out_filename
);
1268 create_options
= append_option_parameters(create_options
,
1269 drv
->create_options
);
1270 create_options
= append_option_parameters(create_options
,
1271 proto_drv
->create_options
);
1274 param
= parse_option_parameters(options
, create_options
, param
);
1275 if (param
== NULL
) {
1276 error_report("Invalid options for file format '%s'.", out_fmt
);
1281 param
= parse_option_parameters("", create_options
, param
);
1284 set_option_parameter_int(param
, BLOCK_OPT_SIZE
, total_sectors
* 512);
1285 ret
= add_old_style_options(out_fmt
, param
, out_baseimg
, NULL
);
1290 /* Get backing file name if -o backing_file was used */
1291 out_baseimg_param
= get_option_parameter(param
, BLOCK_OPT_BACKING_FILE
);
1292 if (out_baseimg_param
) {
1293 out_baseimg
= out_baseimg_param
->value
.s
;
1296 /* Check if compression is supported */
1298 QEMUOptionParameter
*encryption
=
1299 get_option_parameter(param
, BLOCK_OPT_ENCRYPT
);
1300 QEMUOptionParameter
*preallocation
=
1301 get_option_parameter(param
, BLOCK_OPT_PREALLOC
);
1303 if (!drv
->bdrv_write_compressed
) {
1304 error_report("Compression not supported for this file format");
1309 if (encryption
&& encryption
->value
.n
) {
1310 error_report("Compression and encryption not supported at "
1316 if (preallocation
&& preallocation
->value
.s
1317 && strcmp(preallocation
->value
.s
, "off"))
1319 error_report("Compression and preallocation not supported at "
1326 /* Create the new image */
1327 ret
= bdrv_create(drv
, out_filename
, param
);
1329 if (ret
== -ENOTSUP
) {
1330 error_report("Formatting not supported for file format '%s'",
1332 } else if (ret
== -EFBIG
) {
1333 error_report("The image size is too large for file format '%s'",
1336 error_report("%s: error while converting %s: %s",
1337 out_filename
, out_fmt
, strerror(-ret
));
1342 flags
= BDRV_O_RDWR
;
1343 ret
= bdrv_parse_cache_flags(cache
, &flags
);
1345 error_report("Invalid cache option: %s", cache
);
1349 out_bs
= bdrv_new_open(out_filename
, out_fmt
, flags
, true, quiet
);
1357 bdrv_get_geometry(bs
[0], &bs_sectors
);
1358 buf
= qemu_blockalign(out_bs
, IO_BUF_SIZE
);
1361 ret
= bdrv_get_info(out_bs
, &bdi
);
1363 error_report("could not get block driver info");
1366 cluster_size
= bdi
.cluster_size
;
1367 if (cluster_size
<= 0 || cluster_size
> IO_BUF_SIZE
) {
1368 error_report("invalid cluster size");
1372 cluster_sectors
= cluster_size
>> 9;
1375 nb_sectors
= total_sectors
;
1376 if (nb_sectors
!= 0) {
1377 local_progress
= (float)100 /
1378 (nb_sectors
/ MIN(nb_sectors
, cluster_sectors
));
1386 nb_sectors
= total_sectors
- sector_num
;
1387 if (nb_sectors
<= 0)
1389 if (nb_sectors
>= cluster_sectors
)
1390 n
= cluster_sectors
;
1394 bs_num
= sector_num
- bs_offset
;
1395 assert (bs_num
>= 0);
1398 while (remainder
> 0) {
1400 while (bs_num
== bs_sectors
) {
1402 assert (bs_i
< bs_n
);
1403 bs_offset
+= bs_sectors
;
1404 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1406 /* printf("changing part: sector_num=%" PRId64 ", "
1407 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
1408 "\n", sector_num, bs_i, bs_offset, bs_sectors); */
1410 assert (bs_num
< bs_sectors
);
1412 nlow
= (remainder
> bs_sectors
- bs_num
) ? bs_sectors
- bs_num
: remainder
;
1414 ret
= bdrv_read(bs
[bs_i
], bs_num
, buf2
, nlow
);
1416 error_report("error while reading sector %" PRId64
": %s",
1417 bs_num
, strerror(-ret
));
1426 assert (remainder
== 0);
1428 if (!buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)) {
1429 ret
= bdrv_write_compressed(out_bs
, sector_num
, buf
, n
);
1431 error_report("error while compressing sector %" PRId64
1432 ": %s", sector_num
, strerror(-ret
));
1437 qemu_progress_print(local_progress
, 100);
1439 /* signal EOF to align */
1440 bdrv_write_compressed(out_bs
, 0, NULL
, 0);
1442 int has_zero_init
= bdrv_has_zero_init(out_bs
);
1444 sector_num
= 0; // total number of sectors converted so far
1445 nb_sectors
= total_sectors
- sector_num
;
1446 if (nb_sectors
!= 0) {
1447 local_progress
= (float)100 /
1448 (nb_sectors
/ MIN(nb_sectors
, IO_BUF_SIZE
/ 512));
1452 nb_sectors
= total_sectors
- sector_num
;
1453 if (nb_sectors
<= 0) {
1456 if (nb_sectors
>= (IO_BUF_SIZE
/ 512)) {
1457 n
= (IO_BUF_SIZE
/ 512);
1462 while (sector_num
- bs_offset
>= bs_sectors
) {
1464 assert (bs_i
< bs_n
);
1465 bs_offset
+= bs_sectors
;
1466 bdrv_get_geometry(bs
[bs_i
], &bs_sectors
);
1467 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1468 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
1469 sector_num, bs_i, bs_offset, bs_sectors); */
1472 if (n
> bs_offset
+ bs_sectors
- sector_num
) {
1473 n
= bs_offset
+ bs_sectors
- sector_num
;
1476 if (has_zero_init
) {
1477 /* If the output image is being created as a copy on write image,
1478 assume that sectors which are unallocated in the input image
1479 are present in both the output's and input's base images (no
1480 need to copy them). */
1482 if (!bdrv_is_allocated(bs
[bs_i
], sector_num
- bs_offset
,
1487 /* The next 'n1' sectors are allocated in the input image. Copy
1488 only those as they may be followed by unallocated sectors. */
1495 ret
= bdrv_read(bs
[bs_i
], sector_num
- bs_offset
, buf
, n
);
1497 error_report("error while reading sector %" PRId64
": %s",
1498 sector_num
- bs_offset
, strerror(-ret
));
1501 /* NOTE: at the same time we convert, we do not write zero
1502 sectors to have a chance to compress the image. Ideally, we
1503 should add a specific call to have the info to go faster */
1506 /* If the output image is being created as a copy on write image,
1507 copy all sectors even the ones containing only NUL bytes,
1508 because they may differ from the sectors in the base image.
1510 If the output is to a host device, we also write out
1511 sectors that are entirely 0, since whatever data was
1512 already there is garbage, not 0s. */
1513 if (!has_zero_init
|| out_baseimg
||
1514 is_allocated_sectors_min(buf1
, n
, &n1
, min_sparse
)) {
1515 ret
= bdrv_write(out_bs
, sector_num
, buf1
, n1
);
1517 error_report("error while writing sector %" PRId64
1518 ": %s", sector_num
, strerror(-ret
));
1526 qemu_progress_print(local_progress
, 100);
1530 qemu_progress_end();
1531 free_option_parameters(create_options
);
1532 free_option_parameters(param
);
1535 bdrv_delete(out_bs
);
1538 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
1540 bdrv_delete(bs
[bs_i
]);
1552 static void dump_snapshots(BlockDriverState
*bs
)
1554 QEMUSnapshotInfo
*sn_tab
, *sn
;
1558 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
1561 printf("Snapshot list:\n");
1562 printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
1563 for(i
= 0; i
< nb_sns
; i
++) {
1565 printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
1570 static void dump_json_image_info_list(ImageInfoList
*list
)
1574 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
1576 visit_type_ImageInfoList(qmp_output_get_visitor(ov
),
1577 &list
, NULL
, &errp
);
1578 obj
= qmp_output_get_qobject(ov
);
1579 str
= qobject_to_json_pretty(obj
);
1580 assert(str
!= NULL
);
1581 printf("%s\n", qstring_get_str(str
));
1582 qobject_decref(obj
);
1583 qmp_output_visitor_cleanup(ov
);
1587 static void collect_snapshots(BlockDriverState
*bs
, ImageInfo
*info
)
1590 QEMUSnapshotInfo
*sn_tab
= NULL
;
1591 SnapshotInfoList
*info_list
, *cur_item
= NULL
;
1592 sn_count
= bdrv_snapshot_list(bs
, &sn_tab
);
1594 for (i
= 0; i
< sn_count
; i
++) {
1595 info
->has_snapshots
= true;
1596 info_list
= g_new0(SnapshotInfoList
, 1);
1598 info_list
->value
= g_new0(SnapshotInfo
, 1);
1599 info_list
->value
->id
= g_strdup(sn_tab
[i
].id_str
);
1600 info_list
->value
->name
= g_strdup(sn_tab
[i
].name
);
1601 info_list
->value
->vm_state_size
= sn_tab
[i
].vm_state_size
;
1602 info_list
->value
->date_sec
= sn_tab
[i
].date_sec
;
1603 info_list
->value
->date_nsec
= sn_tab
[i
].date_nsec
;
1604 info_list
->value
->vm_clock_sec
= sn_tab
[i
].vm_clock_nsec
/ 1000000000;
1605 info_list
->value
->vm_clock_nsec
= sn_tab
[i
].vm_clock_nsec
% 1000000000;
1607 /* XXX: waiting for the qapi to support qemu-queue.h types */
1609 info
->snapshots
= cur_item
= info_list
;
1611 cur_item
->next
= info_list
;
1612 cur_item
= info_list
;
1620 static void dump_json_image_info(ImageInfo
*info
)
1624 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
1626 visit_type_ImageInfo(qmp_output_get_visitor(ov
),
1627 &info
, NULL
, &errp
);
1628 obj
= qmp_output_get_qobject(ov
);
1629 str
= qobject_to_json_pretty(obj
);
1630 assert(str
!= NULL
);
1631 printf("%s\n", qstring_get_str(str
));
1632 qobject_decref(obj
);
1633 qmp_output_visitor_cleanup(ov
);
1637 static void collect_image_info(BlockDriverState
*bs
,
1639 const char *filename
,
1642 uint64_t total_sectors
;
1643 char backing_filename
[1024];
1644 char backing_filename2
[1024];
1645 BlockDriverInfo bdi
;
1647 bdrv_get_geometry(bs
, &total_sectors
);
1649 info
->filename
= g_strdup(filename
);
1650 info
->format
= g_strdup(bdrv_get_format_name(bs
));
1651 info
->virtual_size
= total_sectors
* 512;
1652 info
->actual_size
= bdrv_get_allocated_file_size(bs
);
1653 info
->has_actual_size
= info
->actual_size
>= 0;
1654 if (bdrv_is_encrypted(bs
)) {
1655 info
->encrypted
= true;
1656 info
->has_encrypted
= true;
1658 if (bdrv_get_info(bs
, &bdi
) >= 0) {
1659 if (bdi
.cluster_size
!= 0) {
1660 info
->cluster_size
= bdi
.cluster_size
;
1661 info
->has_cluster_size
= true;
1663 info
->dirty_flag
= bdi
.is_dirty
;
1664 info
->has_dirty_flag
= true;
1666 bdrv_get_backing_filename(bs
, backing_filename
, sizeof(backing_filename
));
1667 if (backing_filename
[0] != '\0') {
1668 info
->backing_filename
= g_strdup(backing_filename
);
1669 info
->has_backing_filename
= true;
1670 bdrv_get_full_backing_filename(bs
, backing_filename2
,
1671 sizeof(backing_filename2
));
1673 if (strcmp(backing_filename
, backing_filename2
) != 0) {
1674 info
->full_backing_filename
=
1675 g_strdup(backing_filename2
);
1676 info
->has_full_backing_filename
= true;
1679 if (bs
->backing_format
[0]) {
1680 info
->backing_filename_format
= g_strdup(bs
->backing_format
);
1681 info
->has_backing_filename_format
= true;
1686 static void dump_human_image_info(ImageInfo
*info
)
1688 char size_buf
[128], dsize_buf
[128];
1689 if (!info
->has_actual_size
) {
1690 snprintf(dsize_buf
, sizeof(dsize_buf
), "unavailable");
1692 get_human_readable_size(dsize_buf
, sizeof(dsize_buf
),
1695 get_human_readable_size(size_buf
, sizeof(size_buf
), info
->virtual_size
);
1696 printf("image: %s\n"
1698 "virtual size: %s (%" PRId64
" bytes)\n"
1700 info
->filename
, info
->format
, size_buf
,
1704 if (info
->has_encrypted
&& info
->encrypted
) {
1705 printf("encrypted: yes\n");
1708 if (info
->has_cluster_size
) {
1709 printf("cluster_size: %" PRId64
"\n", info
->cluster_size
);
1712 if (info
->has_dirty_flag
&& info
->dirty_flag
) {
1713 printf("cleanly shut down: no\n");
1716 if (info
->has_backing_filename
) {
1717 printf("backing file: %s", info
->backing_filename
);
1718 if (info
->has_full_backing_filename
) {
1719 printf(" (actual path: %s)", info
->full_backing_filename
);
1722 if (info
->has_backing_filename_format
) {
1723 printf("backing file format: %s\n", info
->backing_filename_format
);
1727 if (info
->has_snapshots
) {
1728 SnapshotInfoList
*elem
;
1731 printf("Snapshot list:\n");
1732 printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
1734 /* Ideally bdrv_snapshot_dump() would operate on SnapshotInfoList but
1735 * we convert to the block layer's native QEMUSnapshotInfo for now.
1737 for (elem
= info
->snapshots
; elem
; elem
= elem
->next
) {
1738 QEMUSnapshotInfo sn
= {
1739 .vm_state_size
= elem
->value
->vm_state_size
,
1740 .date_sec
= elem
->value
->date_sec
,
1741 .date_nsec
= elem
->value
->date_nsec
,
1742 .vm_clock_nsec
= elem
->value
->vm_clock_sec
* 1000000000ULL +
1743 elem
->value
->vm_clock_nsec
,
1746 pstrcpy(sn
.id_str
, sizeof(sn
.id_str
), elem
->value
->id
);
1747 pstrcpy(sn
.name
, sizeof(sn
.name
), elem
->value
->name
);
1748 printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), &sn
));
1753 static void dump_human_image_info_list(ImageInfoList
*list
)
1755 ImageInfoList
*elem
;
1758 for (elem
= list
; elem
; elem
= elem
->next
) {
1764 dump_human_image_info(elem
->value
);
1768 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
1770 return strcmp(a
, b
) == 0;
1774 * Open an image file chain and return an ImageInfoList
1776 * @filename: topmost image filename
1777 * @fmt: topmost image format (may be NULL to autodetect)
1778 * @chain: true - enumerate entire backing file chain
1779 * false - only topmost image file
1781 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1782 * image file. If there was an error a message will have been printed to
1785 static ImageInfoList
*collect_image_info_list(const char *filename
,
1789 ImageInfoList
*head
= NULL
;
1790 ImageInfoList
**last
= &head
;
1791 GHashTable
*filenames
;
1793 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
1796 BlockDriverState
*bs
;
1798 ImageInfoList
*elem
;
1800 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
1801 error_report("Backing file '%s' creates an infinite loop.",
1805 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
1807 bs
= bdrv_new_open(filename
, fmt
, BDRV_O_FLAGS
| BDRV_O_NO_BACKING
,
1813 info
= g_new0(ImageInfo
, 1);
1814 collect_image_info(bs
, info
, filename
, fmt
);
1815 collect_snapshots(bs
, info
);
1817 elem
= g_new0(ImageInfoList
, 1);
1824 filename
= fmt
= NULL
;
1826 if (info
->has_full_backing_filename
) {
1827 filename
= info
->full_backing_filename
;
1828 } else if (info
->has_backing_filename
) {
1829 filename
= info
->backing_filename
;
1831 if (info
->has_backing_filename_format
) {
1832 fmt
= info
->backing_filename_format
;
1836 g_hash_table_destroy(filenames
);
1840 qapi_free_ImageInfoList(head
);
1841 g_hash_table_destroy(filenames
);
1845 static int img_info(int argc
, char **argv
)
1848 OutputFormat output_format
= OFORMAT_HUMAN
;
1850 const char *filename
, *fmt
, *output
;
1851 ImageInfoList
*list
;
1856 int option_index
= 0;
1857 static const struct option long_options
[] = {
1858 {"help", no_argument
, 0, 'h'},
1859 {"format", required_argument
, 0, 'f'},
1860 {"output", required_argument
, 0, OPTION_OUTPUT
},
1861 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
1864 c
= getopt_long(argc
, argv
, "f:h",
1865 long_options
, &option_index
);
1880 case OPTION_BACKING_CHAIN
:
1885 if (optind
>= argc
) {
1888 filename
= argv
[optind
++];
1890 if (output
&& !strcmp(output
, "json")) {
1891 output_format
= OFORMAT_JSON
;
1892 } else if (output
&& !strcmp(output
, "human")) {
1893 output_format
= OFORMAT_HUMAN
;
1894 } else if (output
) {
1895 error_report("--output must be used with human or json as argument.");
1899 list
= collect_image_info_list(filename
, fmt
, chain
);
1904 switch (output_format
) {
1906 dump_human_image_info_list(list
);
1910 dump_json_image_info_list(list
);
1912 dump_json_image_info(list
->value
);
1917 qapi_free_ImageInfoList(list
);
1921 #define SNAPSHOT_LIST 1
1922 #define SNAPSHOT_CREATE 2
1923 #define SNAPSHOT_APPLY 3
1924 #define SNAPSHOT_DELETE 4
1926 static int img_snapshot(int argc
, char **argv
)
1928 BlockDriverState
*bs
;
1929 QEMUSnapshotInfo sn
;
1930 char *filename
, *snapshot_name
= NULL
;
1931 int c
, ret
= 0, bdrv_oflags
;
1936 bdrv_oflags
= BDRV_O_FLAGS
| BDRV_O_RDWR
;
1937 /* Parse commandline parameters */
1939 c
= getopt(argc
, argv
, "la:c:d:hq");
1953 action
= SNAPSHOT_LIST
;
1954 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
1961 action
= SNAPSHOT_APPLY
;
1962 snapshot_name
= optarg
;
1969 action
= SNAPSHOT_CREATE
;
1970 snapshot_name
= optarg
;
1977 action
= SNAPSHOT_DELETE
;
1978 snapshot_name
= optarg
;
1986 if (optind
>= argc
) {
1989 filename
= argv
[optind
++];
1991 /* Open the image */
1992 bs
= bdrv_new_open(filename
, NULL
, bdrv_oflags
, true, quiet
);
1997 /* Perform the requested action */
2003 case SNAPSHOT_CREATE
:
2004 memset(&sn
, 0, sizeof(sn
));
2005 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
2007 qemu_gettimeofday(&tv
);
2008 sn
.date_sec
= tv
.tv_sec
;
2009 sn
.date_nsec
= tv
.tv_usec
* 1000;
2011 ret
= bdrv_snapshot_create(bs
, &sn
);
2013 error_report("Could not create snapshot '%s': %d (%s)",
2014 snapshot_name
, ret
, strerror(-ret
));
2018 case SNAPSHOT_APPLY
:
2019 ret
= bdrv_snapshot_goto(bs
, snapshot_name
);
2021 error_report("Could not apply snapshot '%s': %d (%s)",
2022 snapshot_name
, ret
, strerror(-ret
));
2026 case SNAPSHOT_DELETE
:
2027 ret
= bdrv_snapshot_delete(bs
, snapshot_name
);
2029 error_report("Could not delete snapshot '%s': %d (%s)",
2030 snapshot_name
, ret
, strerror(-ret
));
2043 static int img_rebase(int argc
, char **argv
)
2045 BlockDriverState
*bs
, *bs_old_backing
= NULL
, *bs_new_backing
= NULL
;
2046 BlockDriver
*old_backing_drv
, *new_backing_drv
;
2048 const char *fmt
, *cache
, *out_basefmt
, *out_baseimg
;
2054 /* Parse commandline parameters */
2056 cache
= BDRV_DEFAULT_CACHE
;
2060 c
= getopt(argc
, argv
, "uhf:F:b:pt:q");
2073 out_basefmt
= optarg
;
2076 out_baseimg
= optarg
;
2097 if ((optind
>= argc
) || (!unsafe
&& !out_baseimg
)) {
2100 filename
= argv
[optind
++];
2102 qemu_progress_init(progress
, 2.0);
2103 qemu_progress_print(0, 100);
2105 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
2106 ret
= bdrv_parse_cache_flags(cache
, &flags
);
2108 error_report("Invalid cache option: %s", cache
);
2115 * Ignore the old backing file for unsafe rebase in case we want to correct
2116 * the reference to a renamed or moved backing file.
2118 bs
= bdrv_new_open(filename
, fmt
, flags
, true, quiet
);
2123 /* Find the right drivers for the backing files */
2124 old_backing_drv
= NULL
;
2125 new_backing_drv
= NULL
;
2127 if (!unsafe
&& bs
->backing_format
[0] != '\0') {
2128 old_backing_drv
= bdrv_find_format(bs
->backing_format
);
2129 if (old_backing_drv
== NULL
) {
2130 error_report("Invalid format name: '%s'", bs
->backing_format
);
2136 if (out_basefmt
!= NULL
) {
2137 new_backing_drv
= bdrv_find_format(out_basefmt
);
2138 if (new_backing_drv
== NULL
) {
2139 error_report("Invalid format name: '%s'", out_basefmt
);
2145 /* For safe rebasing we need to compare old and new backing file */
2147 /* Make the compiler happy */
2148 bs_old_backing
= NULL
;
2149 bs_new_backing
= NULL
;
2151 char backing_name
[1024];
2153 bs_old_backing
= bdrv_new("old_backing");
2154 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
2155 ret
= bdrv_open(bs_old_backing
, backing_name
, NULL
, BDRV_O_FLAGS
,
2158 error_report("Could not open old backing file '%s'", backing_name
);
2161 if (out_baseimg
[0]) {
2162 bs_new_backing
= bdrv_new("new_backing");
2163 ret
= bdrv_open(bs_new_backing
, out_baseimg
, NULL
, BDRV_O_FLAGS
,
2166 error_report("Could not open new backing file '%s'",
2174 * Check each unallocated cluster in the COW file. If it is unallocated,
2175 * accesses go to the backing file. We must therefore compare this cluster
2176 * in the old and new backing file, and if they differ we need to copy it
2177 * from the old backing file into the COW file.
2179 * If qemu-img crashes during this step, no harm is done. The content of
2180 * the image is the same as the original one at any time.
2183 uint64_t num_sectors
;
2184 uint64_t old_backing_num_sectors
;
2185 uint64_t new_backing_num_sectors
= 0;
2190 float local_progress
= 0;
2192 buf_old
= qemu_blockalign(bs
, IO_BUF_SIZE
);
2193 buf_new
= qemu_blockalign(bs
, IO_BUF_SIZE
);
2195 bdrv_get_geometry(bs
, &num_sectors
);
2196 bdrv_get_geometry(bs_old_backing
, &old_backing_num_sectors
);
2197 if (bs_new_backing
) {
2198 bdrv_get_geometry(bs_new_backing
, &new_backing_num_sectors
);
2201 if (num_sectors
!= 0) {
2202 local_progress
= (float)100 /
2203 (num_sectors
/ MIN(num_sectors
, IO_BUF_SIZE
/ 512));
2206 for (sector
= 0; sector
< num_sectors
; sector
+= n
) {
2208 /* How many sectors can we handle with the next read? */
2209 if (sector
+ (IO_BUF_SIZE
/ 512) <= num_sectors
) {
2210 n
= (IO_BUF_SIZE
/ 512);
2212 n
= num_sectors
- sector
;
2215 /* If the cluster is allocated, we don't need to take action */
2216 ret
= bdrv_is_allocated(bs
, sector
, n
, &n
);
2222 * Read old and new backing file and take into consideration that
2223 * backing files may be smaller than the COW image.
2225 if (sector
>= old_backing_num_sectors
) {
2226 memset(buf_old
, 0, n
* BDRV_SECTOR_SIZE
);
2228 if (sector
+ n
> old_backing_num_sectors
) {
2229 n
= old_backing_num_sectors
- sector
;
2232 ret
= bdrv_read(bs_old_backing
, sector
, buf_old
, n
);
2234 error_report("error while reading from old backing file");
2239 if (sector
>= new_backing_num_sectors
|| !bs_new_backing
) {
2240 memset(buf_new
, 0, n
* BDRV_SECTOR_SIZE
);
2242 if (sector
+ n
> new_backing_num_sectors
) {
2243 n
= new_backing_num_sectors
- sector
;
2246 ret
= bdrv_read(bs_new_backing
, sector
, buf_new
, n
);
2248 error_report("error while reading from new backing file");
2253 /* If they differ, we need to write to the COW file */
2254 uint64_t written
= 0;
2256 while (written
< n
) {
2259 if (compare_sectors(buf_old
+ written
* 512,
2260 buf_new
+ written
* 512, n
- written
, &pnum
))
2262 ret
= bdrv_write(bs
, sector
+ written
,
2263 buf_old
+ written
* 512, pnum
);
2265 error_report("Error while writing to COW image: %s",
2273 qemu_progress_print(local_progress
, 100);
2276 qemu_vfree(buf_old
);
2277 qemu_vfree(buf_new
);
2281 * Change the backing file. All clusters that are different from the old
2282 * backing file are overwritten in the COW file now, so the visible content
2283 * doesn't change when we switch the backing file.
2285 if (out_baseimg
&& *out_baseimg
) {
2286 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
2288 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
2291 if (ret
== -ENOSPC
) {
2292 error_report("Could not change the backing file to '%s': No "
2293 "space left in the file header", out_baseimg
);
2294 } else if (ret
< 0) {
2295 error_report("Could not change the backing file to '%s': %s",
2296 out_baseimg
, strerror(-ret
));
2299 qemu_progress_print(100, 0);
2301 * TODO At this point it is possible to check if any clusters that are
2302 * allocated in the COW file are the same in the backing file. If so, they
2303 * could be dropped from the COW file. Don't do this before switching the
2304 * backing file, in case of a crash this would lead to corruption.
2307 qemu_progress_end();
2310 if (bs_old_backing
!= NULL
) {
2311 bdrv_delete(bs_old_backing
);
2313 if (bs_new_backing
!= NULL
) {
2314 bdrv_delete(bs_new_backing
);
2325 static int img_resize(int argc
, char **argv
)
2327 int c
, ret
, relative
;
2328 const char *filename
, *fmt
, *size
;
2329 int64_t n
, total_size
;
2331 BlockDriverState
*bs
= NULL
;
2333 static QemuOptsList resize_options
= {
2334 .name
= "resize_options",
2335 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
2338 .name
= BLOCK_OPT_SIZE
,
2339 .type
= QEMU_OPT_SIZE
,
2340 .help
= "Virtual disk size"
2347 /* Remove size from argv manually so that negative numbers are not treated
2348 * as options by getopt. */
2354 size
= argv
[--argc
];
2356 /* Parse getopt arguments */
2359 c
= getopt(argc
, argv
, "f:hq");
2376 if (optind
>= argc
) {
2379 filename
= argv
[optind
++];
2381 /* Choose grow, shrink, or absolute resize mode */
2397 param
= qemu_opts_create_nofail(&resize_options
);
2398 if (qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
)) {
2399 /* Error message already printed when size parsing fails */
2401 qemu_opts_del(param
);
2404 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
2405 qemu_opts_del(param
);
2407 bs
= bdrv_new_open(filename
, fmt
, BDRV_O_FLAGS
| BDRV_O_RDWR
, true, quiet
);
2414 total_size
= bdrv_getlength(bs
) + n
* relative
;
2418 if (total_size
<= 0) {
2419 error_report("New image size must be positive");
2424 ret
= bdrv_truncate(bs
, total_size
);
2427 qprintf(quiet
, "Image resized.\n");
2430 error_report("This image does not support resize");
2433 error_report("Image is read-only");
2436 error_report("Error resizing image (%d)", -ret
);
2449 static const img_cmd_t img_cmds
[] = {
2450 #define DEF(option, callback, arg_string) \
2451 { option, callback },
2452 #include "qemu-img-cmds.h"
2458 int main(int argc
, char **argv
)
2460 const img_cmd_t
*cmd
;
2461 const char *cmdname
;
2463 error_set_progname(argv
[0]);
2465 qemu_init_main_loop();
2472 /* find the command */
2473 for(cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
2474 if (!strcmp(cmdname
, cmd
->name
)) {
2475 return cmd
->handler(argc
, argv
);