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
);
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");
1032 run_block_job(job
, &local_err
);
1037 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1038 ret
= bs
->drv
->bdrv_make_empty(bs
);
1040 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1052 qemu_progress_end();
1057 error_report_err(local_err
);
1061 qprintf(quiet
, "Image committed.\n");
1066 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1067 * of the first sector boundary within buf where the sector contains a
1068 * non-zero byte. This function is robust to a buffer that is not
1071 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1074 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1076 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1077 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1081 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1088 * Returns true iff the first sector pointed to by 'buf' contains at least
1091 * 'pnum' is set to the number of sectors (including and immediately following
1092 * the first one) that are known to be in the same allocated/unallocated state.
1093 * The function will try to align the end offset to alignment boundaries so
1094 * that the request will at least end aligned and consequtive requests will
1095 * also start at an aligned offset.
1097 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1098 int64_t sector_num
, int alignment
)
1107 is_zero
= buffer_is_zero(buf
, 512);
1108 for(i
= 1; i
< n
; i
++) {
1110 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1115 tail
= (sector_num
+ i
) & (alignment
- 1);
1117 if (is_zero
&& i
<= tail
) {
1118 /* treat unallocated areas which only consist
1119 * of a small tail as allocated. */
1123 /* align up end offset of allocated areas. */
1124 i
+= alignment
- tail
;
1127 /* align down end offset of zero areas. */
1136 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1137 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1138 * breaking up write requests for only small sparse areas.
1140 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1141 int min
, int64_t sector_num
, int alignment
)
1144 int num_checked
, num_used
;
1150 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1156 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1158 sector_num
+= *pnum
;
1159 num_checked
= num_used
;
1162 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1164 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1166 sector_num
+= *pnum
;
1167 num_checked
+= *pnum
;
1169 num_used
= num_checked
;
1170 } else if (*pnum
>= min
) {
1180 * Compares two buffers sector by sector. Returns 0 if the first
1181 * sector of each buffer matches, non-zero otherwise.
1183 * pnum is set to the sector-aligned size of the buffer prefix that
1184 * has the same matching status as the first sector.
1186 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1187 int64_t bytes
, int64_t *pnum
)
1190 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1194 res
= !!memcmp(buf1
, buf2
, i
);
1196 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1198 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1208 #define IO_BUF_SIZE (2 * 1024 * 1024)
1211 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1213 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1214 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1215 * failure), and 4 on error (the exit status for read errors), after emitting
1218 * @param blk: BlockBackend for the image
1219 * @param offset: Starting offset to check
1220 * @param bytes: Number of bytes to check
1221 * @param filename: Name of disk file we are checking (logging purpose)
1222 * @param buffer: Allocated buffer for storing read data
1223 * @param quiet: Flag for quiet mode
1225 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1226 int64_t bytes
, const char *filename
,
1227 uint8_t *buffer
, bool quiet
)
1232 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1234 error_report("Error while reading offset %" PRId64
" of %s: %s",
1235 offset
, filename
, strerror(-ret
));
1238 idx
= find_nonzero(buffer
, bytes
);
1240 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1249 * Compares two images. Exit codes:
1251 * 0 - Images are identical
1253 * >1 - Error occurred
1255 static int img_compare(int argc
, char **argv
)
1257 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1258 BlockBackend
*blk1
, *blk2
;
1259 BlockDriverState
*bs1
, *bs2
;
1260 int64_t total_size1
, total_size2
;
1261 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1262 int64_t pnum1
, pnum2
;
1263 int allocated1
, allocated2
;
1264 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1265 bool progress
= false, quiet
= false, strict
= false;
1272 uint64_t progress_base
;
1273 bool image_opts
= false;
1274 bool force_share
= false;
1276 cache
= BDRV_DEFAULT_CACHE
;
1278 static const struct option long_options
[] = {
1279 {"help", no_argument
, 0, 'h'},
1280 {"object", required_argument
, 0, OPTION_OBJECT
},
1281 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1282 {"force-share", no_argument
, 0, 'U'},
1285 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1286 long_options
, NULL
);
1292 missing_argument(argv
[optind
- 1]);
1295 unrecognized_option(argv
[optind
- 1]);
1321 case OPTION_OBJECT
: {
1323 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1330 case OPTION_IMAGE_OPTS
:
1336 /* Progress is not shown in Quiet mode */
1342 if (optind
!= argc
- 2) {
1343 error_exit("Expecting two image file names");
1345 filename1
= argv
[optind
++];
1346 filename2
= argv
[optind
++];
1348 if (qemu_opts_foreach(&qemu_object_opts
,
1349 user_creatable_add_opts_foreach
,
1355 /* Initialize before goto out */
1356 qemu_progress_init(progress
, 2.0);
1359 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1361 error_report("Invalid source cache option: %s", cache
);
1366 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1373 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1382 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1383 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1384 total_size1
= blk_getlength(blk1
);
1385 if (total_size1
< 0) {
1386 error_report("Can't get size of %s: %s",
1387 filename1
, strerror(-total_size1
));
1391 total_size2
= blk_getlength(blk2
);
1392 if (total_size2
< 0) {
1393 error_report("Can't get size of %s: %s",
1394 filename2
, strerror(-total_size2
));
1398 total_size
= MIN(total_size1
, total_size2
);
1399 progress_base
= MAX(total_size1
, total_size2
);
1401 qemu_progress_print(0, 100);
1403 if (strict
&& total_size1
!= total_size2
) {
1405 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1409 while (offset
< total_size
) {
1410 int status1
, status2
;
1412 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1413 total_size1
- offset
, &pnum1
, NULL
,
1417 error_report("Sector allocation test failed for %s", filename1
);
1420 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1422 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1423 total_size2
- offset
, &pnum2
, NULL
,
1427 error_report("Sector allocation test failed for %s", filename2
);
1430 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1432 assert(pnum1
&& pnum2
);
1433 chunk
= MIN(pnum1
, pnum2
);
1436 if (status1
!= status2
) {
1438 qprintf(quiet
, "Strict mode: Offset %" PRId64
1439 " block status mismatch!\n", offset
);
1443 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1445 } else if (allocated1
== allocated2
) {
1449 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1450 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1452 error_report("Error while reading offset %" PRId64
1454 offset
, filename1
, strerror(-ret
));
1458 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1460 error_report("Error while reading offset %" PRId64
1462 offset
, filename2
, strerror(-ret
));
1466 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1467 if (ret
|| pnum
!= chunk
) {
1468 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1469 offset
+ (ret
? 0 : pnum
));
1475 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1477 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1478 filename1
, buf1
, quiet
);
1480 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1481 filename2
, buf1
, quiet
);
1488 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1491 if (total_size1
!= total_size2
) {
1492 BlockBackend
*blk_over
;
1493 const char *filename_over
;
1495 qprintf(quiet
, "Warning: Image size mismatch!\n");
1496 if (total_size1
> total_size2
) {
1498 filename_over
= filename1
;
1501 filename_over
= filename2
;
1504 while (offset
< progress_base
) {
1505 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1506 progress_base
- offset
, &chunk
,
1510 error_report("Sector allocation test failed for %s",
1515 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1516 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1517 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1518 filename_over
, buf1
, quiet
);
1524 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1528 qprintf(quiet
, "Images are identical.\n");
1538 qemu_progress_end();
1543 enum ImgConvertBlockStatus
{
1549 #define MAX_COROUTINES 16
1551 typedef struct ImgConvertState
{
1553 int64_t *src_sectors
;
1555 int64_t total_sectors
;
1556 int64_t allocated_sectors
;
1557 int64_t allocated_done
;
1560 enum ImgConvertBlockStatus status
;
1561 int64_t sector_next_status
;
1562 BlockBackend
*target
;
1565 bool unallocated_blocks_are_zero
;
1566 bool target_has_backing
;
1567 int64_t target_backing_sectors
; /* negative if unknown */
1572 size_t cluster_sectors
;
1574 long num_coroutines
;
1575 int running_coroutines
;
1576 Coroutine
*co
[MAX_COROUTINES
];
1577 int64_t wait_sector_num
[MAX_COROUTINES
];
1582 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1583 int *src_cur
, int64_t *src_cur_offset
)
1586 *src_cur_offset
= 0;
1587 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1588 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1590 assert(*src_cur
< s
->src_num
);
1594 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1596 int64_t src_cur_offset
;
1597 int ret
, n
, src_cur
;
1598 bool post_backing_zero
= false;
1600 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1602 assert(s
->total_sectors
> sector_num
);
1603 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1605 if (s
->target_backing_sectors
>= 0) {
1606 if (sector_num
>= s
->target_backing_sectors
) {
1607 post_backing_zero
= s
->unallocated_blocks_are_zero
;
1608 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1609 /* Split requests around target_backing_sectors (because
1610 * starting from there, zeros are handled differently) */
1611 n
= s
->target_backing_sectors
- sector_num
;
1615 if (s
->sector_next_status
<= sector_num
) {
1616 int64_t count
= n
* BDRV_SECTOR_SIZE
;
1618 if (s
->target_has_backing
) {
1620 ret
= bdrv_block_status(blk_bs(s
->src
[src_cur
]),
1621 (sector_num
- src_cur_offset
) *
1623 count
, &count
, NULL
, NULL
);
1625 ret
= bdrv_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1626 (sector_num
- src_cur_offset
) *
1628 count
, &count
, NULL
, NULL
);
1633 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1635 if (ret
& BDRV_BLOCK_ZERO
) {
1636 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1637 } else if (ret
& BDRV_BLOCK_DATA
) {
1638 s
->status
= BLK_DATA
;
1640 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1643 s
->sector_next_status
= sector_num
+ n
;
1646 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1647 if (s
->status
== BLK_DATA
) {
1648 n
= MIN(n
, s
->buf_sectors
);
1651 /* We need to write complete clusters for compressed images, so if an
1652 * unallocated area is shorter than that, we must consider the whole
1653 * cluster allocated. */
1654 if (s
->compressed
) {
1655 if (n
< s
->cluster_sectors
) {
1656 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1657 s
->status
= BLK_DATA
;
1659 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1666 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1667 int nb_sectors
, uint8_t *buf
)
1673 assert(nb_sectors
<= s
->buf_sectors
);
1674 while (nb_sectors
> 0) {
1677 int64_t bs_sectors
, src_cur_offset
;
1679 /* In the case of compression with multiple source files, we can get a
1680 * nb_sectors that spreads into the next part. So we must be able to
1681 * read across multiple BDSes for one convert_read() call. */
1682 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1683 blk
= s
->src
[src_cur
];
1684 bs_sectors
= s
->src_sectors
[src_cur
];
1686 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1688 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1689 qemu_iovec_init_external(&qiov
, &iov
, 1);
1691 ret
= blk_co_preadv(
1692 blk
, (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
,
1693 n
<< BDRV_SECTOR_BITS
, &qiov
, 0);
1700 buf
+= n
* BDRV_SECTOR_SIZE
;
1707 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1708 int nb_sectors
, uint8_t *buf
,
1709 enum ImgConvertBlockStatus status
)
1715 while (nb_sectors
> 0) {
1717 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1720 case BLK_BACKING_FILE
:
1721 /* If we have a backing file, leave clusters unallocated that are
1722 * unallocated in the source image, so that the backing file is
1723 * visible at the respective offset. */
1724 assert(s
->target_has_backing
);
1728 /* If we're told to keep the target fully allocated (-S 0) or there
1729 * is real non-zero data, we must write it. Otherwise we can treat
1730 * it as zero sectors.
1731 * Compressed clusters need to be written as a whole, so in that
1732 * case we can only save the write if the buffer is completely
1734 if (!s
->min_sparse
||
1736 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1737 sector_num
, s
->alignment
)) ||
1739 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1742 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1743 qemu_iovec_init_external(&qiov
, &iov
, 1);
1745 ret
= blk_co_pwritev(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1746 n
<< BDRV_SECTOR_BITS
, &qiov
, flags
);
1755 if (s
->has_zero_init
) {
1756 assert(!s
->target_has_backing
);
1759 ret
= blk_co_pwrite_zeroes(s
->target
,
1760 sector_num
<< BDRV_SECTOR_BITS
,
1761 n
<< BDRV_SECTOR_BITS
, 0);
1770 buf
+= n
* BDRV_SECTOR_SIZE
;
1776 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1781 while (nb_sectors
> 0) {
1784 int64_t bs_sectors
, src_cur_offset
;
1787 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1788 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1789 blk
= s
->src
[src_cur
];
1790 bs_sectors
= s
->src_sectors
[src_cur
];
1792 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1794 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1795 sector_num
<< BDRV_SECTOR_BITS
,
1796 n
<< BDRV_SECTOR_BITS
, 0, 0);
1807 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1809 ImgConvertState
*s
= opaque
;
1810 uint8_t *buf
= NULL
;
1814 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1815 if (s
->co
[i
] == qemu_coroutine_self()) {
1822 s
->running_coroutines
++;
1823 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1828 enum ImgConvertBlockStatus status
;
1831 qemu_co_mutex_lock(&s
->lock
);
1832 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1833 qemu_co_mutex_unlock(&s
->lock
);
1836 n
= convert_iteration_sectors(s
, s
->sector_num
);
1838 qemu_co_mutex_unlock(&s
->lock
);
1842 /* save current sector and allocation status to local variables */
1843 sector_num
= s
->sector_num
;
1845 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1846 n
= MIN(n
, s
->buf_sectors
);
1848 /* increment global sector counter so that other coroutines can
1849 * already continue reading beyond this request */
1851 qemu_co_mutex_unlock(&s
->lock
);
1853 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1854 s
->allocated_done
+= n
;
1855 qemu_progress_print(100.0 * s
->allocated_done
/
1856 s
->allocated_sectors
, 0);
1860 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
1861 if (status
== BLK_DATA
&& !copy_range
) {
1862 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1864 error_report("error while reading sector %" PRId64
1865 ": %s", sector_num
, strerror(-ret
));
1868 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1870 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1873 if (s
->wr_in_order
) {
1874 /* keep writes in order */
1875 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1876 s
->wait_sector_num
[index
] = sector_num
;
1877 qemu_coroutine_yield();
1879 s
->wait_sector_num
[index
] = -1;
1882 if (s
->ret
== -EINPROGRESS
) {
1884 ret
= convert_co_copy_range(s
, sector_num
, n
);
1886 s
->copy_range
= false;
1890 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1893 error_report("error while writing sector %" PRId64
1894 ": %s", sector_num
, strerror(-ret
));
1899 if (s
->wr_in_order
) {
1900 /* reenter the coroutine that might have waited
1901 * for this write to complete */
1902 s
->wr_offs
= sector_num
+ n
;
1903 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1904 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1906 * A -> B -> A cannot occur because A has
1907 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1908 * B will never enter A during this time window.
1910 qemu_coroutine_enter(s
->co
[i
]);
1918 s
->co
[index
] = NULL
;
1919 s
->running_coroutines
--;
1920 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1921 /* the convert job finished successfully */
1926 static int convert_do_copy(ImgConvertState
*s
)
1929 int64_t sector_num
= 0;
1931 /* Check whether we have zero initialisation or can get it efficiently */
1932 s
->has_zero_init
= s
->min_sparse
&& !s
->target_has_backing
1933 ? bdrv_has_zero_init(blk_bs(s
->target
))
1936 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1937 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1939 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
);
1941 s
->has_zero_init
= true;
1945 /* Allocate buffer for copied data. For compressed images, only one cluster
1946 * can be copied at a time. */
1947 if (s
->compressed
) {
1948 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
1949 error_report("invalid cluster size");
1952 s
->buf_sectors
= s
->cluster_sectors
;
1955 while (sector_num
< s
->total_sectors
) {
1956 n
= convert_iteration_sectors(s
, sector_num
);
1960 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1962 s
->allocated_sectors
+= n
;
1968 s
->sector_next_status
= 0;
1969 s
->ret
= -EINPROGRESS
;
1971 qemu_co_mutex_init(&s
->lock
);
1972 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1973 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
1974 s
->wait_sector_num
[i
] = -1;
1975 qemu_coroutine_enter(s
->co
[i
]);
1978 while (s
->running_coroutines
) {
1979 main_loop_wait(false);
1982 if (s
->compressed
&& !s
->ret
) {
1983 /* signal EOF to align */
1984 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
1993 #define MAX_BUF_SECTORS 32768
1995 static int img_convert(int argc
, char **argv
)
1997 int c
, bs_i
, flags
, src_flags
= 0;
1998 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
1999 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2000 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
2001 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2002 BlockDriverInfo bdi
;
2003 BlockDriverState
*out_bs
;
2004 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2005 QemuOptsList
*create_opts
= NULL
;
2006 QDict
*open_opts
= NULL
;
2007 char *options
= NULL
;
2008 Error
*local_err
= NULL
;
2009 bool writethrough
, src_writethrough
, quiet
= false, image_opts
= false,
2010 skip_create
= false, progress
= false, tgt_image_opts
= false;
2011 int64_t ret
= -EINVAL
;
2012 bool force_share
= false;
2013 bool explict_min_sparse
= false;
2015 ImgConvertState s
= (ImgConvertState
) {
2016 /* Need at least 4k of zeros for sparse detection */
2018 .copy_range
= false,
2019 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2020 .wr_in_order
= true,
2021 .num_coroutines
= 8,
2025 static const struct option long_options
[] = {
2026 {"help", no_argument
, 0, 'h'},
2027 {"object", required_argument
, 0, OPTION_OBJECT
},
2028 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2029 {"force-share", no_argument
, 0, 'U'},
2030 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2033 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2034 long_options
, NULL
);
2040 missing_argument(argv
[optind
- 1]);
2043 unrecognized_option(argv
[optind
- 1]);
2055 out_baseimg
= optarg
;
2058 s
.copy_range
= true;
2061 s
.compressed
= true;
2064 if (!is_valid_option_list(optarg
)) {
2065 error_report("Invalid option list: %s", optarg
);
2069 options
= g_strdup(optarg
);
2071 char *old_options
= options
;
2072 options
= g_strdup_printf("%s,%s", options
, optarg
);
2073 g_free(old_options
);
2077 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2078 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2081 error_report("Failed in parsing snapshot param '%s'",
2086 snapshot_name
= optarg
;
2093 sval
= cvtnum(optarg
);
2094 if (sval
< 0 || sval
& (BDRV_SECTOR_SIZE
- 1) ||
2095 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2096 error_report("Invalid buffer size for sparse output specified. "
2097 "Valid sizes are multiples of %llu up to %llu. Select "
2098 "0 to disable sparse detection (fully allocates output).",
2099 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2103 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2104 explict_min_sparse
= true;
2123 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2124 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2125 error_report("Invalid number of coroutines. Allowed number of"
2126 " coroutines is between 1 and %d", MAX_COROUTINES
);
2131 s
.wr_in_order
= false;
2136 case OPTION_OBJECT
: {
2137 QemuOpts
*object_opts
;
2138 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2145 case OPTION_IMAGE_OPTS
:
2148 case OPTION_TARGET_IMAGE_OPTS
:
2149 tgt_image_opts
= true;
2154 if (!out_fmt
&& !tgt_image_opts
) {
2158 if (qemu_opts_foreach(&qemu_object_opts
,
2159 user_creatable_add_opts_foreach
,
2164 if (s
.compressed
&& s
.copy_range
) {
2165 error_report("Cannot enable copy offloading when -c is used");
2169 if (explict_min_sparse
&& s
.copy_range
) {
2170 error_report("Cannot enable copy offloading when -S is used");
2174 if (tgt_image_opts
&& !skip_create
) {
2175 error_report("--target-image-opts requires use of -n flag");
2179 s
.src_num
= argc
- optind
- 1;
2180 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2182 if (options
&& has_help_option(options
)) {
2184 ret
= print_block_option_help(out_filename
, out_fmt
);
2187 error_report("Option help requires a format be specified");
2192 if (s
.src_num
< 1) {
2193 error_report("Must specify image file name");
2198 /* ret is still -EINVAL until here */
2199 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2201 error_report("Invalid source cache option: %s", src_cache
);
2205 /* Initialize before goto out */
2209 qemu_progress_init(progress
, 1.0);
2210 qemu_progress_print(0, 100);
2212 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2213 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2215 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2216 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2217 fmt
, src_flags
, src_writethrough
, quiet
,
2223 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2224 if (s
.src_sectors
[bs_i
] < 0) {
2225 error_report("Could not get size of %s: %s",
2226 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2230 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2234 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2235 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2236 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2238 } else if (snapshot_name
!= NULL
) {
2239 if (s
.src_num
> 1) {
2240 error_report("No support for concatenating multiple snapshot");
2245 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2249 error_reportf_err(local_err
, "Failed to load snapshot: ");
2255 /* Find driver and parse its options */
2256 drv
= bdrv_find_format(out_fmt
);
2258 error_report("Unknown file format '%s'", out_fmt
);
2263 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2265 error_report_err(local_err
);
2270 if (!drv
->create_opts
) {
2271 error_report("Format driver '%s' does not support image creation",
2277 if (!proto_drv
->create_opts
) {
2278 error_report("Protocol driver '%s' does not support image creation",
2279 proto_drv
->format_name
);
2284 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2285 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2287 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2289 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2291 error_report_err(local_err
);
2297 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2299 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2305 /* Get backing file name if -o backing_file was used */
2306 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2307 if (out_baseimg_param
) {
2308 out_baseimg
= out_baseimg_param
;
2310 s
.target_has_backing
= (bool) out_baseimg
;
2312 if (s
.src_num
> 1 && out_baseimg
) {
2313 error_report("Having a backing file for the target makes no sense when "
2314 "concatenating multiple input images");
2319 /* Check if compression is supported */
2322 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2323 const char *encryptfmt
=
2324 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2325 const char *preallocation
=
2326 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2328 if (drv
&& !drv
->bdrv_co_pwritev_compressed
) {
2329 error_report("Compression not supported for this file format");
2334 if (encryption
|| encryptfmt
) {
2335 error_report("Compression and encryption not supported at "
2342 && strcmp(preallocation
, "off"))
2344 error_report("Compression and preallocation not supported at "
2352 * The later open call will need any decryption secrets, and
2353 * bdrv_create() will purge "opts", so extract them now before
2357 open_opts
= qdict_new();
2358 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2362 /* Create the new image */
2363 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2365 error_reportf_err(local_err
, "%s: error while converting %s: ",
2366 out_filename
, out_fmt
);
2371 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2372 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2374 error_report("Invalid cache option: %s", cache
);
2379 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2380 flags
, writethrough
, quiet
, false);
2382 /* TODO ultimately we should allow --target-image-opts
2383 * to be used even when -n is not given.
2384 * That has to wait for bdrv_create to be improved
2385 * to allow filenames in option syntax
2387 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2388 flags
, writethrough
, quiet
, false);
2389 open_opts
= NULL
; /* blk_new_open will have freed it */
2395 out_bs
= blk_bs(s
.target
);
2397 if (s
.compressed
&& !out_bs
->drv
->bdrv_co_pwritev_compressed
) {
2398 error_report("Compression not supported for this file format");
2403 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2404 * or discard_alignment of the out_bs is greater. Limit to
2405 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2406 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2408 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2409 out_bs
->bl
.pdiscard_alignment
>>
2410 BDRV_SECTOR_BITS
)));
2412 /* try to align the write requests to the destination to avoid unnecessary
2414 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2415 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2417 assert(is_power_of_2(s
.alignment
));
2420 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2421 if (output_sectors
< 0) {
2422 error_report("unable to get output image length: %s",
2423 strerror(-output_sectors
));
2426 } else if (output_sectors
< s
.total_sectors
) {
2427 error_report("output file is smaller than input file");
2433 if (s
.target_has_backing
) {
2434 /* Errors are treated as "backing length unknown" (which means
2435 * s.target_backing_sectors has to be negative, which it will
2436 * be automatically). The backing file length is used only
2437 * for optimizations, so such a case is not fatal. */
2438 s
.target_backing_sectors
= bdrv_nb_sectors(out_bs
->backing
->bs
);
2440 s
.target_backing_sectors
= -1;
2443 ret
= bdrv_get_info(out_bs
, &bdi
);
2446 error_report("could not get block driver info");
2450 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2451 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2452 s
.unallocated_blocks_are_zero
= bdi
.unallocated_blocks_are_zero
;
2455 ret
= convert_do_copy(&s
);
2458 qemu_progress_print(100, 0);
2460 qemu_progress_end();
2461 qemu_opts_del(opts
);
2462 qemu_opts_free(create_opts
);
2463 qemu_opts_del(sn_opts
);
2464 qobject_unref(open_opts
);
2465 blk_unref(s
.target
);
2467 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2468 blk_unref(s
.src
[bs_i
]);
2472 g_free(s
.src_sectors
);
2480 static void dump_snapshots(BlockDriverState
*bs
)
2482 QEMUSnapshotInfo
*sn_tab
, *sn
;
2485 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2488 printf("Snapshot list:\n");
2489 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
2491 for(i
= 0; i
< nb_sns
; i
++) {
2493 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
2499 static void dump_json_image_info_list(ImageInfoList
*list
)
2503 Visitor
*v
= qobject_output_visitor_new(&obj
);
2505 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2506 visit_complete(v
, &obj
);
2507 str
= qobject_to_json_pretty(obj
);
2508 assert(str
!= NULL
);
2509 printf("%s\n", qstring_get_str(str
));
2515 static void dump_json_image_info(ImageInfo
*info
)
2519 Visitor
*v
= qobject_output_visitor_new(&obj
);
2521 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2522 visit_complete(v
, &obj
);
2523 str
= qobject_to_json_pretty(obj
);
2524 assert(str
!= NULL
);
2525 printf("%s\n", qstring_get_str(str
));
2531 static void dump_human_image_info_list(ImageInfoList
*list
)
2533 ImageInfoList
*elem
;
2536 for (elem
= list
; elem
; elem
= elem
->next
) {
2542 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
2546 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2548 return strcmp(a
, b
) == 0;
2552 * Open an image file chain and return an ImageInfoList
2554 * @filename: topmost image filename
2555 * @fmt: topmost image format (may be NULL to autodetect)
2556 * @chain: true - enumerate entire backing file chain
2557 * false - only topmost image file
2559 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2560 * image file. If there was an error a message will have been printed to
2563 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2564 const char *filename
,
2566 bool chain
, bool force_share
)
2568 ImageInfoList
*head
= NULL
;
2569 ImageInfoList
**last
= &head
;
2570 GHashTable
*filenames
;
2573 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2577 BlockDriverState
*bs
;
2579 ImageInfoList
*elem
;
2581 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2582 error_report("Backing file '%s' creates an infinite loop.",
2586 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2588 blk
= img_open(image_opts
, filename
, fmt
,
2589 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2596 bdrv_query_image_info(bs
, &info
, &err
);
2598 error_report_err(err
);
2603 elem
= g_new0(ImageInfoList
, 1);
2610 filename
= fmt
= NULL
;
2612 if (info
->has_full_backing_filename
) {
2613 filename
= info
->full_backing_filename
;
2614 } else if (info
->has_backing_filename
) {
2615 error_report("Could not determine absolute backing filename,"
2616 " but backing filename '%s' present",
2617 info
->backing_filename
);
2620 if (info
->has_backing_filename_format
) {
2621 fmt
= info
->backing_filename_format
;
2625 g_hash_table_destroy(filenames
);
2629 qapi_free_ImageInfoList(head
);
2630 g_hash_table_destroy(filenames
);
2634 static int img_info(int argc
, char **argv
)
2637 OutputFormat output_format
= OFORMAT_HUMAN
;
2639 const char *filename
, *fmt
, *output
;
2640 ImageInfoList
*list
;
2641 bool image_opts
= false;
2642 bool force_share
= false;
2647 int option_index
= 0;
2648 static const struct option long_options
[] = {
2649 {"help", no_argument
, 0, 'h'},
2650 {"format", required_argument
, 0, 'f'},
2651 {"output", required_argument
, 0, OPTION_OUTPUT
},
2652 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2653 {"object", required_argument
, 0, OPTION_OBJECT
},
2654 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2655 {"force-share", no_argument
, 0, 'U'},
2658 c
= getopt_long(argc
, argv
, ":f:hU",
2659 long_options
, &option_index
);
2665 missing_argument(argv
[optind
- 1]);
2668 unrecognized_option(argv
[optind
- 1]);
2682 case OPTION_BACKING_CHAIN
:
2685 case OPTION_OBJECT
: {
2687 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2693 case OPTION_IMAGE_OPTS
:
2698 if (optind
!= argc
- 1) {
2699 error_exit("Expecting one image file name");
2701 filename
= argv
[optind
++];
2703 if (output
&& !strcmp(output
, "json")) {
2704 output_format
= OFORMAT_JSON
;
2705 } else if (output
&& !strcmp(output
, "human")) {
2706 output_format
= OFORMAT_HUMAN
;
2707 } else if (output
) {
2708 error_report("--output must be used with human or json as argument.");
2712 if (qemu_opts_foreach(&qemu_object_opts
,
2713 user_creatable_add_opts_foreach
,
2718 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2724 switch (output_format
) {
2726 dump_human_image_info_list(list
);
2730 dump_json_image_info_list(list
);
2732 dump_json_image_info(list
->value
);
2737 qapi_free_ImageInfoList(list
);
2741 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2744 switch (output_format
) {
2746 if (e
->data
&& !e
->has_offset
) {
2747 error_report("File contains external, encrypted or compressed clusters.");
2750 if (e
->data
&& !e
->zero
) {
2751 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2752 e
->start
, e
->length
,
2753 e
->has_offset
? e
->offset
: 0,
2754 e
->has_filename
? e
->filename
: "");
2756 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2757 * Modify the flags here to allow more coalescing.
2759 if (next
&& (!next
->data
|| next
->zero
)) {
2765 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2766 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2767 (e
->start
== 0 ? "[" : ",\n"),
2768 e
->start
, e
->length
, e
->depth
,
2769 e
->zero
? "true" : "false",
2770 e
->data
? "true" : "false");
2771 if (e
->has_offset
) {
2772 printf(", \"offset\": %"PRId64
"", e
->offset
);
2783 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
2784 int64_t bytes
, MapEntry
*e
)
2788 BlockDriverState
*file
;
2792 /* As an optimization, we could cache the current range of unallocated
2793 * clusters in each file of the chain, and avoid querying the same
2799 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
2804 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2807 bs
= backing_bs(bs
);
2816 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2821 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2822 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2824 .has_offset
= has_offset
,
2826 .has_filename
= file
&& has_offset
,
2827 .filename
= file
&& has_offset
? file
->filename
: NULL
,
2833 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2835 if (curr
->length
== 0) {
2838 if (curr
->zero
!= next
->zero
||
2839 curr
->data
!= next
->data
||
2840 curr
->depth
!= next
->depth
||
2841 curr
->has_filename
!= next
->has_filename
||
2842 curr
->has_offset
!= next
->has_offset
) {
2845 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2848 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2854 static int img_map(int argc
, char **argv
)
2857 OutputFormat output_format
= OFORMAT_HUMAN
;
2859 BlockDriverState
*bs
;
2860 const char *filename
, *fmt
, *output
;
2862 MapEntry curr
= { .length
= 0 }, next
;
2864 bool image_opts
= false;
2865 bool force_share
= false;
2870 int option_index
= 0;
2871 static const struct option long_options
[] = {
2872 {"help", no_argument
, 0, 'h'},
2873 {"format", required_argument
, 0, 'f'},
2874 {"output", required_argument
, 0, OPTION_OUTPUT
},
2875 {"object", required_argument
, 0, OPTION_OBJECT
},
2876 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2877 {"force-share", no_argument
, 0, 'U'},
2880 c
= getopt_long(argc
, argv
, ":f:hU",
2881 long_options
, &option_index
);
2887 missing_argument(argv
[optind
- 1]);
2890 unrecognized_option(argv
[optind
- 1]);
2904 case OPTION_OBJECT
: {
2906 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2912 case OPTION_IMAGE_OPTS
:
2917 if (optind
!= argc
- 1) {
2918 error_exit("Expecting one image file name");
2920 filename
= argv
[optind
];
2922 if (output
&& !strcmp(output
, "json")) {
2923 output_format
= OFORMAT_JSON
;
2924 } else if (output
&& !strcmp(output
, "human")) {
2925 output_format
= OFORMAT_HUMAN
;
2926 } else if (output
) {
2927 error_report("--output must be used with human or json as argument.");
2931 if (qemu_opts_foreach(&qemu_object_opts
,
2932 user_creatable_add_opts_foreach
,
2937 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
2943 if (output_format
== OFORMAT_HUMAN
) {
2944 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2947 length
= blk_getlength(blk
);
2948 while (curr
.start
+ curr
.length
< length
) {
2949 int64_t offset
= curr
.start
+ curr
.length
;
2952 /* Probe up to 1 GiB at a time. */
2953 n
= MIN(1 << 30, length
- offset
);
2954 ret
= get_block_status(bs
, offset
, n
, &next
);
2957 error_report("Could not read file metadata: %s", strerror(-ret
));
2961 if (entry_mergeable(&curr
, &next
)) {
2962 curr
.length
+= next
.length
;
2966 if (curr
.length
> 0) {
2967 dump_map_entry(output_format
, &curr
, &next
);
2972 dump_map_entry(output_format
, &curr
, NULL
);
2979 #define SNAPSHOT_LIST 1
2980 #define SNAPSHOT_CREATE 2
2981 #define SNAPSHOT_APPLY 3
2982 #define SNAPSHOT_DELETE 4
2984 static int img_snapshot(int argc
, char **argv
)
2987 BlockDriverState
*bs
;
2988 QEMUSnapshotInfo sn
;
2989 char *filename
, *snapshot_name
= NULL
;
2990 int c
, ret
= 0, bdrv_oflags
;
2995 bool image_opts
= false;
2996 bool force_share
= false;
2998 bdrv_oflags
= BDRV_O_RDWR
;
2999 /* Parse commandline parameters */
3001 static const struct option long_options
[] = {
3002 {"help", no_argument
, 0, 'h'},
3003 {"object", required_argument
, 0, OPTION_OBJECT
},
3004 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3005 {"force-share", no_argument
, 0, 'U'},
3008 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3009 long_options
, NULL
);
3015 missing_argument(argv
[optind
- 1]);
3018 unrecognized_option(argv
[optind
- 1]);
3025 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3028 action
= SNAPSHOT_LIST
;
3029 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3033 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3036 action
= SNAPSHOT_APPLY
;
3037 snapshot_name
= optarg
;
3041 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3044 action
= SNAPSHOT_CREATE
;
3045 snapshot_name
= optarg
;
3049 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3052 action
= SNAPSHOT_DELETE
;
3053 snapshot_name
= optarg
;
3061 case OPTION_OBJECT
: {
3063 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3069 case OPTION_IMAGE_OPTS
:
3075 if (optind
!= argc
- 1) {
3076 error_exit("Expecting one image file name");
3078 filename
= argv
[optind
++];
3080 if (qemu_opts_foreach(&qemu_object_opts
,
3081 user_creatable_add_opts_foreach
,
3086 /* Open the image */
3087 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3094 /* Perform the requested action */
3100 case SNAPSHOT_CREATE
:
3101 memset(&sn
, 0, sizeof(sn
));
3102 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3104 qemu_gettimeofday(&tv
);
3105 sn
.date_sec
= tv
.tv_sec
;
3106 sn
.date_nsec
= tv
.tv_usec
* 1000;
3108 ret
= bdrv_snapshot_create(bs
, &sn
);
3110 error_report("Could not create snapshot '%s': %d (%s)",
3111 snapshot_name
, ret
, strerror(-ret
));
3115 case SNAPSHOT_APPLY
:
3116 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3118 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3123 case SNAPSHOT_DELETE
:
3124 bdrv_snapshot_delete_by_id_or_name(bs
, snapshot_name
, &err
);
3126 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3141 static int img_rebase(int argc
, char **argv
)
3143 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3144 uint8_t *buf_old
= NULL
;
3145 uint8_t *buf_new
= NULL
;
3146 BlockDriverState
*bs
= NULL
;
3148 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3149 int c
, flags
, src_flags
, ret
;
3150 bool writethrough
, src_writethrough
;
3152 bool force_share
= false;
3155 Error
*local_err
= NULL
;
3156 bool image_opts
= false;
3158 /* Parse commandline parameters */
3160 cache
= BDRV_DEFAULT_CACHE
;
3161 src_cache
= BDRV_DEFAULT_CACHE
;
3165 static const struct option long_options
[] = {
3166 {"help", no_argument
, 0, 'h'},
3167 {"object", required_argument
, 0, OPTION_OBJECT
},
3168 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3169 {"force-share", no_argument
, 0, 'U'},
3172 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3173 long_options
, NULL
);
3179 missing_argument(argv
[optind
- 1]);
3182 unrecognized_option(argv
[optind
- 1]);
3191 out_basefmt
= optarg
;
3194 out_baseimg
= optarg
;
3211 case OPTION_OBJECT
: {
3213 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3219 case OPTION_IMAGE_OPTS
:
3232 if (optind
!= argc
- 1) {
3233 error_exit("Expecting one image file name");
3235 if (!unsafe
&& !out_baseimg
) {
3236 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3238 filename
= argv
[optind
++];
3240 if (qemu_opts_foreach(&qemu_object_opts
,
3241 user_creatable_add_opts_foreach
,
3246 qemu_progress_init(progress
, 2.0);
3247 qemu_progress_print(0, 100);
3249 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3250 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3252 error_report("Invalid cache option: %s", cache
);
3257 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3259 error_report("Invalid source cache option: %s", src_cache
);
3263 /* The source files are opened read-only, don't care about WCE */
3264 assert((src_flags
& BDRV_O_RDWR
) == 0);
3265 (void) src_writethrough
;
3270 * Ignore the old backing file for unsafe rebase in case we want to correct
3271 * the reference to a renamed or moved backing file.
3273 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3281 if (out_basefmt
!= NULL
) {
3282 if (bdrv_find_format(out_basefmt
) == NULL
) {
3283 error_report("Invalid format name: '%s'", out_basefmt
);
3289 /* For safe rebasing we need to compare old and new backing file */
3291 char backing_name
[PATH_MAX
];
3292 QDict
*options
= NULL
;
3294 if (bs
->backing_format
[0] != '\0') {
3295 options
= qdict_new();
3296 qdict_put_str(options
, "driver", bs
->backing_format
);
3301 options
= qdict_new();
3303 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3305 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3306 blk_old_backing
= blk_new_open(backing_name
, NULL
,
3307 options
, src_flags
, &local_err
);
3308 if (!blk_old_backing
) {
3309 error_reportf_err(local_err
,
3310 "Could not open old backing file '%s': ",
3316 if (out_baseimg
[0]) {
3317 const char *overlay_filename
;
3318 char *out_real_path
;
3320 options
= qdict_new();
3322 qdict_put_str(options
, "driver", out_basefmt
);
3325 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3328 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3330 out_real_path
= g_malloc(PATH_MAX
);
3332 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3338 error_reportf_err(local_err
,
3339 "Could not resolve backing filename: ");
3341 g_free(out_real_path
);
3345 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3346 options
, src_flags
, &local_err
);
3347 g_free(out_real_path
);
3348 if (!blk_new_backing
) {
3349 error_reportf_err(local_err
,
3350 "Could not open new backing file '%s': ",
3359 * Check each unallocated cluster in the COW file. If it is unallocated,
3360 * accesses go to the backing file. We must therefore compare this cluster
3361 * in the old and new backing file, and if they differ we need to copy it
3362 * from the old backing file into the COW file.
3364 * If qemu-img crashes during this step, no harm is done. The content of
3365 * the image is the same as the original one at any time.
3369 int64_t old_backing_size
;
3370 int64_t new_backing_size
= 0;
3373 float local_progress
= 0;
3375 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3376 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3378 size
= blk_getlength(blk
);
3380 error_report("Could not get size of '%s': %s",
3381 filename
, strerror(-size
));
3385 old_backing_size
= blk_getlength(blk_old_backing
);
3386 if (old_backing_size
< 0) {
3387 char backing_name
[PATH_MAX
];
3389 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3390 error_report("Could not get size of '%s': %s",
3391 backing_name
, strerror(-old_backing_size
));
3395 if (blk_new_backing
) {
3396 new_backing_size
= blk_getlength(blk_new_backing
);
3397 if (new_backing_size
< 0) {
3398 error_report("Could not get size of '%s': %s",
3399 out_baseimg
, strerror(-new_backing_size
));
3406 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3409 for (offset
= 0; offset
< size
; offset
+= n
) {
3410 /* How many bytes can we handle with the next read? */
3411 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3413 /* If the cluster is allocated, we don't need to take action */
3414 ret
= bdrv_is_allocated(bs
, offset
, n
, &n
);
3416 error_report("error while reading image metadata: %s",
3425 * Read old and new backing file and take into consideration that
3426 * backing files may be smaller than the COW image.
3428 if (offset
>= old_backing_size
) {
3429 memset(buf_old
, 0, n
);
3431 if (offset
+ n
> old_backing_size
) {
3432 n
= old_backing_size
- offset
;
3435 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3437 error_report("error while reading from old backing file");
3442 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3443 memset(buf_new
, 0, n
);
3445 if (offset
+ n
> new_backing_size
) {
3446 n
= new_backing_size
- offset
;
3449 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3451 error_report("error while reading from new backing file");
3456 /* If they differ, we need to write to the COW file */
3457 uint64_t written
= 0;
3459 while (written
< n
) {
3462 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3463 n
- written
, &pnum
))
3465 ret
= blk_pwrite(blk
, offset
+ written
,
3466 buf_old
+ written
, pnum
, 0);
3468 error_report("Error while writing to COW image: %s",
3476 qemu_progress_print(local_progress
, 100);
3481 * Change the backing file. All clusters that are different from the old
3482 * backing file are overwritten in the COW file now, so the visible content
3483 * doesn't change when we switch the backing file.
3485 if (out_baseimg
&& *out_baseimg
) {
3486 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3488 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3491 if (ret
== -ENOSPC
) {
3492 error_report("Could not change the backing file to '%s': No "
3493 "space left in the file header", out_baseimg
);
3494 } else if (ret
< 0) {
3495 error_report("Could not change the backing file to '%s': %s",
3496 out_baseimg
, strerror(-ret
));
3499 qemu_progress_print(100, 0);
3501 * TODO At this point it is possible to check if any clusters that are
3502 * allocated in the COW file are the same in the backing file. If so, they
3503 * could be dropped from the COW file. Don't do this before switching the
3504 * backing file, in case of a crash this would lead to corruption.
3507 qemu_progress_end();
3510 blk_unref(blk_old_backing
);
3511 blk_unref(blk_new_backing
);
3513 qemu_vfree(buf_old
);
3514 qemu_vfree(buf_new
);
3523 static int img_resize(int argc
, char **argv
)
3526 int c
, ret
, relative
;
3527 const char *filename
, *fmt
, *size
;
3528 int64_t n
, total_size
, current_size
, new_size
;
3530 BlockBackend
*blk
= NULL
;
3531 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3534 static QemuOptsList resize_options
= {
3535 .name
= "resize_options",
3536 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3539 .name
= BLOCK_OPT_SIZE
,
3540 .type
= QEMU_OPT_SIZE
,
3541 .help
= "Virtual disk size"
3547 bool image_opts
= false;
3548 bool shrink
= false;
3550 /* Remove size from argv manually so that negative numbers are not treated
3551 * as options by getopt. */
3553 error_exit("Not enough arguments");
3557 size
= argv
[--argc
];
3559 /* Parse getopt arguments */
3562 static const struct option long_options
[] = {
3563 {"help", no_argument
, 0, 'h'},
3564 {"object", required_argument
, 0, OPTION_OBJECT
},
3565 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3566 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3567 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3570 c
= getopt_long(argc
, argv
, ":f:hq",
3571 long_options
, NULL
);
3577 missing_argument(argv
[optind
- 1]);
3580 unrecognized_option(argv
[optind
- 1]);
3591 case OPTION_OBJECT
: {
3593 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3599 case OPTION_IMAGE_OPTS
:
3602 case OPTION_PREALLOCATION
:
3603 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3604 PREALLOC_MODE__MAX
, NULL
);
3605 if (prealloc
== PREALLOC_MODE__MAX
) {
3606 error_report("Invalid preallocation mode '%s'", optarg
);
3615 if (optind
!= argc
- 1) {
3616 error_exit("Expecting image file name and size");
3618 filename
= argv
[optind
++];
3620 if (qemu_opts_foreach(&qemu_object_opts
,
3621 user_creatable_add_opts_foreach
,
3626 /* Choose grow, shrink, or absolute resize mode */
3642 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3643 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3645 error_report_err(err
);
3647 qemu_opts_del(param
);
3650 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3651 qemu_opts_del(param
);
3653 blk
= img_open(image_opts
, filename
, fmt
,
3654 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3661 current_size
= blk_getlength(blk
);
3662 if (current_size
< 0) {
3663 error_report("Failed to inquire current image length: %s",
3664 strerror(-current_size
));
3670 total_size
= current_size
+ n
* relative
;
3674 if (total_size
<= 0) {
3675 error_report("New image size must be positive");
3680 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3681 error_report("Preallocation can only be used for growing images");
3686 if (total_size
< current_size
&& !shrink
) {
3687 warn_report("Shrinking an image will delete all data beyond the "
3688 "shrunken image's end. Before performing such an "
3689 "operation, make sure there is no important data there.");
3691 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk
)), "raw") != 0) {
3693 "Use the --shrink option to perform a shrink operation.");
3697 warn_report("Using the --shrink option will suppress this message. "
3698 "Note that future versions of qemu-img may refuse to "
3699 "shrink images without this option.");
3703 ret
= blk_truncate(blk
, total_size
, prealloc
, &err
);
3705 error_report_err(err
);
3709 new_size
= blk_getlength(blk
);
3711 error_report("Failed to verify truncated image length: %s",
3712 strerror(-new_size
));
3717 /* Some block drivers implement a truncation method, but only so
3718 * the user can cause qemu to refresh the image's size from disk.
3719 * The idea is that the user resizes the image outside of qemu and
3720 * then invokes block_resize to inform qemu about it.
3721 * (This includes iscsi and file-posix for device files.)
3722 * Of course, that is not the behavior someone invoking
3723 * qemu-img resize would find useful, so we catch that behavior
3724 * here and tell the user. */
3725 if (new_size
!= total_size
&& new_size
== current_size
) {
3726 error_report("Image was not resized; resizing may not be supported "
3732 if (new_size
!= total_size
) {
3733 warn_report("Image should have been resized to %" PRIi64
3734 " bytes, but was resized to %" PRIi64
" bytes",
3735 total_size
, new_size
);
3738 qprintf(quiet
, "Image resized.\n");
3748 static void amend_status_cb(BlockDriverState
*bs
,
3749 int64_t offset
, int64_t total_work_size
,
3752 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3755 static int print_amend_option_help(const char *format
)
3759 /* Find driver and parse its options */
3760 drv
= bdrv_find_format(format
);
3762 error_report("Unknown file format '%s'", format
);
3766 if (!drv
->bdrv_amend_options
) {
3767 error_report("Format driver '%s' does not support option amendment",
3772 /* Every driver supporting amendment must have create_opts */
3773 assert(drv
->create_opts
);
3775 printf("Creation options for '%s':\n", format
);
3776 qemu_opts_print_help(drv
->create_opts
);
3777 printf("\nNote that not all of these options may be amendable.\n");
3781 static int img_amend(int argc
, char **argv
)
3785 char *options
= NULL
;
3786 QemuOptsList
*create_opts
= NULL
;
3787 QemuOpts
*opts
= NULL
;
3788 const char *fmt
= NULL
, *filename
, *cache
;
3791 bool quiet
= false, progress
= false;
3792 BlockBackend
*blk
= NULL
;
3793 BlockDriverState
*bs
= NULL
;
3794 bool image_opts
= false;
3796 cache
= BDRV_DEFAULT_CACHE
;
3798 static const struct option long_options
[] = {
3799 {"help", no_argument
, 0, 'h'},
3800 {"object", required_argument
, 0, OPTION_OBJECT
},
3801 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3804 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
3805 long_options
, NULL
);
3812 missing_argument(argv
[optind
- 1]);
3815 unrecognized_option(argv
[optind
- 1]);
3821 if (!is_valid_option_list(optarg
)) {
3822 error_report("Invalid option list: %s", optarg
);
3824 goto out_no_progress
;
3827 options
= g_strdup(optarg
);
3829 char *old_options
= options
;
3830 options
= g_strdup_printf("%s,%s", options
, optarg
);
3831 g_free(old_options
);
3847 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3851 goto out_no_progress
;
3854 case OPTION_IMAGE_OPTS
:
3861 error_exit("Must specify options (-o)");
3864 if (qemu_opts_foreach(&qemu_object_opts
,
3865 user_creatable_add_opts_foreach
,
3868 goto out_no_progress
;
3874 qemu_progress_init(progress
, 1.0);
3876 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
3877 if (fmt
&& has_help_option(options
)) {
3878 /* If a format is explicitly specified (and possibly no filename is
3879 * given), print option help here */
3880 ret
= print_amend_option_help(fmt
);
3884 if (optind
!= argc
- 1) {
3885 error_report("Expecting one image file name");
3890 flags
= BDRV_O_RDWR
;
3891 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3893 error_report("Invalid cache option: %s", cache
);
3897 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3905 fmt
= bs
->drv
->format_name
;
3907 if (has_help_option(options
)) {
3908 /* If the format was auto-detected, print option help here */
3909 ret
= print_amend_option_help(fmt
);
3913 if (!bs
->drv
->bdrv_amend_options
) {
3914 error_report("Format driver '%s' does not support option amendment",
3920 /* Every driver supporting amendment must have create_opts */
3921 assert(bs
->drv
->create_opts
);
3923 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
3924 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
3925 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
3927 error_report_err(err
);
3932 /* In case the driver does not call amend_status_cb() */
3933 qemu_progress_print(0.f
, 0);
3934 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, &err
);
3935 qemu_progress_print(100.f
, 0);
3937 error_report_err(err
);
3942 qemu_progress_end();
3946 qemu_opts_del(opts
);
3947 qemu_opts_free(create_opts
);
3956 typedef struct BenchData
{
3958 uint64_t image_size
;
3965 bool drain_on_flush
;
3974 static void bench_undrained_flush_cb(void *opaque
, int ret
)
3977 error_report("Failed flush request: %s", strerror(-ret
));
3982 static void bench_cb(void *opaque
, int ret
)
3984 BenchData
*b
= opaque
;
3988 error_report("Failed request: %s", strerror(-ret
));
3993 /* Just finished a flush with drained queue: Start next requests */
3994 assert(b
->in_flight
== 0);
3995 b
->in_flush
= false;
3996 } else if (b
->in_flight
> 0) {
3997 int remaining
= b
->n
- b
->in_flight
;
4002 /* Time for flush? Drain queue if requested, then flush */
4003 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4004 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4005 BlockCompletionFunc
*cb
;
4007 if (b
->drain_on_flush
) {
4011 cb
= bench_undrained_flush_cb
;
4014 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4016 error_report("Failed to issue flush request");
4020 if (b
->drain_on_flush
) {
4026 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4027 int64_t offset
= b
->offset
;
4028 /* blk_aio_* might look for completed I/Os and kick bench_cb
4029 * again, so make sure this operation is counted by in_flight
4030 * and b->offset is ready for the next submission.
4033 b
->offset
+= b
->step
;
4034 b
->offset
%= b
->image_size
;
4036 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4038 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4041 error_report("Failed to issue request");
4047 static int img_bench(int argc
, char **argv
)
4050 const char *fmt
= NULL
, *filename
;
4052 bool image_opts
= false;
4053 bool is_write
= false;
4057 size_t bufsize
= 4096;
4060 int flush_interval
= 0;
4061 bool drain_on_flush
= true;
4063 BlockBackend
*blk
= NULL
;
4064 BenchData data
= {};
4066 bool writethrough
= false;
4067 struct timeval t1
, t2
;
4069 bool force_share
= false;
4073 static const struct option long_options
[] = {
4074 {"help", no_argument
, 0, 'h'},
4075 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4076 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4077 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4078 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4079 {"force-share", no_argument
, 0, 'U'},
4082 c
= getopt_long(argc
, argv
, ":hc:d:f:no:qs:S:t:wU", long_options
, NULL
);
4089 missing_argument(argv
[optind
- 1]);
4092 unrecognized_option(argv
[optind
- 1]);
4101 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4102 error_report("Invalid request count specified");
4112 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4113 error_report("Invalid queue depth specified");
4123 flags
|= BDRV_O_NATIVE_AIO
;
4127 offset
= cvtnum(optarg
);
4129 error_report("Invalid offset specified");
4142 sval
= cvtnum(optarg
);
4143 if (sval
< 0 || sval
> INT_MAX
) {
4144 error_report("Invalid buffer size specified");
4155 sval
= cvtnum(optarg
);
4156 if (sval
< 0 || sval
> INT_MAX
) {
4157 error_report("Invalid step size specified");
4165 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4167 error_report("Invalid cache mode");
4173 flags
|= BDRV_O_RDWR
;
4179 case OPTION_PATTERN
:
4183 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4184 error_report("Invalid pattern byte specified");
4190 case OPTION_FLUSH_INTERVAL
:
4194 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4195 error_report("Invalid flush interval specified");
4198 flush_interval
= res
;
4201 case OPTION_NO_DRAIN
:
4202 drain_on_flush
= false;
4204 case OPTION_IMAGE_OPTS
:
4210 if (optind
!= argc
- 1) {
4211 error_exit("Expecting one image file name");
4213 filename
= argv
[argc
- 1];
4215 if (!is_write
&& flush_interval
) {
4216 error_report("--flush-interval is only available in write tests");
4220 if (flush_interval
&& flush_interval
< depth
) {
4221 error_report("Flush interval can't be smaller than depth");
4226 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4233 image_size
= blk_getlength(blk
);
4234 if (image_size
< 0) {
4239 data
= (BenchData
) {
4241 .image_size
= image_size
,
4243 .step
= step
?: bufsize
,
4248 .flush_interval
= flush_interval
,
4249 .drain_on_flush
= drain_on_flush
,
4251 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4252 "(starting at offset %" PRId64
", step size %d)\n",
4253 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4254 data
.offset
, data
.step
);
4255 if (flush_interval
) {
4256 printf("Sending flush every %d requests\n", flush_interval
);
4259 buf_size
= data
.nrreq
* data
.bufsize
;
4260 data
.buf
= blk_blockalign(blk
, buf_size
);
4261 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4263 blk_register_buf(blk
, data
.buf
, buf_size
);
4265 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4266 for (i
= 0; i
< data
.nrreq
; i
++) {
4267 qemu_iovec_init(&data
.qiov
[i
], 1);
4268 qemu_iovec_add(&data
.qiov
[i
],
4269 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4272 gettimeofday(&t1
, NULL
);
4275 while (data
.n
> 0) {
4276 main_loop_wait(false);
4278 gettimeofday(&t2
, NULL
);
4280 printf("Run completed in %3.3f seconds.\n",
4281 (t2
.tv_sec
- t1
.tv_sec
)
4282 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4286 blk_unregister_buf(blk
, data
.buf
);
4288 qemu_vfree(data
.buf
);
4309 int bsz
; /* Block size */
4317 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4321 static int img_dd_bs(const char *arg
,
4322 struct DdIo
*in
, struct DdIo
*out
,
4329 if (res
<= 0 || res
> INT_MAX
) {
4330 error_report("invalid number: '%s'", arg
);
4333 in
->bsz
= out
->bsz
= res
;
4338 static int img_dd_count(const char *arg
,
4339 struct DdIo
*in
, struct DdIo
*out
,
4342 dd
->count
= cvtnum(arg
);
4344 if (dd
->count
< 0) {
4345 error_report("invalid number: '%s'", arg
);
4352 static int img_dd_if(const char *arg
,
4353 struct DdIo
*in
, struct DdIo
*out
,
4356 in
->filename
= g_strdup(arg
);
4361 static int img_dd_of(const char *arg
,
4362 struct DdIo
*in
, struct DdIo
*out
,
4365 out
->filename
= g_strdup(arg
);
4370 static int img_dd_skip(const char *arg
,
4371 struct DdIo
*in
, struct DdIo
*out
,
4374 in
->offset
= cvtnum(arg
);
4376 if (in
->offset
< 0) {
4377 error_report("invalid number: '%s'", arg
);
4384 static int img_dd(int argc
, char **argv
)
4389 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4390 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4391 QemuOpts
*opts
= NULL
;
4392 QemuOptsList
*create_opts
= NULL
;
4393 Error
*local_err
= NULL
;
4394 bool image_opts
= false;
4396 const char *out_fmt
= "raw";
4397 const char *fmt
= NULL
;
4399 int64_t block_count
= 0, out_pos
, in_pos
;
4400 bool force_share
= false;
4401 struct DdInfo dd
= {
4406 .bsz
= 512, /* Block size is by default 512 bytes */
4418 const struct DdOpts options
[] = {
4419 { "bs", img_dd_bs
, C_BS
},
4420 { "count", img_dd_count
, C_COUNT
},
4421 { "if", img_dd_if
, C_IF
},
4422 { "of", img_dd_of
, C_OF
},
4423 { "skip", img_dd_skip
, C_SKIP
},
4426 const struct option long_options
[] = {
4427 { "help", no_argument
, 0, 'h'},
4428 { "object", required_argument
, 0, OPTION_OBJECT
},
4429 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4430 { "force-share", no_argument
, 0, 'U'},
4434 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4446 missing_argument(argv
[optind
- 1]);
4449 unrecognized_option(argv
[optind
- 1]);
4458 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4463 case OPTION_IMAGE_OPTS
:
4469 for (i
= optind
; i
< argc
; i
++) {
4471 arg
= g_strdup(argv
[i
]);
4473 tmp
= strchr(arg
, '=');
4475 error_report("unrecognized operand %s", arg
);
4482 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4483 if (!strcmp(arg
, options
[j
].name
)) {
4487 if (options
[j
].name
== NULL
) {
4488 error_report("unrecognized operand %s", arg
);
4493 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4497 dd
.flags
|= options
[j
].flag
;
4502 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4503 error_report("Must specify both input and output files");
4508 if (qemu_opts_foreach(&qemu_object_opts
,
4509 user_creatable_add_opts_foreach
,
4515 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4523 drv
= bdrv_find_format(out_fmt
);
4525 error_report("Unknown file format");
4529 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4532 error_report_err(local_err
);
4536 if (!drv
->create_opts
) {
4537 error_report("Format driver '%s' does not support image creation",
4542 if (!proto_drv
->create_opts
) {
4543 error_report("Protocol driver '%s' does not support image creation",
4544 proto_drv
->format_name
);
4548 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4549 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4551 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4553 size
= blk_getlength(blk1
);
4555 error_report("Failed to get size for '%s'", in
.filename
);
4560 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4561 dd
.count
* in
.bsz
< size
) {
4562 size
= dd
.count
* in
.bsz
;
4565 /* Overflow means the specified offset is beyond input image's size */
4566 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4567 size
< in
.bsz
* in
.offset
)) {
4568 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4570 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4571 size
- in
.bsz
* in
.offset
, &error_abort
);
4574 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4576 error_reportf_err(local_err
,
4577 "%s: error while creating output image: ",
4583 /* TODO, we can't honour --image-opts for the target,
4584 * since it needs to be given in a format compatible
4585 * with the bdrv_create() call above which does not
4586 * support image-opts style.
4588 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
4589 false, false, false);
4596 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4597 size
< in
.offset
* in
.bsz
)) {
4598 /* We give a warning if the skip option is bigger than the input
4599 * size and create an empty output disk image (i.e. like dd(1)).
4601 error_report("%s: cannot skip to specified offset", in
.filename
);
4604 in_pos
= in
.offset
* in
.bsz
;
4607 in
.buf
= g_new(uint8_t, in
.bsz
);
4609 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4610 int in_ret
, out_ret
;
4612 if (in_pos
+ in
.bsz
> size
) {
4613 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4615 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4618 error_report("error while reading from input image file: %s",
4625 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4628 error_report("error while writing to output image file: %s",
4629 strerror(-out_ret
));
4638 qemu_opts_del(opts
);
4639 qemu_opts_free(create_opts
);
4642 g_free(in
.filename
);
4643 g_free(out
.filename
);
4653 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
4657 Visitor
*v
= qobject_output_visitor_new(&obj
);
4659 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
4660 visit_complete(v
, &obj
);
4661 str
= qobject_to_json_pretty(obj
);
4662 assert(str
!= NULL
);
4663 printf("%s\n", qstring_get_str(str
));
4669 static int img_measure(int argc
, char **argv
)
4671 static const struct option long_options
[] = {
4672 {"help", no_argument
, 0, 'h'},
4673 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4674 {"object", required_argument
, 0, OPTION_OBJECT
},
4675 {"output", required_argument
, 0, OPTION_OUTPUT
},
4676 {"size", required_argument
, 0, OPTION_SIZE
},
4677 {"force-share", no_argument
, 0, 'U'},
4680 OutputFormat output_format
= OFORMAT_HUMAN
;
4681 BlockBackend
*in_blk
= NULL
;
4683 const char *filename
= NULL
;
4684 const char *fmt
= NULL
;
4685 const char *out_fmt
= "raw";
4686 char *options
= NULL
;
4687 char *snapshot_name
= NULL
;
4688 bool force_share
= false;
4689 QemuOpts
*opts
= NULL
;
4690 QemuOpts
*object_opts
= NULL
;
4691 QemuOpts
*sn_opts
= NULL
;
4692 QemuOptsList
*create_opts
= NULL
;
4693 bool image_opts
= false;
4694 uint64_t img_size
= UINT64_MAX
;
4695 BlockMeasureInfo
*info
= NULL
;
4696 Error
*local_err
= NULL
;
4700 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
4701 long_options
, NULL
)) != -1) {
4714 if (!is_valid_option_list(optarg
)) {
4715 error_report("Invalid option list: %s", optarg
);
4719 options
= g_strdup(optarg
);
4721 char *old_options
= options
;
4722 options
= g_strdup_printf("%s,%s", options
, optarg
);
4723 g_free(old_options
);
4727 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
4728 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
4731 error_report("Failed in parsing snapshot param '%s'",
4736 snapshot_name
= optarg
;
4743 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4749 case OPTION_IMAGE_OPTS
:
4753 if (!strcmp(optarg
, "json")) {
4754 output_format
= OFORMAT_JSON
;
4755 } else if (!strcmp(optarg
, "human")) {
4756 output_format
= OFORMAT_HUMAN
;
4758 error_report("--output must be used with human or json "
4767 sval
= cvtnum(optarg
);
4769 if (sval
== -ERANGE
) {
4770 error_report("Image size must be less than 8 EiB!");
4772 error_report("Invalid image size specified! You may use "
4773 "k, M, G, T, P or E suffixes for ");
4774 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4775 "petabytes and exabytes.");
4779 img_size
= (uint64_t)sval
;
4785 if (qemu_opts_foreach(&qemu_object_opts
,
4786 user_creatable_add_opts_foreach
,
4791 if (argc
- optind
> 1) {
4792 error_report("At most one filename argument is allowed.");
4794 } else if (argc
- optind
== 1) {
4795 filename
= argv
[optind
];
4799 (object_opts
|| image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
4800 error_report("--object, --image-opts, -f, and -l "
4801 "require a filename argument.");
4804 if (filename
&& img_size
!= UINT64_MAX
) {
4805 error_report("--size N cannot be used together with a filename.");
4808 if (!filename
&& img_size
== UINT64_MAX
) {
4809 error_report("Either --size N or one filename must be specified.");
4814 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
4815 false, false, force_share
);
4821 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
4822 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
4823 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
4825 } else if (snapshot_name
!= NULL
) {
4826 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
4827 snapshot_name
, &local_err
);
4830 error_reportf_err(local_err
, "Failed to load snapshot: ");
4835 drv
= bdrv_find_format(out_fmt
);
4837 error_report("Unknown file format '%s'", out_fmt
);
4840 if (!drv
->create_opts
) {
4841 error_report("Format driver '%s' does not support image creation",
4846 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4847 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
4848 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4850 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
4852 error_report_err(local_err
);
4853 error_report("Invalid options for file format '%s'", out_fmt
);
4857 if (img_size
!= UINT64_MAX
) {
4858 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
4861 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
4863 error_report_err(local_err
);
4867 if (output_format
== OFORMAT_HUMAN
) {
4868 printf("required size: %" PRIu64
"\n", info
->required
);
4869 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
4871 dump_json_block_measure_info(info
);
4877 qapi_free_BlockMeasureInfo(info
);
4878 qemu_opts_del(object_opts
);
4879 qemu_opts_del(opts
);
4880 qemu_opts_del(sn_opts
);
4881 qemu_opts_free(create_opts
);
4887 static const img_cmd_t img_cmds
[] = {
4888 #define DEF(option, callback, arg_string) \
4889 { option, callback },
4890 #include "qemu-img-cmds.h"
4895 int main(int argc
, char **argv
)
4897 const img_cmd_t
*cmd
;
4898 const char *cmdname
;
4899 Error
*local_error
= NULL
;
4900 char *trace_file
= NULL
;
4902 static const struct option long_options
[] = {
4903 {"help", no_argument
, 0, 'h'},
4904 {"version", no_argument
, 0, 'V'},
4905 {"trace", required_argument
, NULL
, 'T'},
4910 signal(SIGPIPE
, SIG_IGN
);
4913 module_call_init(MODULE_INIT_TRACE
);
4914 error_set_progname(argv
[0]);
4915 qemu_init_exec_dir(argv
[0]);
4917 if (qemu_init_main_loop(&local_error
)) {
4918 error_report_err(local_error
);
4922 qcrypto_init(&error_fatal
);
4924 module_call_init(MODULE_INIT_QOM
);
4927 error_exit("Not enough arguments");
4930 qemu_add_opts(&qemu_object_opts
);
4931 qemu_add_opts(&qemu_source_opts
);
4932 qemu_add_opts(&qemu_trace_opts
);
4934 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
4937 missing_argument(argv
[optind
- 1]);
4940 unrecognized_option(argv
[optind
- 1]);
4946 printf(QEMU_IMG_VERSION
);
4950 trace_file
= trace_opt_parse(optarg
);
4955 cmdname
= argv
[optind
];
4957 /* reset getopt_long scanning */
4965 if (!trace_init_backends()) {
4968 trace_init_file(trace_file
);
4969 qemu_set_log(LOG_TRACE
);
4971 /* find the command */
4972 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
4973 if (!strcmp(cmdname
, cmd
->name
)) {
4974 return cmd
->handler(argc
, argv
);
4979 error_exit("Command not found: %s", cmdname
);