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
25 #include "qemu/osdep.h"
28 #include "qemu-version.h"
29 #include "qapi/error.h"
30 #include "qapi/qapi-visit-block-core.h"
31 #include "qapi/qobject-output-visitor.h"
32 #include "qapi/qmp/qjson.h"
33 #include "qapi/qmp/qdict.h"
34 #include "qapi/qmp/qstring.h"
35 #include "qemu/cutils.h"
36 #include "qemu/config-file.h"
37 #include "qemu/option.h"
38 #include "qemu/error-report.h"
40 #include "qom/object_interfaces.h"
41 #include "sysemu/sysemu.h"
42 #include "sysemu/block-backend.h"
43 #include "block/block_int.h"
44 #include "block/blockjob.h"
45 #include "block/qapi.h"
46 #include "crypto/init.h"
47 #include "trace/control.h"
49 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
50 "\n" QEMU_COPYRIGHT "\n"
52 typedef struct img_cmd_t
{
54 int (*handler
)(int argc
, char **argv
);
59 OPTION_BACKING_CHAIN
= 257,
61 OPTION_IMAGE_OPTS
= 259,
63 OPTION_FLUSH_INTERVAL
= 261,
64 OPTION_NO_DRAIN
= 262,
65 OPTION_TARGET_IMAGE_OPTS
= 263,
67 OPTION_PREALLOCATION
= 265,
71 typedef enum OutputFormat
{
76 /* Default to cache=writeback as data integrity is not important for qemu-img */
77 #define BDRV_DEFAULT_CACHE "writeback"
79 static void format_print(void *opaque
, const char *name
)
84 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
88 error_printf("qemu-img: ");
91 error_vprintf(fmt
, ap
);
94 error_printf("\nTry 'qemu-img --help' for more information\n");
98 static void QEMU_NORETURN
missing_argument(const char *option
)
100 error_exit("missing argument for option '%s'", option
);
103 static void QEMU_NORETURN
unrecognized_option(const char *option
)
105 error_exit("unrecognized option '%s'", option
);
108 /* Please keep in synch with qemu-img.texi */
109 static void QEMU_NORETURN
help(void)
111 const char *help_msg
=
113 "usage: qemu-img [standard options] command [command options]\n"
114 "QEMU disk image utility\n"
116 " '-h', '--help' display this help and exit\n"
117 " '-V', '--version' output version information and exit\n"
118 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
119 " specify tracing options\n"
122 #define DEF(option, callback, arg_string) \
124 #include "qemu-img-cmds.h"
127 "Command parameters:\n"
128 " 'filename' is a disk image filename\n"
129 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
130 " manual page for a description of the object properties. The most common\n"
131 " object type is a 'secret', which is used to supply passwords and/or\n"
132 " encryption keys.\n"
133 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
134 " 'cache' is the cache mode used to write the output disk image, the valid\n"
135 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
136 " 'directsync' and 'unsafe' (default for convert)\n"
137 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
138 " options are the same as for the 'cache' option\n"
139 " 'size' is the disk image size in bytes. Optional suffixes\n"
140 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
141 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
142 " supported. 'b' is ignored.\n"
143 " 'output_filename' is the destination disk image filename\n"
144 " 'output_fmt' is the destination format\n"
145 " 'options' is a comma separated list of format specific options in a\n"
146 " name=value format. Use -o ? for an overview of the options supported by the\n"
148 " 'snapshot_param' is param used for internal snapshot, format\n"
149 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
151 " '-c' indicates that target image must be compressed (qcow format only)\n"
152 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
153 " new backing file match exactly. The image doesn't need a working\n"
154 " backing file before rebasing in this case (useful for renaming the\n"
155 " backing file). For image creation, allow creating without attempting\n"
156 " to open the backing file.\n"
157 " '-h' with or without a command shows this help and lists the supported formats\n"
158 " '-p' show progress of command (only certain commands)\n"
159 " '-q' use Quiet mode - do not print any output (except errors)\n"
160 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
161 " contain only zeros for qemu-img to create a sparse image during\n"
162 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
163 " unallocated or zero sectors, and the destination image will always be\n"
165 " '--output' takes the format in which the output must be done (human or json)\n"
166 " '-n' skips the target volume creation (useful if the volume is created\n"
167 " prior to running qemu-img)\n"
169 "Parameters to check subcommand:\n"
170 " '-r' tries to repair any inconsistencies that are found during the check.\n"
171 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
172 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
173 " hiding corruption that has already occurred.\n"
175 "Parameters to convert subcommand:\n"
176 " '-m' specifies how many coroutines work in parallel during the convert\n"
177 " process (defaults to 8)\n"
178 " '-W' allow to write to the target out of order rather than sequential\n"
180 "Parameters to snapshot subcommand:\n"
181 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
182 " '-a' applies a snapshot (revert disk to saved state)\n"
183 " '-c' creates a snapshot\n"
184 " '-d' deletes a snapshot\n"
185 " '-l' lists all snapshots in the given image\n"
187 "Parameters to compare subcommand:\n"
188 " '-f' first image format\n"
189 " '-F' second image format\n"
190 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
192 "Parameters to dd subcommand:\n"
193 " 'bs=BYTES' read and write up to BYTES bytes at a time "
195 " 'count=N' copy only N input blocks\n"
196 " 'if=FILE' read from FILE\n"
197 " 'of=FILE' write to FILE\n"
198 " 'skip=N' skip N bs-sized blocks at the start of input\n";
200 printf("%s\nSupported formats:", help_msg
);
201 bdrv_iterate_format(format_print
, NULL
);
202 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
206 static QemuOptsList qemu_object_opts
= {
208 .implied_opt_name
= "qom-type",
209 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
215 static QemuOptsList qemu_source_opts
= {
217 .implied_opt_name
= "file",
218 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
224 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
230 ret
= vprintf(fmt
, args
);
237 static int print_block_option_help(const char *filename
, const char *fmt
)
239 BlockDriver
*drv
, *proto_drv
;
240 QemuOptsList
*create_opts
= NULL
;
241 Error
*local_err
= NULL
;
243 /* Find driver and parse its options */
244 drv
= bdrv_find_format(fmt
);
246 error_report("Unknown file format '%s'", fmt
);
250 if (!drv
->create_opts
) {
251 error_report("Format driver '%s' does not support image creation", fmt
);
255 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
257 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
259 error_report_err(local_err
);
260 qemu_opts_free(create_opts
);
263 if (!proto_drv
->create_opts
) {
264 error_report("Protocal driver '%s' does not support image creation",
265 proto_drv
->format_name
);
268 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
271 printf("Supported options:\n");
272 qemu_opts_print_help(create_opts
, false);
273 qemu_opts_free(create_opts
);
278 static BlockBackend
*img_open_opts(const char *optstr
,
279 QemuOpts
*opts
, int flags
, bool writethrough
,
280 bool quiet
, bool force_share
)
283 Error
*local_err
= NULL
;
285 options
= qemu_opts_to_qdict(opts
, NULL
);
287 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
288 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
289 error_report("--force-share/-U conflicts with image options");
290 qobject_unref(options
);
293 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
295 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
297 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
300 blk_set_enable_write_cache(blk
, !writethrough
);
305 static BlockBackend
*img_open_file(const char *filename
,
307 const char *fmt
, int flags
,
308 bool writethrough
, bool quiet
,
312 Error
*local_err
= NULL
;
315 options
= qdict_new();
318 qdict_put_str(options
, "driver", fmt
);
322 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
324 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
326 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
329 blk_set_enable_write_cache(blk
, !writethrough
);
335 static int img_add_key_secrets(void *opaque
,
336 const char *name
, const char *value
,
339 QDict
*options
= opaque
;
341 if (g_str_has_suffix(name
, "key-secret")) {
342 qdict_put_str(options
, name
, value
);
349 static BlockBackend
*img_open(bool image_opts
,
350 const char *filename
,
351 const char *fmt
, int flags
, bool writethrough
,
352 bool quiet
, bool force_share
)
358 error_report("--image-opts and --format are mutually exclusive");
361 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
366 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
369 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
376 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
377 const char *base_filename
,
378 const char *base_fmt
)
383 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
385 error_report("Backing file not supported for file format '%s'",
392 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
394 error_report("Backing file format not supported for file "
403 static int64_t cvtnum(const char *s
)
408 err
= qemu_strtosz(s
, NULL
, &value
);
412 if (value
> INT64_MAX
) {
418 static int img_create(int argc
, char **argv
)
421 uint64_t img_size
= -1;
422 const char *fmt
= "raw";
423 const char *base_fmt
= NULL
;
424 const char *filename
;
425 const char *base_filename
= NULL
;
426 char *options
= NULL
;
427 Error
*local_err
= NULL
;
432 static const struct option long_options
[] = {
433 {"help", no_argument
, 0, 'h'},
434 {"object", required_argument
, 0, OPTION_OBJECT
},
437 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
444 missing_argument(argv
[optind
- 1]);
447 unrecognized_option(argv
[optind
- 1]);
456 base_filename
= optarg
;
462 if (!is_valid_option_list(optarg
)) {
463 error_report("Invalid option list: %s", optarg
);
467 options
= g_strdup(optarg
);
469 char *old_options
= options
;
470 options
= g_strdup_printf("%s,%s", options
, optarg
);
478 flags
|= BDRV_O_NO_BACKING
;
480 case OPTION_OBJECT
: {
482 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
491 /* Get the filename */
492 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
493 if (options
&& has_help_option(options
)) {
495 return print_block_option_help(filename
, fmt
);
498 if (optind
>= argc
) {
499 error_exit("Expecting image file name");
503 if (qemu_opts_foreach(&qemu_object_opts
,
504 user_creatable_add_opts_foreach
,
509 /* Get image size, if specified */
513 sval
= cvtnum(argv
[optind
++]);
515 if (sval
== -ERANGE
) {
516 error_report("Image size must be less than 8 EiB!");
518 error_report("Invalid image size specified! You may use k, M, "
519 "G, T, P or E suffixes for ");
520 error_report("kilobytes, megabytes, gigabytes, terabytes, "
521 "petabytes and exabytes.");
525 img_size
= (uint64_t)sval
;
527 if (optind
!= argc
) {
528 error_exit("Unexpected argument: %s", argv
[optind
]);
531 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
532 options
, img_size
, flags
, quiet
, &local_err
);
534 error_reportf_err(local_err
, "%s: ", filename
);
546 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
550 Visitor
*v
= qobject_output_visitor_new(&obj
);
552 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
553 visit_complete(v
, &obj
);
554 str
= qobject_to_json_pretty(obj
);
556 qprintf(quiet
, "%s\n", qstring_get_str(str
));
562 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
564 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
565 qprintf(quiet
, "No errors were found on the image.\n");
567 if (check
->corruptions
) {
568 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
569 "Data may be corrupted, or further writes to the image "
576 "\n%" PRId64
" leaked clusters were found on the image.\n"
577 "This means waste of disk space, but no harm to data.\n",
581 if (check
->check_errors
) {
584 " internal errors have occurred during the check.\n",
585 check
->check_errors
);
589 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
590 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
591 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
592 check
->allocated_clusters
, check
->total_clusters
,
593 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
594 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
595 check
->compressed_clusters
* 100.0 /
596 check
->allocated_clusters
);
599 if (check
->image_end_offset
) {
601 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
605 static int collect_image_check(BlockDriverState
*bs
,
607 const char *filename
,
612 BdrvCheckResult result
;
614 ret
= bdrv_check(bs
, &result
, fix
);
619 check
->filename
= g_strdup(filename
);
620 check
->format
= g_strdup(bdrv_get_format_name(bs
));
621 check
->check_errors
= result
.check_errors
;
622 check
->corruptions
= result
.corruptions
;
623 check
->has_corruptions
= result
.corruptions
!= 0;
624 check
->leaks
= result
.leaks
;
625 check
->has_leaks
= result
.leaks
!= 0;
626 check
->corruptions_fixed
= result
.corruptions_fixed
;
627 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
628 check
->leaks_fixed
= result
.leaks_fixed
;
629 check
->has_leaks_fixed
= result
.leaks
!= 0;
630 check
->image_end_offset
= result
.image_end_offset
;
631 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
632 check
->total_clusters
= result
.bfi
.total_clusters
;
633 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
634 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
635 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
636 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
637 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
638 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
639 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
645 * Checks an image for consistency. Exit codes:
647 * 0 - Check completed, image is good
648 * 1 - Check not completed because of internal errors
649 * 2 - Check completed, image is corrupted
650 * 3 - Check completed, image has leaked clusters, but is good otherwise
651 * 63 - Checks are not supported by the image format
653 static int img_check(int argc
, char **argv
)
656 OutputFormat output_format
= OFORMAT_HUMAN
;
657 const char *filename
, *fmt
, *output
, *cache
;
659 BlockDriverState
*bs
;
661 int flags
= BDRV_O_CHECK
;
665 bool image_opts
= false;
666 bool force_share
= false;
670 cache
= BDRV_DEFAULT_CACHE
;
673 int option_index
= 0;
674 static const struct option long_options
[] = {
675 {"help", no_argument
, 0, 'h'},
676 {"format", required_argument
, 0, 'f'},
677 {"repair", required_argument
, 0, 'r'},
678 {"output", required_argument
, 0, OPTION_OUTPUT
},
679 {"object", required_argument
, 0, OPTION_OBJECT
},
680 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
681 {"force-share", no_argument
, 0, 'U'},
684 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
685 long_options
, &option_index
);
691 missing_argument(argv
[optind
- 1]);
694 unrecognized_option(argv
[optind
- 1]);
703 flags
|= BDRV_O_RDWR
;
705 if (!strcmp(optarg
, "leaks")) {
706 fix
= BDRV_FIX_LEAKS
;
707 } else if (!strcmp(optarg
, "all")) {
708 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
710 error_exit("Unknown option value for -r "
711 "(expecting 'leaks' or 'all'): %s", optarg
);
726 case OPTION_OBJECT
: {
728 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
734 case OPTION_IMAGE_OPTS
:
739 if (optind
!= argc
- 1) {
740 error_exit("Expecting one image file name");
742 filename
= argv
[optind
++];
744 if (output
&& !strcmp(output
, "json")) {
745 output_format
= OFORMAT_JSON
;
746 } else if (output
&& !strcmp(output
, "human")) {
747 output_format
= OFORMAT_HUMAN
;
749 error_report("--output must be used with human or json as argument.");
753 if (qemu_opts_foreach(&qemu_object_opts
,
754 user_creatable_add_opts_foreach
,
759 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
761 error_report("Invalid source cache option: %s", cache
);
765 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
772 check
= g_new0(ImageCheck
, 1);
773 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
775 if (ret
== -ENOTSUP
) {
776 error_report("This image format does not support checks");
781 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
782 int corruptions_fixed
, leaks_fixed
;
784 leaks_fixed
= check
->leaks_fixed
;
785 corruptions_fixed
= check
->corruptions_fixed
;
787 if (output_format
== OFORMAT_HUMAN
) {
789 "The following inconsistencies were found and repaired:\n\n"
790 " %" PRId64
" leaked clusters\n"
791 " %" PRId64
" corruptions\n\n"
792 "Double checking the fixed image now...\n",
794 check
->corruptions_fixed
);
797 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
799 check
->leaks_fixed
= leaks_fixed
;
800 check
->corruptions_fixed
= corruptions_fixed
;
804 switch (output_format
) {
806 dump_human_image_check(check
, quiet
);
809 dump_json_image_check(check
, quiet
);
814 if (ret
|| check
->check_errors
) {
816 error_report("Check failed: %s", strerror(-ret
));
818 error_report("Check failed");
824 if (check
->corruptions
) {
826 } else if (check
->leaks
) {
833 qapi_free_ImageCheck(check
);
838 typedef struct CommonBlockJobCBInfo
{
839 BlockDriverState
*bs
;
841 } CommonBlockJobCBInfo
;
843 static void common_block_job_cb(void *opaque
, int ret
)
845 CommonBlockJobCBInfo
*cbi
= opaque
;
848 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
852 static void run_block_job(BlockJob
*job
, Error
**errp
)
854 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
857 aio_context_acquire(aio_context
);
860 float progress
= 0.0f
;
861 aio_poll(aio_context
, true);
862 if (job
->job
.progress_total
) {
863 progress
= (float)job
->job
.progress_current
/
864 job
->job
.progress_total
* 100.f
;
866 qemu_progress_print(progress
, 0);
867 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
869 if (!job_is_completed(&job
->job
)) {
870 ret
= job_complete_sync(&job
->job
, errp
);
874 job_unref(&job
->job
);
875 aio_context_release(aio_context
);
877 /* publish completion progress only when success */
879 qemu_progress_print(100.f
, 0);
883 static int img_commit(int argc
, char **argv
)
886 const char *filename
, *fmt
, *cache
, *base
;
888 BlockDriverState
*bs
, *base_bs
;
890 bool progress
= false, quiet
= false, drop
= false;
892 Error
*local_err
= NULL
;
893 CommonBlockJobCBInfo cbi
;
894 bool image_opts
= false;
895 AioContext
*aio_context
;
898 cache
= BDRV_DEFAULT_CACHE
;
901 static const struct option long_options
[] = {
902 {"help", no_argument
, 0, 'h'},
903 {"object", required_argument
, 0, OPTION_OBJECT
},
904 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
907 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
914 missing_argument(argv
[optind
- 1]);
917 unrecognized_option(argv
[optind
- 1]);
942 case OPTION_OBJECT
: {
944 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
950 case OPTION_IMAGE_OPTS
:
956 /* Progress is not shown in Quiet mode */
961 if (optind
!= argc
- 1) {
962 error_exit("Expecting one image file name");
964 filename
= argv
[optind
++];
966 if (qemu_opts_foreach(&qemu_object_opts
,
967 user_creatable_add_opts_foreach
,
972 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
973 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
975 error_report("Invalid cache option: %s", cache
);
979 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
986 qemu_progress_init(progress
, 1.f
);
987 qemu_progress_print(0.f
, 100);
990 base_bs
= bdrv_find_backing_image(bs
, base
);
992 error_setg(&local_err
,
993 "Did not find '%s' in the backing chain of '%s'",
998 /* This is different from QMP, which by default uses the deepest file in
999 * the backing chain (i.e., the very base); however, the traditional
1000 * behavior of qemu-img commit is using the immediate backing file. */
1001 base_bs
= backing_bs(bs
);
1003 error_setg(&local_err
, "Image does not have a backing file");
1008 cbi
= (CommonBlockJobCBInfo
){
1013 aio_context
= bdrv_get_aio_context(bs
);
1014 aio_context_acquire(aio_context
);
1015 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, 0,
1016 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1017 &cbi
, false, &local_err
);
1018 aio_context_release(aio_context
);
1023 /* When the block job completes, the BlockBackend reference will point to
1024 * the old backing file. In order to avoid that the top image is already
1025 * deleted, so we can still empty it afterwards, increment the reference
1026 * counter here preemptively. */
1031 job
= block_job_get("commit");
1033 run_block_job(job
, &local_err
);
1038 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1039 ret
= bs
->drv
->bdrv_make_empty(bs
);
1041 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1053 qemu_progress_end();
1058 error_report_err(local_err
);
1062 qprintf(quiet
, "Image committed.\n");
1067 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1068 * of the first sector boundary within buf where the sector contains a
1069 * non-zero byte. This function is robust to a buffer that is not
1072 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1075 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1077 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1078 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1082 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1089 * Returns true iff the first sector pointed to by 'buf' contains at least
1092 * 'pnum' is set to the number of sectors (including and immediately following
1093 * the first one) that are known to be in the same allocated/unallocated state.
1094 * The function will try to align the end offset to alignment boundaries so
1095 * that the request will at least end aligned and consequtive requests will
1096 * also start at an aligned offset.
1098 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1099 int64_t sector_num
, int alignment
)
1108 is_zero
= buffer_is_zero(buf
, 512);
1109 for(i
= 1; i
< n
; i
++) {
1111 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1116 tail
= (sector_num
+ i
) & (alignment
- 1);
1118 if (is_zero
&& i
<= tail
) {
1119 /* treat unallocated areas which only consist
1120 * of a small tail as allocated. */
1124 /* align up end offset of allocated areas. */
1125 i
+= alignment
- tail
;
1128 /* align down end offset of zero areas. */
1137 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1138 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1139 * breaking up write requests for only small sparse areas.
1141 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1142 int min
, int64_t sector_num
, int alignment
)
1145 int num_checked
, num_used
;
1151 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1157 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1159 sector_num
+= *pnum
;
1160 num_checked
= num_used
;
1163 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1165 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1167 sector_num
+= *pnum
;
1168 num_checked
+= *pnum
;
1170 num_used
= num_checked
;
1171 } else if (*pnum
>= min
) {
1181 * Compares two buffers sector by sector. Returns 0 if the first
1182 * sector of each buffer matches, non-zero otherwise.
1184 * pnum is set to the sector-aligned size of the buffer prefix that
1185 * has the same matching status as the first sector.
1187 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1188 int64_t bytes
, int64_t *pnum
)
1191 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1195 res
= !!memcmp(buf1
, buf2
, i
);
1197 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1199 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1209 #define IO_BUF_SIZE (2 * 1024 * 1024)
1212 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1214 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1215 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1216 * failure), and 4 on error (the exit status for read errors), after emitting
1219 * @param blk: BlockBackend for the image
1220 * @param offset: Starting offset to check
1221 * @param bytes: Number of bytes to check
1222 * @param filename: Name of disk file we are checking (logging purpose)
1223 * @param buffer: Allocated buffer for storing read data
1224 * @param quiet: Flag for quiet mode
1226 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1227 int64_t bytes
, const char *filename
,
1228 uint8_t *buffer
, bool quiet
)
1233 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1235 error_report("Error while reading offset %" PRId64
" of %s: %s",
1236 offset
, filename
, strerror(-ret
));
1239 idx
= find_nonzero(buffer
, bytes
);
1241 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1250 * Compares two images. Exit codes:
1252 * 0 - Images are identical
1254 * >1 - Error occurred
1256 static int img_compare(int argc
, char **argv
)
1258 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1259 BlockBackend
*blk1
, *blk2
;
1260 BlockDriverState
*bs1
, *bs2
;
1261 int64_t total_size1
, total_size2
;
1262 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1263 int64_t pnum1
, pnum2
;
1264 int allocated1
, allocated2
;
1265 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1266 bool progress
= false, quiet
= false, strict
= false;
1273 uint64_t progress_base
;
1274 bool image_opts
= false;
1275 bool force_share
= false;
1277 cache
= BDRV_DEFAULT_CACHE
;
1279 static const struct option long_options
[] = {
1280 {"help", no_argument
, 0, 'h'},
1281 {"object", required_argument
, 0, OPTION_OBJECT
},
1282 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1283 {"force-share", no_argument
, 0, 'U'},
1286 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1287 long_options
, NULL
);
1293 missing_argument(argv
[optind
- 1]);
1296 unrecognized_option(argv
[optind
- 1]);
1322 case OPTION_OBJECT
: {
1324 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1331 case OPTION_IMAGE_OPTS
:
1337 /* Progress is not shown in Quiet mode */
1343 if (optind
!= argc
- 2) {
1344 error_exit("Expecting two image file names");
1346 filename1
= argv
[optind
++];
1347 filename2
= argv
[optind
++];
1349 if (qemu_opts_foreach(&qemu_object_opts
,
1350 user_creatable_add_opts_foreach
,
1356 /* Initialize before goto out */
1357 qemu_progress_init(progress
, 2.0);
1360 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1362 error_report("Invalid source cache option: %s", cache
);
1367 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1374 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1383 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1384 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1385 total_size1
= blk_getlength(blk1
);
1386 if (total_size1
< 0) {
1387 error_report("Can't get size of %s: %s",
1388 filename1
, strerror(-total_size1
));
1392 total_size2
= blk_getlength(blk2
);
1393 if (total_size2
< 0) {
1394 error_report("Can't get size of %s: %s",
1395 filename2
, strerror(-total_size2
));
1399 total_size
= MIN(total_size1
, total_size2
);
1400 progress_base
= MAX(total_size1
, total_size2
);
1402 qemu_progress_print(0, 100);
1404 if (strict
&& total_size1
!= total_size2
) {
1406 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1410 while (offset
< total_size
) {
1411 int status1
, status2
;
1413 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1414 total_size1
- offset
, &pnum1
, NULL
,
1418 error_report("Sector allocation test failed for %s", filename1
);
1421 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1423 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1424 total_size2
- offset
, &pnum2
, NULL
,
1428 error_report("Sector allocation test failed for %s", filename2
);
1431 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1433 assert(pnum1
&& pnum2
);
1434 chunk
= MIN(pnum1
, pnum2
);
1437 if (status1
!= status2
) {
1439 qprintf(quiet
, "Strict mode: Offset %" PRId64
1440 " block status mismatch!\n", offset
);
1444 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1446 } else if (allocated1
== allocated2
) {
1450 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1451 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1453 error_report("Error while reading offset %" PRId64
1455 offset
, filename1
, strerror(-ret
));
1459 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1461 error_report("Error while reading offset %" PRId64
1463 offset
, filename2
, strerror(-ret
));
1467 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1468 if (ret
|| pnum
!= chunk
) {
1469 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1470 offset
+ (ret
? 0 : pnum
));
1476 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1478 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1479 filename1
, buf1
, quiet
);
1481 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1482 filename2
, buf1
, quiet
);
1489 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1492 if (total_size1
!= total_size2
) {
1493 BlockBackend
*blk_over
;
1494 const char *filename_over
;
1496 qprintf(quiet
, "Warning: Image size mismatch!\n");
1497 if (total_size1
> total_size2
) {
1499 filename_over
= filename1
;
1502 filename_over
= filename2
;
1505 while (offset
< progress_base
) {
1506 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1507 progress_base
- offset
, &chunk
,
1511 error_report("Sector allocation test failed for %s",
1516 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1517 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1518 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1519 filename_over
, buf1
, quiet
);
1525 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1529 qprintf(quiet
, "Images are identical.\n");
1539 qemu_progress_end();
1544 enum ImgConvertBlockStatus
{
1550 #define MAX_COROUTINES 16
1552 typedef struct ImgConvertState
{
1554 int64_t *src_sectors
;
1556 int64_t total_sectors
;
1557 int64_t allocated_sectors
;
1558 int64_t allocated_done
;
1561 enum ImgConvertBlockStatus status
;
1562 int64_t sector_next_status
;
1563 BlockBackend
*target
;
1566 bool unallocated_blocks_are_zero
;
1567 bool target_has_backing
;
1568 int64_t target_backing_sectors
; /* negative if unknown */
1573 size_t cluster_sectors
;
1575 long num_coroutines
;
1576 int running_coroutines
;
1577 Coroutine
*co
[MAX_COROUTINES
];
1578 int64_t wait_sector_num
[MAX_COROUTINES
];
1583 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1584 int *src_cur
, int64_t *src_cur_offset
)
1587 *src_cur_offset
= 0;
1588 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1589 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1591 assert(*src_cur
< s
->src_num
);
1595 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1597 int64_t src_cur_offset
;
1598 int ret
, n
, src_cur
;
1599 bool post_backing_zero
= false;
1601 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1603 assert(s
->total_sectors
> sector_num
);
1604 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1606 if (s
->target_backing_sectors
>= 0) {
1607 if (sector_num
>= s
->target_backing_sectors
) {
1608 post_backing_zero
= s
->unallocated_blocks_are_zero
;
1609 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1610 /* Split requests around target_backing_sectors (because
1611 * starting from there, zeros are handled differently) */
1612 n
= s
->target_backing_sectors
- sector_num
;
1616 if (s
->sector_next_status
<= sector_num
) {
1617 int64_t count
= n
* BDRV_SECTOR_SIZE
;
1619 if (s
->target_has_backing
) {
1621 ret
= bdrv_block_status(blk_bs(s
->src
[src_cur
]),
1622 (sector_num
- src_cur_offset
) *
1624 count
, &count
, NULL
, NULL
);
1626 ret
= bdrv_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1627 (sector_num
- src_cur_offset
) *
1629 count
, &count
, NULL
, NULL
);
1634 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1636 if (ret
& BDRV_BLOCK_ZERO
) {
1637 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1638 } else if (ret
& BDRV_BLOCK_DATA
) {
1639 s
->status
= BLK_DATA
;
1641 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1644 s
->sector_next_status
= sector_num
+ n
;
1647 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1648 if (s
->status
== BLK_DATA
) {
1649 n
= MIN(n
, s
->buf_sectors
);
1652 /* We need to write complete clusters for compressed images, so if an
1653 * unallocated area is shorter than that, we must consider the whole
1654 * cluster allocated. */
1655 if (s
->compressed
) {
1656 if (n
< s
->cluster_sectors
) {
1657 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1658 s
->status
= BLK_DATA
;
1660 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1667 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1668 int nb_sectors
, uint8_t *buf
)
1674 assert(nb_sectors
<= s
->buf_sectors
);
1675 while (nb_sectors
> 0) {
1678 int64_t bs_sectors
, src_cur_offset
;
1680 /* In the case of compression with multiple source files, we can get a
1681 * nb_sectors that spreads into the next part. So we must be able to
1682 * read across multiple BDSes for one convert_read() call. */
1683 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1684 blk
= s
->src
[src_cur
];
1685 bs_sectors
= s
->src_sectors
[src_cur
];
1687 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1689 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1690 qemu_iovec_init_external(&qiov
, &iov
, 1);
1692 ret
= blk_co_preadv(
1693 blk
, (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
,
1694 n
<< BDRV_SECTOR_BITS
, &qiov
, 0);
1701 buf
+= n
* BDRV_SECTOR_SIZE
;
1708 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1709 int nb_sectors
, uint8_t *buf
,
1710 enum ImgConvertBlockStatus status
)
1716 while (nb_sectors
> 0) {
1718 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1721 case BLK_BACKING_FILE
:
1722 /* If we have a backing file, leave clusters unallocated that are
1723 * unallocated in the source image, so that the backing file is
1724 * visible at the respective offset. */
1725 assert(s
->target_has_backing
);
1729 /* If we're told to keep the target fully allocated (-S 0) or there
1730 * is real non-zero data, we must write it. Otherwise we can treat
1731 * it as zero sectors.
1732 * Compressed clusters need to be written as a whole, so in that
1733 * case we can only save the write if the buffer is completely
1735 if (!s
->min_sparse
||
1737 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1738 sector_num
, s
->alignment
)) ||
1740 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1743 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1744 qemu_iovec_init_external(&qiov
, &iov
, 1);
1746 ret
= blk_co_pwritev(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1747 n
<< BDRV_SECTOR_BITS
, &qiov
, flags
);
1756 if (s
->has_zero_init
) {
1757 assert(!s
->target_has_backing
);
1760 ret
= blk_co_pwrite_zeroes(s
->target
,
1761 sector_num
<< BDRV_SECTOR_BITS
,
1762 n
<< BDRV_SECTOR_BITS
, 0);
1771 buf
+= n
* BDRV_SECTOR_SIZE
;
1777 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1782 while (nb_sectors
> 0) {
1785 int64_t bs_sectors
, src_cur_offset
;
1788 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1789 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1790 blk
= s
->src
[src_cur
];
1791 bs_sectors
= s
->src_sectors
[src_cur
];
1793 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1795 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1796 sector_num
<< BDRV_SECTOR_BITS
,
1797 n
<< BDRV_SECTOR_BITS
, 0, 0);
1808 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1810 ImgConvertState
*s
= opaque
;
1811 uint8_t *buf
= NULL
;
1815 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1816 if (s
->co
[i
] == qemu_coroutine_self()) {
1823 s
->running_coroutines
++;
1824 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1829 enum ImgConvertBlockStatus status
;
1832 qemu_co_mutex_lock(&s
->lock
);
1833 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1834 qemu_co_mutex_unlock(&s
->lock
);
1837 n
= convert_iteration_sectors(s
, s
->sector_num
);
1839 qemu_co_mutex_unlock(&s
->lock
);
1843 /* save current sector and allocation status to local variables */
1844 sector_num
= s
->sector_num
;
1846 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1847 n
= MIN(n
, s
->buf_sectors
);
1849 /* increment global sector counter so that other coroutines can
1850 * already continue reading beyond this request */
1852 qemu_co_mutex_unlock(&s
->lock
);
1854 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1855 s
->allocated_done
+= n
;
1856 qemu_progress_print(100.0 * s
->allocated_done
/
1857 s
->allocated_sectors
, 0);
1861 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
1862 if (status
== BLK_DATA
&& !copy_range
) {
1863 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1865 error_report("error while reading sector %" PRId64
1866 ": %s", sector_num
, strerror(-ret
));
1869 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1871 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1874 if (s
->wr_in_order
) {
1875 /* keep writes in order */
1876 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1877 s
->wait_sector_num
[index
] = sector_num
;
1878 qemu_coroutine_yield();
1880 s
->wait_sector_num
[index
] = -1;
1883 if (s
->ret
== -EINPROGRESS
) {
1885 ret
= convert_co_copy_range(s
, sector_num
, n
);
1887 s
->copy_range
= false;
1891 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1894 error_report("error while writing sector %" PRId64
1895 ": %s", sector_num
, strerror(-ret
));
1900 if (s
->wr_in_order
) {
1901 /* reenter the coroutine that might have waited
1902 * for this write to complete */
1903 s
->wr_offs
= sector_num
+ n
;
1904 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1905 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1907 * A -> B -> A cannot occur because A has
1908 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1909 * B will never enter A during this time window.
1911 qemu_coroutine_enter(s
->co
[i
]);
1919 s
->co
[index
] = NULL
;
1920 s
->running_coroutines
--;
1921 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1922 /* the convert job finished successfully */
1927 static int convert_do_copy(ImgConvertState
*s
)
1930 int64_t sector_num
= 0;
1932 /* Check whether we have zero initialisation or can get it efficiently */
1933 s
->has_zero_init
= s
->min_sparse
&& !s
->target_has_backing
1934 ? bdrv_has_zero_init(blk_bs(s
->target
))
1937 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1938 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1940 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
);
1942 s
->has_zero_init
= true;
1946 /* Allocate buffer for copied data. For compressed images, only one cluster
1947 * can be copied at a time. */
1948 if (s
->compressed
) {
1949 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
1950 error_report("invalid cluster size");
1953 s
->buf_sectors
= s
->cluster_sectors
;
1956 while (sector_num
< s
->total_sectors
) {
1957 n
= convert_iteration_sectors(s
, sector_num
);
1961 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1963 s
->allocated_sectors
+= n
;
1969 s
->sector_next_status
= 0;
1970 s
->ret
= -EINPROGRESS
;
1972 qemu_co_mutex_init(&s
->lock
);
1973 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1974 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
1975 s
->wait_sector_num
[i
] = -1;
1976 qemu_coroutine_enter(s
->co
[i
]);
1979 while (s
->running_coroutines
) {
1980 main_loop_wait(false);
1983 if (s
->compressed
&& !s
->ret
) {
1984 /* signal EOF to align */
1985 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
1994 #define MAX_BUF_SECTORS 32768
1996 static int img_convert(int argc
, char **argv
)
1998 int c
, bs_i
, flags
, src_flags
= 0;
1999 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2000 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2001 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
2002 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2003 BlockDriverInfo bdi
;
2004 BlockDriverState
*out_bs
;
2005 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2006 QemuOptsList
*create_opts
= NULL
;
2007 QDict
*open_opts
= NULL
;
2008 char *options
= NULL
;
2009 Error
*local_err
= NULL
;
2010 bool writethrough
, src_writethrough
, quiet
= false, image_opts
= false,
2011 skip_create
= false, progress
= false, tgt_image_opts
= false;
2012 int64_t ret
= -EINVAL
;
2013 bool force_share
= false;
2014 bool explict_min_sparse
= false;
2016 ImgConvertState s
= (ImgConvertState
) {
2017 /* Need at least 4k of zeros for sparse detection */
2019 .copy_range
= false,
2020 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2021 .wr_in_order
= true,
2022 .num_coroutines
= 8,
2026 static const struct option long_options
[] = {
2027 {"help", no_argument
, 0, 'h'},
2028 {"object", required_argument
, 0, OPTION_OBJECT
},
2029 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2030 {"force-share", no_argument
, 0, 'U'},
2031 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2034 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2035 long_options
, NULL
);
2041 missing_argument(argv
[optind
- 1]);
2044 unrecognized_option(argv
[optind
- 1]);
2056 out_baseimg
= optarg
;
2059 s
.copy_range
= true;
2062 s
.compressed
= true;
2065 if (!is_valid_option_list(optarg
)) {
2066 error_report("Invalid option list: %s", optarg
);
2070 options
= g_strdup(optarg
);
2072 char *old_options
= options
;
2073 options
= g_strdup_printf("%s,%s", options
, optarg
);
2074 g_free(old_options
);
2078 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2079 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2082 error_report("Failed in parsing snapshot param '%s'",
2087 snapshot_name
= optarg
;
2094 sval
= cvtnum(optarg
);
2095 if (sval
< 0 || sval
& (BDRV_SECTOR_SIZE
- 1) ||
2096 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2097 error_report("Invalid buffer size for sparse output specified. "
2098 "Valid sizes are multiples of %llu up to %llu. Select "
2099 "0 to disable sparse detection (fully allocates output).",
2100 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2104 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2105 explict_min_sparse
= true;
2124 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2125 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2126 error_report("Invalid number of coroutines. Allowed number of"
2127 " coroutines is between 1 and %d", MAX_COROUTINES
);
2132 s
.wr_in_order
= false;
2137 case OPTION_OBJECT
: {
2138 QemuOpts
*object_opts
;
2139 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2146 case OPTION_IMAGE_OPTS
:
2149 case OPTION_TARGET_IMAGE_OPTS
:
2150 tgt_image_opts
= true;
2155 if (!out_fmt
&& !tgt_image_opts
) {
2159 if (qemu_opts_foreach(&qemu_object_opts
,
2160 user_creatable_add_opts_foreach
,
2165 if (s
.compressed
&& s
.copy_range
) {
2166 error_report("Cannot enable copy offloading when -c is used");
2170 if (explict_min_sparse
&& s
.copy_range
) {
2171 error_report("Cannot enable copy offloading when -S is used");
2175 if (tgt_image_opts
&& !skip_create
) {
2176 error_report("--target-image-opts requires use of -n flag");
2180 s
.src_num
= argc
- optind
- 1;
2181 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2183 if (options
&& has_help_option(options
)) {
2185 ret
= print_block_option_help(out_filename
, out_fmt
);
2188 error_report("Option help requires a format be specified");
2193 if (s
.src_num
< 1) {
2194 error_report("Must specify image file name");
2199 /* ret is still -EINVAL until here */
2200 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2202 error_report("Invalid source cache option: %s", src_cache
);
2206 /* Initialize before goto out */
2210 qemu_progress_init(progress
, 1.0);
2211 qemu_progress_print(0, 100);
2213 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2214 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2216 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2217 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2218 fmt
, src_flags
, src_writethrough
, quiet
,
2224 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2225 if (s
.src_sectors
[bs_i
] < 0) {
2226 error_report("Could not get size of %s: %s",
2227 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2231 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2235 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2236 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2237 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2239 } else if (snapshot_name
!= NULL
) {
2240 if (s
.src_num
> 1) {
2241 error_report("No support for concatenating multiple snapshot");
2246 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2250 error_reportf_err(local_err
, "Failed to load snapshot: ");
2256 /* Find driver and parse its options */
2257 drv
= bdrv_find_format(out_fmt
);
2259 error_report("Unknown file format '%s'", out_fmt
);
2264 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2266 error_report_err(local_err
);
2271 if (!drv
->create_opts
) {
2272 error_report("Format driver '%s' does not support image creation",
2278 if (!proto_drv
->create_opts
) {
2279 error_report("Protocol driver '%s' does not support image creation",
2280 proto_drv
->format_name
);
2285 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2286 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2288 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2290 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2292 error_report_err(local_err
);
2298 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2300 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2306 /* Get backing file name if -o backing_file was used */
2307 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2308 if (out_baseimg_param
) {
2309 out_baseimg
= out_baseimg_param
;
2311 s
.target_has_backing
= (bool) out_baseimg
;
2313 if (s
.src_num
> 1 && out_baseimg
) {
2314 error_report("Having a backing file for the target makes no sense when "
2315 "concatenating multiple input images");
2320 /* Check if compression is supported */
2323 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2324 const char *encryptfmt
=
2325 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2326 const char *preallocation
=
2327 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2329 if (drv
&& !drv
->bdrv_co_pwritev_compressed
) {
2330 error_report("Compression not supported for this file format");
2335 if (encryption
|| encryptfmt
) {
2336 error_report("Compression and encryption not supported at "
2343 && strcmp(preallocation
, "off"))
2345 error_report("Compression and preallocation not supported at "
2353 * The later open call will need any decryption secrets, and
2354 * bdrv_create() will purge "opts", so extract them now before
2358 open_opts
= qdict_new();
2359 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2363 /* Create the new image */
2364 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2366 error_reportf_err(local_err
, "%s: error while converting %s: ",
2367 out_filename
, out_fmt
);
2372 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2373 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2375 error_report("Invalid cache option: %s", cache
);
2380 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2381 flags
, writethrough
, quiet
, false);
2383 /* TODO ultimately we should allow --target-image-opts
2384 * to be used even when -n is not given.
2385 * That has to wait for bdrv_create to be improved
2386 * to allow filenames in option syntax
2388 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2389 flags
, writethrough
, quiet
, false);
2390 open_opts
= NULL
; /* blk_new_open will have freed it */
2396 out_bs
= blk_bs(s
.target
);
2398 if (s
.compressed
&& !out_bs
->drv
->bdrv_co_pwritev_compressed
) {
2399 error_report("Compression not supported for this file format");
2404 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2405 * or discard_alignment of the out_bs is greater. Limit to
2406 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2407 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2409 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2410 out_bs
->bl
.pdiscard_alignment
>>
2411 BDRV_SECTOR_BITS
)));
2413 /* try to align the write requests to the destination to avoid unnecessary
2415 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2416 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2418 assert(is_power_of_2(s
.alignment
));
2421 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2422 if (output_sectors
< 0) {
2423 error_report("unable to get output image length: %s",
2424 strerror(-output_sectors
));
2427 } else if (output_sectors
< s
.total_sectors
) {
2428 error_report("output file is smaller than input file");
2434 if (s
.target_has_backing
) {
2435 /* Errors are treated as "backing length unknown" (which means
2436 * s.target_backing_sectors has to be negative, which it will
2437 * be automatically). The backing file length is used only
2438 * for optimizations, so such a case is not fatal. */
2439 s
.target_backing_sectors
= bdrv_nb_sectors(out_bs
->backing
->bs
);
2441 s
.target_backing_sectors
= -1;
2444 ret
= bdrv_get_info(out_bs
, &bdi
);
2447 error_report("could not get block driver info");
2451 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2452 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2453 s
.unallocated_blocks_are_zero
= bdi
.unallocated_blocks_are_zero
;
2456 ret
= convert_do_copy(&s
);
2459 qemu_progress_print(100, 0);
2461 qemu_progress_end();
2462 qemu_opts_del(opts
);
2463 qemu_opts_free(create_opts
);
2464 qemu_opts_del(sn_opts
);
2465 qobject_unref(open_opts
);
2466 blk_unref(s
.target
);
2468 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2469 blk_unref(s
.src
[bs_i
]);
2473 g_free(s
.src_sectors
);
2481 static void dump_snapshots(BlockDriverState
*bs
)
2483 QEMUSnapshotInfo
*sn_tab
, *sn
;
2486 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2489 printf("Snapshot list:\n");
2490 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
2492 for(i
= 0; i
< nb_sns
; i
++) {
2494 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
2500 static void dump_json_image_info_list(ImageInfoList
*list
)
2504 Visitor
*v
= qobject_output_visitor_new(&obj
);
2506 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2507 visit_complete(v
, &obj
);
2508 str
= qobject_to_json_pretty(obj
);
2509 assert(str
!= NULL
);
2510 printf("%s\n", qstring_get_str(str
));
2516 static void dump_json_image_info(ImageInfo
*info
)
2520 Visitor
*v
= qobject_output_visitor_new(&obj
);
2522 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2523 visit_complete(v
, &obj
);
2524 str
= qobject_to_json_pretty(obj
);
2525 assert(str
!= NULL
);
2526 printf("%s\n", qstring_get_str(str
));
2532 static void dump_human_image_info_list(ImageInfoList
*list
)
2534 ImageInfoList
*elem
;
2537 for (elem
= list
; elem
; elem
= elem
->next
) {
2543 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
2547 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2549 return strcmp(a
, b
) == 0;
2553 * Open an image file chain and return an ImageInfoList
2555 * @filename: topmost image filename
2556 * @fmt: topmost image format (may be NULL to autodetect)
2557 * @chain: true - enumerate entire backing file chain
2558 * false - only topmost image file
2560 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2561 * image file. If there was an error a message will have been printed to
2564 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2565 const char *filename
,
2567 bool chain
, bool force_share
)
2569 ImageInfoList
*head
= NULL
;
2570 ImageInfoList
**last
= &head
;
2571 GHashTable
*filenames
;
2574 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2578 BlockDriverState
*bs
;
2580 ImageInfoList
*elem
;
2582 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2583 error_report("Backing file '%s' creates an infinite loop.",
2587 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2589 blk
= img_open(image_opts
, filename
, fmt
,
2590 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2597 bdrv_query_image_info(bs
, &info
, &err
);
2599 error_report_err(err
);
2604 elem
= g_new0(ImageInfoList
, 1);
2611 filename
= fmt
= NULL
;
2613 if (info
->has_full_backing_filename
) {
2614 filename
= info
->full_backing_filename
;
2615 } else if (info
->has_backing_filename
) {
2616 error_report("Could not determine absolute backing filename,"
2617 " but backing filename '%s' present",
2618 info
->backing_filename
);
2621 if (info
->has_backing_filename_format
) {
2622 fmt
= info
->backing_filename_format
;
2626 g_hash_table_destroy(filenames
);
2630 qapi_free_ImageInfoList(head
);
2631 g_hash_table_destroy(filenames
);
2635 static int img_info(int argc
, char **argv
)
2638 OutputFormat output_format
= OFORMAT_HUMAN
;
2640 const char *filename
, *fmt
, *output
;
2641 ImageInfoList
*list
;
2642 bool image_opts
= false;
2643 bool force_share
= false;
2648 int option_index
= 0;
2649 static const struct option long_options
[] = {
2650 {"help", no_argument
, 0, 'h'},
2651 {"format", required_argument
, 0, 'f'},
2652 {"output", required_argument
, 0, OPTION_OUTPUT
},
2653 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2654 {"object", required_argument
, 0, OPTION_OBJECT
},
2655 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2656 {"force-share", no_argument
, 0, 'U'},
2659 c
= getopt_long(argc
, argv
, ":f:hU",
2660 long_options
, &option_index
);
2666 missing_argument(argv
[optind
- 1]);
2669 unrecognized_option(argv
[optind
- 1]);
2683 case OPTION_BACKING_CHAIN
:
2686 case OPTION_OBJECT
: {
2688 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2694 case OPTION_IMAGE_OPTS
:
2699 if (optind
!= argc
- 1) {
2700 error_exit("Expecting one image file name");
2702 filename
= argv
[optind
++];
2704 if (output
&& !strcmp(output
, "json")) {
2705 output_format
= OFORMAT_JSON
;
2706 } else if (output
&& !strcmp(output
, "human")) {
2707 output_format
= OFORMAT_HUMAN
;
2708 } else if (output
) {
2709 error_report("--output must be used with human or json as argument.");
2713 if (qemu_opts_foreach(&qemu_object_opts
,
2714 user_creatable_add_opts_foreach
,
2719 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2725 switch (output_format
) {
2727 dump_human_image_info_list(list
);
2731 dump_json_image_info_list(list
);
2733 dump_json_image_info(list
->value
);
2738 qapi_free_ImageInfoList(list
);
2742 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2745 switch (output_format
) {
2747 if (e
->data
&& !e
->has_offset
) {
2748 error_report("File contains external, encrypted or compressed clusters.");
2751 if (e
->data
&& !e
->zero
) {
2752 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2753 e
->start
, e
->length
,
2754 e
->has_offset
? e
->offset
: 0,
2755 e
->has_filename
? e
->filename
: "");
2757 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2758 * Modify the flags here to allow more coalescing.
2760 if (next
&& (!next
->data
|| next
->zero
)) {
2766 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2767 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2768 (e
->start
== 0 ? "[" : ",\n"),
2769 e
->start
, e
->length
, e
->depth
,
2770 e
->zero
? "true" : "false",
2771 e
->data
? "true" : "false");
2772 if (e
->has_offset
) {
2773 printf(", \"offset\": %"PRId64
"", e
->offset
);
2784 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
2785 int64_t bytes
, MapEntry
*e
)
2789 BlockDriverState
*file
;
2793 /* As an optimization, we could cache the current range of unallocated
2794 * clusters in each file of the chain, and avoid querying the same
2800 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
2805 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2808 bs
= backing_bs(bs
);
2817 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2822 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2823 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2825 .has_offset
= has_offset
,
2827 .has_filename
= file
&& has_offset
,
2828 .filename
= file
&& has_offset
? file
->filename
: NULL
,
2834 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2836 if (curr
->length
== 0) {
2839 if (curr
->zero
!= next
->zero
||
2840 curr
->data
!= next
->data
||
2841 curr
->depth
!= next
->depth
||
2842 curr
->has_filename
!= next
->has_filename
||
2843 curr
->has_offset
!= next
->has_offset
) {
2846 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2849 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2855 static int img_map(int argc
, char **argv
)
2858 OutputFormat output_format
= OFORMAT_HUMAN
;
2860 BlockDriverState
*bs
;
2861 const char *filename
, *fmt
, *output
;
2863 MapEntry curr
= { .length
= 0 }, next
;
2865 bool image_opts
= false;
2866 bool force_share
= false;
2871 int option_index
= 0;
2872 static const struct option long_options
[] = {
2873 {"help", no_argument
, 0, 'h'},
2874 {"format", required_argument
, 0, 'f'},
2875 {"output", required_argument
, 0, OPTION_OUTPUT
},
2876 {"object", required_argument
, 0, OPTION_OBJECT
},
2877 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2878 {"force-share", no_argument
, 0, 'U'},
2881 c
= getopt_long(argc
, argv
, ":f:hU",
2882 long_options
, &option_index
);
2888 missing_argument(argv
[optind
- 1]);
2891 unrecognized_option(argv
[optind
- 1]);
2905 case OPTION_OBJECT
: {
2907 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2913 case OPTION_IMAGE_OPTS
:
2918 if (optind
!= argc
- 1) {
2919 error_exit("Expecting one image file name");
2921 filename
= argv
[optind
];
2923 if (output
&& !strcmp(output
, "json")) {
2924 output_format
= OFORMAT_JSON
;
2925 } else if (output
&& !strcmp(output
, "human")) {
2926 output_format
= OFORMAT_HUMAN
;
2927 } else if (output
) {
2928 error_report("--output must be used with human or json as argument.");
2932 if (qemu_opts_foreach(&qemu_object_opts
,
2933 user_creatable_add_opts_foreach
,
2938 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
2944 if (output_format
== OFORMAT_HUMAN
) {
2945 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2948 length
= blk_getlength(blk
);
2949 while (curr
.start
+ curr
.length
< length
) {
2950 int64_t offset
= curr
.start
+ curr
.length
;
2953 /* Probe up to 1 GiB at a time. */
2954 n
= MIN(1 << 30, length
- offset
);
2955 ret
= get_block_status(bs
, offset
, n
, &next
);
2958 error_report("Could not read file metadata: %s", strerror(-ret
));
2962 if (entry_mergeable(&curr
, &next
)) {
2963 curr
.length
+= next
.length
;
2967 if (curr
.length
> 0) {
2968 dump_map_entry(output_format
, &curr
, &next
);
2973 dump_map_entry(output_format
, &curr
, NULL
);
2980 #define SNAPSHOT_LIST 1
2981 #define SNAPSHOT_CREATE 2
2982 #define SNAPSHOT_APPLY 3
2983 #define SNAPSHOT_DELETE 4
2985 static int img_snapshot(int argc
, char **argv
)
2988 BlockDriverState
*bs
;
2989 QEMUSnapshotInfo sn
;
2990 char *filename
, *snapshot_name
= NULL
;
2991 int c
, ret
= 0, bdrv_oflags
;
2996 bool image_opts
= false;
2997 bool force_share
= false;
2999 bdrv_oflags
= BDRV_O_RDWR
;
3000 /* Parse commandline parameters */
3002 static const struct option long_options
[] = {
3003 {"help", no_argument
, 0, 'h'},
3004 {"object", required_argument
, 0, OPTION_OBJECT
},
3005 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3006 {"force-share", no_argument
, 0, 'U'},
3009 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3010 long_options
, NULL
);
3016 missing_argument(argv
[optind
- 1]);
3019 unrecognized_option(argv
[optind
- 1]);
3026 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3029 action
= SNAPSHOT_LIST
;
3030 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3034 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3037 action
= SNAPSHOT_APPLY
;
3038 snapshot_name
= optarg
;
3042 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3045 action
= SNAPSHOT_CREATE
;
3046 snapshot_name
= optarg
;
3050 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3053 action
= SNAPSHOT_DELETE
;
3054 snapshot_name
= optarg
;
3062 case OPTION_OBJECT
: {
3064 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3070 case OPTION_IMAGE_OPTS
:
3076 if (optind
!= argc
- 1) {
3077 error_exit("Expecting one image file name");
3079 filename
= argv
[optind
++];
3081 if (qemu_opts_foreach(&qemu_object_opts
,
3082 user_creatable_add_opts_foreach
,
3087 /* Open the image */
3088 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3095 /* Perform the requested action */
3101 case SNAPSHOT_CREATE
:
3102 memset(&sn
, 0, sizeof(sn
));
3103 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3105 qemu_gettimeofday(&tv
);
3106 sn
.date_sec
= tv
.tv_sec
;
3107 sn
.date_nsec
= tv
.tv_usec
* 1000;
3109 ret
= bdrv_snapshot_create(bs
, &sn
);
3111 error_report("Could not create snapshot '%s': %d (%s)",
3112 snapshot_name
, ret
, strerror(-ret
));
3116 case SNAPSHOT_APPLY
:
3117 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3119 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3124 case SNAPSHOT_DELETE
:
3125 bdrv_snapshot_delete_by_id_or_name(bs
, snapshot_name
, &err
);
3127 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3142 static int img_rebase(int argc
, char **argv
)
3144 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3145 uint8_t *buf_old
= NULL
;
3146 uint8_t *buf_new
= NULL
;
3147 BlockDriverState
*bs
= NULL
;
3149 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3150 int c
, flags
, src_flags
, ret
;
3151 bool writethrough
, src_writethrough
;
3153 bool force_share
= false;
3156 Error
*local_err
= NULL
;
3157 bool image_opts
= false;
3159 /* Parse commandline parameters */
3161 cache
= BDRV_DEFAULT_CACHE
;
3162 src_cache
= BDRV_DEFAULT_CACHE
;
3166 static const struct option long_options
[] = {
3167 {"help", no_argument
, 0, 'h'},
3168 {"object", required_argument
, 0, OPTION_OBJECT
},
3169 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3170 {"force-share", no_argument
, 0, 'U'},
3173 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3174 long_options
, NULL
);
3180 missing_argument(argv
[optind
- 1]);
3183 unrecognized_option(argv
[optind
- 1]);
3192 out_basefmt
= optarg
;
3195 out_baseimg
= optarg
;
3212 case OPTION_OBJECT
: {
3214 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3220 case OPTION_IMAGE_OPTS
:
3233 if (optind
!= argc
- 1) {
3234 error_exit("Expecting one image file name");
3236 if (!unsafe
&& !out_baseimg
) {
3237 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3239 filename
= argv
[optind
++];
3241 if (qemu_opts_foreach(&qemu_object_opts
,
3242 user_creatable_add_opts_foreach
,
3247 qemu_progress_init(progress
, 2.0);
3248 qemu_progress_print(0, 100);
3250 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3251 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3253 error_report("Invalid cache option: %s", cache
);
3258 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3260 error_report("Invalid source cache option: %s", src_cache
);
3264 /* The source files are opened read-only, don't care about WCE */
3265 assert((src_flags
& BDRV_O_RDWR
) == 0);
3266 (void) src_writethrough
;
3271 * Ignore the old backing file for unsafe rebase in case we want to correct
3272 * the reference to a renamed or moved backing file.
3274 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3282 if (out_basefmt
!= NULL
) {
3283 if (bdrv_find_format(out_basefmt
) == NULL
) {
3284 error_report("Invalid format name: '%s'", out_basefmt
);
3290 /* For safe rebasing we need to compare old and new backing file */
3292 char backing_name
[PATH_MAX
];
3293 QDict
*options
= NULL
;
3295 if (bs
->backing_format
[0] != '\0') {
3296 options
= qdict_new();
3297 qdict_put_str(options
, "driver", bs
->backing_format
);
3302 options
= qdict_new();
3304 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3306 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3307 blk_old_backing
= blk_new_open(backing_name
, NULL
,
3308 options
, src_flags
, &local_err
);
3309 if (!blk_old_backing
) {
3310 error_reportf_err(local_err
,
3311 "Could not open old backing file '%s': ",
3317 if (out_baseimg
[0]) {
3318 const char *overlay_filename
;
3319 char *out_real_path
;
3321 options
= qdict_new();
3323 qdict_put_str(options
, "driver", out_basefmt
);
3326 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3329 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3331 out_real_path
= g_malloc(PATH_MAX
);
3333 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3339 error_reportf_err(local_err
,
3340 "Could not resolve backing filename: ");
3342 g_free(out_real_path
);
3346 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3347 options
, src_flags
, &local_err
);
3348 g_free(out_real_path
);
3349 if (!blk_new_backing
) {
3350 error_reportf_err(local_err
,
3351 "Could not open new backing file '%s': ",
3360 * Check each unallocated cluster in the COW file. If it is unallocated,
3361 * accesses go to the backing file. We must therefore compare this cluster
3362 * in the old and new backing file, and if they differ we need to copy it
3363 * from the old backing file into the COW file.
3365 * If qemu-img crashes during this step, no harm is done. The content of
3366 * the image is the same as the original one at any time.
3370 int64_t old_backing_size
;
3371 int64_t new_backing_size
= 0;
3374 float local_progress
= 0;
3376 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3377 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3379 size
= blk_getlength(blk
);
3381 error_report("Could not get size of '%s': %s",
3382 filename
, strerror(-size
));
3386 old_backing_size
= blk_getlength(blk_old_backing
);
3387 if (old_backing_size
< 0) {
3388 char backing_name
[PATH_MAX
];
3390 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3391 error_report("Could not get size of '%s': %s",
3392 backing_name
, strerror(-old_backing_size
));
3396 if (blk_new_backing
) {
3397 new_backing_size
= blk_getlength(blk_new_backing
);
3398 if (new_backing_size
< 0) {
3399 error_report("Could not get size of '%s': %s",
3400 out_baseimg
, strerror(-new_backing_size
));
3407 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3410 for (offset
= 0; offset
< size
; offset
+= n
) {
3411 /* How many bytes can we handle with the next read? */
3412 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3414 /* If the cluster is allocated, we don't need to take action */
3415 ret
= bdrv_is_allocated(bs
, offset
, n
, &n
);
3417 error_report("error while reading image metadata: %s",
3426 * Read old and new backing file and take into consideration that
3427 * backing files may be smaller than the COW image.
3429 if (offset
>= old_backing_size
) {
3430 memset(buf_old
, 0, n
);
3432 if (offset
+ n
> old_backing_size
) {
3433 n
= old_backing_size
- offset
;
3436 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3438 error_report("error while reading from old backing file");
3443 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3444 memset(buf_new
, 0, n
);
3446 if (offset
+ n
> new_backing_size
) {
3447 n
= new_backing_size
- offset
;
3450 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3452 error_report("error while reading from new backing file");
3457 /* If they differ, we need to write to the COW file */
3458 uint64_t written
= 0;
3460 while (written
< n
) {
3463 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3464 n
- written
, &pnum
))
3466 ret
= blk_pwrite(blk
, offset
+ written
,
3467 buf_old
+ written
, pnum
, 0);
3469 error_report("Error while writing to COW image: %s",
3477 qemu_progress_print(local_progress
, 100);
3482 * Change the backing file. All clusters that are different from the old
3483 * backing file are overwritten in the COW file now, so the visible content
3484 * doesn't change when we switch the backing file.
3486 if (out_baseimg
&& *out_baseimg
) {
3487 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3489 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3492 if (ret
== -ENOSPC
) {
3493 error_report("Could not change the backing file to '%s': No "
3494 "space left in the file header", out_baseimg
);
3495 } else if (ret
< 0) {
3496 error_report("Could not change the backing file to '%s': %s",
3497 out_baseimg
, strerror(-ret
));
3500 qemu_progress_print(100, 0);
3502 * TODO At this point it is possible to check if any clusters that are
3503 * allocated in the COW file are the same in the backing file. If so, they
3504 * could be dropped from the COW file. Don't do this before switching the
3505 * backing file, in case of a crash this would lead to corruption.
3508 qemu_progress_end();
3511 blk_unref(blk_old_backing
);
3512 blk_unref(blk_new_backing
);
3514 qemu_vfree(buf_old
);
3515 qemu_vfree(buf_new
);
3524 static int img_resize(int argc
, char **argv
)
3527 int c
, ret
, relative
;
3528 const char *filename
, *fmt
, *size
;
3529 int64_t n
, total_size
, current_size
, new_size
;
3531 BlockBackend
*blk
= NULL
;
3532 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3535 static QemuOptsList resize_options
= {
3536 .name
= "resize_options",
3537 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3540 .name
= BLOCK_OPT_SIZE
,
3541 .type
= QEMU_OPT_SIZE
,
3542 .help
= "Virtual disk size"
3548 bool image_opts
= false;
3549 bool shrink
= false;
3551 /* Remove size from argv manually so that negative numbers are not treated
3552 * as options by getopt. */
3554 error_exit("Not enough arguments");
3558 size
= argv
[--argc
];
3560 /* Parse getopt arguments */
3563 static const struct option long_options
[] = {
3564 {"help", no_argument
, 0, 'h'},
3565 {"object", required_argument
, 0, OPTION_OBJECT
},
3566 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3567 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3568 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3571 c
= getopt_long(argc
, argv
, ":f:hq",
3572 long_options
, NULL
);
3578 missing_argument(argv
[optind
- 1]);
3581 unrecognized_option(argv
[optind
- 1]);
3592 case OPTION_OBJECT
: {
3594 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3600 case OPTION_IMAGE_OPTS
:
3603 case OPTION_PREALLOCATION
:
3604 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3605 PREALLOC_MODE__MAX
, NULL
);
3606 if (prealloc
== PREALLOC_MODE__MAX
) {
3607 error_report("Invalid preallocation mode '%s'", optarg
);
3616 if (optind
!= argc
- 1) {
3617 error_exit("Expecting image file name and size");
3619 filename
= argv
[optind
++];
3621 if (qemu_opts_foreach(&qemu_object_opts
,
3622 user_creatable_add_opts_foreach
,
3627 /* Choose grow, shrink, or absolute resize mode */
3643 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3644 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3646 error_report_err(err
);
3648 qemu_opts_del(param
);
3651 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3652 qemu_opts_del(param
);
3654 blk
= img_open(image_opts
, filename
, fmt
,
3655 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3662 current_size
= blk_getlength(blk
);
3663 if (current_size
< 0) {
3664 error_report("Failed to inquire current image length: %s",
3665 strerror(-current_size
));
3671 total_size
= current_size
+ n
* relative
;
3675 if (total_size
<= 0) {
3676 error_report("New image size must be positive");
3681 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3682 error_report("Preallocation can only be used for growing images");
3687 if (total_size
< current_size
&& !shrink
) {
3688 warn_report("Shrinking an image will delete all data beyond the "
3689 "shrunken image's end. Before performing such an "
3690 "operation, make sure there is no important data there.");
3692 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk
)), "raw") != 0) {
3694 "Use the --shrink option to perform a shrink operation.");
3698 warn_report("Using the --shrink option will suppress this message. "
3699 "Note that future versions of qemu-img may refuse to "
3700 "shrink images without this option.");
3704 ret
= blk_truncate(blk
, total_size
, prealloc
, &err
);
3706 error_report_err(err
);
3710 new_size
= blk_getlength(blk
);
3712 error_report("Failed to verify truncated image length: %s",
3713 strerror(-new_size
));
3718 /* Some block drivers implement a truncation method, but only so
3719 * the user can cause qemu to refresh the image's size from disk.
3720 * The idea is that the user resizes the image outside of qemu and
3721 * then invokes block_resize to inform qemu about it.
3722 * (This includes iscsi and file-posix for device files.)
3723 * Of course, that is not the behavior someone invoking
3724 * qemu-img resize would find useful, so we catch that behavior
3725 * here and tell the user. */
3726 if (new_size
!= total_size
&& new_size
== current_size
) {
3727 error_report("Image was not resized; resizing may not be supported "
3733 if (new_size
!= total_size
) {
3734 warn_report("Image should have been resized to %" PRIi64
3735 " bytes, but was resized to %" PRIi64
" bytes",
3736 total_size
, new_size
);
3739 qprintf(quiet
, "Image resized.\n");
3749 static void amend_status_cb(BlockDriverState
*bs
,
3750 int64_t offset
, int64_t total_work_size
,
3753 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3756 static int print_amend_option_help(const char *format
)
3760 /* Find driver and parse its options */
3761 drv
= bdrv_find_format(format
);
3763 error_report("Unknown file format '%s'", format
);
3767 if (!drv
->bdrv_amend_options
) {
3768 error_report("Format driver '%s' does not support option amendment",
3773 /* Every driver supporting amendment must have create_opts */
3774 assert(drv
->create_opts
);
3776 printf("Creation options for '%s':\n", format
);
3777 qemu_opts_print_help(drv
->create_opts
, false);
3778 printf("\nNote that not all of these options may be amendable.\n");
3782 static int img_amend(int argc
, char **argv
)
3786 char *options
= NULL
;
3787 QemuOptsList
*create_opts
= NULL
;
3788 QemuOpts
*opts
= NULL
;
3789 const char *fmt
= NULL
, *filename
, *cache
;
3792 bool quiet
= false, progress
= false;
3793 BlockBackend
*blk
= NULL
;
3794 BlockDriverState
*bs
= NULL
;
3795 bool image_opts
= false;
3797 cache
= BDRV_DEFAULT_CACHE
;
3799 static const struct option long_options
[] = {
3800 {"help", no_argument
, 0, 'h'},
3801 {"object", required_argument
, 0, OPTION_OBJECT
},
3802 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3805 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
3806 long_options
, NULL
);
3813 missing_argument(argv
[optind
- 1]);
3816 unrecognized_option(argv
[optind
- 1]);
3822 if (!is_valid_option_list(optarg
)) {
3823 error_report("Invalid option list: %s", optarg
);
3825 goto out_no_progress
;
3828 options
= g_strdup(optarg
);
3830 char *old_options
= options
;
3831 options
= g_strdup_printf("%s,%s", options
, optarg
);
3832 g_free(old_options
);
3848 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3852 goto out_no_progress
;
3855 case OPTION_IMAGE_OPTS
:
3862 error_exit("Must specify options (-o)");
3865 if (qemu_opts_foreach(&qemu_object_opts
,
3866 user_creatable_add_opts_foreach
,
3869 goto out_no_progress
;
3875 qemu_progress_init(progress
, 1.0);
3877 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
3878 if (fmt
&& has_help_option(options
)) {
3879 /* If a format is explicitly specified (and possibly no filename is
3880 * given), print option help here */
3881 ret
= print_amend_option_help(fmt
);
3885 if (optind
!= argc
- 1) {
3886 error_report("Expecting one image file name");
3891 flags
= BDRV_O_RDWR
;
3892 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3894 error_report("Invalid cache option: %s", cache
);
3898 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3906 fmt
= bs
->drv
->format_name
;
3908 if (has_help_option(options
)) {
3909 /* If the format was auto-detected, print option help here */
3910 ret
= print_amend_option_help(fmt
);
3914 if (!bs
->drv
->bdrv_amend_options
) {
3915 error_report("Format driver '%s' does not support option amendment",
3921 /* Every driver supporting amendment must have create_opts */
3922 assert(bs
->drv
->create_opts
);
3924 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
3925 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
3926 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
3928 error_report_err(err
);
3933 /* In case the driver does not call amend_status_cb() */
3934 qemu_progress_print(0.f
, 0);
3935 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, &err
);
3936 qemu_progress_print(100.f
, 0);
3938 error_report_err(err
);
3943 qemu_progress_end();
3947 qemu_opts_del(opts
);
3948 qemu_opts_free(create_opts
);
3957 typedef struct BenchData
{
3959 uint64_t image_size
;
3966 bool drain_on_flush
;
3975 static void bench_undrained_flush_cb(void *opaque
, int ret
)
3978 error_report("Failed flush request: %s", strerror(-ret
));
3983 static void bench_cb(void *opaque
, int ret
)
3985 BenchData
*b
= opaque
;
3989 error_report("Failed request: %s", strerror(-ret
));
3994 /* Just finished a flush with drained queue: Start next requests */
3995 assert(b
->in_flight
== 0);
3996 b
->in_flush
= false;
3997 } else if (b
->in_flight
> 0) {
3998 int remaining
= b
->n
- b
->in_flight
;
4003 /* Time for flush? Drain queue if requested, then flush */
4004 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4005 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4006 BlockCompletionFunc
*cb
;
4008 if (b
->drain_on_flush
) {
4012 cb
= bench_undrained_flush_cb
;
4015 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4017 error_report("Failed to issue flush request");
4021 if (b
->drain_on_flush
) {
4027 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4028 int64_t offset
= b
->offset
;
4029 /* blk_aio_* might look for completed I/Os and kick bench_cb
4030 * again, so make sure this operation is counted by in_flight
4031 * and b->offset is ready for the next submission.
4034 b
->offset
+= b
->step
;
4035 b
->offset
%= b
->image_size
;
4037 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4039 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4042 error_report("Failed to issue request");
4048 static int img_bench(int argc
, char **argv
)
4051 const char *fmt
= NULL
, *filename
;
4053 bool image_opts
= false;
4054 bool is_write
= false;
4058 size_t bufsize
= 4096;
4061 int flush_interval
= 0;
4062 bool drain_on_flush
= true;
4064 BlockBackend
*blk
= NULL
;
4065 BenchData data
= {};
4067 bool writethrough
= false;
4068 struct timeval t1
, t2
;
4070 bool force_share
= false;
4074 static const struct option long_options
[] = {
4075 {"help", no_argument
, 0, 'h'},
4076 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4077 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4078 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4079 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4080 {"force-share", no_argument
, 0, 'U'},
4083 c
= getopt_long(argc
, argv
, ":hc:d:f:no:qs:S:t:wU", long_options
, NULL
);
4090 missing_argument(argv
[optind
- 1]);
4093 unrecognized_option(argv
[optind
- 1]);
4102 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4103 error_report("Invalid request count specified");
4113 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4114 error_report("Invalid queue depth specified");
4124 flags
|= BDRV_O_NATIVE_AIO
;
4128 offset
= cvtnum(optarg
);
4130 error_report("Invalid offset specified");
4143 sval
= cvtnum(optarg
);
4144 if (sval
< 0 || sval
> INT_MAX
) {
4145 error_report("Invalid buffer size specified");
4156 sval
= cvtnum(optarg
);
4157 if (sval
< 0 || sval
> INT_MAX
) {
4158 error_report("Invalid step size specified");
4166 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4168 error_report("Invalid cache mode");
4174 flags
|= BDRV_O_RDWR
;
4180 case OPTION_PATTERN
:
4184 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4185 error_report("Invalid pattern byte specified");
4191 case OPTION_FLUSH_INTERVAL
:
4195 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4196 error_report("Invalid flush interval specified");
4199 flush_interval
= res
;
4202 case OPTION_NO_DRAIN
:
4203 drain_on_flush
= false;
4205 case OPTION_IMAGE_OPTS
:
4211 if (optind
!= argc
- 1) {
4212 error_exit("Expecting one image file name");
4214 filename
= argv
[argc
- 1];
4216 if (!is_write
&& flush_interval
) {
4217 error_report("--flush-interval is only available in write tests");
4221 if (flush_interval
&& flush_interval
< depth
) {
4222 error_report("Flush interval can't be smaller than depth");
4227 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4234 image_size
= blk_getlength(blk
);
4235 if (image_size
< 0) {
4240 data
= (BenchData
) {
4242 .image_size
= image_size
,
4244 .step
= step
?: bufsize
,
4249 .flush_interval
= flush_interval
,
4250 .drain_on_flush
= drain_on_flush
,
4252 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4253 "(starting at offset %" PRId64
", step size %d)\n",
4254 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4255 data
.offset
, data
.step
);
4256 if (flush_interval
) {
4257 printf("Sending flush every %d requests\n", flush_interval
);
4260 buf_size
= data
.nrreq
* data
.bufsize
;
4261 data
.buf
= blk_blockalign(blk
, buf_size
);
4262 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4264 blk_register_buf(blk
, data
.buf
, buf_size
);
4266 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4267 for (i
= 0; i
< data
.nrreq
; i
++) {
4268 qemu_iovec_init(&data
.qiov
[i
], 1);
4269 qemu_iovec_add(&data
.qiov
[i
],
4270 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4273 gettimeofday(&t1
, NULL
);
4276 while (data
.n
> 0) {
4277 main_loop_wait(false);
4279 gettimeofday(&t2
, NULL
);
4281 printf("Run completed in %3.3f seconds.\n",
4282 (t2
.tv_sec
- t1
.tv_sec
)
4283 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4287 blk_unregister_buf(blk
, data
.buf
);
4289 qemu_vfree(data
.buf
);
4310 int bsz
; /* Block size */
4318 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4322 static int img_dd_bs(const char *arg
,
4323 struct DdIo
*in
, struct DdIo
*out
,
4330 if (res
<= 0 || res
> INT_MAX
) {
4331 error_report("invalid number: '%s'", arg
);
4334 in
->bsz
= out
->bsz
= res
;
4339 static int img_dd_count(const char *arg
,
4340 struct DdIo
*in
, struct DdIo
*out
,
4343 dd
->count
= cvtnum(arg
);
4345 if (dd
->count
< 0) {
4346 error_report("invalid number: '%s'", arg
);
4353 static int img_dd_if(const char *arg
,
4354 struct DdIo
*in
, struct DdIo
*out
,
4357 in
->filename
= g_strdup(arg
);
4362 static int img_dd_of(const char *arg
,
4363 struct DdIo
*in
, struct DdIo
*out
,
4366 out
->filename
= g_strdup(arg
);
4371 static int img_dd_skip(const char *arg
,
4372 struct DdIo
*in
, struct DdIo
*out
,
4375 in
->offset
= cvtnum(arg
);
4377 if (in
->offset
< 0) {
4378 error_report("invalid number: '%s'", arg
);
4385 static int img_dd(int argc
, char **argv
)
4390 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4391 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4392 QemuOpts
*opts
= NULL
;
4393 QemuOptsList
*create_opts
= NULL
;
4394 Error
*local_err
= NULL
;
4395 bool image_opts
= false;
4397 const char *out_fmt
= "raw";
4398 const char *fmt
= NULL
;
4400 int64_t block_count
= 0, out_pos
, in_pos
;
4401 bool force_share
= false;
4402 struct DdInfo dd
= {
4407 .bsz
= 512, /* Block size is by default 512 bytes */
4419 const struct DdOpts options
[] = {
4420 { "bs", img_dd_bs
, C_BS
},
4421 { "count", img_dd_count
, C_COUNT
},
4422 { "if", img_dd_if
, C_IF
},
4423 { "of", img_dd_of
, C_OF
},
4424 { "skip", img_dd_skip
, C_SKIP
},
4427 const struct option long_options
[] = {
4428 { "help", no_argument
, 0, 'h'},
4429 { "object", required_argument
, 0, OPTION_OBJECT
},
4430 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4431 { "force-share", no_argument
, 0, 'U'},
4435 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4447 missing_argument(argv
[optind
- 1]);
4450 unrecognized_option(argv
[optind
- 1]);
4459 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4464 case OPTION_IMAGE_OPTS
:
4470 for (i
= optind
; i
< argc
; i
++) {
4472 arg
= g_strdup(argv
[i
]);
4474 tmp
= strchr(arg
, '=');
4476 error_report("unrecognized operand %s", arg
);
4483 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4484 if (!strcmp(arg
, options
[j
].name
)) {
4488 if (options
[j
].name
== NULL
) {
4489 error_report("unrecognized operand %s", arg
);
4494 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4498 dd
.flags
|= options
[j
].flag
;
4503 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4504 error_report("Must specify both input and output files");
4509 if (qemu_opts_foreach(&qemu_object_opts
,
4510 user_creatable_add_opts_foreach
,
4516 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4524 drv
= bdrv_find_format(out_fmt
);
4526 error_report("Unknown file format");
4530 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4533 error_report_err(local_err
);
4537 if (!drv
->create_opts
) {
4538 error_report("Format driver '%s' does not support image creation",
4543 if (!proto_drv
->create_opts
) {
4544 error_report("Protocol driver '%s' does not support image creation",
4545 proto_drv
->format_name
);
4549 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4550 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4552 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4554 size
= blk_getlength(blk1
);
4556 error_report("Failed to get size for '%s'", in
.filename
);
4561 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4562 dd
.count
* in
.bsz
< size
) {
4563 size
= dd
.count
* in
.bsz
;
4566 /* Overflow means the specified offset is beyond input image's size */
4567 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4568 size
< in
.bsz
* in
.offset
)) {
4569 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4571 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4572 size
- in
.bsz
* in
.offset
, &error_abort
);
4575 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4577 error_reportf_err(local_err
,
4578 "%s: error while creating output image: ",
4584 /* TODO, we can't honour --image-opts for the target,
4585 * since it needs to be given in a format compatible
4586 * with the bdrv_create() call above which does not
4587 * support image-opts style.
4589 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
4590 false, false, false);
4597 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4598 size
< in
.offset
* in
.bsz
)) {
4599 /* We give a warning if the skip option is bigger than the input
4600 * size and create an empty output disk image (i.e. like dd(1)).
4602 error_report("%s: cannot skip to specified offset", in
.filename
);
4605 in_pos
= in
.offset
* in
.bsz
;
4608 in
.buf
= g_new(uint8_t, in
.bsz
);
4610 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4611 int in_ret
, out_ret
;
4613 if (in_pos
+ in
.bsz
> size
) {
4614 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4616 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4619 error_report("error while reading from input image file: %s",
4626 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4629 error_report("error while writing to output image file: %s",
4630 strerror(-out_ret
));
4639 qemu_opts_del(opts
);
4640 qemu_opts_free(create_opts
);
4643 g_free(in
.filename
);
4644 g_free(out
.filename
);
4654 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
4658 Visitor
*v
= qobject_output_visitor_new(&obj
);
4660 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
4661 visit_complete(v
, &obj
);
4662 str
= qobject_to_json_pretty(obj
);
4663 assert(str
!= NULL
);
4664 printf("%s\n", qstring_get_str(str
));
4670 static int img_measure(int argc
, char **argv
)
4672 static const struct option long_options
[] = {
4673 {"help", no_argument
, 0, 'h'},
4674 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4675 {"object", required_argument
, 0, OPTION_OBJECT
},
4676 {"output", required_argument
, 0, OPTION_OUTPUT
},
4677 {"size", required_argument
, 0, OPTION_SIZE
},
4678 {"force-share", no_argument
, 0, 'U'},
4681 OutputFormat output_format
= OFORMAT_HUMAN
;
4682 BlockBackend
*in_blk
= NULL
;
4684 const char *filename
= NULL
;
4685 const char *fmt
= NULL
;
4686 const char *out_fmt
= "raw";
4687 char *options
= NULL
;
4688 char *snapshot_name
= NULL
;
4689 bool force_share
= false;
4690 QemuOpts
*opts
= NULL
;
4691 QemuOpts
*object_opts
= NULL
;
4692 QemuOpts
*sn_opts
= NULL
;
4693 QemuOptsList
*create_opts
= NULL
;
4694 bool image_opts
= false;
4695 uint64_t img_size
= UINT64_MAX
;
4696 BlockMeasureInfo
*info
= NULL
;
4697 Error
*local_err
= NULL
;
4701 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
4702 long_options
, NULL
)) != -1) {
4715 if (!is_valid_option_list(optarg
)) {
4716 error_report("Invalid option list: %s", optarg
);
4720 options
= g_strdup(optarg
);
4722 char *old_options
= options
;
4723 options
= g_strdup_printf("%s,%s", options
, optarg
);
4724 g_free(old_options
);
4728 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
4729 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
4732 error_report("Failed in parsing snapshot param '%s'",
4737 snapshot_name
= optarg
;
4744 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4750 case OPTION_IMAGE_OPTS
:
4754 if (!strcmp(optarg
, "json")) {
4755 output_format
= OFORMAT_JSON
;
4756 } else if (!strcmp(optarg
, "human")) {
4757 output_format
= OFORMAT_HUMAN
;
4759 error_report("--output must be used with human or json "
4768 sval
= cvtnum(optarg
);
4770 if (sval
== -ERANGE
) {
4771 error_report("Image size must be less than 8 EiB!");
4773 error_report("Invalid image size specified! You may use "
4774 "k, M, G, T, P or E suffixes for ");
4775 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4776 "petabytes and exabytes.");
4780 img_size
= (uint64_t)sval
;
4786 if (qemu_opts_foreach(&qemu_object_opts
,
4787 user_creatable_add_opts_foreach
,
4792 if (argc
- optind
> 1) {
4793 error_report("At most one filename argument is allowed.");
4795 } else if (argc
- optind
== 1) {
4796 filename
= argv
[optind
];
4800 (object_opts
|| image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
4801 error_report("--object, --image-opts, -f, and -l "
4802 "require a filename argument.");
4805 if (filename
&& img_size
!= UINT64_MAX
) {
4806 error_report("--size N cannot be used together with a filename.");
4809 if (!filename
&& img_size
== UINT64_MAX
) {
4810 error_report("Either --size N or one filename must be specified.");
4815 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
4816 false, false, force_share
);
4822 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
4823 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
4824 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
4826 } else if (snapshot_name
!= NULL
) {
4827 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
4828 snapshot_name
, &local_err
);
4831 error_reportf_err(local_err
, "Failed to load snapshot: ");
4836 drv
= bdrv_find_format(out_fmt
);
4838 error_report("Unknown file format '%s'", out_fmt
);
4841 if (!drv
->create_opts
) {
4842 error_report("Format driver '%s' does not support image creation",
4847 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4848 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
4849 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4851 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
4853 error_report_err(local_err
);
4854 error_report("Invalid options for file format '%s'", out_fmt
);
4858 if (img_size
!= UINT64_MAX
) {
4859 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
4862 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
4864 error_report_err(local_err
);
4868 if (output_format
== OFORMAT_HUMAN
) {
4869 printf("required size: %" PRIu64
"\n", info
->required
);
4870 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
4872 dump_json_block_measure_info(info
);
4878 qapi_free_BlockMeasureInfo(info
);
4879 qemu_opts_del(object_opts
);
4880 qemu_opts_del(opts
);
4881 qemu_opts_del(sn_opts
);
4882 qemu_opts_free(create_opts
);
4888 static const img_cmd_t img_cmds
[] = {
4889 #define DEF(option, callback, arg_string) \
4890 { option, callback },
4891 #include "qemu-img-cmds.h"
4896 int main(int argc
, char **argv
)
4898 const img_cmd_t
*cmd
;
4899 const char *cmdname
;
4900 Error
*local_error
= NULL
;
4901 char *trace_file
= NULL
;
4903 static const struct option long_options
[] = {
4904 {"help", no_argument
, 0, 'h'},
4905 {"version", no_argument
, 0, 'V'},
4906 {"trace", required_argument
, NULL
, 'T'},
4911 signal(SIGPIPE
, SIG_IGN
);
4914 module_call_init(MODULE_INIT_TRACE
);
4915 error_set_progname(argv
[0]);
4916 qemu_init_exec_dir(argv
[0]);
4918 if (qemu_init_main_loop(&local_error
)) {
4919 error_report_err(local_error
);
4923 qcrypto_init(&error_fatal
);
4925 module_call_init(MODULE_INIT_QOM
);
4928 error_exit("Not enough arguments");
4931 qemu_add_opts(&qemu_object_opts
);
4932 qemu_add_opts(&qemu_source_opts
);
4933 qemu_add_opts(&qemu_trace_opts
);
4935 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
4938 missing_argument(argv
[optind
- 1]);
4941 unrecognized_option(argv
[optind
- 1]);
4947 printf(QEMU_IMG_VERSION
);
4951 trace_file
= trace_opt_parse(optarg
);
4956 cmdname
= argv
[optind
];
4958 /* reset getopt_long scanning */
4966 if (!trace_init_backends()) {
4969 trace_init_file(trace_file
);
4970 qemu_set_log(LOG_TRACE
);
4972 /* find the command */
4973 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
4974 if (!strcmp(cmdname
, cmd
->name
)) {
4975 return cmd
->handler(argc
, argv
);
4980 error_exit("Command not found: %s", cmdname
);