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
, false);
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("Protocol driver '%s' does not support image creation",
265 proto_drv
->format_name
);
266 qemu_opts_free(create_opts
);
269 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
272 printf("Supported options:\n");
273 qemu_opts_print_help(create_opts
, false);
274 qemu_opts_free(create_opts
);
279 static BlockBackend
*img_open_opts(const char *optstr
,
280 QemuOpts
*opts
, int flags
, bool writethrough
,
281 bool quiet
, bool force_share
)
284 Error
*local_err
= NULL
;
286 options
= qemu_opts_to_qdict(opts
, NULL
);
288 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
289 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
290 error_report("--force-share/-U conflicts with image options");
291 qobject_unref(options
);
294 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
296 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
298 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
301 blk_set_enable_write_cache(blk
, !writethrough
);
306 static BlockBackend
*img_open_file(const char *filename
,
308 const char *fmt
, int flags
,
309 bool writethrough
, bool quiet
,
313 Error
*local_err
= NULL
;
316 options
= qdict_new();
319 qdict_put_str(options
, "driver", fmt
);
323 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
325 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
327 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
330 blk_set_enable_write_cache(blk
, !writethrough
);
336 static int img_add_key_secrets(void *opaque
,
337 const char *name
, const char *value
,
340 QDict
*options
= opaque
;
342 if (g_str_has_suffix(name
, "key-secret")) {
343 qdict_put_str(options
, name
, value
);
350 static BlockBackend
*img_open(bool image_opts
,
351 const char *filename
,
352 const char *fmt
, int flags
, bool writethrough
,
353 bool quiet
, bool force_share
)
359 error_report("--image-opts and --format are mutually exclusive");
362 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
367 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
370 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
377 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
378 const char *base_filename
,
379 const char *base_fmt
)
384 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
386 error_report("Backing file not supported for file format '%s'",
393 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
395 error_report("Backing file format not supported for file "
404 static int64_t cvtnum(const char *s
)
409 err
= qemu_strtosz(s
, NULL
, &value
);
413 if (value
> INT64_MAX
) {
419 static int img_create(int argc
, char **argv
)
422 uint64_t img_size
= -1;
423 const char *fmt
= "raw";
424 const char *base_fmt
= NULL
;
425 const char *filename
;
426 const char *base_filename
= NULL
;
427 char *options
= NULL
;
428 Error
*local_err
= NULL
;
433 static const struct option long_options
[] = {
434 {"help", no_argument
, 0, 'h'},
435 {"object", required_argument
, 0, OPTION_OBJECT
},
438 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
445 missing_argument(argv
[optind
- 1]);
448 unrecognized_option(argv
[optind
- 1]);
457 base_filename
= optarg
;
463 if (!is_valid_option_list(optarg
)) {
464 error_report("Invalid option list: %s", optarg
);
468 options
= g_strdup(optarg
);
470 char *old_options
= options
;
471 options
= g_strdup_printf("%s,%s", options
, optarg
);
479 flags
|= BDRV_O_NO_BACKING
;
481 case OPTION_OBJECT
: {
483 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
492 /* Get the filename */
493 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
494 if (options
&& has_help_option(options
)) {
496 return print_block_option_help(filename
, fmt
);
499 if (optind
>= argc
) {
500 error_exit("Expecting image file name");
504 if (qemu_opts_foreach(&qemu_object_opts
,
505 user_creatable_add_opts_foreach
,
506 NULL
, &error_fatal
)) {
510 /* Get image size, if specified */
514 sval
= cvtnum(argv
[optind
++]);
516 if (sval
== -ERANGE
) {
517 error_report("Image size must be less than 8 EiB!");
519 error_report("Invalid image size specified! You may use k, M, "
520 "G, T, P or E suffixes for ");
521 error_report("kilobytes, megabytes, gigabytes, terabytes, "
522 "petabytes and exabytes.");
526 img_size
= (uint64_t)sval
;
528 if (optind
!= argc
) {
529 error_exit("Unexpected argument: %s", argv
[optind
]);
532 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
533 options
, img_size
, flags
, quiet
, &local_err
);
535 error_reportf_err(local_err
, "%s: ", filename
);
547 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
551 Visitor
*v
= qobject_output_visitor_new(&obj
);
553 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
554 visit_complete(v
, &obj
);
555 str
= qobject_to_json_pretty(obj
);
557 qprintf(quiet
, "%s\n", qstring_get_str(str
));
563 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
565 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
566 qprintf(quiet
, "No errors were found on the image.\n");
568 if (check
->corruptions
) {
569 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
570 "Data may be corrupted, or further writes to the image "
577 "\n%" PRId64
" leaked clusters were found on the image.\n"
578 "This means waste of disk space, but no harm to data.\n",
582 if (check
->check_errors
) {
585 " internal errors have occurred during the check.\n",
586 check
->check_errors
);
590 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
591 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
592 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
593 check
->allocated_clusters
, check
->total_clusters
,
594 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
595 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
596 check
->compressed_clusters
* 100.0 /
597 check
->allocated_clusters
);
600 if (check
->image_end_offset
) {
602 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
606 static int collect_image_check(BlockDriverState
*bs
,
608 const char *filename
,
613 BdrvCheckResult result
;
615 ret
= bdrv_check(bs
, &result
, fix
);
620 check
->filename
= g_strdup(filename
);
621 check
->format
= g_strdup(bdrv_get_format_name(bs
));
622 check
->check_errors
= result
.check_errors
;
623 check
->corruptions
= result
.corruptions
;
624 check
->has_corruptions
= result
.corruptions
!= 0;
625 check
->leaks
= result
.leaks
;
626 check
->has_leaks
= result
.leaks
!= 0;
627 check
->corruptions_fixed
= result
.corruptions_fixed
;
628 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
629 check
->leaks_fixed
= result
.leaks_fixed
;
630 check
->has_leaks_fixed
= result
.leaks
!= 0;
631 check
->image_end_offset
= result
.image_end_offset
;
632 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
633 check
->total_clusters
= result
.bfi
.total_clusters
;
634 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
635 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
636 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
637 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
638 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
639 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
640 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
646 * Checks an image for consistency. Exit codes:
648 * 0 - Check completed, image is good
649 * 1 - Check not completed because of internal errors
650 * 2 - Check completed, image is corrupted
651 * 3 - Check completed, image has leaked clusters, but is good otherwise
652 * 63 - Checks are not supported by the image format
654 static int img_check(int argc
, char **argv
)
657 OutputFormat output_format
= OFORMAT_HUMAN
;
658 const char *filename
, *fmt
, *output
, *cache
;
660 BlockDriverState
*bs
;
662 int flags
= BDRV_O_CHECK
;
666 bool image_opts
= false;
667 bool force_share
= false;
671 cache
= BDRV_DEFAULT_CACHE
;
674 int option_index
= 0;
675 static const struct option long_options
[] = {
676 {"help", no_argument
, 0, 'h'},
677 {"format", required_argument
, 0, 'f'},
678 {"repair", required_argument
, 0, 'r'},
679 {"output", required_argument
, 0, OPTION_OUTPUT
},
680 {"object", required_argument
, 0, OPTION_OBJECT
},
681 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
682 {"force-share", no_argument
, 0, 'U'},
685 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
686 long_options
, &option_index
);
692 missing_argument(argv
[optind
- 1]);
695 unrecognized_option(argv
[optind
- 1]);
704 flags
|= BDRV_O_RDWR
;
706 if (!strcmp(optarg
, "leaks")) {
707 fix
= BDRV_FIX_LEAKS
;
708 } else if (!strcmp(optarg
, "all")) {
709 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
711 error_exit("Unknown option value for -r "
712 "(expecting 'leaks' or 'all'): %s", optarg
);
727 case OPTION_OBJECT
: {
729 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
735 case OPTION_IMAGE_OPTS
:
740 if (optind
!= argc
- 1) {
741 error_exit("Expecting one image file name");
743 filename
= argv
[optind
++];
745 if (output
&& !strcmp(output
, "json")) {
746 output_format
= OFORMAT_JSON
;
747 } else if (output
&& !strcmp(output
, "human")) {
748 output_format
= OFORMAT_HUMAN
;
750 error_report("--output must be used with human or json as argument.");
754 if (qemu_opts_foreach(&qemu_object_opts
,
755 user_creatable_add_opts_foreach
,
756 NULL
, &error_fatal
)) {
760 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
762 error_report("Invalid source cache option: %s", cache
);
766 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
773 check
= g_new0(ImageCheck
, 1);
774 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
776 if (ret
== -ENOTSUP
) {
777 error_report("This image format does not support checks");
782 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
783 int corruptions_fixed
, leaks_fixed
;
785 leaks_fixed
= check
->leaks_fixed
;
786 corruptions_fixed
= check
->corruptions_fixed
;
788 if (output_format
== OFORMAT_HUMAN
) {
790 "The following inconsistencies were found and repaired:\n\n"
791 " %" PRId64
" leaked clusters\n"
792 " %" PRId64
" corruptions\n\n"
793 "Double checking the fixed image now...\n",
795 check
->corruptions_fixed
);
798 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
800 check
->leaks_fixed
= leaks_fixed
;
801 check
->corruptions_fixed
= corruptions_fixed
;
805 switch (output_format
) {
807 dump_human_image_check(check
, quiet
);
810 dump_json_image_check(check
, quiet
);
815 if (ret
|| check
->check_errors
) {
817 error_report("Check failed: %s", strerror(-ret
));
819 error_report("Check failed");
825 if (check
->corruptions
) {
827 } else if (check
->leaks
) {
834 qapi_free_ImageCheck(check
);
839 typedef struct CommonBlockJobCBInfo
{
840 BlockDriverState
*bs
;
842 } CommonBlockJobCBInfo
;
844 static void common_block_job_cb(void *opaque
, int ret
)
846 CommonBlockJobCBInfo
*cbi
= opaque
;
849 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
853 static void run_block_job(BlockJob
*job
, Error
**errp
)
855 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
858 aio_context_acquire(aio_context
);
861 float progress
= 0.0f
;
862 aio_poll(aio_context
, true);
863 if (job
->job
.progress_total
) {
864 progress
= (float)job
->job
.progress_current
/
865 job
->job
.progress_total
* 100.f
;
867 qemu_progress_print(progress
, 0);
868 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
870 if (!job_is_completed(&job
->job
)) {
871 ret
= job_complete_sync(&job
->job
, errp
);
875 job_unref(&job
->job
);
876 aio_context_release(aio_context
);
878 /* publish completion progress only when success */
880 qemu_progress_print(100.f
, 0);
884 static int img_commit(int argc
, char **argv
)
887 const char *filename
, *fmt
, *cache
, *base
;
889 BlockDriverState
*bs
, *base_bs
;
891 bool progress
= false, quiet
= false, drop
= false;
893 Error
*local_err
= NULL
;
894 CommonBlockJobCBInfo cbi
;
895 bool image_opts
= false;
896 AioContext
*aio_context
;
899 cache
= BDRV_DEFAULT_CACHE
;
902 static const struct option long_options
[] = {
903 {"help", no_argument
, 0, 'h'},
904 {"object", required_argument
, 0, OPTION_OBJECT
},
905 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
908 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
915 missing_argument(argv
[optind
- 1]);
918 unrecognized_option(argv
[optind
- 1]);
943 case OPTION_OBJECT
: {
945 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
951 case OPTION_IMAGE_OPTS
:
957 /* Progress is not shown in Quiet mode */
962 if (optind
!= argc
- 1) {
963 error_exit("Expecting one image file name");
965 filename
= argv
[optind
++];
967 if (qemu_opts_foreach(&qemu_object_opts
,
968 user_creatable_add_opts_foreach
,
969 NULL
, &error_fatal
)) {
973 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
974 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
976 error_report("Invalid cache option: %s", cache
);
980 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
987 qemu_progress_init(progress
, 1.f
);
988 qemu_progress_print(0.f
, 100);
991 base_bs
= bdrv_find_backing_image(bs
, base
);
993 error_setg(&local_err
,
994 "Did not find '%s' in the backing chain of '%s'",
999 /* This is different from QMP, which by default uses the deepest file in
1000 * the backing chain (i.e., the very base); however, the traditional
1001 * behavior of qemu-img commit is using the immediate backing file. */
1002 base_bs
= backing_bs(bs
);
1004 error_setg(&local_err
, "Image does not have a backing file");
1009 cbi
= (CommonBlockJobCBInfo
){
1014 aio_context
= bdrv_get_aio_context(bs
);
1015 aio_context_acquire(aio_context
);
1016 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, 0,
1017 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1018 &cbi
, false, &local_err
);
1019 aio_context_release(aio_context
);
1024 /* When the block job completes, the BlockBackend reference will point to
1025 * the old backing file. In order to avoid that the top image is already
1026 * deleted, so we can still empty it afterwards, increment the reference
1027 * counter here preemptively. */
1032 job
= block_job_get("commit");
1034 run_block_job(job
, &local_err
);
1039 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1040 ret
= bs
->drv
->bdrv_make_empty(bs
);
1042 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1054 qemu_progress_end();
1059 error_report_err(local_err
);
1063 qprintf(quiet
, "Image committed.\n");
1068 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1069 * of the first sector boundary within buf where the sector contains a
1070 * non-zero byte. This function is robust to a buffer that is not
1073 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1076 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1078 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1079 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1083 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1090 * Returns true iff the first sector pointed to by 'buf' contains at least
1093 * 'pnum' is set to the number of sectors (including and immediately following
1094 * the first one) that are known to be in the same allocated/unallocated state.
1095 * The function will try to align the end offset to alignment boundaries so
1096 * that the request will at least end aligned and consequtive requests will
1097 * also start at an aligned offset.
1099 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1100 int64_t sector_num
, int alignment
)
1109 is_zero
= buffer_is_zero(buf
, 512);
1110 for(i
= 1; i
< n
; i
++) {
1112 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1117 tail
= (sector_num
+ i
) & (alignment
- 1);
1119 if (is_zero
&& i
<= tail
) {
1120 /* treat unallocated areas which only consist
1121 * of a small tail as allocated. */
1125 /* align up end offset of allocated areas. */
1126 i
+= alignment
- tail
;
1129 /* align down end offset of zero areas. */
1138 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1139 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1140 * breaking up write requests for only small sparse areas.
1142 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1143 int min
, int64_t sector_num
, int alignment
)
1146 int num_checked
, num_used
;
1152 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1158 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1160 sector_num
+= *pnum
;
1161 num_checked
= num_used
;
1164 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1166 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1168 sector_num
+= *pnum
;
1169 num_checked
+= *pnum
;
1171 num_used
= num_checked
;
1172 } else if (*pnum
>= min
) {
1182 * Compares two buffers sector by sector. Returns 0 if the first
1183 * sector of each buffer matches, non-zero otherwise.
1185 * pnum is set to the sector-aligned size of the buffer prefix that
1186 * has the same matching status as the first sector.
1188 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1189 int64_t bytes
, int64_t *pnum
)
1192 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1196 res
= !!memcmp(buf1
, buf2
, i
);
1198 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1200 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1210 #define IO_BUF_SIZE (2 * 1024 * 1024)
1213 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1215 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1216 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1217 * failure), and 4 on error (the exit status for read errors), after emitting
1220 * @param blk: BlockBackend for the image
1221 * @param offset: Starting offset to check
1222 * @param bytes: Number of bytes to check
1223 * @param filename: Name of disk file we are checking (logging purpose)
1224 * @param buffer: Allocated buffer for storing read data
1225 * @param quiet: Flag for quiet mode
1227 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1228 int64_t bytes
, const char *filename
,
1229 uint8_t *buffer
, bool quiet
)
1234 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1236 error_report("Error while reading offset %" PRId64
" of %s: %s",
1237 offset
, filename
, strerror(-ret
));
1240 idx
= find_nonzero(buffer
, bytes
);
1242 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1251 * Compares two images. Exit codes:
1253 * 0 - Images are identical
1255 * >1 - Error occurred
1257 static int img_compare(int argc
, char **argv
)
1259 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1260 BlockBackend
*blk1
, *blk2
;
1261 BlockDriverState
*bs1
, *bs2
;
1262 int64_t total_size1
, total_size2
;
1263 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1264 int64_t pnum1
, pnum2
;
1265 int allocated1
, allocated2
;
1266 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1267 bool progress
= false, quiet
= false, strict
= false;
1274 uint64_t progress_base
;
1275 bool image_opts
= false;
1276 bool force_share
= false;
1278 cache
= BDRV_DEFAULT_CACHE
;
1280 static const struct option long_options
[] = {
1281 {"help", no_argument
, 0, 'h'},
1282 {"object", required_argument
, 0, OPTION_OBJECT
},
1283 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1284 {"force-share", no_argument
, 0, 'U'},
1287 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1288 long_options
, NULL
);
1294 missing_argument(argv
[optind
- 1]);
1297 unrecognized_option(argv
[optind
- 1]);
1323 case OPTION_OBJECT
: {
1325 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1332 case OPTION_IMAGE_OPTS
:
1338 /* Progress is not shown in Quiet mode */
1344 if (optind
!= argc
- 2) {
1345 error_exit("Expecting two image file names");
1347 filename1
= argv
[optind
++];
1348 filename2
= argv
[optind
++];
1350 if (qemu_opts_foreach(&qemu_object_opts
,
1351 user_creatable_add_opts_foreach
,
1352 NULL
, &error_fatal
)) {
1357 /* Initialize before goto out */
1358 qemu_progress_init(progress
, 2.0);
1361 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1363 error_report("Invalid source cache option: %s", cache
);
1368 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1375 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1384 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1385 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1386 total_size1
= blk_getlength(blk1
);
1387 if (total_size1
< 0) {
1388 error_report("Can't get size of %s: %s",
1389 filename1
, strerror(-total_size1
));
1393 total_size2
= blk_getlength(blk2
);
1394 if (total_size2
< 0) {
1395 error_report("Can't get size of %s: %s",
1396 filename2
, strerror(-total_size2
));
1400 total_size
= MIN(total_size1
, total_size2
);
1401 progress_base
= MAX(total_size1
, total_size2
);
1403 qemu_progress_print(0, 100);
1405 if (strict
&& total_size1
!= total_size2
) {
1407 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1411 while (offset
< total_size
) {
1412 int status1
, status2
;
1414 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1415 total_size1
- offset
, &pnum1
, NULL
,
1419 error_report("Sector allocation test failed for %s", filename1
);
1422 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1424 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1425 total_size2
- offset
, &pnum2
, NULL
,
1429 error_report("Sector allocation test failed for %s", filename2
);
1432 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1434 assert(pnum1
&& pnum2
);
1435 chunk
= MIN(pnum1
, pnum2
);
1438 if (status1
!= status2
) {
1440 qprintf(quiet
, "Strict mode: Offset %" PRId64
1441 " block status mismatch!\n", offset
);
1445 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1447 } else if (allocated1
== allocated2
) {
1451 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1452 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1454 error_report("Error while reading offset %" PRId64
1456 offset
, filename1
, strerror(-ret
));
1460 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1462 error_report("Error while reading offset %" PRId64
1464 offset
, filename2
, strerror(-ret
));
1468 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1469 if (ret
|| pnum
!= chunk
) {
1470 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1471 offset
+ (ret
? 0 : pnum
));
1477 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1479 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1480 filename1
, buf1
, quiet
);
1482 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1483 filename2
, buf1
, quiet
);
1490 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1493 if (total_size1
!= total_size2
) {
1494 BlockBackend
*blk_over
;
1495 const char *filename_over
;
1497 qprintf(quiet
, "Warning: Image size mismatch!\n");
1498 if (total_size1
> total_size2
) {
1500 filename_over
= filename1
;
1503 filename_over
= filename2
;
1506 while (offset
< progress_base
) {
1507 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1508 progress_base
- offset
, &chunk
,
1512 error_report("Sector allocation test failed for %s",
1517 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1518 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1519 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1520 filename_over
, buf1
, quiet
);
1526 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1530 qprintf(quiet
, "Images are identical.\n");
1540 qemu_progress_end();
1545 enum ImgConvertBlockStatus
{
1551 #define MAX_COROUTINES 16
1553 typedef struct ImgConvertState
{
1555 int64_t *src_sectors
;
1557 int64_t total_sectors
;
1558 int64_t allocated_sectors
;
1559 int64_t allocated_done
;
1562 enum ImgConvertBlockStatus status
;
1563 int64_t sector_next_status
;
1564 BlockBackend
*target
;
1567 bool unallocated_blocks_are_zero
;
1568 bool target_has_backing
;
1569 int64_t target_backing_sectors
; /* negative if unknown */
1574 size_t cluster_sectors
;
1576 long num_coroutines
;
1577 int running_coroutines
;
1578 Coroutine
*co
[MAX_COROUTINES
];
1579 int64_t wait_sector_num
[MAX_COROUTINES
];
1584 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1585 int *src_cur
, int64_t *src_cur_offset
)
1588 *src_cur_offset
= 0;
1589 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1590 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1592 assert(*src_cur
< s
->src_num
);
1596 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1598 int64_t src_cur_offset
;
1599 int ret
, n
, src_cur
;
1600 bool post_backing_zero
= false;
1602 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1604 assert(s
->total_sectors
> sector_num
);
1605 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1607 if (s
->target_backing_sectors
>= 0) {
1608 if (sector_num
>= s
->target_backing_sectors
) {
1609 post_backing_zero
= s
->unallocated_blocks_are_zero
;
1610 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1611 /* Split requests around target_backing_sectors (because
1612 * starting from there, zeros are handled differently) */
1613 n
= s
->target_backing_sectors
- sector_num
;
1617 if (s
->sector_next_status
<= sector_num
) {
1618 int64_t count
= n
* BDRV_SECTOR_SIZE
;
1620 if (s
->target_has_backing
) {
1622 ret
= bdrv_block_status(blk_bs(s
->src
[src_cur
]),
1623 (sector_num
- src_cur_offset
) *
1625 count
, &count
, NULL
, NULL
);
1627 ret
= bdrv_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1628 (sector_num
- src_cur_offset
) *
1630 count
, &count
, NULL
, NULL
);
1635 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1637 if (ret
& BDRV_BLOCK_ZERO
) {
1638 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1639 } else if (ret
& BDRV_BLOCK_DATA
) {
1640 s
->status
= BLK_DATA
;
1642 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1645 s
->sector_next_status
= sector_num
+ n
;
1648 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1649 if (s
->status
== BLK_DATA
) {
1650 n
= MIN(n
, s
->buf_sectors
);
1653 /* We need to write complete clusters for compressed images, so if an
1654 * unallocated area is shorter than that, we must consider the whole
1655 * cluster allocated. */
1656 if (s
->compressed
) {
1657 if (n
< s
->cluster_sectors
) {
1658 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1659 s
->status
= BLK_DATA
;
1661 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1668 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1669 int nb_sectors
, uint8_t *buf
)
1674 assert(nb_sectors
<= s
->buf_sectors
);
1675 while (nb_sectors
> 0) {
1678 int64_t bs_sectors
, src_cur_offset
;
1680 /* In the case of compression with multiple source files, we can get a
1681 * nb_sectors that spreads into the next part. So we must be able to
1682 * read across multiple BDSes for one convert_read() call. */
1683 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1684 blk
= s
->src
[src_cur
];
1685 bs_sectors
= s
->src_sectors
[src_cur
];
1687 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1688 qemu_iovec_init_buf(&qiov
, buf
, n
<< BDRV_SECTOR_BITS
);
1690 ret
= blk_co_preadv(
1691 blk
, (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
,
1692 n
<< BDRV_SECTOR_BITS
, &qiov
, 0);
1699 buf
+= n
* BDRV_SECTOR_SIZE
;
1706 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1707 int nb_sectors
, uint8_t *buf
,
1708 enum ImgConvertBlockStatus status
)
1713 while (nb_sectors
> 0) {
1715 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1718 case BLK_BACKING_FILE
:
1719 /* If we have a backing file, leave clusters unallocated that are
1720 * unallocated in the source image, so that the backing file is
1721 * visible at the respective offset. */
1722 assert(s
->target_has_backing
);
1726 /* If we're told to keep the target fully allocated (-S 0) or there
1727 * is real non-zero data, we must write it. Otherwise we can treat
1728 * it as zero sectors.
1729 * Compressed clusters need to be written as a whole, so in that
1730 * case we can only save the write if the buffer is completely
1732 if (!s
->min_sparse
||
1734 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1735 sector_num
, s
->alignment
)) ||
1737 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1739 qemu_iovec_init_buf(&qiov
, buf
, n
<< BDRV_SECTOR_BITS
);
1741 ret
= blk_co_pwritev(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1742 n
<< BDRV_SECTOR_BITS
, &qiov
, flags
);
1751 if (s
->has_zero_init
) {
1752 assert(!s
->target_has_backing
);
1755 ret
= blk_co_pwrite_zeroes(s
->target
,
1756 sector_num
<< BDRV_SECTOR_BITS
,
1757 n
<< BDRV_SECTOR_BITS
, 0);
1766 buf
+= n
* BDRV_SECTOR_SIZE
;
1772 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1777 while (nb_sectors
> 0) {
1780 int64_t bs_sectors
, src_cur_offset
;
1783 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1784 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1785 blk
= s
->src
[src_cur
];
1786 bs_sectors
= s
->src_sectors
[src_cur
];
1788 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1790 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1791 sector_num
<< BDRV_SECTOR_BITS
,
1792 n
<< BDRV_SECTOR_BITS
, 0, 0);
1803 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1805 ImgConvertState
*s
= opaque
;
1806 uint8_t *buf
= NULL
;
1810 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1811 if (s
->co
[i
] == qemu_coroutine_self()) {
1818 s
->running_coroutines
++;
1819 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1824 enum ImgConvertBlockStatus status
;
1827 qemu_co_mutex_lock(&s
->lock
);
1828 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1829 qemu_co_mutex_unlock(&s
->lock
);
1832 n
= convert_iteration_sectors(s
, s
->sector_num
);
1834 qemu_co_mutex_unlock(&s
->lock
);
1838 /* save current sector and allocation status to local variables */
1839 sector_num
= s
->sector_num
;
1841 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1842 n
= MIN(n
, s
->buf_sectors
);
1844 /* increment global sector counter so that other coroutines can
1845 * already continue reading beyond this request */
1847 qemu_co_mutex_unlock(&s
->lock
);
1849 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1850 s
->allocated_done
+= n
;
1851 qemu_progress_print(100.0 * s
->allocated_done
/
1852 s
->allocated_sectors
, 0);
1856 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
1857 if (status
== BLK_DATA
&& !copy_range
) {
1858 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1860 error_report("error while reading sector %" PRId64
1861 ": %s", sector_num
, strerror(-ret
));
1864 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1866 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1869 if (s
->wr_in_order
) {
1870 /* keep writes in order */
1871 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1872 s
->wait_sector_num
[index
] = sector_num
;
1873 qemu_coroutine_yield();
1875 s
->wait_sector_num
[index
] = -1;
1878 if (s
->ret
== -EINPROGRESS
) {
1880 ret
= convert_co_copy_range(s
, sector_num
, n
);
1882 s
->copy_range
= false;
1886 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1889 error_report("error while writing sector %" PRId64
1890 ": %s", sector_num
, strerror(-ret
));
1895 if (s
->wr_in_order
) {
1896 /* reenter the coroutine that might have waited
1897 * for this write to complete */
1898 s
->wr_offs
= sector_num
+ n
;
1899 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1900 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1902 * A -> B -> A cannot occur because A has
1903 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1904 * B will never enter A during this time window.
1906 qemu_coroutine_enter(s
->co
[i
]);
1914 s
->co
[index
] = NULL
;
1915 s
->running_coroutines
--;
1916 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1917 /* the convert job finished successfully */
1922 static int convert_do_copy(ImgConvertState
*s
)
1925 int64_t sector_num
= 0;
1927 /* Check whether we have zero initialisation or can get it efficiently */
1928 s
->has_zero_init
= s
->min_sparse
&& !s
->target_has_backing
1929 ? bdrv_has_zero_init(blk_bs(s
->target
))
1932 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1933 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1935 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
);
1937 s
->has_zero_init
= true;
1941 /* Allocate buffer for copied data. For compressed images, only one cluster
1942 * can be copied at a time. */
1943 if (s
->compressed
) {
1944 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
1945 error_report("invalid cluster size");
1948 s
->buf_sectors
= s
->cluster_sectors
;
1951 while (sector_num
< s
->total_sectors
) {
1952 n
= convert_iteration_sectors(s
, sector_num
);
1956 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1958 s
->allocated_sectors
+= n
;
1964 s
->sector_next_status
= 0;
1965 s
->ret
= -EINPROGRESS
;
1967 qemu_co_mutex_init(&s
->lock
);
1968 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1969 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
1970 s
->wait_sector_num
[i
] = -1;
1971 qemu_coroutine_enter(s
->co
[i
]);
1974 while (s
->running_coroutines
) {
1975 main_loop_wait(false);
1978 if (s
->compressed
&& !s
->ret
) {
1979 /* signal EOF to align */
1980 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
1989 #define MAX_BUF_SECTORS 32768
1991 static int img_convert(int argc
, char **argv
)
1993 int c
, bs_i
, flags
, src_flags
= 0;
1994 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
1995 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
1996 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
1997 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
1998 BlockDriverInfo bdi
;
1999 BlockDriverState
*out_bs
;
2000 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2001 QemuOptsList
*create_opts
= NULL
;
2002 QDict
*open_opts
= NULL
;
2003 char *options
= NULL
;
2004 Error
*local_err
= NULL
;
2005 bool writethrough
, src_writethrough
, quiet
= false, image_opts
= false,
2006 skip_create
= false, progress
= false, tgt_image_opts
= false;
2007 int64_t ret
= -EINVAL
;
2008 bool force_share
= false;
2009 bool explict_min_sparse
= false;
2011 ImgConvertState s
= (ImgConvertState
) {
2012 /* Need at least 4k of zeros for sparse detection */
2014 .copy_range
= false,
2015 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2016 .wr_in_order
= true,
2017 .num_coroutines
= 8,
2021 static const struct option long_options
[] = {
2022 {"help", no_argument
, 0, 'h'},
2023 {"object", required_argument
, 0, OPTION_OBJECT
},
2024 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2025 {"force-share", no_argument
, 0, 'U'},
2026 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2029 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2030 long_options
, NULL
);
2036 missing_argument(argv
[optind
- 1]);
2039 unrecognized_option(argv
[optind
- 1]);
2051 out_baseimg
= optarg
;
2054 s
.copy_range
= true;
2057 s
.compressed
= true;
2060 if (!is_valid_option_list(optarg
)) {
2061 error_report("Invalid option list: %s", optarg
);
2065 options
= g_strdup(optarg
);
2067 char *old_options
= options
;
2068 options
= g_strdup_printf("%s,%s", options
, optarg
);
2069 g_free(old_options
);
2073 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2074 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2077 error_report("Failed in parsing snapshot param '%s'",
2082 snapshot_name
= optarg
;
2089 sval
= cvtnum(optarg
);
2090 if (sval
< 0 || sval
& (BDRV_SECTOR_SIZE
- 1) ||
2091 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2092 error_report("Invalid buffer size for sparse output specified. "
2093 "Valid sizes are multiples of %llu up to %llu. Select "
2094 "0 to disable sparse detection (fully allocates output).",
2095 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2099 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2100 explict_min_sparse
= true;
2119 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2120 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2121 error_report("Invalid number of coroutines. Allowed number of"
2122 " coroutines is between 1 and %d", MAX_COROUTINES
);
2127 s
.wr_in_order
= false;
2132 case OPTION_OBJECT
: {
2133 QemuOpts
*object_opts
;
2134 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2141 case OPTION_IMAGE_OPTS
:
2144 case OPTION_TARGET_IMAGE_OPTS
:
2145 tgt_image_opts
= true;
2150 if (!out_fmt
&& !tgt_image_opts
) {
2154 if (qemu_opts_foreach(&qemu_object_opts
,
2155 user_creatable_add_opts_foreach
,
2156 NULL
, &error_fatal
)) {
2160 if (s
.compressed
&& s
.copy_range
) {
2161 error_report("Cannot enable copy offloading when -c is used");
2165 if (explict_min_sparse
&& s
.copy_range
) {
2166 error_report("Cannot enable copy offloading when -S is used");
2170 if (tgt_image_opts
&& !skip_create
) {
2171 error_report("--target-image-opts requires use of -n flag");
2175 s
.src_num
= argc
- optind
- 1;
2176 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2178 if (options
&& has_help_option(options
)) {
2180 ret
= print_block_option_help(out_filename
, out_fmt
);
2183 error_report("Option help requires a format be specified");
2188 if (s
.src_num
< 1) {
2189 error_report("Must specify image file name");
2194 /* ret is still -EINVAL until here */
2195 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2197 error_report("Invalid source cache option: %s", src_cache
);
2201 /* Initialize before goto out */
2205 qemu_progress_init(progress
, 1.0);
2206 qemu_progress_print(0, 100);
2208 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2209 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2211 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2212 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2213 fmt
, src_flags
, src_writethrough
, quiet
,
2219 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2220 if (s
.src_sectors
[bs_i
] < 0) {
2221 error_report("Could not get size of %s: %s",
2222 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2226 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2230 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2231 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2232 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2234 } else if (snapshot_name
!= NULL
) {
2235 if (s
.src_num
> 1) {
2236 error_report("No support for concatenating multiple snapshot");
2241 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2245 error_reportf_err(local_err
, "Failed to load snapshot: ");
2251 /* Find driver and parse its options */
2252 drv
= bdrv_find_format(out_fmt
);
2254 error_report("Unknown file format '%s'", out_fmt
);
2259 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2261 error_report_err(local_err
);
2266 if (!drv
->create_opts
) {
2267 error_report("Format driver '%s' does not support image creation",
2273 if (!proto_drv
->create_opts
) {
2274 error_report("Protocol driver '%s' does not support image creation",
2275 proto_drv
->format_name
);
2280 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2281 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2283 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2285 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2287 error_report_err(local_err
);
2293 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2295 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2301 /* Get backing file name if -o backing_file was used */
2302 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2303 if (out_baseimg_param
) {
2304 out_baseimg
= out_baseimg_param
;
2306 s
.target_has_backing
= (bool) out_baseimg
;
2308 if (s
.src_num
> 1 && out_baseimg
) {
2309 error_report("Having a backing file for the target makes no sense when "
2310 "concatenating multiple input images");
2315 /* Check if compression is supported */
2318 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2319 const char *encryptfmt
=
2320 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2321 const char *preallocation
=
2322 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2324 if (drv
&& !drv
->bdrv_co_pwritev_compressed
) {
2325 error_report("Compression not supported for this file format");
2330 if (encryption
|| encryptfmt
) {
2331 error_report("Compression and encryption not supported at "
2338 && strcmp(preallocation
, "off"))
2340 error_report("Compression and preallocation not supported at "
2348 * The later open call will need any decryption secrets, and
2349 * bdrv_create() will purge "opts", so extract them now before
2353 open_opts
= qdict_new();
2354 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2358 /* Create the new image */
2359 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2361 error_reportf_err(local_err
, "%s: error while converting %s: ",
2362 out_filename
, out_fmt
);
2367 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2368 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2370 error_report("Invalid cache option: %s", cache
);
2375 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2376 flags
, writethrough
, quiet
, false);
2378 /* TODO ultimately we should allow --target-image-opts
2379 * to be used even when -n is not given.
2380 * That has to wait for bdrv_create to be improved
2381 * to allow filenames in option syntax
2383 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2384 flags
, writethrough
, quiet
, false);
2385 open_opts
= NULL
; /* blk_new_open will have freed it */
2391 out_bs
= blk_bs(s
.target
);
2393 if (s
.compressed
&& !out_bs
->drv
->bdrv_co_pwritev_compressed
) {
2394 error_report("Compression not supported for this file format");
2399 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2400 * or discard_alignment of the out_bs is greater. Limit to
2401 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2402 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2404 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2405 out_bs
->bl
.pdiscard_alignment
>>
2406 BDRV_SECTOR_BITS
)));
2408 /* try to align the write requests to the destination to avoid unnecessary
2410 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2411 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2413 assert(is_power_of_2(s
.alignment
));
2416 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2417 if (output_sectors
< 0) {
2418 error_report("unable to get output image length: %s",
2419 strerror(-output_sectors
));
2422 } else if (output_sectors
< s
.total_sectors
) {
2423 error_report("output file is smaller than input file");
2429 if (s
.target_has_backing
) {
2430 /* Errors are treated as "backing length unknown" (which means
2431 * s.target_backing_sectors has to be negative, which it will
2432 * be automatically). The backing file length is used only
2433 * for optimizations, so such a case is not fatal. */
2434 s
.target_backing_sectors
= bdrv_nb_sectors(out_bs
->backing
->bs
);
2436 s
.target_backing_sectors
= -1;
2439 ret
= bdrv_get_info(out_bs
, &bdi
);
2442 error_report("could not get block driver info");
2446 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2447 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2448 s
.unallocated_blocks_are_zero
= bdi
.unallocated_blocks_are_zero
;
2451 ret
= convert_do_copy(&s
);
2454 qemu_progress_print(100, 0);
2456 qemu_progress_end();
2457 qemu_opts_del(opts
);
2458 qemu_opts_free(create_opts
);
2459 qemu_opts_del(sn_opts
);
2460 qobject_unref(open_opts
);
2461 blk_unref(s
.target
);
2463 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2464 blk_unref(s
.src
[bs_i
]);
2468 g_free(s
.src_sectors
);
2476 static void dump_snapshots(BlockDriverState
*bs
)
2478 QEMUSnapshotInfo
*sn_tab
, *sn
;
2481 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2484 printf("Snapshot list:\n");
2485 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
2487 for(i
= 0; i
< nb_sns
; i
++) {
2489 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
2495 static void dump_json_image_info_list(ImageInfoList
*list
)
2499 Visitor
*v
= qobject_output_visitor_new(&obj
);
2501 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2502 visit_complete(v
, &obj
);
2503 str
= qobject_to_json_pretty(obj
);
2504 assert(str
!= NULL
);
2505 printf("%s\n", qstring_get_str(str
));
2511 static void dump_json_image_info(ImageInfo
*info
)
2515 Visitor
*v
= qobject_output_visitor_new(&obj
);
2517 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2518 visit_complete(v
, &obj
);
2519 str
= qobject_to_json_pretty(obj
);
2520 assert(str
!= NULL
);
2521 printf("%s\n", qstring_get_str(str
));
2527 static void dump_human_image_info_list(ImageInfoList
*list
)
2529 ImageInfoList
*elem
;
2532 for (elem
= list
; elem
; elem
= elem
->next
) {
2538 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
2542 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2544 return strcmp(a
, b
) == 0;
2548 * Open an image file chain and return an ImageInfoList
2550 * @filename: topmost image filename
2551 * @fmt: topmost image format (may be NULL to autodetect)
2552 * @chain: true - enumerate entire backing file chain
2553 * false - only topmost image file
2555 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2556 * image file. If there was an error a message will have been printed to
2559 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2560 const char *filename
,
2562 bool chain
, bool force_share
)
2564 ImageInfoList
*head
= NULL
;
2565 ImageInfoList
**last
= &head
;
2566 GHashTable
*filenames
;
2569 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2573 BlockDriverState
*bs
;
2575 ImageInfoList
*elem
;
2577 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2578 error_report("Backing file '%s' creates an infinite loop.",
2582 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2584 blk
= img_open(image_opts
, filename
, fmt
,
2585 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2592 bdrv_query_image_info(bs
, &info
, &err
);
2594 error_report_err(err
);
2599 elem
= g_new0(ImageInfoList
, 1);
2606 filename
= fmt
= NULL
;
2608 if (info
->has_full_backing_filename
) {
2609 filename
= info
->full_backing_filename
;
2610 } else if (info
->has_backing_filename
) {
2611 error_report("Could not determine absolute backing filename,"
2612 " but backing filename '%s' present",
2613 info
->backing_filename
);
2616 if (info
->has_backing_filename_format
) {
2617 fmt
= info
->backing_filename_format
;
2621 g_hash_table_destroy(filenames
);
2625 qapi_free_ImageInfoList(head
);
2626 g_hash_table_destroy(filenames
);
2630 static int img_info(int argc
, char **argv
)
2633 OutputFormat output_format
= OFORMAT_HUMAN
;
2635 const char *filename
, *fmt
, *output
;
2636 ImageInfoList
*list
;
2637 bool image_opts
= false;
2638 bool force_share
= false;
2643 int option_index
= 0;
2644 static const struct option long_options
[] = {
2645 {"help", no_argument
, 0, 'h'},
2646 {"format", required_argument
, 0, 'f'},
2647 {"output", required_argument
, 0, OPTION_OUTPUT
},
2648 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2649 {"object", required_argument
, 0, OPTION_OBJECT
},
2650 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2651 {"force-share", no_argument
, 0, 'U'},
2654 c
= getopt_long(argc
, argv
, ":f:hU",
2655 long_options
, &option_index
);
2661 missing_argument(argv
[optind
- 1]);
2664 unrecognized_option(argv
[optind
- 1]);
2678 case OPTION_BACKING_CHAIN
:
2681 case OPTION_OBJECT
: {
2683 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2689 case OPTION_IMAGE_OPTS
:
2694 if (optind
!= argc
- 1) {
2695 error_exit("Expecting one image file name");
2697 filename
= argv
[optind
++];
2699 if (output
&& !strcmp(output
, "json")) {
2700 output_format
= OFORMAT_JSON
;
2701 } else if (output
&& !strcmp(output
, "human")) {
2702 output_format
= OFORMAT_HUMAN
;
2703 } else if (output
) {
2704 error_report("--output must be used with human or json as argument.");
2708 if (qemu_opts_foreach(&qemu_object_opts
,
2709 user_creatable_add_opts_foreach
,
2710 NULL
, &error_fatal
)) {
2714 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2720 switch (output_format
) {
2722 dump_human_image_info_list(list
);
2726 dump_json_image_info_list(list
);
2728 dump_json_image_info(list
->value
);
2733 qapi_free_ImageInfoList(list
);
2737 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2740 switch (output_format
) {
2742 if (e
->data
&& !e
->has_offset
) {
2743 error_report("File contains external, encrypted or compressed clusters.");
2746 if (e
->data
&& !e
->zero
) {
2747 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2748 e
->start
, e
->length
,
2749 e
->has_offset
? e
->offset
: 0,
2750 e
->has_filename
? e
->filename
: "");
2752 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2753 * Modify the flags here to allow more coalescing.
2755 if (next
&& (!next
->data
|| next
->zero
)) {
2761 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2762 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2763 (e
->start
== 0 ? "[" : ",\n"),
2764 e
->start
, e
->length
, e
->depth
,
2765 e
->zero
? "true" : "false",
2766 e
->data
? "true" : "false");
2767 if (e
->has_offset
) {
2768 printf(", \"offset\": %"PRId64
"", e
->offset
);
2779 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
2780 int64_t bytes
, MapEntry
*e
)
2784 BlockDriverState
*file
;
2787 char *filename
= NULL
;
2789 /* As an optimization, we could cache the current range of unallocated
2790 * clusters in each file of the chain, and avoid querying the same
2796 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
2801 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2804 bs
= backing_bs(bs
);
2813 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2815 if (file
&& has_offset
) {
2816 bdrv_refresh_filename(file
);
2817 filename
= file
->filename
;
2823 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2824 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2826 .has_offset
= has_offset
,
2828 .has_filename
= filename
,
2829 .filename
= filename
,
2835 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2837 if (curr
->length
== 0) {
2840 if (curr
->zero
!= next
->zero
||
2841 curr
->data
!= next
->data
||
2842 curr
->depth
!= next
->depth
||
2843 curr
->has_filename
!= next
->has_filename
||
2844 curr
->has_offset
!= next
->has_offset
) {
2847 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2850 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2856 static int img_map(int argc
, char **argv
)
2859 OutputFormat output_format
= OFORMAT_HUMAN
;
2861 BlockDriverState
*bs
;
2862 const char *filename
, *fmt
, *output
;
2864 MapEntry curr
= { .length
= 0 }, next
;
2866 bool image_opts
= false;
2867 bool force_share
= false;
2872 int option_index
= 0;
2873 static const struct option long_options
[] = {
2874 {"help", no_argument
, 0, 'h'},
2875 {"format", required_argument
, 0, 'f'},
2876 {"output", required_argument
, 0, OPTION_OUTPUT
},
2877 {"object", required_argument
, 0, OPTION_OBJECT
},
2878 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2879 {"force-share", no_argument
, 0, 'U'},
2882 c
= getopt_long(argc
, argv
, ":f:hU",
2883 long_options
, &option_index
);
2889 missing_argument(argv
[optind
- 1]);
2892 unrecognized_option(argv
[optind
- 1]);
2906 case OPTION_OBJECT
: {
2908 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2914 case OPTION_IMAGE_OPTS
:
2919 if (optind
!= argc
- 1) {
2920 error_exit("Expecting one image file name");
2922 filename
= argv
[optind
];
2924 if (output
&& !strcmp(output
, "json")) {
2925 output_format
= OFORMAT_JSON
;
2926 } else if (output
&& !strcmp(output
, "human")) {
2927 output_format
= OFORMAT_HUMAN
;
2928 } else if (output
) {
2929 error_report("--output must be used with human or json as argument.");
2933 if (qemu_opts_foreach(&qemu_object_opts
,
2934 user_creatable_add_opts_foreach
,
2935 NULL
, &error_fatal
)) {
2939 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
2945 if (output_format
== OFORMAT_HUMAN
) {
2946 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2949 length
= blk_getlength(blk
);
2950 while (curr
.start
+ curr
.length
< length
) {
2951 int64_t offset
= curr
.start
+ curr
.length
;
2954 /* Probe up to 1 GiB at a time. */
2955 n
= MIN(1 << 30, length
- offset
);
2956 ret
= get_block_status(bs
, offset
, n
, &next
);
2959 error_report("Could not read file metadata: %s", strerror(-ret
));
2963 if (entry_mergeable(&curr
, &next
)) {
2964 curr
.length
+= next
.length
;
2968 if (curr
.length
> 0) {
2969 dump_map_entry(output_format
, &curr
, &next
);
2974 dump_map_entry(output_format
, &curr
, NULL
);
2981 #define SNAPSHOT_LIST 1
2982 #define SNAPSHOT_CREATE 2
2983 #define SNAPSHOT_APPLY 3
2984 #define SNAPSHOT_DELETE 4
2986 static int img_snapshot(int argc
, char **argv
)
2989 BlockDriverState
*bs
;
2990 QEMUSnapshotInfo sn
;
2991 char *filename
, *snapshot_name
= NULL
;
2992 int c
, ret
= 0, bdrv_oflags
;
2997 bool image_opts
= false;
2998 bool force_share
= false;
3000 bdrv_oflags
= BDRV_O_RDWR
;
3001 /* Parse commandline parameters */
3003 static const struct option long_options
[] = {
3004 {"help", no_argument
, 0, 'h'},
3005 {"object", required_argument
, 0, OPTION_OBJECT
},
3006 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3007 {"force-share", no_argument
, 0, 'U'},
3010 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3011 long_options
, NULL
);
3017 missing_argument(argv
[optind
- 1]);
3020 unrecognized_option(argv
[optind
- 1]);
3027 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3030 action
= SNAPSHOT_LIST
;
3031 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3035 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3038 action
= SNAPSHOT_APPLY
;
3039 snapshot_name
= optarg
;
3043 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3046 action
= SNAPSHOT_CREATE
;
3047 snapshot_name
= optarg
;
3051 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3054 action
= SNAPSHOT_DELETE
;
3055 snapshot_name
= optarg
;
3063 case OPTION_OBJECT
: {
3065 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3071 case OPTION_IMAGE_OPTS
:
3077 if (optind
!= argc
- 1) {
3078 error_exit("Expecting one image file name");
3080 filename
= argv
[optind
++];
3082 if (qemu_opts_foreach(&qemu_object_opts
,
3083 user_creatable_add_opts_foreach
,
3084 NULL
, &error_fatal
)) {
3088 /* Open the image */
3089 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3096 /* Perform the requested action */
3102 case SNAPSHOT_CREATE
:
3103 memset(&sn
, 0, sizeof(sn
));
3104 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3106 qemu_gettimeofday(&tv
);
3107 sn
.date_sec
= tv
.tv_sec
;
3108 sn
.date_nsec
= tv
.tv_usec
* 1000;
3110 ret
= bdrv_snapshot_create(bs
, &sn
);
3112 error_report("Could not create snapshot '%s': %d (%s)",
3113 snapshot_name
, ret
, strerror(-ret
));
3117 case SNAPSHOT_APPLY
:
3118 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3120 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3125 case SNAPSHOT_DELETE
:
3126 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3128 error_report("Could not delete snapshot '%s': snapshot not "
3129 "found", snapshot_name
);
3132 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3134 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3150 static int img_rebase(int argc
, char **argv
)
3152 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3153 uint8_t *buf_old
= NULL
;
3154 uint8_t *buf_new
= NULL
;
3155 BlockDriverState
*bs
= NULL
;
3157 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3158 int c
, flags
, src_flags
, ret
;
3159 bool writethrough
, src_writethrough
;
3161 bool force_share
= false;
3164 Error
*local_err
= NULL
;
3165 bool image_opts
= false;
3167 /* Parse commandline parameters */
3169 cache
= BDRV_DEFAULT_CACHE
;
3170 src_cache
= BDRV_DEFAULT_CACHE
;
3174 static const struct option long_options
[] = {
3175 {"help", no_argument
, 0, 'h'},
3176 {"object", required_argument
, 0, OPTION_OBJECT
},
3177 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3178 {"force-share", no_argument
, 0, 'U'},
3181 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3182 long_options
, NULL
);
3188 missing_argument(argv
[optind
- 1]);
3191 unrecognized_option(argv
[optind
- 1]);
3200 out_basefmt
= optarg
;
3203 out_baseimg
= optarg
;
3220 case OPTION_OBJECT
: {
3222 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3228 case OPTION_IMAGE_OPTS
:
3241 if (optind
!= argc
- 1) {
3242 error_exit("Expecting one image file name");
3244 if (!unsafe
&& !out_baseimg
) {
3245 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3247 filename
= argv
[optind
++];
3249 if (qemu_opts_foreach(&qemu_object_opts
,
3250 user_creatable_add_opts_foreach
,
3251 NULL
, &error_fatal
)) {
3255 qemu_progress_init(progress
, 2.0);
3256 qemu_progress_print(0, 100);
3258 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3259 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3261 error_report("Invalid cache option: %s", cache
);
3266 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3268 error_report("Invalid source cache option: %s", src_cache
);
3272 /* The source files are opened read-only, don't care about WCE */
3273 assert((src_flags
& BDRV_O_RDWR
) == 0);
3274 (void) src_writethrough
;
3279 * Ignore the old backing file for unsafe rebase in case we want to correct
3280 * the reference to a renamed or moved backing file.
3282 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3290 if (out_basefmt
!= NULL
) {
3291 if (bdrv_find_format(out_basefmt
) == NULL
) {
3292 error_report("Invalid format name: '%s'", out_basefmt
);
3298 /* For safe rebasing we need to compare old and new backing file */
3300 char backing_name
[PATH_MAX
];
3301 QDict
*options
= NULL
;
3303 if (bs
->backing_format
[0] != '\0') {
3304 options
= qdict_new();
3305 qdict_put_str(options
, "driver", bs
->backing_format
);
3310 options
= qdict_new();
3312 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3314 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3315 blk_old_backing
= blk_new_open(backing_name
, NULL
,
3316 options
, src_flags
, &local_err
);
3317 if (!blk_old_backing
) {
3318 error_reportf_err(local_err
,
3319 "Could not open old backing file '%s': ",
3325 if (out_baseimg
[0]) {
3326 const char *overlay_filename
;
3327 char *out_real_path
;
3329 options
= qdict_new();
3331 qdict_put_str(options
, "driver", out_basefmt
);
3334 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3337 bdrv_refresh_filename(bs
);
3338 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3341 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3345 error_reportf_err(local_err
,
3346 "Could not resolve backing filename: ");
3351 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3352 options
, src_flags
, &local_err
);
3353 g_free(out_real_path
);
3354 if (!blk_new_backing
) {
3355 error_reportf_err(local_err
,
3356 "Could not open new backing file '%s': ",
3365 * Check each unallocated cluster in the COW file. If it is unallocated,
3366 * accesses go to the backing file. We must therefore compare this cluster
3367 * in the old and new backing file, and if they differ we need to copy it
3368 * from the old backing file into the COW file.
3370 * If qemu-img crashes during this step, no harm is done. The content of
3371 * the image is the same as the original one at any time.
3375 int64_t old_backing_size
;
3376 int64_t new_backing_size
= 0;
3379 float local_progress
= 0;
3381 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3382 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3384 size
= blk_getlength(blk
);
3386 error_report("Could not get size of '%s': %s",
3387 filename
, strerror(-size
));
3391 old_backing_size
= blk_getlength(blk_old_backing
);
3392 if (old_backing_size
< 0) {
3393 char backing_name
[PATH_MAX
];
3395 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3396 error_report("Could not get size of '%s': %s",
3397 backing_name
, strerror(-old_backing_size
));
3401 if (blk_new_backing
) {
3402 new_backing_size
= blk_getlength(blk_new_backing
);
3403 if (new_backing_size
< 0) {
3404 error_report("Could not get size of '%s': %s",
3405 out_baseimg
, strerror(-new_backing_size
));
3412 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3415 for (offset
= 0; offset
< size
; offset
+= n
) {
3416 /* How many bytes can we handle with the next read? */
3417 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3419 /* If the cluster is allocated, we don't need to take action */
3420 ret
= bdrv_is_allocated(bs
, offset
, n
, &n
);
3422 error_report("error while reading image metadata: %s",
3431 * Read old and new backing file and take into consideration that
3432 * backing files may be smaller than the COW image.
3434 if (offset
>= old_backing_size
) {
3435 memset(buf_old
, 0, n
);
3437 if (offset
+ n
> old_backing_size
) {
3438 n
= old_backing_size
- offset
;
3441 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3443 error_report("error while reading from old backing file");
3448 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3449 memset(buf_new
, 0, n
);
3451 if (offset
+ n
> new_backing_size
) {
3452 n
= new_backing_size
- offset
;
3455 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3457 error_report("error while reading from new backing file");
3462 /* If they differ, we need to write to the COW file */
3463 uint64_t written
= 0;
3465 while (written
< n
) {
3468 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3469 n
- written
, &pnum
))
3471 ret
= blk_pwrite(blk
, offset
+ written
,
3472 buf_old
+ written
, pnum
, 0);
3474 error_report("Error while writing to COW image: %s",
3482 qemu_progress_print(local_progress
, 100);
3487 * Change the backing file. All clusters that are different from the old
3488 * backing file are overwritten in the COW file now, so the visible content
3489 * doesn't change when we switch the backing file.
3491 if (out_baseimg
&& *out_baseimg
) {
3492 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3494 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3497 if (ret
== -ENOSPC
) {
3498 error_report("Could not change the backing file to '%s': No "
3499 "space left in the file header", out_baseimg
);
3500 } else if (ret
< 0) {
3501 error_report("Could not change the backing file to '%s': %s",
3502 out_baseimg
, strerror(-ret
));
3505 qemu_progress_print(100, 0);
3507 * TODO At this point it is possible to check if any clusters that are
3508 * allocated in the COW file are the same in the backing file. If so, they
3509 * could be dropped from the COW file. Don't do this before switching the
3510 * backing file, in case of a crash this would lead to corruption.
3513 qemu_progress_end();
3516 blk_unref(blk_old_backing
);
3517 blk_unref(blk_new_backing
);
3519 qemu_vfree(buf_old
);
3520 qemu_vfree(buf_new
);
3529 static int img_resize(int argc
, char **argv
)
3532 int c
, ret
, relative
;
3533 const char *filename
, *fmt
, *size
;
3534 int64_t n
, total_size
, current_size
, new_size
;
3536 BlockBackend
*blk
= NULL
;
3537 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3540 static QemuOptsList resize_options
= {
3541 .name
= "resize_options",
3542 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3545 .name
= BLOCK_OPT_SIZE
,
3546 .type
= QEMU_OPT_SIZE
,
3547 .help
= "Virtual disk size"
3553 bool image_opts
= false;
3554 bool shrink
= false;
3556 /* Remove size from argv manually so that negative numbers are not treated
3557 * as options by getopt. */
3559 error_exit("Not enough arguments");
3563 size
= argv
[--argc
];
3565 /* Parse getopt arguments */
3568 static const struct option long_options
[] = {
3569 {"help", no_argument
, 0, 'h'},
3570 {"object", required_argument
, 0, OPTION_OBJECT
},
3571 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3572 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3573 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3576 c
= getopt_long(argc
, argv
, ":f:hq",
3577 long_options
, NULL
);
3583 missing_argument(argv
[optind
- 1]);
3586 unrecognized_option(argv
[optind
- 1]);
3597 case OPTION_OBJECT
: {
3599 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3605 case OPTION_IMAGE_OPTS
:
3608 case OPTION_PREALLOCATION
:
3609 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3610 PREALLOC_MODE__MAX
, NULL
);
3611 if (prealloc
== PREALLOC_MODE__MAX
) {
3612 error_report("Invalid preallocation mode '%s'", optarg
);
3621 if (optind
!= argc
- 1) {
3622 error_exit("Expecting image file name and size");
3624 filename
= argv
[optind
++];
3626 if (qemu_opts_foreach(&qemu_object_opts
,
3627 user_creatable_add_opts_foreach
,
3628 NULL
, &error_fatal
)) {
3632 /* Choose grow, shrink, or absolute resize mode */
3648 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3649 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3651 error_report_err(err
);
3653 qemu_opts_del(param
);
3656 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3657 qemu_opts_del(param
);
3659 blk
= img_open(image_opts
, filename
, fmt
,
3660 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3667 current_size
= blk_getlength(blk
);
3668 if (current_size
< 0) {
3669 error_report("Failed to inquire current image length: %s",
3670 strerror(-current_size
));
3676 total_size
= current_size
+ n
* relative
;
3680 if (total_size
<= 0) {
3681 error_report("New image size must be positive");
3686 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3687 error_report("Preallocation can only be used for growing images");
3692 if (total_size
< current_size
&& !shrink
) {
3693 warn_report("Shrinking an image will delete all data beyond the "
3694 "shrunken image's end. Before performing such an "
3695 "operation, make sure there is no important data there.");
3697 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk
)), "raw") != 0) {
3699 "Use the --shrink option to perform a shrink operation.");
3703 warn_report("Using the --shrink option will suppress this message. "
3704 "Note that future versions of qemu-img may refuse to "
3705 "shrink images without this option.");
3709 ret
= blk_truncate(blk
, total_size
, prealloc
, &err
);
3711 error_report_err(err
);
3715 new_size
= blk_getlength(blk
);
3717 error_report("Failed to verify truncated image length: %s",
3718 strerror(-new_size
));
3723 /* Some block drivers implement a truncation method, but only so
3724 * the user can cause qemu to refresh the image's size from disk.
3725 * The idea is that the user resizes the image outside of qemu and
3726 * then invokes block_resize to inform qemu about it.
3727 * (This includes iscsi and file-posix for device files.)
3728 * Of course, that is not the behavior someone invoking
3729 * qemu-img resize would find useful, so we catch that behavior
3730 * here and tell the user. */
3731 if (new_size
!= total_size
&& new_size
== current_size
) {
3732 error_report("Image was not resized; resizing may not be supported "
3738 if (new_size
!= total_size
) {
3739 warn_report("Image should have been resized to %" PRIi64
3740 " bytes, but was resized to %" PRIi64
" bytes",
3741 total_size
, new_size
);
3744 qprintf(quiet
, "Image resized.\n");
3754 static void amend_status_cb(BlockDriverState
*bs
,
3755 int64_t offset
, int64_t total_work_size
,
3758 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3761 static int print_amend_option_help(const char *format
)
3765 /* Find driver and parse its options */
3766 drv
= bdrv_find_format(format
);
3768 error_report("Unknown file format '%s'", format
);
3772 if (!drv
->bdrv_amend_options
) {
3773 error_report("Format driver '%s' does not support option amendment",
3778 /* Every driver supporting amendment must have create_opts */
3779 assert(drv
->create_opts
);
3781 printf("Creation options for '%s':\n", format
);
3782 qemu_opts_print_help(drv
->create_opts
, false);
3783 printf("\nNote that not all of these options may be amendable.\n");
3787 static int img_amend(int argc
, char **argv
)
3791 char *options
= NULL
;
3792 QemuOptsList
*create_opts
= NULL
;
3793 QemuOpts
*opts
= NULL
;
3794 const char *fmt
= NULL
, *filename
, *cache
;
3797 bool quiet
= false, progress
= false;
3798 BlockBackend
*blk
= NULL
;
3799 BlockDriverState
*bs
= NULL
;
3800 bool image_opts
= false;
3802 cache
= BDRV_DEFAULT_CACHE
;
3804 static const struct option long_options
[] = {
3805 {"help", no_argument
, 0, 'h'},
3806 {"object", required_argument
, 0, OPTION_OBJECT
},
3807 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3810 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
3811 long_options
, NULL
);
3818 missing_argument(argv
[optind
- 1]);
3821 unrecognized_option(argv
[optind
- 1]);
3827 if (!is_valid_option_list(optarg
)) {
3828 error_report("Invalid option list: %s", optarg
);
3830 goto out_no_progress
;
3833 options
= g_strdup(optarg
);
3835 char *old_options
= options
;
3836 options
= g_strdup_printf("%s,%s", options
, optarg
);
3837 g_free(old_options
);
3853 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3857 goto out_no_progress
;
3860 case OPTION_IMAGE_OPTS
:
3867 error_exit("Must specify options (-o)");
3870 if (qemu_opts_foreach(&qemu_object_opts
,
3871 user_creatable_add_opts_foreach
,
3872 NULL
, &error_fatal
)) {
3874 goto out_no_progress
;
3880 qemu_progress_init(progress
, 1.0);
3882 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
3883 if (fmt
&& has_help_option(options
)) {
3884 /* If a format is explicitly specified (and possibly no filename is
3885 * given), print option help here */
3886 ret
= print_amend_option_help(fmt
);
3890 if (optind
!= argc
- 1) {
3891 error_report("Expecting one image file name");
3896 flags
= BDRV_O_RDWR
;
3897 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3899 error_report("Invalid cache option: %s", cache
);
3903 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3911 fmt
= bs
->drv
->format_name
;
3913 if (has_help_option(options
)) {
3914 /* If the format was auto-detected, print option help here */
3915 ret
= print_amend_option_help(fmt
);
3919 if (!bs
->drv
->bdrv_amend_options
) {
3920 error_report("Format driver '%s' does not support option amendment",
3926 /* Every driver supporting amendment must have create_opts */
3927 assert(bs
->drv
->create_opts
);
3929 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
3930 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
3931 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
3933 error_report_err(err
);
3938 /* In case the driver does not call amend_status_cb() */
3939 qemu_progress_print(0.f
, 0);
3940 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, &err
);
3941 qemu_progress_print(100.f
, 0);
3943 error_report_err(err
);
3948 qemu_progress_end();
3952 qemu_opts_del(opts
);
3953 qemu_opts_free(create_opts
);
3962 typedef struct BenchData
{
3964 uint64_t image_size
;
3971 bool drain_on_flush
;
3980 static void bench_undrained_flush_cb(void *opaque
, int ret
)
3983 error_report("Failed flush request: %s", strerror(-ret
));
3988 static void bench_cb(void *opaque
, int ret
)
3990 BenchData
*b
= opaque
;
3994 error_report("Failed request: %s", strerror(-ret
));
3999 /* Just finished a flush with drained queue: Start next requests */
4000 assert(b
->in_flight
== 0);
4001 b
->in_flush
= false;
4002 } else if (b
->in_flight
> 0) {
4003 int remaining
= b
->n
- b
->in_flight
;
4008 /* Time for flush? Drain queue if requested, then flush */
4009 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4010 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4011 BlockCompletionFunc
*cb
;
4013 if (b
->drain_on_flush
) {
4017 cb
= bench_undrained_flush_cb
;
4020 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4022 error_report("Failed to issue flush request");
4026 if (b
->drain_on_flush
) {
4032 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4033 int64_t offset
= b
->offset
;
4034 /* blk_aio_* might look for completed I/Os and kick bench_cb
4035 * again, so make sure this operation is counted by in_flight
4036 * and b->offset is ready for the next submission.
4039 b
->offset
+= b
->step
;
4040 b
->offset
%= b
->image_size
;
4042 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4044 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4047 error_report("Failed to issue request");
4053 static int img_bench(int argc
, char **argv
)
4056 const char *fmt
= NULL
, *filename
;
4058 bool image_opts
= false;
4059 bool is_write
= false;
4063 size_t bufsize
= 4096;
4066 int flush_interval
= 0;
4067 bool drain_on_flush
= true;
4069 BlockBackend
*blk
= NULL
;
4070 BenchData data
= {};
4072 bool writethrough
= false;
4073 struct timeval t1
, t2
;
4075 bool force_share
= false;
4079 static const struct option long_options
[] = {
4080 {"help", no_argument
, 0, 'h'},
4081 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4082 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4083 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4084 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4085 {"force-share", no_argument
, 0, 'U'},
4088 c
= getopt_long(argc
, argv
, ":hc:d:f:no:qs:S:t:wU", long_options
, NULL
);
4095 missing_argument(argv
[optind
- 1]);
4098 unrecognized_option(argv
[optind
- 1]);
4107 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4108 error_report("Invalid request count specified");
4118 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4119 error_report("Invalid queue depth specified");
4129 flags
|= BDRV_O_NATIVE_AIO
;
4133 offset
= cvtnum(optarg
);
4135 error_report("Invalid offset specified");
4148 sval
= cvtnum(optarg
);
4149 if (sval
< 0 || sval
> INT_MAX
) {
4150 error_report("Invalid buffer size specified");
4161 sval
= cvtnum(optarg
);
4162 if (sval
< 0 || sval
> INT_MAX
) {
4163 error_report("Invalid step size specified");
4171 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4173 error_report("Invalid cache mode");
4179 flags
|= BDRV_O_RDWR
;
4185 case OPTION_PATTERN
:
4189 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4190 error_report("Invalid pattern byte specified");
4196 case OPTION_FLUSH_INTERVAL
:
4200 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4201 error_report("Invalid flush interval specified");
4204 flush_interval
= res
;
4207 case OPTION_NO_DRAIN
:
4208 drain_on_flush
= false;
4210 case OPTION_IMAGE_OPTS
:
4216 if (optind
!= argc
- 1) {
4217 error_exit("Expecting one image file name");
4219 filename
= argv
[argc
- 1];
4221 if (!is_write
&& flush_interval
) {
4222 error_report("--flush-interval is only available in write tests");
4226 if (flush_interval
&& flush_interval
< depth
) {
4227 error_report("Flush interval can't be smaller than depth");
4232 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4239 image_size
= blk_getlength(blk
);
4240 if (image_size
< 0) {
4245 data
= (BenchData
) {
4247 .image_size
= image_size
,
4249 .step
= step
?: bufsize
,
4254 .flush_interval
= flush_interval
,
4255 .drain_on_flush
= drain_on_flush
,
4257 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4258 "(starting at offset %" PRId64
", step size %d)\n",
4259 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4260 data
.offset
, data
.step
);
4261 if (flush_interval
) {
4262 printf("Sending flush every %d requests\n", flush_interval
);
4265 buf_size
= data
.nrreq
* data
.bufsize
;
4266 data
.buf
= blk_blockalign(blk
, buf_size
);
4267 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4269 blk_register_buf(blk
, data
.buf
, buf_size
);
4271 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4272 for (i
= 0; i
< data
.nrreq
; i
++) {
4273 qemu_iovec_init(&data
.qiov
[i
], 1);
4274 qemu_iovec_add(&data
.qiov
[i
],
4275 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4278 gettimeofday(&t1
, NULL
);
4281 while (data
.n
> 0) {
4282 main_loop_wait(false);
4284 gettimeofday(&t2
, NULL
);
4286 printf("Run completed in %3.3f seconds.\n",
4287 (t2
.tv_sec
- t1
.tv_sec
)
4288 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4292 blk_unregister_buf(blk
, data
.buf
);
4294 qemu_vfree(data
.buf
);
4315 int bsz
; /* Block size */
4323 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4327 static int img_dd_bs(const char *arg
,
4328 struct DdIo
*in
, struct DdIo
*out
,
4335 if (res
<= 0 || res
> INT_MAX
) {
4336 error_report("invalid number: '%s'", arg
);
4339 in
->bsz
= out
->bsz
= res
;
4344 static int img_dd_count(const char *arg
,
4345 struct DdIo
*in
, struct DdIo
*out
,
4348 dd
->count
= cvtnum(arg
);
4350 if (dd
->count
< 0) {
4351 error_report("invalid number: '%s'", arg
);
4358 static int img_dd_if(const char *arg
,
4359 struct DdIo
*in
, struct DdIo
*out
,
4362 in
->filename
= g_strdup(arg
);
4367 static int img_dd_of(const char *arg
,
4368 struct DdIo
*in
, struct DdIo
*out
,
4371 out
->filename
= g_strdup(arg
);
4376 static int img_dd_skip(const char *arg
,
4377 struct DdIo
*in
, struct DdIo
*out
,
4380 in
->offset
= cvtnum(arg
);
4382 if (in
->offset
< 0) {
4383 error_report("invalid number: '%s'", arg
);
4390 static int img_dd(int argc
, char **argv
)
4395 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4396 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4397 QemuOpts
*opts
= NULL
;
4398 QemuOptsList
*create_opts
= NULL
;
4399 Error
*local_err
= NULL
;
4400 bool image_opts
= false;
4402 const char *out_fmt
= "raw";
4403 const char *fmt
= NULL
;
4405 int64_t block_count
= 0, out_pos
, in_pos
;
4406 bool force_share
= false;
4407 struct DdInfo dd
= {
4412 .bsz
= 512, /* Block size is by default 512 bytes */
4424 const struct DdOpts options
[] = {
4425 { "bs", img_dd_bs
, C_BS
},
4426 { "count", img_dd_count
, C_COUNT
},
4427 { "if", img_dd_if
, C_IF
},
4428 { "of", img_dd_of
, C_OF
},
4429 { "skip", img_dd_skip
, C_SKIP
},
4432 const struct option long_options
[] = {
4433 { "help", no_argument
, 0, 'h'},
4434 { "object", required_argument
, 0, OPTION_OBJECT
},
4435 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4436 { "force-share", no_argument
, 0, 'U'},
4440 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4452 missing_argument(argv
[optind
- 1]);
4455 unrecognized_option(argv
[optind
- 1]);
4464 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4469 case OPTION_IMAGE_OPTS
:
4475 for (i
= optind
; i
< argc
; i
++) {
4477 arg
= g_strdup(argv
[i
]);
4479 tmp
= strchr(arg
, '=');
4481 error_report("unrecognized operand %s", arg
);
4488 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4489 if (!strcmp(arg
, options
[j
].name
)) {
4493 if (options
[j
].name
== NULL
) {
4494 error_report("unrecognized operand %s", arg
);
4499 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4503 dd
.flags
|= options
[j
].flag
;
4508 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4509 error_report("Must specify both input and output files");
4514 if (qemu_opts_foreach(&qemu_object_opts
,
4515 user_creatable_add_opts_foreach
,
4516 NULL
, &error_fatal
)) {
4521 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4529 drv
= bdrv_find_format(out_fmt
);
4531 error_report("Unknown file format");
4535 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4538 error_report_err(local_err
);
4542 if (!drv
->create_opts
) {
4543 error_report("Format driver '%s' does not support image creation",
4548 if (!proto_drv
->create_opts
) {
4549 error_report("Protocol driver '%s' does not support image creation",
4550 proto_drv
->format_name
);
4554 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4555 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4557 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4559 size
= blk_getlength(blk1
);
4561 error_report("Failed to get size for '%s'", in
.filename
);
4566 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4567 dd
.count
* in
.bsz
< size
) {
4568 size
= dd
.count
* in
.bsz
;
4571 /* Overflow means the specified offset is beyond input image's size */
4572 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4573 size
< in
.bsz
* in
.offset
)) {
4574 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4576 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4577 size
- in
.bsz
* in
.offset
, &error_abort
);
4580 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4582 error_reportf_err(local_err
,
4583 "%s: error while creating output image: ",
4589 /* TODO, we can't honour --image-opts for the target,
4590 * since it needs to be given in a format compatible
4591 * with the bdrv_create() call above which does not
4592 * support image-opts style.
4594 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
4595 false, false, false);
4602 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4603 size
< in
.offset
* in
.bsz
)) {
4604 /* We give a warning if the skip option is bigger than the input
4605 * size and create an empty output disk image (i.e. like dd(1)).
4607 error_report("%s: cannot skip to specified offset", in
.filename
);
4610 in_pos
= in
.offset
* in
.bsz
;
4613 in
.buf
= g_new(uint8_t, in
.bsz
);
4615 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4616 int in_ret
, out_ret
;
4618 if (in_pos
+ in
.bsz
> size
) {
4619 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4621 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4624 error_report("error while reading from input image file: %s",
4631 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4634 error_report("error while writing to output image file: %s",
4635 strerror(-out_ret
));
4644 qemu_opts_del(opts
);
4645 qemu_opts_free(create_opts
);
4648 g_free(in
.filename
);
4649 g_free(out
.filename
);
4659 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
4663 Visitor
*v
= qobject_output_visitor_new(&obj
);
4665 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
4666 visit_complete(v
, &obj
);
4667 str
= qobject_to_json_pretty(obj
);
4668 assert(str
!= NULL
);
4669 printf("%s\n", qstring_get_str(str
));
4675 static int img_measure(int argc
, char **argv
)
4677 static const struct option long_options
[] = {
4678 {"help", no_argument
, 0, 'h'},
4679 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4680 {"object", required_argument
, 0, OPTION_OBJECT
},
4681 {"output", required_argument
, 0, OPTION_OUTPUT
},
4682 {"size", required_argument
, 0, OPTION_SIZE
},
4683 {"force-share", no_argument
, 0, 'U'},
4686 OutputFormat output_format
= OFORMAT_HUMAN
;
4687 BlockBackend
*in_blk
= NULL
;
4689 const char *filename
= NULL
;
4690 const char *fmt
= NULL
;
4691 const char *out_fmt
= "raw";
4692 char *options
= NULL
;
4693 char *snapshot_name
= NULL
;
4694 bool force_share
= false;
4695 QemuOpts
*opts
= NULL
;
4696 QemuOpts
*object_opts
= NULL
;
4697 QemuOpts
*sn_opts
= NULL
;
4698 QemuOptsList
*create_opts
= NULL
;
4699 bool image_opts
= false;
4700 uint64_t img_size
= UINT64_MAX
;
4701 BlockMeasureInfo
*info
= NULL
;
4702 Error
*local_err
= NULL
;
4706 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
4707 long_options
, NULL
)) != -1) {
4720 if (!is_valid_option_list(optarg
)) {
4721 error_report("Invalid option list: %s", optarg
);
4725 options
= g_strdup(optarg
);
4727 char *old_options
= options
;
4728 options
= g_strdup_printf("%s,%s", options
, optarg
);
4729 g_free(old_options
);
4733 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
4734 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
4737 error_report("Failed in parsing snapshot param '%s'",
4742 snapshot_name
= optarg
;
4749 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4755 case OPTION_IMAGE_OPTS
:
4759 if (!strcmp(optarg
, "json")) {
4760 output_format
= OFORMAT_JSON
;
4761 } else if (!strcmp(optarg
, "human")) {
4762 output_format
= OFORMAT_HUMAN
;
4764 error_report("--output must be used with human or json "
4773 sval
= cvtnum(optarg
);
4775 if (sval
== -ERANGE
) {
4776 error_report("Image size must be less than 8 EiB!");
4778 error_report("Invalid image size specified! You may use "
4779 "k, M, G, T, P or E suffixes for ");
4780 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4781 "petabytes and exabytes.");
4785 img_size
= (uint64_t)sval
;
4791 if (qemu_opts_foreach(&qemu_object_opts
,
4792 user_creatable_add_opts_foreach
,
4793 NULL
, &error_fatal
)) {
4797 if (argc
- optind
> 1) {
4798 error_report("At most one filename argument is allowed.");
4800 } else if (argc
- optind
== 1) {
4801 filename
= argv
[optind
];
4805 (object_opts
|| image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
4806 error_report("--object, --image-opts, -f, and -l "
4807 "require a filename argument.");
4810 if (filename
&& img_size
!= UINT64_MAX
) {
4811 error_report("--size N cannot be used together with a filename.");
4814 if (!filename
&& img_size
== UINT64_MAX
) {
4815 error_report("Either --size N or one filename must be specified.");
4820 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
4821 false, false, force_share
);
4827 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
4828 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
4829 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
4831 } else if (snapshot_name
!= NULL
) {
4832 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
4833 snapshot_name
, &local_err
);
4836 error_reportf_err(local_err
, "Failed to load snapshot: ");
4841 drv
= bdrv_find_format(out_fmt
);
4843 error_report("Unknown file format '%s'", out_fmt
);
4846 if (!drv
->create_opts
) {
4847 error_report("Format driver '%s' does not support image creation",
4852 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4853 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
4854 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4856 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
4858 error_report_err(local_err
);
4859 error_report("Invalid options for file format '%s'", out_fmt
);
4863 if (img_size
!= UINT64_MAX
) {
4864 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
4867 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
4869 error_report_err(local_err
);
4873 if (output_format
== OFORMAT_HUMAN
) {
4874 printf("required size: %" PRIu64
"\n", info
->required
);
4875 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
4877 dump_json_block_measure_info(info
);
4883 qapi_free_BlockMeasureInfo(info
);
4884 qemu_opts_del(object_opts
);
4885 qemu_opts_del(opts
);
4886 qemu_opts_del(sn_opts
);
4887 qemu_opts_free(create_opts
);
4893 static const img_cmd_t img_cmds
[] = {
4894 #define DEF(option, callback, arg_string) \
4895 { option, callback },
4896 #include "qemu-img-cmds.h"
4901 int main(int argc
, char **argv
)
4903 const img_cmd_t
*cmd
;
4904 const char *cmdname
;
4905 Error
*local_error
= NULL
;
4906 char *trace_file
= NULL
;
4908 static const struct option long_options
[] = {
4909 {"help", no_argument
, 0, 'h'},
4910 {"version", no_argument
, 0, 'V'},
4911 {"trace", required_argument
, NULL
, 'T'},
4916 signal(SIGPIPE
, SIG_IGN
);
4919 module_call_init(MODULE_INIT_TRACE
);
4920 error_set_progname(argv
[0]);
4921 qemu_init_exec_dir(argv
[0]);
4923 if (qemu_init_main_loop(&local_error
)) {
4924 error_report_err(local_error
);
4928 qcrypto_init(&error_fatal
);
4930 module_call_init(MODULE_INIT_QOM
);
4933 error_exit("Not enough arguments");
4936 qemu_add_opts(&qemu_object_opts
);
4937 qemu_add_opts(&qemu_source_opts
);
4938 qemu_add_opts(&qemu_trace_opts
);
4940 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
4943 missing_argument(argv
[optind
- 1]);
4946 unrecognized_option(argv
[optind
- 1]);
4952 printf(QEMU_IMG_VERSION
);
4956 trace_file
= trace_opt_parse(optarg
);
4961 cmdname
= argv
[optind
];
4963 /* reset getopt_long scanning */
4969 qemu_reset_optind();
4971 if (!trace_init_backends()) {
4974 trace_init_file(trace_file
);
4975 qemu_set_log(LOG_TRACE
);
4977 /* find the command */
4978 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
4979 if (!strcmp(cmdname
, cmd
->name
)) {
4980 return cmd
->handler(argc
, argv
);
4985 error_exit("Command not found: %s", cmdname
);