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 "qemu/osdep.h"
25 #include "qemu-version.h"
26 #include "qapi/error.h"
27 #include "qapi-visit.h"
28 #include "qapi/qmp-output-visitor.h"
29 #include "qapi/qmp/qerror.h"
30 #include "qapi/qmp/qjson.h"
31 #include "qemu/cutils.h"
32 #include "qemu/config-file.h"
33 #include "qemu/option.h"
34 #include "qemu/error-report.h"
35 #include "qom/object_interfaces.h"
36 #include "sysemu/sysemu.h"
37 #include "sysemu/block-backend.h"
38 #include "block/block_int.h"
39 #include "block/blockjob.h"
40 #include "block/qapi.h"
41 #include "crypto/init.h"
44 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
45 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
47 typedef struct img_cmd_t
{
49 int (*handler
)(int argc
, char **argv
);
54 OPTION_BACKING_CHAIN
= 257,
56 OPTION_IMAGE_OPTS
= 259,
58 OPTION_FLUSH_INTERVAL
= 261,
59 OPTION_NO_DRAIN
= 262,
62 typedef enum OutputFormat
{
67 /* Default to cache=writeback as data integrity is not important for qemu-img */
68 #define BDRV_DEFAULT_CACHE "writeback"
70 static void format_print(void *opaque
, const char *name
)
75 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
79 error_printf("qemu-img: ");
82 error_vprintf(fmt
, ap
);
85 error_printf("\nTry 'qemu-img --help' for more information\n");
89 /* Please keep in synch with qemu-img.texi */
90 static void QEMU_NORETURN
help(void)
92 const char *help_msg
=
94 "usage: qemu-img command [command options]\n"
95 "QEMU disk image utility\n"
98 #define DEF(option, callback, arg_string) \
100 #include "qemu-img-cmds.h"
104 "Command parameters:\n"
105 " 'filename' is a disk image filename\n"
106 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
107 " manual page for a description of the object properties. The most common\n"
108 " object type is a 'secret', which is used to supply passwords and/or\n"
109 " encryption keys.\n"
110 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
111 " 'cache' is the cache mode used to write the output disk image, the valid\n"
112 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
113 " 'directsync' and 'unsafe' (default for convert)\n"
114 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
115 " options are the same as for the 'cache' option\n"
116 " 'size' is the disk image size in bytes. Optional suffixes\n"
117 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
118 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
119 " supported. 'b' is ignored.\n"
120 " 'output_filename' is the destination disk image filename\n"
121 " 'output_fmt' is the destination format\n"
122 " 'options' is a comma separated list of format specific options in a\n"
123 " name=value format. Use -o ? for an overview of the options supported by the\n"
125 " 'snapshot_param' is param used for internal snapshot, format\n"
126 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
128 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
130 " '-c' indicates that target image must be compressed (qcow format only)\n"
131 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
132 " match exactly. The image doesn't need a working backing file before\n"
133 " rebasing in this case (useful for renaming the backing file)\n"
134 " '-h' with or without a command shows this help and lists the supported formats\n"
135 " '-p' show progress of command (only certain commands)\n"
136 " '-q' use Quiet mode - do not print any output (except errors)\n"
137 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
138 " contain only zeros for qemu-img to create a sparse image during\n"
139 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
140 " unallocated or zero sectors, and the destination image will always be\n"
142 " '--output' takes the format in which the output must be done (human or json)\n"
143 " '-n' skips the target volume creation (useful if the volume is created\n"
144 " prior to running qemu-img)\n"
146 "Parameters to check subcommand:\n"
147 " '-r' tries to repair any inconsistencies that are found during the check.\n"
148 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
149 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
150 " hiding corruption that has already occurred.\n"
152 "Parameters to snapshot subcommand:\n"
153 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
154 " '-a' applies a snapshot (revert disk to saved state)\n"
155 " '-c' creates a snapshot\n"
156 " '-d' deletes a snapshot\n"
157 " '-l' lists all snapshots in the given image\n"
159 "Parameters to compare subcommand:\n"
160 " '-f' first image format\n"
161 " '-F' second image format\n"
162 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
164 printf("%s\nSupported formats:", help_msg
);
165 bdrv_iterate_format(format_print
, NULL
);
170 static QemuOptsList qemu_object_opts
= {
172 .implied_opt_name
= "qom-type",
173 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
179 static QemuOptsList qemu_source_opts
= {
181 .implied_opt_name
= "file",
182 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
188 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
194 ret
= vprintf(fmt
, args
);
201 static int print_block_option_help(const char *filename
, const char *fmt
)
203 BlockDriver
*drv
, *proto_drv
;
204 QemuOptsList
*create_opts
= NULL
;
205 Error
*local_err
= NULL
;
207 /* Find driver and parse its options */
208 drv
= bdrv_find_format(fmt
);
210 error_report("Unknown file format '%s'", fmt
);
214 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
216 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
218 error_report_err(local_err
);
219 qemu_opts_free(create_opts
);
222 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
225 qemu_opts_print_help(create_opts
);
226 qemu_opts_free(create_opts
);
231 static int img_open_password(BlockBackend
*blk
, const char *filename
,
232 int flags
, bool quiet
)
234 BlockDriverState
*bs
;
238 if (bdrv_is_encrypted(bs
) && bdrv_key_required(bs
) &&
239 !(flags
& BDRV_O_NO_IO
)) {
240 qprintf(quiet
, "Disk image '%s' is encrypted.\n", filename
);
241 if (qemu_read_password(password
, sizeof(password
)) < 0) {
242 error_report("No password given");
245 if (bdrv_set_key(bs
, password
) < 0) {
246 error_report("invalid password");
254 static BlockBackend
*img_open_opts(const char *optstr
,
255 QemuOpts
*opts
, int flags
, bool writethrough
,
259 Error
*local_err
= NULL
;
261 options
= qemu_opts_to_qdict(opts
, NULL
);
262 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
264 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
267 blk_set_enable_write_cache(blk
, !writethrough
);
269 if (img_open_password(blk
, optstr
, flags
, quiet
) < 0) {
276 static BlockBackend
*img_open_file(const char *filename
,
277 const char *fmt
, int flags
,
278 bool writethrough
, bool quiet
)
281 Error
*local_err
= NULL
;
282 QDict
*options
= NULL
;
285 options
= qdict_new();
286 qdict_put(options
, "driver", qstring_from_str(fmt
));
289 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
291 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
294 blk_set_enable_write_cache(blk
, !writethrough
);
296 if (img_open_password(blk
, filename
, flags
, quiet
) < 0) {
304 static BlockBackend
*img_open(bool image_opts
,
305 const char *filename
,
306 const char *fmt
, int flags
, bool writethrough
,
313 error_report("--image-opts and --format are mutually exclusive");
316 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
321 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
);
323 blk
= img_open_file(filename
, fmt
, flags
, writethrough
, quiet
);
329 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
330 const char *base_filename
,
331 const char *base_fmt
)
336 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
338 error_report("Backing file not supported for file format '%s'",
345 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
347 error_report("Backing file format not supported for file "
356 static int img_create(int argc
, char **argv
)
359 uint64_t img_size
= -1;
360 const char *fmt
= "raw";
361 const char *base_fmt
= NULL
;
362 const char *filename
;
363 const char *base_filename
= NULL
;
364 char *options
= NULL
;
365 Error
*local_err
= NULL
;
369 static const struct option long_options
[] = {
370 {"help", no_argument
, 0, 'h'},
371 {"object", required_argument
, 0, OPTION_OBJECT
},
374 c
= getopt_long(argc
, argv
, "F:b:f:he6o:q",
388 base_filename
= optarg
;
394 error_report("option -e is deprecated, please use \'-o "
395 "encryption\' instead!");
398 error_report("option -6 is deprecated, please use \'-o "
399 "compat6\' instead!");
402 if (!is_valid_option_list(optarg
)) {
403 error_report("Invalid option list: %s", optarg
);
407 options
= g_strdup(optarg
);
409 char *old_options
= options
;
410 options
= g_strdup_printf("%s,%s", options
, optarg
);
417 case OPTION_OBJECT
: {
419 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
428 /* Get the filename */
429 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
430 if (options
&& has_help_option(options
)) {
432 return print_block_option_help(filename
, fmt
);
435 if (optind
>= argc
) {
436 error_exit("Expecting image file name");
440 if (qemu_opts_foreach(&qemu_object_opts
,
441 user_creatable_add_opts_foreach
,
446 /* Get image size, if specified */
450 sval
= qemu_strtosz_suffix(argv
[optind
++], &end
,
451 QEMU_STRTOSZ_DEFSUFFIX_B
);
452 if (sval
< 0 || *end
) {
453 if (sval
== -ERANGE
) {
454 error_report("Image size must be less than 8 EiB!");
456 error_report("Invalid image size specified! You may use k, M, "
457 "G, T, P or E suffixes for ");
458 error_report("kilobytes, megabytes, gigabytes, terabytes, "
459 "petabytes and exabytes.");
463 img_size
= (uint64_t)sval
;
465 if (optind
!= argc
) {
466 error_exit("Unexpected argument: %s", argv
[optind
]);
469 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
470 options
, img_size
, 0, &local_err
, quiet
);
472 error_reportf_err(local_err
, "%s: ", filename
);
484 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
486 Error
*local_err
= NULL
;
488 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
490 visit_type_ImageCheck(qmp_output_get_visitor(ov
), NULL
, &check
,
492 obj
= qmp_output_get_qobject(ov
);
493 str
= qobject_to_json_pretty(obj
);
495 qprintf(quiet
, "%s\n", qstring_get_str(str
));
497 qmp_output_visitor_cleanup(ov
);
501 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
503 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
504 qprintf(quiet
, "No errors were found on the image.\n");
506 if (check
->corruptions
) {
507 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
508 "Data may be corrupted, or further writes to the image "
515 "\n%" PRId64
" leaked clusters were found on the image.\n"
516 "This means waste of disk space, but no harm to data.\n",
520 if (check
->check_errors
) {
523 " internal errors have occurred during the check.\n",
524 check
->check_errors
);
528 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
529 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
530 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
531 check
->allocated_clusters
, check
->total_clusters
,
532 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
533 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
534 check
->compressed_clusters
* 100.0 /
535 check
->allocated_clusters
);
538 if (check
->image_end_offset
) {
540 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
544 static int collect_image_check(BlockDriverState
*bs
,
546 const char *filename
,
551 BdrvCheckResult result
;
553 ret
= bdrv_check(bs
, &result
, fix
);
558 check
->filename
= g_strdup(filename
);
559 check
->format
= g_strdup(bdrv_get_format_name(bs
));
560 check
->check_errors
= result
.check_errors
;
561 check
->corruptions
= result
.corruptions
;
562 check
->has_corruptions
= result
.corruptions
!= 0;
563 check
->leaks
= result
.leaks
;
564 check
->has_leaks
= result
.leaks
!= 0;
565 check
->corruptions_fixed
= result
.corruptions_fixed
;
566 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
567 check
->leaks_fixed
= result
.leaks_fixed
;
568 check
->has_leaks_fixed
= result
.leaks
!= 0;
569 check
->image_end_offset
= result
.image_end_offset
;
570 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
571 check
->total_clusters
= result
.bfi
.total_clusters
;
572 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
573 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
574 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
575 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
576 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
577 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
578 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
584 * Checks an image for consistency. Exit codes:
586 * 0 - Check completed, image is good
587 * 1 - Check not completed because of internal errors
588 * 2 - Check completed, image is corrupted
589 * 3 - Check completed, image has leaked clusters, but is good otherwise
590 * 63 - Checks are not supported by the image format
592 static int img_check(int argc
, char **argv
)
595 OutputFormat output_format
= OFORMAT_HUMAN
;
596 const char *filename
, *fmt
, *output
, *cache
;
598 BlockDriverState
*bs
;
600 int flags
= BDRV_O_CHECK
;
604 bool image_opts
= false;
608 cache
= BDRV_DEFAULT_CACHE
;
611 int option_index
= 0;
612 static const struct option long_options
[] = {
613 {"help", no_argument
, 0, 'h'},
614 {"format", required_argument
, 0, 'f'},
615 {"repair", required_argument
, 0, 'r'},
616 {"output", required_argument
, 0, OPTION_OUTPUT
},
617 {"object", required_argument
, 0, OPTION_OBJECT
},
618 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
621 c
= getopt_long(argc
, argv
, "hf:r:T:q",
622 long_options
, &option_index
);
635 flags
|= BDRV_O_RDWR
;
637 if (!strcmp(optarg
, "leaks")) {
638 fix
= BDRV_FIX_LEAKS
;
639 } else if (!strcmp(optarg
, "all")) {
640 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
642 error_exit("Unknown option value for -r "
643 "(expecting 'leaks' or 'all'): %s", optarg
);
655 case OPTION_OBJECT
: {
657 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
663 case OPTION_IMAGE_OPTS
:
668 if (optind
!= argc
- 1) {
669 error_exit("Expecting one image file name");
671 filename
= argv
[optind
++];
673 if (output
&& !strcmp(output
, "json")) {
674 output_format
= OFORMAT_JSON
;
675 } else if (output
&& !strcmp(output
, "human")) {
676 output_format
= OFORMAT_HUMAN
;
678 error_report("--output must be used with human or json as argument.");
682 if (qemu_opts_foreach(&qemu_object_opts
,
683 user_creatable_add_opts_foreach
,
688 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
690 error_report("Invalid source cache option: %s", cache
);
694 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
700 check
= g_new0(ImageCheck
, 1);
701 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
703 if (ret
== -ENOTSUP
) {
704 error_report("This image format does not support checks");
709 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
710 int corruptions_fixed
, leaks_fixed
;
712 leaks_fixed
= check
->leaks_fixed
;
713 corruptions_fixed
= check
->corruptions_fixed
;
715 if (output_format
== OFORMAT_HUMAN
) {
717 "The following inconsistencies were found and repaired:\n\n"
718 " %" PRId64
" leaked clusters\n"
719 " %" PRId64
" corruptions\n\n"
720 "Double checking the fixed image now...\n",
722 check
->corruptions_fixed
);
725 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
727 check
->leaks_fixed
= leaks_fixed
;
728 check
->corruptions_fixed
= corruptions_fixed
;
732 switch (output_format
) {
734 dump_human_image_check(check
, quiet
);
737 dump_json_image_check(check
, quiet
);
742 if (ret
|| check
->check_errors
) {
744 error_report("Check failed: %s", strerror(-ret
));
746 error_report("Check failed");
752 if (check
->corruptions
) {
754 } else if (check
->leaks
) {
761 qapi_free_ImageCheck(check
);
766 typedef struct CommonBlockJobCBInfo
{
767 BlockDriverState
*bs
;
769 } CommonBlockJobCBInfo
;
771 static void common_block_job_cb(void *opaque
, int ret
)
773 CommonBlockJobCBInfo
*cbi
= opaque
;
776 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
780 static void run_block_job(BlockJob
*job
, Error
**errp
)
782 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
785 aio_poll(aio_context
, true);
786 qemu_progress_print(job
->len
?
787 ((float)job
->offset
/ job
->len
* 100.f
) : 0.0f
, 0);
788 } while (!job
->ready
);
790 block_job_complete_sync(job
, errp
);
792 /* A block job may finish instantaneously without publishing any progress,
793 * so just signal completion here */
794 qemu_progress_print(100.f
, 0);
797 static int img_commit(int argc
, char **argv
)
800 const char *filename
, *fmt
, *cache
, *base
;
802 BlockDriverState
*bs
, *base_bs
;
803 bool progress
= false, quiet
= false, drop
= false;
805 Error
*local_err
= NULL
;
806 CommonBlockJobCBInfo cbi
;
807 bool image_opts
= false;
810 cache
= BDRV_DEFAULT_CACHE
;
813 static const struct option long_options
[] = {
814 {"help", no_argument
, 0, 'h'},
815 {"object", required_argument
, 0, OPTION_OBJECT
},
816 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
819 c
= getopt_long(argc
, argv
, "f:ht:b:dpq",
849 case OPTION_OBJECT
: {
851 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
857 case OPTION_IMAGE_OPTS
:
863 /* Progress is not shown in Quiet mode */
868 if (optind
!= argc
- 1) {
869 error_exit("Expecting one image file name");
871 filename
= argv
[optind
++];
873 if (qemu_opts_foreach(&qemu_object_opts
,
874 user_creatable_add_opts_foreach
,
879 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
880 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
882 error_report("Invalid cache option: %s", cache
);
886 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
892 qemu_progress_init(progress
, 1.f
);
893 qemu_progress_print(0.f
, 100);
896 base_bs
= bdrv_find_backing_image(bs
, base
);
898 error_setg(&local_err
, QERR_BASE_NOT_FOUND
, base
);
902 /* This is different from QMP, which by default uses the deepest file in
903 * the backing chain (i.e., the very base); however, the traditional
904 * behavior of qemu-img commit is using the immediate backing file. */
905 base_bs
= backing_bs(bs
);
907 error_setg(&local_err
, "Image does not have a backing file");
912 cbi
= (CommonBlockJobCBInfo
){
917 commit_active_start(bs
, base_bs
, 0, BLOCKDEV_ON_ERROR_REPORT
,
918 common_block_job_cb
, &cbi
, &local_err
);
923 /* When the block job completes, the BlockBackend reference will point to
924 * the old backing file. In order to avoid that the top image is already
925 * deleted, so we can still empty it afterwards, increment the reference
926 * counter here preemptively. */
931 run_block_job(bs
->job
, &local_err
);
936 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
937 ret
= bs
->drv
->bdrv_make_empty(bs
);
939 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
956 error_report_err(local_err
);
960 qprintf(quiet
, "Image committed.\n");
965 * Returns true iff the first sector pointed to by 'buf' contains at least
968 * 'pnum' is set to the number of sectors (including and immediately following
969 * the first one) that are known to be in the same allocated/unallocated state.
971 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
)
980 is_zero
= buffer_is_zero(buf
, 512);
981 for(i
= 1; i
< n
; i
++) {
983 if (is_zero
!= buffer_is_zero(buf
, 512)) {
992 * Like is_allocated_sectors, but if the buffer starts with a used sector,
993 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
994 * breaking up write requests for only small sparse areas.
996 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1000 int num_checked
, num_used
;
1006 ret
= is_allocated_sectors(buf
, n
, pnum
);
1012 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1014 num_checked
= num_used
;
1017 ret
= is_allocated_sectors(buf
, n
, pnum
);
1019 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1021 num_checked
+= *pnum
;
1023 num_used
= num_checked
;
1024 } else if (*pnum
>= min
) {
1034 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1035 * buffers matches, non-zero otherwise.
1037 * pnum is set to the number of sectors (including and immediately following
1038 * the first one) that are known to have the same comparison result
1040 static int compare_sectors(const uint8_t *buf1
, const uint8_t *buf2
, int n
,
1051 res
= !!memcmp(buf1
, buf2
, 512);
1052 for(i
= 1; i
< n
; i
++) {
1056 if (!!memcmp(buf1
, buf2
, 512) != res
) {
1065 #define IO_BUF_SIZE (2 * 1024 * 1024)
1067 static int64_t sectors_to_bytes(int64_t sectors
)
1069 return sectors
<< BDRV_SECTOR_BITS
;
1072 static int64_t sectors_to_process(int64_t total
, int64_t from
)
1074 return MIN(total
- from
, IO_BUF_SIZE
>> BDRV_SECTOR_BITS
);
1078 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1080 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1081 * data and negative value on error.
1083 * @param blk: BlockBackend for the image
1084 * @param sect_num: Number of first sector to check
1085 * @param sect_count: Number of sectors to check
1086 * @param filename: Name of disk file we are checking (logging purpose)
1087 * @param buffer: Allocated buffer for storing read data
1088 * @param quiet: Flag for quiet mode
1090 static int check_empty_sectors(BlockBackend
*blk
, int64_t sect_num
,
1091 int sect_count
, const char *filename
,
1092 uint8_t *buffer
, bool quiet
)
1095 ret
= blk_pread(blk
, sect_num
<< BDRV_SECTOR_BITS
, buffer
,
1096 sect_count
<< BDRV_SECTOR_BITS
);
1098 error_report("Error while reading offset %" PRId64
" of %s: %s",
1099 sectors_to_bytes(sect_num
), filename
, strerror(-ret
));
1102 ret
= is_allocated_sectors(buffer
, sect_count
, &pnum
);
1103 if (ret
|| pnum
!= sect_count
) {
1104 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1105 sectors_to_bytes(ret
? sect_num
: sect_num
+ pnum
));
1113 * Compares two images. Exit codes:
1115 * 0 - Images are identical
1117 * >1 - Error occurred
1119 static int img_compare(int argc
, char **argv
)
1121 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1122 BlockBackend
*blk1
, *blk2
;
1123 BlockDriverState
*bs1
, *bs2
;
1124 int64_t total_sectors1
, total_sectors2
;
1125 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1127 int allocated1
, allocated2
;
1128 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1129 bool progress
= false, quiet
= false, strict
= false;
1132 int64_t total_sectors
;
1133 int64_t sector_num
= 0;
1136 uint64_t progress_base
;
1137 bool image_opts
= false;
1139 cache
= BDRV_DEFAULT_CACHE
;
1141 static const struct option long_options
[] = {
1142 {"help", no_argument
, 0, 'h'},
1143 {"object", required_argument
, 0, OPTION_OBJECT
},
1144 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1147 c
= getopt_long(argc
, argv
, "hf:F:T:pqs",
1148 long_options
, NULL
);
1175 case OPTION_OBJECT
: {
1177 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1184 case OPTION_IMAGE_OPTS
:
1190 /* Progress is not shown in Quiet mode */
1196 if (optind
!= argc
- 2) {
1197 error_exit("Expecting two image file names");
1199 filename1
= argv
[optind
++];
1200 filename2
= argv
[optind
++];
1202 if (qemu_opts_foreach(&qemu_object_opts
,
1203 user_creatable_add_opts_foreach
,
1209 /* Initialize before goto out */
1210 qemu_progress_init(progress
, 2.0);
1213 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1215 error_report("Invalid source cache option: %s", cache
);
1220 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
);
1226 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
);
1234 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1235 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1236 total_sectors1
= blk_nb_sectors(blk1
);
1237 if (total_sectors1
< 0) {
1238 error_report("Can't get size of %s: %s",
1239 filename1
, strerror(-total_sectors1
));
1243 total_sectors2
= blk_nb_sectors(blk2
);
1244 if (total_sectors2
< 0) {
1245 error_report("Can't get size of %s: %s",
1246 filename2
, strerror(-total_sectors2
));
1250 total_sectors
= MIN(total_sectors1
, total_sectors2
);
1251 progress_base
= MAX(total_sectors1
, total_sectors2
);
1253 qemu_progress_print(0, 100);
1255 if (strict
&& total_sectors1
!= total_sectors2
) {
1257 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1262 int64_t status1
, status2
;
1263 BlockDriverState
*file
;
1265 nb_sectors
= sectors_to_process(total_sectors
, sector_num
);
1266 if (nb_sectors
<= 0) {
1269 status1
= bdrv_get_block_status_above(bs1
, NULL
, sector_num
,
1270 total_sectors1
- sector_num
,
1274 error_report("Sector allocation test failed for %s", filename1
);
1277 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1279 status2
= bdrv_get_block_status_above(bs2
, NULL
, sector_num
,
1280 total_sectors2
- sector_num
,
1284 error_report("Sector allocation test failed for %s", filename2
);
1287 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1289 nb_sectors
= MIN(nb_sectors
, pnum1
);
1292 nb_sectors
= MIN(nb_sectors
, pnum2
);
1296 if ((status1
& ~BDRV_BLOCK_OFFSET_MASK
) !=
1297 (status2
& ~BDRV_BLOCK_OFFSET_MASK
)) {
1299 qprintf(quiet
, "Strict mode: Offset %" PRId64
1300 " block status mismatch!\n",
1301 sectors_to_bytes(sector_num
));
1305 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1306 nb_sectors
= MIN(pnum1
, pnum2
);
1307 } else if (allocated1
== allocated2
) {
1309 ret
= blk_pread(blk1
, sector_num
<< BDRV_SECTOR_BITS
, buf1
,
1310 nb_sectors
<< BDRV_SECTOR_BITS
);
1312 error_report("Error while reading offset %" PRId64
" of %s:"
1313 " %s", sectors_to_bytes(sector_num
), filename1
,
1318 ret
= blk_pread(blk2
, sector_num
<< BDRV_SECTOR_BITS
, buf2
,
1319 nb_sectors
<< BDRV_SECTOR_BITS
);
1321 error_report("Error while reading offset %" PRId64
1322 " of %s: %s", sectors_to_bytes(sector_num
),
1323 filename2
, strerror(-ret
));
1327 ret
= compare_sectors(buf1
, buf2
, nb_sectors
, &pnum
);
1328 if (ret
|| pnum
!= nb_sectors
) {
1329 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1331 ret
? sector_num
: sector_num
+ pnum
));
1339 ret
= check_empty_sectors(blk1
, sector_num
, nb_sectors
,
1340 filename1
, buf1
, quiet
);
1342 ret
= check_empty_sectors(blk2
, sector_num
, nb_sectors
,
1343 filename2
, buf1
, quiet
);
1347 error_report("Error while reading offset %" PRId64
": %s",
1348 sectors_to_bytes(sector_num
), strerror(-ret
));
1354 sector_num
+= nb_sectors
;
1355 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1358 if (total_sectors1
!= total_sectors2
) {
1359 BlockBackend
*blk_over
;
1360 int64_t total_sectors_over
;
1361 const char *filename_over
;
1363 qprintf(quiet
, "Warning: Image size mismatch!\n");
1364 if (total_sectors1
> total_sectors2
) {
1365 total_sectors_over
= total_sectors1
;
1367 filename_over
= filename1
;
1369 total_sectors_over
= total_sectors2
;
1371 filename_over
= filename2
;
1375 nb_sectors
= sectors_to_process(total_sectors_over
, sector_num
);
1376 if (nb_sectors
<= 0) {
1379 ret
= bdrv_is_allocated_above(blk_bs(blk_over
), NULL
, sector_num
,
1383 error_report("Sector allocation test failed for %s",
1390 ret
= check_empty_sectors(blk_over
, sector_num
, nb_sectors
,
1391 filename_over
, buf1
, quiet
);
1394 error_report("Error while reading offset %" PRId64
1395 " of %s: %s", sectors_to_bytes(sector_num
),
1396 filename_over
, strerror(-ret
));
1402 sector_num
+= nb_sectors
;
1403 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1407 qprintf(quiet
, "Images are identical.\n");
1417 qemu_progress_end();
1422 enum ImgConvertBlockStatus
{
1428 typedef struct ImgConvertState
{
1430 int64_t *src_sectors
;
1431 int src_cur
, src_num
;
1432 int64_t src_cur_offset
;
1433 int64_t total_sectors
;
1434 int64_t allocated_sectors
;
1435 enum ImgConvertBlockStatus status
;
1436 int64_t sector_next_status
;
1437 BlockBackend
*target
;
1440 bool target_has_backing
;
1442 size_t cluster_sectors
;
1446 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
)
1448 assert(sector_num
>= s
->src_cur_offset
);
1449 while (sector_num
- s
->src_cur_offset
>= s
->src_sectors
[s
->src_cur
]) {
1450 s
->src_cur_offset
+= s
->src_sectors
[s
->src_cur
];
1452 assert(s
->src_cur
< s
->src_num
);
1456 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1461 convert_select_part(s
, sector_num
);
1463 assert(s
->total_sectors
> sector_num
);
1464 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1466 if (s
->sector_next_status
<= sector_num
) {
1467 BlockDriverState
*file
;
1468 ret
= bdrv_get_block_status(blk_bs(s
->src
[s
->src_cur
]),
1469 sector_num
- s
->src_cur_offset
,
1475 if (ret
& BDRV_BLOCK_ZERO
) {
1476 s
->status
= BLK_ZERO
;
1477 } else if (ret
& BDRV_BLOCK_DATA
) {
1478 s
->status
= BLK_DATA
;
1479 } else if (!s
->target_has_backing
) {
1480 /* Without a target backing file we must copy over the contents of
1481 * the backing file as well. */
1482 /* Check block status of the backing file chain to avoid
1483 * needlessly reading zeroes and limiting the iteration to the
1485 ret
= bdrv_get_block_status_above(blk_bs(s
->src
[s
->src_cur
]), NULL
,
1486 sector_num
- s
->src_cur_offset
,
1492 if (ret
& BDRV_BLOCK_ZERO
) {
1493 s
->status
= BLK_ZERO
;
1495 s
->status
= BLK_DATA
;
1498 s
->status
= BLK_BACKING_FILE
;
1501 s
->sector_next_status
= sector_num
+ n
;
1504 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1505 if (s
->status
== BLK_DATA
) {
1506 n
= MIN(n
, s
->buf_sectors
);
1509 /* We need to write complete clusters for compressed images, so if an
1510 * unallocated area is shorter than that, we must consider the whole
1511 * cluster allocated. */
1512 if (s
->compressed
) {
1513 if (n
< s
->cluster_sectors
) {
1514 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1515 s
->status
= BLK_DATA
;
1517 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1524 static int convert_read(ImgConvertState
*s
, int64_t sector_num
, int nb_sectors
,
1530 assert(nb_sectors
<= s
->buf_sectors
);
1531 while (nb_sectors
> 0) {
1535 /* In the case of compression with multiple source files, we can get a
1536 * nb_sectors that spreads into the next part. So we must be able to
1537 * read across multiple BDSes for one convert_read() call. */
1538 convert_select_part(s
, sector_num
);
1539 blk
= s
->src
[s
->src_cur
];
1540 bs_sectors
= s
->src_sectors
[s
->src_cur
];
1542 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- s
->src_cur_offset
));
1543 ret
= blk_pread(blk
,
1544 (sector_num
- s
->src_cur_offset
) << BDRV_SECTOR_BITS
,
1545 buf
, n
<< BDRV_SECTOR_BITS
);
1552 buf
+= n
* BDRV_SECTOR_SIZE
;
1558 static int convert_write(ImgConvertState
*s
, int64_t sector_num
, int nb_sectors
,
1563 while (nb_sectors
> 0) {
1566 switch (s
->status
) {
1567 case BLK_BACKING_FILE
:
1568 /* If we have a backing file, leave clusters unallocated that are
1569 * unallocated in the source image, so that the backing file is
1570 * visible at the respective offset. */
1571 assert(s
->target_has_backing
);
1575 /* We must always write compressed clusters as a whole, so don't
1576 * try to find zeroed parts in the buffer. We can only save the
1577 * write if the buffer is completely zeroed and we're allowed to
1578 * keep the target sparse. */
1579 if (s
->compressed
) {
1580 if (s
->has_zero_init
&& s
->min_sparse
&&
1581 buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
))
1583 assert(!s
->target_has_backing
);
1587 ret
= blk_write_compressed(s
->target
, sector_num
, buf
, n
);
1594 /* If there is real non-zero data or we're told to keep the target
1595 * fully allocated (-S 0), we must write it. Otherwise we can treat
1596 * it as zero sectors. */
1597 if (!s
->min_sparse
||
1598 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
))
1600 ret
= blk_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1601 buf
, n
<< BDRV_SECTOR_BITS
, 0);
1610 if (s
->has_zero_init
) {
1613 ret
= blk_pwrite_zeroes(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1614 n
<< BDRV_SECTOR_BITS
, 0);
1623 buf
+= n
* BDRV_SECTOR_SIZE
;
1629 static int convert_do_copy(ImgConvertState
*s
)
1631 uint8_t *buf
= NULL
;
1632 int64_t sector_num
, allocated_done
;
1636 /* Check whether we have zero initialisation or can get it efficiently */
1637 s
->has_zero_init
= s
->min_sparse
&& !s
->target_has_backing
1638 ? bdrv_has_zero_init(blk_bs(s
->target
))
1641 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1642 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1644 ret
= bdrv_make_zero(blk_bs(s
->target
), BDRV_REQ_MAY_UNMAP
);
1646 s
->has_zero_init
= true;
1650 /* Allocate buffer for copied data. For compressed images, only one cluster
1651 * can be copied at a time. */
1652 if (s
->compressed
) {
1653 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
1654 error_report("invalid cluster size");
1658 s
->buf_sectors
= s
->cluster_sectors
;
1660 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1662 /* Calculate allocated sectors for progress */
1663 s
->allocated_sectors
= 0;
1665 while (sector_num
< s
->total_sectors
) {
1666 n
= convert_iteration_sectors(s
, sector_num
);
1671 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1673 s
->allocated_sectors
+= n
;
1680 s
->src_cur_offset
= 0;
1681 s
->sector_next_status
= 0;
1686 while (sector_num
< s
->total_sectors
) {
1687 n
= convert_iteration_sectors(s
, sector_num
);
1692 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1694 allocated_done
+= n
;
1695 qemu_progress_print(100.0 * allocated_done
/ s
->allocated_sectors
,
1699 if (s
->status
== BLK_DATA
) {
1700 ret
= convert_read(s
, sector_num
, n
, buf
);
1702 error_report("error while reading sector %" PRId64
1703 ": %s", sector_num
, strerror(-ret
));
1706 } else if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1707 n
= MIN(n
, s
->buf_sectors
);
1708 memset(buf
, 0, n
* BDRV_SECTOR_SIZE
);
1709 s
->status
= BLK_DATA
;
1712 ret
= convert_write(s
, sector_num
, n
, buf
);
1714 error_report("error while writing sector %" PRId64
1715 ": %s", sector_num
, strerror(-ret
));
1722 if (s
->compressed
) {
1723 /* signal EOF to align */
1724 ret
= blk_write_compressed(s
->target
, 0, NULL
, 0);
1736 static int img_convert(int argc
, char **argv
)
1738 int c
, bs_n
, bs_i
, compress
, cluster_sectors
, skip_create
;
1740 int progress
= 0, flags
, src_flags
;
1741 bool writethrough
, src_writethrough
;
1742 const char *fmt
, *out_fmt
, *cache
, *src_cache
, *out_baseimg
, *out_filename
;
1743 BlockDriver
*drv
, *proto_drv
;
1744 BlockBackend
**blk
= NULL
, *out_blk
= NULL
;
1745 BlockDriverState
**bs
= NULL
, *out_bs
= NULL
;
1746 int64_t total_sectors
;
1747 int64_t *bs_sectors
= NULL
;
1748 size_t bufsectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
;
1749 BlockDriverInfo bdi
;
1750 QemuOpts
*opts
= NULL
;
1751 QemuOptsList
*create_opts
= NULL
;
1752 const char *out_baseimg_param
;
1753 char *options
= NULL
;
1754 const char *snapshot_name
= NULL
;
1755 int min_sparse
= 8; /* Need at least 4k of zeros for sparse detection */
1757 Error
*local_err
= NULL
;
1758 QemuOpts
*sn_opts
= NULL
;
1759 ImgConvertState state
;
1760 bool image_opts
= false;
1765 src_cache
= BDRV_DEFAULT_CACHE
;
1770 static const struct option long_options
[] = {
1771 {"help", no_argument
, 0, 'h'},
1772 {"object", required_argument
, 0, OPTION_OBJECT
},
1773 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1776 c
= getopt_long(argc
, argv
, "hf:O:B:ce6o:s:l:S:pt:T:qn",
1777 long_options
, NULL
);
1793 out_baseimg
= optarg
;
1799 error_report("option -e is deprecated, please use \'-o "
1800 "encryption\' instead!");
1804 error_report("option -6 is deprecated, please use \'-o "
1805 "compat6\' instead!");
1809 if (!is_valid_option_list(optarg
)) {
1810 error_report("Invalid option list: %s", optarg
);
1815 options
= g_strdup(optarg
);
1817 char *old_options
= options
;
1818 options
= g_strdup_printf("%s,%s", options
, optarg
);
1819 g_free(old_options
);
1823 snapshot_name
= optarg
;
1826 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
1827 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
1830 error_report("Failed in parsing snapshot param '%s'",
1836 snapshot_name
= optarg
;
1843 sval
= qemu_strtosz_suffix(optarg
, &end
, QEMU_STRTOSZ_DEFSUFFIX_B
);
1844 if (sval
< 0 || *end
) {
1845 error_report("Invalid minimum zero buffer size for sparse output specified");
1850 min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
1869 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1875 case OPTION_IMAGE_OPTS
:
1881 if (qemu_opts_foreach(&qemu_object_opts
,
1882 user_creatable_add_opts_foreach
,
1887 /* Initialize before goto out */
1891 qemu_progress_init(progress
, 1.0);
1893 bs_n
= argc
- optind
- 1;
1894 out_filename
= bs_n
>= 1 ? argv
[argc
- 1] : NULL
;
1896 if (options
&& has_help_option(options
)) {
1897 ret
= print_block_option_help(out_filename
, out_fmt
);
1902 error_exit("Must specify image file name");
1906 if (bs_n
> 1 && out_baseimg
) {
1907 error_report("-B makes no sense when concatenating multiple input "
1914 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
1916 error_report("Invalid source cache option: %s", src_cache
);
1920 qemu_progress_print(0, 100);
1922 blk
= g_new0(BlockBackend
*, bs_n
);
1923 bs
= g_new0(BlockDriverState
*, bs_n
);
1924 bs_sectors
= g_new(int64_t, bs_n
);
1927 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
1928 blk
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
1929 fmt
, src_flags
, src_writethrough
, quiet
);
1934 bs
[bs_i
] = blk_bs(blk
[bs_i
]);
1935 bs_sectors
[bs_i
] = blk_nb_sectors(blk
[bs_i
]);
1936 if (bs_sectors
[bs_i
] < 0) {
1937 error_report("Could not get size of %s: %s",
1938 argv
[optind
+ bs_i
], strerror(-bs_sectors
[bs_i
]));
1942 total_sectors
+= bs_sectors
[bs_i
];
1946 ret
= bdrv_snapshot_load_tmp(bs
[0],
1947 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
1948 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
1950 } else if (snapshot_name
!= NULL
) {
1952 error_report("No support for concatenating multiple snapshot");
1957 bdrv_snapshot_load_tmp_by_id_or_name(bs
[0], snapshot_name
, &local_err
);
1960 error_reportf_err(local_err
, "Failed to load snapshot: ");
1965 /* Find driver and parse its options */
1966 drv
= bdrv_find_format(out_fmt
);
1968 error_report("Unknown file format '%s'", out_fmt
);
1973 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
1975 error_report_err(local_err
);
1981 if (!drv
->create_opts
) {
1982 error_report("Format driver '%s' does not support image creation",
1988 if (!proto_drv
->create_opts
) {
1989 error_report("Protocol driver '%s' does not support image creation",
1990 proto_drv
->format_name
);
1995 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
1996 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
1998 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2000 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2002 error_report_err(local_err
);
2008 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, total_sectors
* 512,
2010 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2016 /* Get backing file name if -o backing_file was used */
2017 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2018 if (out_baseimg_param
) {
2019 out_baseimg
= out_baseimg_param
;
2022 /* Check if compression is supported */
2025 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2026 const char *preallocation
=
2027 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2029 if (!drv
->bdrv_write_compressed
) {
2030 error_report("Compression not supported for this file format");
2036 error_report("Compression and encryption not supported at "
2043 && strcmp(preallocation
, "off"))
2045 error_report("Compression and preallocation not supported at "
2053 /* Create the new image */
2054 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2056 error_reportf_err(local_err
, "%s: error while converting %s: ",
2057 out_filename
, out_fmt
);
2062 flags
= min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2063 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2065 error_report("Invalid cache option: %s", cache
);
2069 /* XXX we should allow --image-opts to trigger use of
2070 * img_open() here, but then we have trouble with
2071 * the bdrv_create() call which takes different params.
2072 * Not critical right now, so fix can wait...
2074 out_blk
= img_open_file(out_filename
, out_fmt
, flags
, writethrough
, quiet
);
2079 out_bs
= blk_bs(out_blk
);
2081 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
2082 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2084 bufsectors
= MIN(32768,
2085 MAX(bufsectors
, MAX(out_bs
->bl
.opt_transfer_length
,
2086 out_bs
->bl
.discard_alignment
))
2090 int64_t output_sectors
= blk_nb_sectors(out_blk
);
2091 if (output_sectors
< 0) {
2092 error_report("unable to get output image length: %s",
2093 strerror(-output_sectors
));
2096 } else if (output_sectors
< total_sectors
) {
2097 error_report("output file is smaller than input file");
2103 cluster_sectors
= 0;
2104 ret
= bdrv_get_info(out_bs
, &bdi
);
2107 error_report("could not get block driver info");
2111 compress
= compress
|| bdi
.needs_compressed_writes
;
2112 cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2115 state
= (ImgConvertState
) {
2117 .src_sectors
= bs_sectors
,
2119 .total_sectors
= total_sectors
,
2121 .compressed
= compress
,
2122 .target_has_backing
= (bool) out_baseimg
,
2123 .min_sparse
= min_sparse
,
2124 .cluster_sectors
= cluster_sectors
,
2125 .buf_sectors
= bufsectors
,
2127 ret
= convert_do_copy(&state
);
2131 qemu_progress_print(100, 0);
2133 qemu_progress_end();
2134 qemu_opts_del(opts
);
2135 qemu_opts_free(create_opts
);
2136 qemu_opts_del(sn_opts
);
2140 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
2141 blk_unref(blk
[bs_i
]);
2156 static void dump_snapshots(BlockDriverState
*bs
)
2158 QEMUSnapshotInfo
*sn_tab
, *sn
;
2161 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2164 printf("Snapshot list:\n");
2165 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
2167 for(i
= 0; i
< nb_sns
; i
++) {
2169 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
2175 static void dump_json_image_info_list(ImageInfoList
*list
)
2177 Error
*local_err
= NULL
;
2179 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
2181 visit_type_ImageInfoList(qmp_output_get_visitor(ov
), NULL
, &list
,
2183 obj
= qmp_output_get_qobject(ov
);
2184 str
= qobject_to_json_pretty(obj
);
2185 assert(str
!= NULL
);
2186 printf("%s\n", qstring_get_str(str
));
2187 qobject_decref(obj
);
2188 qmp_output_visitor_cleanup(ov
);
2192 static void dump_json_image_info(ImageInfo
*info
)
2194 Error
*local_err
= NULL
;
2196 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
2198 visit_type_ImageInfo(qmp_output_get_visitor(ov
), NULL
, &info
, &local_err
);
2199 obj
= qmp_output_get_qobject(ov
);
2200 str
= qobject_to_json_pretty(obj
);
2201 assert(str
!= NULL
);
2202 printf("%s\n", qstring_get_str(str
));
2203 qobject_decref(obj
);
2204 qmp_output_visitor_cleanup(ov
);
2208 static void dump_human_image_info_list(ImageInfoList
*list
)
2210 ImageInfoList
*elem
;
2213 for (elem
= list
; elem
; elem
= elem
->next
) {
2219 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
2223 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2225 return strcmp(a
, b
) == 0;
2229 * Open an image file chain and return an ImageInfoList
2231 * @filename: topmost image filename
2232 * @fmt: topmost image format (may be NULL to autodetect)
2233 * @chain: true - enumerate entire backing file chain
2234 * false - only topmost image file
2236 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2237 * image file. If there was an error a message will have been printed to
2240 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2241 const char *filename
,
2245 ImageInfoList
*head
= NULL
;
2246 ImageInfoList
**last
= &head
;
2247 GHashTable
*filenames
;
2250 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2254 BlockDriverState
*bs
;
2256 ImageInfoList
*elem
;
2258 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2259 error_report("Backing file '%s' creates an infinite loop.",
2263 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2265 blk
= img_open(image_opts
, filename
, fmt
,
2266 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false);
2272 bdrv_query_image_info(bs
, &info
, &err
);
2274 error_report_err(err
);
2279 elem
= g_new0(ImageInfoList
, 1);
2286 filename
= fmt
= NULL
;
2288 if (info
->has_full_backing_filename
) {
2289 filename
= info
->full_backing_filename
;
2290 } else if (info
->has_backing_filename
) {
2291 error_report("Could not determine absolute backing filename,"
2292 " but backing filename '%s' present",
2293 info
->backing_filename
);
2296 if (info
->has_backing_filename_format
) {
2297 fmt
= info
->backing_filename_format
;
2301 g_hash_table_destroy(filenames
);
2305 qapi_free_ImageInfoList(head
);
2306 g_hash_table_destroy(filenames
);
2310 static int img_info(int argc
, char **argv
)
2313 OutputFormat output_format
= OFORMAT_HUMAN
;
2315 const char *filename
, *fmt
, *output
;
2316 ImageInfoList
*list
;
2317 bool image_opts
= false;
2322 int option_index
= 0;
2323 static const struct option long_options
[] = {
2324 {"help", no_argument
, 0, 'h'},
2325 {"format", required_argument
, 0, 'f'},
2326 {"output", required_argument
, 0, OPTION_OUTPUT
},
2327 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2328 {"object", required_argument
, 0, OPTION_OBJECT
},
2329 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2332 c
= getopt_long(argc
, argv
, "f:h",
2333 long_options
, &option_index
);
2348 case OPTION_BACKING_CHAIN
:
2351 case OPTION_OBJECT
: {
2353 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2359 case OPTION_IMAGE_OPTS
:
2364 if (optind
!= argc
- 1) {
2365 error_exit("Expecting one image file name");
2367 filename
= argv
[optind
++];
2369 if (output
&& !strcmp(output
, "json")) {
2370 output_format
= OFORMAT_JSON
;
2371 } else if (output
&& !strcmp(output
, "human")) {
2372 output_format
= OFORMAT_HUMAN
;
2373 } else if (output
) {
2374 error_report("--output must be used with human or json as argument.");
2378 if (qemu_opts_foreach(&qemu_object_opts
,
2379 user_creatable_add_opts_foreach
,
2384 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
);
2389 switch (output_format
) {
2391 dump_human_image_info_list(list
);
2395 dump_json_image_info_list(list
);
2397 dump_json_image_info(list
->value
);
2402 qapi_free_ImageInfoList(list
);
2406 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2409 switch (output_format
) {
2411 if (e
->data
&& !e
->has_offset
) {
2412 error_report("File contains external, encrypted or compressed clusters.");
2415 if (e
->data
&& !e
->zero
) {
2416 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2417 e
->start
, e
->length
,
2418 e
->has_offset
? e
->offset
: 0,
2419 e
->has_filename
? e
->filename
: "");
2421 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2422 * Modify the flags here to allow more coalescing.
2424 if (next
&& (!next
->data
|| next
->zero
)) {
2430 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2431 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2432 (e
->start
== 0 ? "[" : ",\n"),
2433 e
->start
, e
->length
, e
->depth
,
2434 e
->zero
? "true" : "false",
2435 e
->data
? "true" : "false");
2436 if (e
->has_offset
) {
2437 printf(", \"offset\": %"PRId64
"", e
->offset
);
2448 static int get_block_status(BlockDriverState
*bs
, int64_t sector_num
,
2449 int nb_sectors
, MapEntry
*e
)
2453 BlockDriverState
*file
;
2456 /* As an optimization, we could cache the current range of unallocated
2457 * clusters in each file of the chain, and avoid querying the same
2463 ret
= bdrv_get_block_status(bs
, sector_num
, nb_sectors
, &nb_sectors
,
2469 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2472 bs
= backing_bs(bs
);
2481 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2484 .start
= sector_num
* BDRV_SECTOR_SIZE
,
2485 .length
= nb_sectors
* BDRV_SECTOR_SIZE
,
2486 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2487 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2488 .offset
= ret
& BDRV_BLOCK_OFFSET_MASK
,
2489 .has_offset
= has_offset
,
2491 .has_filename
= file
&& has_offset
,
2492 .filename
= file
&& has_offset
? file
->filename
: NULL
,
2498 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2500 if (curr
->length
== 0) {
2503 if (curr
->zero
!= next
->zero
||
2504 curr
->data
!= next
->data
||
2505 curr
->depth
!= next
->depth
||
2506 curr
->has_filename
!= next
->has_filename
||
2507 curr
->has_offset
!= next
->has_offset
) {
2510 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2513 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2519 static int img_map(int argc
, char **argv
)
2522 OutputFormat output_format
= OFORMAT_HUMAN
;
2524 BlockDriverState
*bs
;
2525 const char *filename
, *fmt
, *output
;
2527 MapEntry curr
= { .length
= 0 }, next
;
2529 bool image_opts
= false;
2534 int option_index
= 0;
2535 static const struct option long_options
[] = {
2536 {"help", no_argument
, 0, 'h'},
2537 {"format", required_argument
, 0, 'f'},
2538 {"output", required_argument
, 0, OPTION_OUTPUT
},
2539 {"object", required_argument
, 0, OPTION_OBJECT
},
2540 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2543 c
= getopt_long(argc
, argv
, "f:h",
2544 long_options
, &option_index
);
2559 case OPTION_OBJECT
: {
2561 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2567 case OPTION_IMAGE_OPTS
:
2572 if (optind
!= argc
- 1) {
2573 error_exit("Expecting one image file name");
2575 filename
= argv
[optind
];
2577 if (output
&& !strcmp(output
, "json")) {
2578 output_format
= OFORMAT_JSON
;
2579 } else if (output
&& !strcmp(output
, "human")) {
2580 output_format
= OFORMAT_HUMAN
;
2581 } else if (output
) {
2582 error_report("--output must be used with human or json as argument.");
2586 if (qemu_opts_foreach(&qemu_object_opts
,
2587 user_creatable_add_opts_foreach
,
2592 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false);
2598 if (output_format
== OFORMAT_HUMAN
) {
2599 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2602 length
= blk_getlength(blk
);
2603 while (curr
.start
+ curr
.length
< length
) {
2604 int64_t nsectors_left
;
2608 sector_num
= (curr
.start
+ curr
.length
) >> BDRV_SECTOR_BITS
;
2610 /* Probe up to 1 GiB at a time. */
2611 nsectors_left
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
) - sector_num
;
2612 n
= MIN(1 << (30 - BDRV_SECTOR_BITS
), nsectors_left
);
2613 ret
= get_block_status(bs
, sector_num
, n
, &next
);
2616 error_report("Could not read file metadata: %s", strerror(-ret
));
2620 if (entry_mergeable(&curr
, &next
)) {
2621 curr
.length
+= next
.length
;
2625 if (curr
.length
> 0) {
2626 dump_map_entry(output_format
, &curr
, &next
);
2631 dump_map_entry(output_format
, &curr
, NULL
);
2638 #define SNAPSHOT_LIST 1
2639 #define SNAPSHOT_CREATE 2
2640 #define SNAPSHOT_APPLY 3
2641 #define SNAPSHOT_DELETE 4
2643 static int img_snapshot(int argc
, char **argv
)
2646 BlockDriverState
*bs
;
2647 QEMUSnapshotInfo sn
;
2648 char *filename
, *snapshot_name
= NULL
;
2649 int c
, ret
= 0, bdrv_oflags
;
2654 bool image_opts
= false;
2656 bdrv_oflags
= BDRV_O_RDWR
;
2657 /* Parse commandline parameters */
2659 static const struct option long_options
[] = {
2660 {"help", no_argument
, 0, 'h'},
2661 {"object", required_argument
, 0, OPTION_OBJECT
},
2662 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2665 c
= getopt_long(argc
, argv
, "la:c:d:hq",
2666 long_options
, NULL
);
2677 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2680 action
= SNAPSHOT_LIST
;
2681 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
2685 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2688 action
= SNAPSHOT_APPLY
;
2689 snapshot_name
= optarg
;
2693 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2696 action
= SNAPSHOT_CREATE
;
2697 snapshot_name
= optarg
;
2701 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2704 action
= SNAPSHOT_DELETE
;
2705 snapshot_name
= optarg
;
2710 case OPTION_OBJECT
: {
2712 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2718 case OPTION_IMAGE_OPTS
:
2724 if (optind
!= argc
- 1) {
2725 error_exit("Expecting one image file name");
2727 filename
= argv
[optind
++];
2729 if (qemu_opts_foreach(&qemu_object_opts
,
2730 user_creatable_add_opts_foreach
,
2735 /* Open the image */
2736 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
);
2742 /* Perform the requested action */
2748 case SNAPSHOT_CREATE
:
2749 memset(&sn
, 0, sizeof(sn
));
2750 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
2752 qemu_gettimeofday(&tv
);
2753 sn
.date_sec
= tv
.tv_sec
;
2754 sn
.date_nsec
= tv
.tv_usec
* 1000;
2756 ret
= bdrv_snapshot_create(bs
, &sn
);
2758 error_report("Could not create snapshot '%s': %d (%s)",
2759 snapshot_name
, ret
, strerror(-ret
));
2763 case SNAPSHOT_APPLY
:
2764 ret
= bdrv_snapshot_goto(bs
, snapshot_name
);
2766 error_report("Could not apply snapshot '%s': %d (%s)",
2767 snapshot_name
, ret
, strerror(-ret
));
2771 case SNAPSHOT_DELETE
:
2772 bdrv_snapshot_delete_by_id_or_name(bs
, snapshot_name
, &err
);
2774 error_reportf_err(err
, "Could not delete snapshot '%s': ",
2789 static int img_rebase(int argc
, char **argv
)
2791 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
2792 uint8_t *buf_old
= NULL
;
2793 uint8_t *buf_new
= NULL
;
2794 BlockDriverState
*bs
= NULL
;
2796 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
2797 int c
, flags
, src_flags
, ret
;
2798 bool writethrough
, src_writethrough
;
2802 Error
*local_err
= NULL
;
2803 bool image_opts
= false;
2805 /* Parse commandline parameters */
2807 cache
= BDRV_DEFAULT_CACHE
;
2808 src_cache
= BDRV_DEFAULT_CACHE
;
2812 static const struct option long_options
[] = {
2813 {"help", no_argument
, 0, 'h'},
2814 {"object", required_argument
, 0, OPTION_OBJECT
},
2815 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2818 c
= getopt_long(argc
, argv
, "hf:F:b:upt:T:q",
2819 long_options
, NULL
);
2832 out_basefmt
= optarg
;
2835 out_baseimg
= optarg
;
2852 case OPTION_OBJECT
: {
2854 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2860 case OPTION_IMAGE_OPTS
:
2870 if (optind
!= argc
- 1) {
2871 error_exit("Expecting one image file name");
2873 if (!unsafe
&& !out_baseimg
) {
2874 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
2876 filename
= argv
[optind
++];
2878 if (qemu_opts_foreach(&qemu_object_opts
,
2879 user_creatable_add_opts_foreach
,
2884 qemu_progress_init(progress
, 2.0);
2885 qemu_progress_print(0, 100);
2887 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
2888 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2890 error_report("Invalid cache option: %s", cache
);
2895 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2897 error_report("Invalid source cache option: %s", src_cache
);
2901 /* The source files are opened read-only, don't care about WCE */
2902 assert((src_flags
& BDRV_O_RDWR
) == 0);
2903 (void) src_writethrough
;
2908 * Ignore the old backing file for unsafe rebase in case we want to correct
2909 * the reference to a renamed or moved backing file.
2911 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
2918 if (out_basefmt
!= NULL
) {
2919 if (bdrv_find_format(out_basefmt
) == NULL
) {
2920 error_report("Invalid format name: '%s'", out_basefmt
);
2926 /* For safe rebasing we need to compare old and new backing file */
2928 char backing_name
[PATH_MAX
];
2929 QDict
*options
= NULL
;
2931 if (bs
->backing_format
[0] != '\0') {
2932 options
= qdict_new();
2933 qdict_put(options
, "driver", qstring_from_str(bs
->backing_format
));
2936 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
2937 blk_old_backing
= blk_new_open(backing_name
, NULL
,
2938 options
, src_flags
, &local_err
);
2939 if (!blk_old_backing
) {
2940 error_reportf_err(local_err
,
2941 "Could not open old backing file '%s': ",
2946 if (out_baseimg
[0]) {
2948 options
= qdict_new();
2949 qdict_put(options
, "driver", qstring_from_str(out_basefmt
));
2954 blk_new_backing
= blk_new_open(out_baseimg
, NULL
,
2955 options
, src_flags
, &local_err
);
2956 if (!blk_new_backing
) {
2957 error_reportf_err(local_err
,
2958 "Could not open new backing file '%s': ",
2966 * Check each unallocated cluster in the COW file. If it is unallocated,
2967 * accesses go to the backing file. We must therefore compare this cluster
2968 * in the old and new backing file, and if they differ we need to copy it
2969 * from the old backing file into the COW file.
2971 * If qemu-img crashes during this step, no harm is done. The content of
2972 * the image is the same as the original one at any time.
2975 int64_t num_sectors
;
2976 int64_t old_backing_num_sectors
;
2977 int64_t new_backing_num_sectors
= 0;
2980 float local_progress
= 0;
2982 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
2983 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
2985 num_sectors
= blk_nb_sectors(blk
);
2986 if (num_sectors
< 0) {
2987 error_report("Could not get size of '%s': %s",
2988 filename
, strerror(-num_sectors
));
2992 old_backing_num_sectors
= blk_nb_sectors(blk_old_backing
);
2993 if (old_backing_num_sectors
< 0) {
2994 char backing_name
[PATH_MAX
];
2996 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
2997 error_report("Could not get size of '%s': %s",
2998 backing_name
, strerror(-old_backing_num_sectors
));
3002 if (blk_new_backing
) {
3003 new_backing_num_sectors
= blk_nb_sectors(blk_new_backing
);
3004 if (new_backing_num_sectors
< 0) {
3005 error_report("Could not get size of '%s': %s",
3006 out_baseimg
, strerror(-new_backing_num_sectors
));
3012 if (num_sectors
!= 0) {
3013 local_progress
= (float)100 /
3014 (num_sectors
/ MIN(num_sectors
, IO_BUF_SIZE
/ 512));
3017 for (sector
= 0; sector
< num_sectors
; sector
+= n
) {
3019 /* How many sectors can we handle with the next read? */
3020 if (sector
+ (IO_BUF_SIZE
/ 512) <= num_sectors
) {
3021 n
= (IO_BUF_SIZE
/ 512);
3023 n
= num_sectors
- sector
;
3026 /* If the cluster is allocated, we don't need to take action */
3027 ret
= bdrv_is_allocated(bs
, sector
, n
, &n
);
3029 error_report("error while reading image metadata: %s",
3038 * Read old and new backing file and take into consideration that
3039 * backing files may be smaller than the COW image.
3041 if (sector
>= old_backing_num_sectors
) {
3042 memset(buf_old
, 0, n
* BDRV_SECTOR_SIZE
);
3044 if (sector
+ n
> old_backing_num_sectors
) {
3045 n
= old_backing_num_sectors
- sector
;
3048 ret
= blk_pread(blk_old_backing
, sector
<< BDRV_SECTOR_BITS
,
3049 buf_old
, n
<< BDRV_SECTOR_BITS
);
3051 error_report("error while reading from old backing file");
3056 if (sector
>= new_backing_num_sectors
|| !blk_new_backing
) {
3057 memset(buf_new
, 0, n
* BDRV_SECTOR_SIZE
);
3059 if (sector
+ n
> new_backing_num_sectors
) {
3060 n
= new_backing_num_sectors
- sector
;
3063 ret
= blk_pread(blk_new_backing
, sector
<< BDRV_SECTOR_BITS
,
3064 buf_new
, n
<< BDRV_SECTOR_BITS
);
3066 error_report("error while reading from new backing file");
3071 /* If they differ, we need to write to the COW file */
3072 uint64_t written
= 0;
3074 while (written
< n
) {
3077 if (compare_sectors(buf_old
+ written
* 512,
3078 buf_new
+ written
* 512, n
- written
, &pnum
))
3080 ret
= blk_pwrite(blk
,
3081 (sector
+ written
) << BDRV_SECTOR_BITS
,
3082 buf_old
+ written
* 512,
3083 pnum
<< BDRV_SECTOR_BITS
, 0);
3085 error_report("Error while writing to COW image: %s",
3093 qemu_progress_print(local_progress
, 100);
3098 * Change the backing file. All clusters that are different from the old
3099 * backing file are overwritten in the COW file now, so the visible content
3100 * doesn't change when we switch the backing file.
3102 if (out_baseimg
&& *out_baseimg
) {
3103 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3105 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3108 if (ret
== -ENOSPC
) {
3109 error_report("Could not change the backing file to '%s': No "
3110 "space left in the file header", out_baseimg
);
3111 } else if (ret
< 0) {
3112 error_report("Could not change the backing file to '%s': %s",
3113 out_baseimg
, strerror(-ret
));
3116 qemu_progress_print(100, 0);
3118 * TODO At this point it is possible to check if any clusters that are
3119 * allocated in the COW file are the same in the backing file. If so, they
3120 * could be dropped from the COW file. Don't do this before switching the
3121 * backing file, in case of a crash this would lead to corruption.
3124 qemu_progress_end();
3127 blk_unref(blk_old_backing
);
3128 blk_unref(blk_new_backing
);
3130 qemu_vfree(buf_old
);
3131 qemu_vfree(buf_new
);
3140 static int img_resize(int argc
, char **argv
)
3143 int c
, ret
, relative
;
3144 const char *filename
, *fmt
, *size
;
3145 int64_t n
, total_size
;
3147 BlockBackend
*blk
= NULL
;
3150 static QemuOptsList resize_options
= {
3151 .name
= "resize_options",
3152 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3155 .name
= BLOCK_OPT_SIZE
,
3156 .type
= QEMU_OPT_SIZE
,
3157 .help
= "Virtual disk size"
3163 bool image_opts
= false;
3165 /* Remove size from argv manually so that negative numbers are not treated
3166 * as options by getopt. */
3168 error_exit("Not enough arguments");
3172 size
= argv
[--argc
];
3174 /* Parse getopt arguments */
3177 static const struct option long_options
[] = {
3178 {"help", no_argument
, 0, 'h'},
3179 {"object", required_argument
, 0, OPTION_OBJECT
},
3180 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3183 c
= getopt_long(argc
, argv
, "f:hq",
3184 long_options
, NULL
);
3199 case OPTION_OBJECT
: {
3201 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3207 case OPTION_IMAGE_OPTS
:
3212 if (optind
!= argc
- 1) {
3213 error_exit("Expecting one image file name");
3215 filename
= argv
[optind
++];
3217 if (qemu_opts_foreach(&qemu_object_opts
,
3218 user_creatable_add_opts_foreach
,
3223 /* Choose grow, shrink, or absolute resize mode */
3239 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3240 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3242 error_report_err(err
);
3244 qemu_opts_del(param
);
3247 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3248 qemu_opts_del(param
);
3250 blk
= img_open(image_opts
, filename
, fmt
,
3251 BDRV_O_RDWR
, false, quiet
);
3258 total_size
= blk_getlength(blk
) + n
* relative
;
3262 if (total_size
<= 0) {
3263 error_report("New image size must be positive");
3268 ret
= blk_truncate(blk
, total_size
);
3271 qprintf(quiet
, "Image resized.\n");
3274 error_report("This image does not support resize");
3277 error_report("Image is read-only");
3280 error_report("Error resizing image (%d)", -ret
);
3291 static void amend_status_cb(BlockDriverState
*bs
,
3292 int64_t offset
, int64_t total_work_size
,
3295 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3298 static int img_amend(int argc
, char **argv
)
3302 char *options
= NULL
;
3303 QemuOptsList
*create_opts
= NULL
;
3304 QemuOpts
*opts
= NULL
;
3305 const char *fmt
= NULL
, *filename
, *cache
;
3308 bool quiet
= false, progress
= false;
3309 BlockBackend
*blk
= NULL
;
3310 BlockDriverState
*bs
= NULL
;
3311 bool image_opts
= false;
3313 cache
= BDRV_DEFAULT_CACHE
;
3315 static const struct option long_options
[] = {
3316 {"help", no_argument
, 0, 'h'},
3317 {"object", required_argument
, 0, OPTION_OBJECT
},
3318 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3321 c
= getopt_long(argc
, argv
, "ho:f:t:pq",
3322 long_options
, NULL
);
3333 if (!is_valid_option_list(optarg
)) {
3334 error_report("Invalid option list: %s", optarg
);
3336 goto out_no_progress
;
3339 options
= g_strdup(optarg
);
3341 char *old_options
= options
;
3342 options
= g_strdup_printf("%s,%s", options
, optarg
);
3343 g_free(old_options
);
3359 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3363 goto out_no_progress
;
3366 case OPTION_IMAGE_OPTS
:
3373 error_exit("Must specify options (-o)");
3376 if (qemu_opts_foreach(&qemu_object_opts
,
3377 user_creatable_add_opts_foreach
,
3380 goto out_no_progress
;
3386 qemu_progress_init(progress
, 1.0);
3388 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
3389 if (fmt
&& has_help_option(options
)) {
3390 /* If a format is explicitly specified (and possibly no filename is
3391 * given), print option help here */
3392 ret
= print_block_option_help(filename
, fmt
);
3396 if (optind
!= argc
- 1) {
3397 error_report("Expecting one image file name");
3402 flags
= BDRV_O_RDWR
;
3403 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3405 error_report("Invalid cache option: %s", cache
);
3409 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
3416 fmt
= bs
->drv
->format_name
;
3418 if (has_help_option(options
)) {
3419 /* If the format was auto-detected, print option help here */
3420 ret
= print_block_option_help(filename
, fmt
);
3424 if (!bs
->drv
->create_opts
) {
3425 error_report("Format driver '%s' does not support any options to amend",
3431 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
3432 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
3434 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
3436 error_report_err(err
);
3442 /* In case the driver does not call amend_status_cb() */
3443 qemu_progress_print(0.f
, 0);
3444 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
);
3445 qemu_progress_print(100.f
, 0);
3447 error_report("Error while amending options: %s", strerror(-ret
));
3452 qemu_progress_end();
3456 qemu_opts_del(opts
);
3457 qemu_opts_free(create_opts
);
3466 typedef struct BenchData
{
3468 uint64_t image_size
;
3475 bool drain_on_flush
;
3484 static void bench_undrained_flush_cb(void *opaque
, int ret
)
3487 error_report("Failed flush request: %s\n", strerror(-ret
));
3492 static void bench_cb(void *opaque
, int ret
)
3494 BenchData
*b
= opaque
;
3498 error_report("Failed request: %s\n", strerror(-ret
));
3503 /* Just finished a flush with drained queue: Start next requests */
3504 assert(b
->in_flight
== 0);
3505 b
->in_flush
= false;
3506 } else if (b
->in_flight
> 0) {
3507 int remaining
= b
->n
- b
->in_flight
;
3512 /* Time for flush? Drain queue if requested, then flush */
3513 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
3514 if (!b
->in_flight
|| !b
->drain_on_flush
) {
3515 BlockCompletionFunc
*cb
;
3517 if (b
->drain_on_flush
) {
3521 cb
= bench_undrained_flush_cb
;
3524 acb
= blk_aio_flush(b
->blk
, cb
, b
);
3526 error_report("Failed to issue flush request");
3530 if (b
->drain_on_flush
) {
3536 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
3538 acb
= blk_aio_pwritev(b
->blk
, b
->offset
, b
->qiov
, 0,
3541 acb
= blk_aio_preadv(b
->blk
, b
->offset
, b
->qiov
, 0,
3545 error_report("Failed to issue request");
3549 b
->offset
+= b
->step
;
3550 b
->offset
%= b
->image_size
;
3554 static int img_bench(int argc
, char **argv
)
3557 const char *fmt
= NULL
, *filename
;
3559 bool image_opts
= false;
3560 bool is_write
= false;
3564 size_t bufsize
= 4096;
3567 int flush_interval
= 0;
3568 bool drain_on_flush
= true;
3570 BlockBackend
*blk
= NULL
;
3571 BenchData data
= {};
3574 struct timeval t1
, t2
;
3578 static const struct option long_options
[] = {
3579 {"help", no_argument
, 0, 'h'},
3580 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
3581 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3582 {"pattern", required_argument
, 0, OPTION_PATTERN
},
3583 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
3586 c
= getopt_long(argc
, argv
, "hc:d:f:no:qs:S:t:w", long_options
, NULL
);
3600 count
= strtoul(optarg
, &end
, 0);
3601 if (errno
|| *end
|| count
> INT_MAX
) {
3602 error_report("Invalid request count specified");
3611 depth
= strtoul(optarg
, &end
, 0);
3612 if (errno
|| *end
|| depth
> INT_MAX
) {
3613 error_report("Invalid queue depth specified");
3622 flags
|= BDRV_O_NATIVE_AIO
;
3628 offset
= qemu_strtosz_suffix(optarg
, &end
,
3629 QEMU_STRTOSZ_DEFSUFFIX_B
);
3630 if (offset
< 0|| *end
) {
3631 error_report("Invalid offset specified");
3645 sval
= qemu_strtosz_suffix(optarg
, &end
, QEMU_STRTOSZ_DEFSUFFIX_B
);
3646 if (sval
< 0 || sval
> INT_MAX
|| *end
) {
3647 error_report("Invalid buffer size specified");
3659 sval
= qemu_strtosz_suffix(optarg
, &end
, QEMU_STRTOSZ_DEFSUFFIX_B
);
3660 if (sval
< 0 || sval
> INT_MAX
|| *end
) {
3661 error_report("Invalid step size specified");
3669 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
3671 error_report("Invalid cache mode");
3677 flags
|= BDRV_O_RDWR
;
3680 case OPTION_PATTERN
:
3684 pattern
= strtoul(optarg
, &end
, 0);
3685 if (errno
|| *end
|| pattern
> 0xff) {
3686 error_report("Invalid pattern byte specified");
3691 case OPTION_FLUSH_INTERVAL
:
3695 flush_interval
= strtoul(optarg
, &end
, 0);
3696 if (errno
|| *end
|| flush_interval
> INT_MAX
) {
3697 error_report("Invalid flush interval specified");
3702 case OPTION_NO_DRAIN
:
3703 drain_on_flush
= false;
3705 case OPTION_IMAGE_OPTS
:
3711 if (optind
!= argc
- 1) {
3712 error_exit("Expecting one image file name");
3714 filename
= argv
[argc
- 1];
3716 if (!is_write
&& flush_interval
) {
3717 error_report("--flush-interval is only available in write tests");
3721 if (flush_interval
&& flush_interval
< depth
) {
3722 error_report("Flush interval can't be smaller than depth");
3727 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
3733 image_size
= blk_getlength(blk
);
3734 if (image_size
< 0) {
3739 data
= (BenchData
) {
3741 .image_size
= image_size
,
3743 .step
= step
?: bufsize
,
3748 .flush_interval
= flush_interval
,
3749 .drain_on_flush
= drain_on_flush
,
3751 printf("Sending %d %s requests, %d bytes each, %d in parallel "
3752 "(starting at offset %" PRId64
", step size %d)\n",
3753 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
3754 data
.offset
, data
.step
);
3755 if (flush_interval
) {
3756 printf("Sending flush every %d requests\n", flush_interval
);
3759 data
.buf
= blk_blockalign(blk
, data
.nrreq
* data
.bufsize
);
3760 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
3762 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
3763 for (i
= 0; i
< data
.nrreq
; i
++) {
3764 qemu_iovec_init(&data
.qiov
[i
], 1);
3765 qemu_iovec_add(&data
.qiov
[i
],
3766 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
3769 gettimeofday(&t1
, NULL
);
3772 while (data
.n
> 0) {
3773 main_loop_wait(false);
3775 gettimeofday(&t2
, NULL
);
3777 printf("Run completed in %3.3f seconds.\n",
3778 (t2
.tv_sec
- t1
.tv_sec
)
3779 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
3782 qemu_vfree(data
.buf
);
3792 static const img_cmd_t img_cmds
[] = {
3793 #define DEF(option, callback, arg_string) \
3794 { option, callback },
3795 #include "qemu-img-cmds.h"
3801 int main(int argc
, char **argv
)
3803 const img_cmd_t
*cmd
;
3804 const char *cmdname
;
3805 Error
*local_error
= NULL
;
3807 static const struct option long_options
[] = {
3808 {"help", no_argument
, 0, 'h'},
3809 {"version", no_argument
, 0, 'v'},
3814 signal(SIGPIPE
, SIG_IGN
);
3817 error_set_progname(argv
[0]);
3818 qemu_init_exec_dir(argv
[0]);
3820 if (qemu_init_main_loop(&local_error
)) {
3821 error_report_err(local_error
);
3825 qcrypto_init(&error_fatal
);
3827 module_call_init(MODULE_INIT_QOM
);
3830 error_exit("Not enough arguments");
3834 qemu_add_opts(&qemu_object_opts
);
3835 qemu_add_opts(&qemu_source_opts
);
3837 /* find the command */
3838 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
3839 if (!strcmp(cmdname
, cmd
->name
)) {
3840 return cmd
->handler(argc
- 1, argv
+ 1);
3844 c
= getopt_long(argc
, argv
, "h", long_options
, NULL
);
3850 printf(QEMU_IMG_VERSION
);
3855 error_exit("Command not found: %s", cmdname
);