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-common.h"
29 #include "qemu-version.h"
30 #include "qapi/error.h"
31 #include "qapi/qapi-visit-block-core.h"
32 #include "qapi/qobject-output-visitor.h"
33 #include "qapi/qmp/qjson.h"
34 #include "qapi/qmp/qdict.h"
35 #include "qapi/qmp/qstring.h"
36 #include "qemu/cutils.h"
37 #include "qemu/config-file.h"
38 #include "qemu/option.h"
39 #include "qemu/error-report.h"
41 #include "qemu/main-loop.h"
42 #include "qemu/module.h"
43 #include "qemu/units.h"
44 #include "qom/object_interfaces.h"
45 #include "sysemu/block-backend.h"
46 #include "block/block_int.h"
47 #include "block/blockjob.h"
48 #include "block/qapi.h"
49 #include "crypto/init.h"
50 #include "trace/control.h"
52 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
53 "\n" QEMU_COPYRIGHT "\n"
55 typedef struct img_cmd_t
{
57 int (*handler
)(int argc
, char **argv
);
62 OPTION_BACKING_CHAIN
= 257,
64 OPTION_IMAGE_OPTS
= 259,
66 OPTION_FLUSH_INTERVAL
= 261,
67 OPTION_NO_DRAIN
= 262,
68 OPTION_TARGET_IMAGE_OPTS
= 263,
70 OPTION_PREALLOCATION
= 265,
73 OPTION_TARGET_IS_ZERO
= 268,
76 typedef enum OutputFormat
{
81 /* Default to cache=writeback as data integrity is not important for qemu-img */
82 #define BDRV_DEFAULT_CACHE "writeback"
84 static void format_print(void *opaque
, const char *name
)
89 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
94 error_vreport(fmt
, ap
);
97 error_printf("Try 'qemu-img --help' for more information\n");
101 static void QEMU_NORETURN
missing_argument(const char *option
)
103 error_exit("missing argument for option '%s'", option
);
106 static void QEMU_NORETURN
unrecognized_option(const char *option
)
108 error_exit("unrecognized option '%s'", option
);
111 /* Please keep in synch with qemu-img.texi */
112 static void QEMU_NORETURN
help(void)
114 const char *help_msg
=
116 "usage: qemu-img [standard options] command [command options]\n"
117 "QEMU disk image utility\n"
119 " '-h', '--help' display this help and exit\n"
120 " '-V', '--version' output version information and exit\n"
121 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
122 " specify tracing options\n"
125 #define DEF(option, callback, arg_string) \
127 #include "qemu-img-cmds.h"
130 "Command parameters:\n"
131 " 'filename' is a disk image filename\n"
132 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
133 " manual page for a description of the object properties. The most common\n"
134 " object type is a 'secret', which is used to supply passwords and/or\n"
135 " encryption keys.\n"
136 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
137 " 'cache' is the cache mode used to write the output disk image, the valid\n"
138 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
139 " 'directsync' and 'unsafe' (default for convert)\n"
140 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
141 " options are the same as for the 'cache' option\n"
142 " 'size' is the disk image size in bytes. Optional suffixes\n"
143 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
144 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
145 " supported. 'b' is ignored.\n"
146 " 'output_filename' is the destination disk image filename\n"
147 " 'output_fmt' is the destination format\n"
148 " 'options' is a comma separated list of format specific options in a\n"
149 " name=value format. Use -o ? for an overview of the options supported by the\n"
151 " 'snapshot_param' is param used for internal snapshot, format\n"
152 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
154 " '-c' indicates that target image must be compressed (qcow format only)\n"
155 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
156 " new backing file match exactly. The image doesn't need a working\n"
157 " backing file before rebasing in this case (useful for renaming the\n"
158 " backing file). For image creation, allow creating without attempting\n"
159 " to open the backing file.\n"
160 " '-h' with or without a command shows this help and lists the supported formats\n"
161 " '-p' show progress of command (only certain commands)\n"
162 " '-q' use Quiet mode - do not print any output (except errors)\n"
163 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
164 " contain only zeros for qemu-img to create a sparse image during\n"
165 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
166 " unallocated or zero sectors, and the destination image will always be\n"
168 " '--output' takes the format in which the output must be done (human or json)\n"
169 " '-n' skips the target volume creation (useful if the volume is created\n"
170 " prior to running qemu-img)\n"
172 "Parameters to check subcommand:\n"
173 " '-r' tries to repair any inconsistencies that are found during the check.\n"
174 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
175 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
176 " hiding corruption that has already occurred.\n"
178 "Parameters to convert subcommand:\n"
179 " '-m' specifies how many coroutines work in parallel during the convert\n"
180 " process (defaults to 8)\n"
181 " '-W' allow to write to the target out of order rather than sequential\n"
183 "Parameters to snapshot subcommand:\n"
184 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
185 " '-a' applies a snapshot (revert disk to saved state)\n"
186 " '-c' creates a snapshot\n"
187 " '-d' deletes a snapshot\n"
188 " '-l' lists all snapshots in the given image\n"
190 "Parameters to compare subcommand:\n"
191 " '-f' first image format\n"
192 " '-F' second image format\n"
193 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
195 "Parameters to dd subcommand:\n"
196 " 'bs=BYTES' read and write up to BYTES bytes at a time "
198 " 'count=N' copy only N input blocks\n"
199 " 'if=FILE' read from FILE\n"
200 " 'of=FILE' write to FILE\n"
201 " 'skip=N' skip N bs-sized blocks at the start of input\n";
203 printf("%s\nSupported formats:", help_msg
);
204 bdrv_iterate_format(format_print
, NULL
, false);
205 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
209 static QemuOptsList qemu_object_opts
= {
211 .implied_opt_name
= "qom-type",
212 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
218 static bool qemu_img_object_print_help(const char *type
, QemuOpts
*opts
)
220 if (user_creatable_print_help(type
, opts
)) {
226 static QemuOptsList qemu_source_opts
= {
228 .implied_opt_name
= "file",
229 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
235 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
241 ret
= vprintf(fmt
, args
);
248 static int print_block_option_help(const char *filename
, const char *fmt
)
250 BlockDriver
*drv
, *proto_drv
;
251 QemuOptsList
*create_opts
= NULL
;
252 Error
*local_err
= NULL
;
254 /* Find driver and parse its options */
255 drv
= bdrv_find_format(fmt
);
257 error_report("Unknown file format '%s'", fmt
);
261 if (!drv
->create_opts
) {
262 error_report("Format driver '%s' does not support image creation", fmt
);
266 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
268 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
270 error_report_err(local_err
);
271 qemu_opts_free(create_opts
);
274 if (!proto_drv
->create_opts
) {
275 error_report("Protocol driver '%s' does not support image creation",
276 proto_drv
->format_name
);
277 qemu_opts_free(create_opts
);
280 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
284 printf("Supported options:\n");
286 printf("Supported %s options:\n", fmt
);
288 qemu_opts_print_help(create_opts
, false);
289 qemu_opts_free(create_opts
);
293 "The protocol level may support further options.\n"
294 "Specify the target filename to include those options.\n");
301 static BlockBackend
*img_open_opts(const char *optstr
,
302 QemuOpts
*opts
, int flags
, bool writethrough
,
303 bool quiet
, bool force_share
)
306 Error
*local_err
= NULL
;
308 options
= qemu_opts_to_qdict(opts
, NULL
);
310 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
311 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
312 error_report("--force-share/-U conflicts with image options");
313 qobject_unref(options
);
316 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
318 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
320 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
323 blk_set_enable_write_cache(blk
, !writethrough
);
328 static BlockBackend
*img_open_file(const char *filename
,
330 const char *fmt
, int flags
,
331 bool writethrough
, bool quiet
,
335 Error
*local_err
= NULL
;
338 options
= qdict_new();
341 qdict_put_str(options
, "driver", fmt
);
345 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
347 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
349 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
352 blk_set_enable_write_cache(blk
, !writethrough
);
358 static int img_add_key_secrets(void *opaque
,
359 const char *name
, const char *value
,
362 QDict
*options
= opaque
;
364 if (g_str_has_suffix(name
, "key-secret")) {
365 qdict_put_str(options
, name
, value
);
372 static BlockBackend
*img_open(bool image_opts
,
373 const char *filename
,
374 const char *fmt
, int flags
, bool writethrough
,
375 bool quiet
, bool force_share
)
381 error_report("--image-opts and --format are mutually exclusive");
384 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
389 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
392 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
399 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
400 const char *base_filename
,
401 const char *base_fmt
)
406 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
408 error_report("Backing file not supported for file format '%s'",
415 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
417 error_report("Backing file format not supported for file "
426 static int64_t cvtnum(const char *s
)
431 err
= qemu_strtosz(s
, NULL
, &value
);
435 if (value
> INT64_MAX
) {
441 static int img_create(int argc
, char **argv
)
444 uint64_t img_size
= -1;
445 const char *fmt
= "raw";
446 const char *base_fmt
= NULL
;
447 const char *filename
;
448 const char *base_filename
= NULL
;
449 char *options
= NULL
;
450 Error
*local_err
= NULL
;
455 static const struct option long_options
[] = {
456 {"help", no_argument
, 0, 'h'},
457 {"object", required_argument
, 0, OPTION_OBJECT
},
460 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
467 missing_argument(argv
[optind
- 1]);
470 unrecognized_option(argv
[optind
- 1]);
479 base_filename
= optarg
;
485 if (!is_valid_option_list(optarg
)) {
486 error_report("Invalid option list: %s", optarg
);
490 options
= g_strdup(optarg
);
492 char *old_options
= options
;
493 options
= g_strdup_printf("%s,%s", options
, optarg
);
501 flags
|= BDRV_O_NO_BACKING
;
503 case OPTION_OBJECT
: {
505 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
514 /* Get the filename */
515 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
516 if (options
&& has_help_option(options
)) {
518 return print_block_option_help(filename
, fmt
);
521 if (optind
>= argc
) {
522 error_exit("Expecting image file name");
526 if (qemu_opts_foreach(&qemu_object_opts
,
527 user_creatable_add_opts_foreach
,
528 qemu_img_object_print_help
, &error_fatal
)) {
532 /* Get image size, if specified */
536 sval
= cvtnum(argv
[optind
++]);
538 if (sval
== -ERANGE
) {
539 error_report("Image size must be less than 8 EiB!");
541 error_report("Invalid image size specified! You may use k, M, "
542 "G, T, P or E suffixes for ");
543 error_report("kilobytes, megabytes, gigabytes, terabytes, "
544 "petabytes and exabytes.");
548 img_size
= (uint64_t)sval
;
550 if (optind
!= argc
) {
551 error_exit("Unexpected argument: %s", argv
[optind
]);
554 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
555 options
, img_size
, flags
, quiet
, &local_err
);
557 error_reportf_err(local_err
, "%s: ", filename
);
569 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
573 Visitor
*v
= qobject_output_visitor_new(&obj
);
575 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
576 visit_complete(v
, &obj
);
577 str
= qobject_to_json_pretty(obj
);
579 qprintf(quiet
, "%s\n", qstring_get_str(str
));
585 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
587 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
588 qprintf(quiet
, "No errors were found on the image.\n");
590 if (check
->corruptions
) {
591 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
592 "Data may be corrupted, or further writes to the image "
599 "\n%" PRId64
" leaked clusters were found on the image.\n"
600 "This means waste of disk space, but no harm to data.\n",
604 if (check
->check_errors
) {
607 " internal errors have occurred during the check.\n",
608 check
->check_errors
);
612 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
613 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
614 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
615 check
->allocated_clusters
, check
->total_clusters
,
616 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
617 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
618 check
->compressed_clusters
* 100.0 /
619 check
->allocated_clusters
);
622 if (check
->image_end_offset
) {
624 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
628 static int collect_image_check(BlockDriverState
*bs
,
630 const char *filename
,
635 BdrvCheckResult result
;
637 ret
= bdrv_check(bs
, &result
, fix
);
642 check
->filename
= g_strdup(filename
);
643 check
->format
= g_strdup(bdrv_get_format_name(bs
));
644 check
->check_errors
= result
.check_errors
;
645 check
->corruptions
= result
.corruptions
;
646 check
->has_corruptions
= result
.corruptions
!= 0;
647 check
->leaks
= result
.leaks
;
648 check
->has_leaks
= result
.leaks
!= 0;
649 check
->corruptions_fixed
= result
.corruptions_fixed
;
650 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
651 check
->leaks_fixed
= result
.leaks_fixed
;
652 check
->has_leaks_fixed
= result
.leaks
!= 0;
653 check
->image_end_offset
= result
.image_end_offset
;
654 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
655 check
->total_clusters
= result
.bfi
.total_clusters
;
656 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
657 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
658 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
659 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
660 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
661 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
662 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
668 * Checks an image for consistency. Exit codes:
670 * 0 - Check completed, image is good
671 * 1 - Check not completed because of internal errors
672 * 2 - Check completed, image is corrupted
673 * 3 - Check completed, image has leaked clusters, but is good otherwise
674 * 63 - Checks are not supported by the image format
676 static int img_check(int argc
, char **argv
)
679 OutputFormat output_format
= OFORMAT_HUMAN
;
680 const char *filename
, *fmt
, *output
, *cache
;
682 BlockDriverState
*bs
;
684 int flags
= BDRV_O_CHECK
;
688 bool image_opts
= false;
689 bool force_share
= false;
693 cache
= BDRV_DEFAULT_CACHE
;
696 int option_index
= 0;
697 static const struct option long_options
[] = {
698 {"help", no_argument
, 0, 'h'},
699 {"format", required_argument
, 0, 'f'},
700 {"repair", required_argument
, 0, 'r'},
701 {"output", required_argument
, 0, OPTION_OUTPUT
},
702 {"object", required_argument
, 0, OPTION_OBJECT
},
703 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
704 {"force-share", no_argument
, 0, 'U'},
707 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
708 long_options
, &option_index
);
714 missing_argument(argv
[optind
- 1]);
717 unrecognized_option(argv
[optind
- 1]);
726 flags
|= BDRV_O_RDWR
;
728 if (!strcmp(optarg
, "leaks")) {
729 fix
= BDRV_FIX_LEAKS
;
730 } else if (!strcmp(optarg
, "all")) {
731 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
733 error_exit("Unknown option value for -r "
734 "(expecting 'leaks' or 'all'): %s", optarg
);
749 case OPTION_OBJECT
: {
751 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
757 case OPTION_IMAGE_OPTS
:
762 if (optind
!= argc
- 1) {
763 error_exit("Expecting one image file name");
765 filename
= argv
[optind
++];
767 if (output
&& !strcmp(output
, "json")) {
768 output_format
= OFORMAT_JSON
;
769 } else if (output
&& !strcmp(output
, "human")) {
770 output_format
= OFORMAT_HUMAN
;
772 error_report("--output must be used with human or json as argument.");
776 if (qemu_opts_foreach(&qemu_object_opts
,
777 user_creatable_add_opts_foreach
,
778 qemu_img_object_print_help
, &error_fatal
)) {
782 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
784 error_report("Invalid source cache option: %s", cache
);
788 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
795 check
= g_new0(ImageCheck
, 1);
796 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
798 if (ret
== -ENOTSUP
) {
799 error_report("This image format does not support checks");
804 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
805 int corruptions_fixed
, leaks_fixed
;
807 leaks_fixed
= check
->leaks_fixed
;
808 corruptions_fixed
= check
->corruptions_fixed
;
810 if (output_format
== OFORMAT_HUMAN
) {
812 "The following inconsistencies were found and repaired:\n\n"
813 " %" PRId64
" leaked clusters\n"
814 " %" PRId64
" corruptions\n\n"
815 "Double checking the fixed image now...\n",
817 check
->corruptions_fixed
);
820 qapi_free_ImageCheck(check
);
821 check
= g_new0(ImageCheck
, 1);
822 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
824 check
->leaks_fixed
= leaks_fixed
;
825 check
->corruptions_fixed
= corruptions_fixed
;
829 switch (output_format
) {
831 dump_human_image_check(check
, quiet
);
834 dump_json_image_check(check
, quiet
);
839 if (ret
|| check
->check_errors
) {
841 error_report("Check failed: %s", strerror(-ret
));
843 error_report("Check failed");
849 if (check
->corruptions
) {
851 } else if (check
->leaks
) {
858 qapi_free_ImageCheck(check
);
863 typedef struct CommonBlockJobCBInfo
{
864 BlockDriverState
*bs
;
866 } CommonBlockJobCBInfo
;
868 static void common_block_job_cb(void *opaque
, int ret
)
870 CommonBlockJobCBInfo
*cbi
= opaque
;
873 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
877 static void run_block_job(BlockJob
*job
, Error
**errp
)
879 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
882 aio_context_acquire(aio_context
);
885 float progress
= 0.0f
;
886 aio_poll(aio_context
, true);
887 if (job
->job
.progress
.total
) {
888 progress
= (float)job
->job
.progress
.current
/
889 job
->job
.progress
.total
* 100.f
;
891 qemu_progress_print(progress
, 0);
892 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
894 if (!job_is_completed(&job
->job
)) {
895 ret
= job_complete_sync(&job
->job
, errp
);
899 job_unref(&job
->job
);
900 aio_context_release(aio_context
);
902 /* publish completion progress only when success */
904 qemu_progress_print(100.f
, 0);
908 static int img_commit(int argc
, char **argv
)
911 const char *filename
, *fmt
, *cache
, *base
;
913 BlockDriverState
*bs
, *base_bs
;
915 bool progress
= false, quiet
= false, drop
= false;
917 Error
*local_err
= NULL
;
918 CommonBlockJobCBInfo cbi
;
919 bool image_opts
= false;
920 AioContext
*aio_context
;
923 cache
= BDRV_DEFAULT_CACHE
;
926 static const struct option long_options
[] = {
927 {"help", no_argument
, 0, 'h'},
928 {"object", required_argument
, 0, OPTION_OBJECT
},
929 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
932 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
939 missing_argument(argv
[optind
- 1]);
942 unrecognized_option(argv
[optind
- 1]);
967 case OPTION_OBJECT
: {
969 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
975 case OPTION_IMAGE_OPTS
:
981 /* Progress is not shown in Quiet mode */
986 if (optind
!= argc
- 1) {
987 error_exit("Expecting one image file name");
989 filename
= argv
[optind
++];
991 if (qemu_opts_foreach(&qemu_object_opts
,
992 user_creatable_add_opts_foreach
,
993 qemu_img_object_print_help
, &error_fatal
)) {
997 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
998 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1000 error_report("Invalid cache option: %s", cache
);
1004 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1011 qemu_progress_init(progress
, 1.f
);
1012 qemu_progress_print(0.f
, 100);
1015 base_bs
= bdrv_find_backing_image(bs
, base
);
1017 error_setg(&local_err
,
1018 "Did not find '%s' in the backing chain of '%s'",
1023 /* This is different from QMP, which by default uses the deepest file in
1024 * the backing chain (i.e., the very base); however, the traditional
1025 * behavior of qemu-img commit is using the immediate backing file. */
1026 base_bs
= backing_bs(bs
);
1028 error_setg(&local_err
, "Image does not have a backing file");
1033 cbi
= (CommonBlockJobCBInfo
){
1038 aio_context
= bdrv_get_aio_context(bs
);
1039 aio_context_acquire(aio_context
);
1040 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, 0,
1041 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1042 &cbi
, false, &local_err
);
1043 aio_context_release(aio_context
);
1048 /* When the block job completes, the BlockBackend reference will point to
1049 * the old backing file. In order to avoid that the top image is already
1050 * deleted, so we can still empty it afterwards, increment the reference
1051 * counter here preemptively. */
1056 job
= block_job_get("commit");
1058 run_block_job(job
, &local_err
);
1063 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1064 ret
= bs
->drv
->bdrv_make_empty(bs
);
1066 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1078 qemu_progress_end();
1083 error_report_err(local_err
);
1087 qprintf(quiet
, "Image committed.\n");
1092 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1093 * of the first sector boundary within buf where the sector contains a
1094 * non-zero byte. This function is robust to a buffer that is not
1097 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1100 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1102 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1103 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1107 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1114 * Returns true iff the first sector pointed to by 'buf' contains at least
1117 * 'pnum' is set to the number of sectors (including and immediately following
1118 * the first one) that are known to be in the same allocated/unallocated state.
1119 * The function will try to align the end offset to alignment boundaries so
1120 * that the request will at least end aligned and consequtive requests will
1121 * also start at an aligned offset.
1123 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1124 int64_t sector_num
, int alignment
)
1133 is_zero
= buffer_is_zero(buf
, 512);
1134 for(i
= 1; i
< n
; i
++) {
1136 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1141 tail
= (sector_num
+ i
) & (alignment
- 1);
1143 if (is_zero
&& i
<= tail
) {
1144 /* treat unallocated areas which only consist
1145 * of a small tail as allocated. */
1149 /* align up end offset of allocated areas. */
1150 i
+= alignment
- tail
;
1153 /* align down end offset of zero areas. */
1162 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1163 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1164 * breaking up write requests for only small sparse areas.
1166 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1167 int min
, int64_t sector_num
, int alignment
)
1170 int num_checked
, num_used
;
1176 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1182 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1184 sector_num
+= *pnum
;
1185 num_checked
= num_used
;
1188 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1190 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1192 sector_num
+= *pnum
;
1193 num_checked
+= *pnum
;
1195 num_used
= num_checked
;
1196 } else if (*pnum
>= min
) {
1206 * Compares two buffers sector by sector. Returns 0 if the first
1207 * sector of each buffer matches, non-zero otherwise.
1209 * pnum is set to the sector-aligned size of the buffer prefix that
1210 * has the same matching status as the first sector.
1212 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1213 int64_t bytes
, int64_t *pnum
)
1216 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1220 res
= !!memcmp(buf1
, buf2
, i
);
1222 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1224 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1234 #define IO_BUF_SIZE (2 * MiB)
1237 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1239 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1240 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1241 * failure), and 4 on error (the exit status for read errors), after emitting
1244 * @param blk: BlockBackend for the image
1245 * @param offset: Starting offset to check
1246 * @param bytes: Number of bytes to check
1247 * @param filename: Name of disk file we are checking (logging purpose)
1248 * @param buffer: Allocated buffer for storing read data
1249 * @param quiet: Flag for quiet mode
1251 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1252 int64_t bytes
, const char *filename
,
1253 uint8_t *buffer
, bool quiet
)
1258 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1260 error_report("Error while reading offset %" PRId64
" of %s: %s",
1261 offset
, filename
, strerror(-ret
));
1264 idx
= find_nonzero(buffer
, bytes
);
1266 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1275 * Compares two images. Exit codes:
1277 * 0 - Images are identical
1279 * >1 - Error occurred
1281 static int img_compare(int argc
, char **argv
)
1283 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1284 BlockBackend
*blk1
, *blk2
;
1285 BlockDriverState
*bs1
, *bs2
;
1286 int64_t total_size1
, total_size2
;
1287 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1288 int64_t pnum1
, pnum2
;
1289 int allocated1
, allocated2
;
1290 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1291 bool progress
= false, quiet
= false, strict
= false;
1298 uint64_t progress_base
;
1299 bool image_opts
= false;
1300 bool force_share
= false;
1302 cache
= BDRV_DEFAULT_CACHE
;
1304 static const struct option long_options
[] = {
1305 {"help", no_argument
, 0, 'h'},
1306 {"object", required_argument
, 0, OPTION_OBJECT
},
1307 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1308 {"force-share", no_argument
, 0, 'U'},
1311 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1312 long_options
, NULL
);
1318 missing_argument(argv
[optind
- 1]);
1321 unrecognized_option(argv
[optind
- 1]);
1347 case OPTION_OBJECT
: {
1349 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1356 case OPTION_IMAGE_OPTS
:
1362 /* Progress is not shown in Quiet mode */
1368 if (optind
!= argc
- 2) {
1369 error_exit("Expecting two image file names");
1371 filename1
= argv
[optind
++];
1372 filename2
= argv
[optind
++];
1374 if (qemu_opts_foreach(&qemu_object_opts
,
1375 user_creatable_add_opts_foreach
,
1376 qemu_img_object_print_help
, &error_fatal
)) {
1381 /* Initialize before goto out */
1382 qemu_progress_init(progress
, 2.0);
1385 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1387 error_report("Invalid source cache option: %s", cache
);
1392 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1399 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1408 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1409 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1410 total_size1
= blk_getlength(blk1
);
1411 if (total_size1
< 0) {
1412 error_report("Can't get size of %s: %s",
1413 filename1
, strerror(-total_size1
));
1417 total_size2
= blk_getlength(blk2
);
1418 if (total_size2
< 0) {
1419 error_report("Can't get size of %s: %s",
1420 filename2
, strerror(-total_size2
));
1424 total_size
= MIN(total_size1
, total_size2
);
1425 progress_base
= MAX(total_size1
, total_size2
);
1427 qemu_progress_print(0, 100);
1429 if (strict
&& total_size1
!= total_size2
) {
1431 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1435 while (offset
< total_size
) {
1436 int status1
, status2
;
1438 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1439 total_size1
- offset
, &pnum1
, NULL
,
1443 error_report("Sector allocation test failed for %s", filename1
);
1446 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1448 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1449 total_size2
- offset
, &pnum2
, NULL
,
1453 error_report("Sector allocation test failed for %s", filename2
);
1456 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1458 assert(pnum1
&& pnum2
);
1459 chunk
= MIN(pnum1
, pnum2
);
1462 if (status1
!= status2
) {
1464 qprintf(quiet
, "Strict mode: Offset %" PRId64
1465 " block status mismatch!\n", offset
);
1469 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1471 } else if (allocated1
== allocated2
) {
1475 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1476 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1478 error_report("Error while reading offset %" PRId64
1480 offset
, filename1
, strerror(-ret
));
1484 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1486 error_report("Error while reading offset %" PRId64
1488 offset
, filename2
, strerror(-ret
));
1492 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1493 if (ret
|| pnum
!= chunk
) {
1494 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1495 offset
+ (ret
? 0 : pnum
));
1501 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1503 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1504 filename1
, buf1
, quiet
);
1506 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1507 filename2
, buf1
, quiet
);
1514 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1517 if (total_size1
!= total_size2
) {
1518 BlockBackend
*blk_over
;
1519 const char *filename_over
;
1521 qprintf(quiet
, "Warning: Image size mismatch!\n");
1522 if (total_size1
> total_size2
) {
1524 filename_over
= filename1
;
1527 filename_over
= filename2
;
1530 while (offset
< progress_base
) {
1531 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1532 progress_base
- offset
, &chunk
,
1536 error_report("Sector allocation test failed for %s",
1541 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1542 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1543 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1544 filename_over
, buf1
, quiet
);
1550 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1554 qprintf(quiet
, "Images are identical.\n");
1564 qemu_progress_end();
1569 enum ImgConvertBlockStatus
{
1575 #define MAX_COROUTINES 16
1577 typedef struct ImgConvertState
{
1579 int64_t *src_sectors
;
1581 int64_t total_sectors
;
1582 int64_t allocated_sectors
;
1583 int64_t allocated_done
;
1586 enum ImgConvertBlockStatus status
;
1587 int64_t sector_next_status
;
1588 BlockBackend
*target
;
1591 bool unallocated_blocks_are_zero
;
1593 bool target_has_backing
;
1594 int64_t target_backing_sectors
; /* negative if unknown */
1601 size_t cluster_sectors
;
1603 long num_coroutines
;
1604 int running_coroutines
;
1605 Coroutine
*co
[MAX_COROUTINES
];
1606 int64_t wait_sector_num
[MAX_COROUTINES
];
1611 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1612 int *src_cur
, int64_t *src_cur_offset
)
1615 *src_cur_offset
= 0;
1616 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1617 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1619 assert(*src_cur
< s
->src_num
);
1623 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1625 int64_t src_cur_offset
;
1626 int ret
, n
, src_cur
;
1627 bool post_backing_zero
= false;
1629 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1631 assert(s
->total_sectors
> sector_num
);
1632 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1634 if (s
->target_backing_sectors
>= 0) {
1635 if (sector_num
>= s
->target_backing_sectors
) {
1636 post_backing_zero
= s
->unallocated_blocks_are_zero
;
1637 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1638 /* Split requests around target_backing_sectors (because
1639 * starting from there, zeros are handled differently) */
1640 n
= s
->target_backing_sectors
- sector_num
;
1644 if (s
->sector_next_status
<= sector_num
) {
1645 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1649 count
= n
* BDRV_SECTOR_SIZE
;
1651 if (s
->target_has_backing
) {
1652 ret
= bdrv_block_status(blk_bs(s
->src
[src_cur
]), offset
,
1653 count
, &count
, NULL
, NULL
);
1655 ret
= bdrv_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1656 offset
, count
, &count
, NULL
,
1664 warn_report("error while reading block status at "
1665 "offset %" PRIu64
": %s", offset
,
1668 /* Just try to read the data, then */
1669 ret
= BDRV_BLOCK_DATA
;
1670 count
= BDRV_SECTOR_SIZE
;
1672 /* Retry on a shorter range */
1673 n
= DIV_ROUND_UP(n
, 4);
1676 error_report("error while reading block status at offset "
1677 "%" PRIu64
": %s", offset
, strerror(-ret
));
1683 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1685 if (ret
& BDRV_BLOCK_ZERO
) {
1686 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1687 } else if (ret
& BDRV_BLOCK_DATA
) {
1688 s
->status
= BLK_DATA
;
1690 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1693 s
->sector_next_status
= sector_num
+ n
;
1696 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1697 if (s
->status
== BLK_DATA
) {
1698 n
= MIN(n
, s
->buf_sectors
);
1701 /* We need to write complete clusters for compressed images, so if an
1702 * unallocated area is shorter than that, we must consider the whole
1703 * cluster allocated. */
1704 if (s
->compressed
) {
1705 if (n
< s
->cluster_sectors
) {
1706 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1707 s
->status
= BLK_DATA
;
1709 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1716 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1717 int nb_sectors
, uint8_t *buf
)
1719 uint64_t single_read_until
= 0;
1722 assert(nb_sectors
<= s
->buf_sectors
);
1723 while (nb_sectors
> 0) {
1726 int64_t bs_sectors
, src_cur_offset
;
1729 /* In the case of compression with multiple source files, we can get a
1730 * nb_sectors that spreads into the next part. So we must be able to
1731 * read across multiple BDSes for one convert_read() call. */
1732 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1733 blk
= s
->src
[src_cur
];
1734 bs_sectors
= s
->src_sectors
[src_cur
];
1736 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1738 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1739 if (single_read_until
> offset
) {
1743 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1747 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1751 warn_report("error while reading offset %" PRIu64
1752 ": %s", offset
, strerror(-ret
));
1754 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1763 buf
+= n
* BDRV_SECTOR_SIZE
;
1770 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1771 int nb_sectors
, uint8_t *buf
,
1772 enum ImgConvertBlockStatus status
)
1776 while (nb_sectors
> 0) {
1778 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1781 case BLK_BACKING_FILE
:
1782 /* If we have a backing file, leave clusters unallocated that are
1783 * unallocated in the source image, so that the backing file is
1784 * visible at the respective offset. */
1785 assert(s
->target_has_backing
);
1789 /* If we're told to keep the target fully allocated (-S 0) or there
1790 * is real non-zero data, we must write it. Otherwise we can treat
1791 * it as zero sectors.
1792 * Compressed clusters need to be written as a whole, so in that
1793 * case we can only save the write if the buffer is completely
1795 if (!s
->min_sparse
||
1797 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1798 sector_num
, s
->alignment
)) ||
1800 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1802 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1803 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1812 if (s
->has_zero_init
) {
1813 assert(!s
->target_has_backing
);
1816 ret
= blk_co_pwrite_zeroes(s
->target
,
1817 sector_num
<< BDRV_SECTOR_BITS
,
1818 n
<< BDRV_SECTOR_BITS
,
1819 BDRV_REQ_MAY_UNMAP
);
1828 buf
+= n
* BDRV_SECTOR_SIZE
;
1834 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1839 while (nb_sectors
> 0) {
1842 int64_t bs_sectors
, src_cur_offset
;
1845 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1846 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1847 blk
= s
->src
[src_cur
];
1848 bs_sectors
= s
->src_sectors
[src_cur
];
1850 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1852 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1853 sector_num
<< BDRV_SECTOR_BITS
,
1854 n
<< BDRV_SECTOR_BITS
, 0, 0);
1865 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1867 ImgConvertState
*s
= opaque
;
1868 uint8_t *buf
= NULL
;
1872 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1873 if (s
->co
[i
] == qemu_coroutine_self()) {
1880 s
->running_coroutines
++;
1881 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1886 enum ImgConvertBlockStatus status
;
1889 qemu_co_mutex_lock(&s
->lock
);
1890 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1891 qemu_co_mutex_unlock(&s
->lock
);
1894 n
= convert_iteration_sectors(s
, s
->sector_num
);
1896 qemu_co_mutex_unlock(&s
->lock
);
1900 /* save current sector and allocation status to local variables */
1901 sector_num
= s
->sector_num
;
1903 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1904 n
= MIN(n
, s
->buf_sectors
);
1906 /* increment global sector counter so that other coroutines can
1907 * already continue reading beyond this request */
1909 qemu_co_mutex_unlock(&s
->lock
);
1911 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1912 s
->allocated_done
+= n
;
1913 qemu_progress_print(100.0 * s
->allocated_done
/
1914 s
->allocated_sectors
, 0);
1918 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
1919 if (status
== BLK_DATA
&& !copy_range
) {
1920 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1922 error_report("error while reading sector %" PRId64
1923 ": %s", sector_num
, strerror(-ret
));
1926 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1928 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1931 if (s
->wr_in_order
) {
1932 /* keep writes in order */
1933 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1934 s
->wait_sector_num
[index
] = sector_num
;
1935 qemu_coroutine_yield();
1937 s
->wait_sector_num
[index
] = -1;
1940 if (s
->ret
== -EINPROGRESS
) {
1942 ret
= convert_co_copy_range(s
, sector_num
, n
);
1944 s
->copy_range
= false;
1948 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1951 error_report("error while writing sector %" PRId64
1952 ": %s", sector_num
, strerror(-ret
));
1957 if (s
->wr_in_order
) {
1958 /* reenter the coroutine that might have waited
1959 * for this write to complete */
1960 s
->wr_offs
= sector_num
+ n
;
1961 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1962 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1964 * A -> B -> A cannot occur because A has
1965 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1966 * B will never enter A during this time window.
1968 qemu_coroutine_enter(s
->co
[i
]);
1976 s
->co
[index
] = NULL
;
1977 s
->running_coroutines
--;
1978 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1979 /* the convert job finished successfully */
1984 static int convert_do_copy(ImgConvertState
*s
)
1987 int64_t sector_num
= 0;
1989 /* Check whether we have zero initialisation or can get it efficiently */
1990 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
1991 !s
->target_has_backing
) {
1992 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
1995 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1996 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1998 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
| BDRV_REQ_NO_FALLBACK
);
2000 s
->has_zero_init
= true;
2004 /* Allocate buffer for copied data. For compressed images, only one cluster
2005 * can be copied at a time. */
2006 if (s
->compressed
) {
2007 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2008 error_report("invalid cluster size");
2011 s
->buf_sectors
= s
->cluster_sectors
;
2014 while (sector_num
< s
->total_sectors
) {
2015 n
= convert_iteration_sectors(s
, sector_num
);
2019 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2021 s
->allocated_sectors
+= n
;
2027 s
->sector_next_status
= 0;
2028 s
->ret
= -EINPROGRESS
;
2030 qemu_co_mutex_init(&s
->lock
);
2031 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2032 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2033 s
->wait_sector_num
[i
] = -1;
2034 qemu_coroutine_enter(s
->co
[i
]);
2037 while (s
->running_coroutines
) {
2038 main_loop_wait(false);
2041 if (s
->compressed
&& !s
->ret
) {
2042 /* signal EOF to align */
2043 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
2052 #define MAX_BUF_SECTORS 32768
2054 static int img_convert(int argc
, char **argv
)
2056 int c
, bs_i
, flags
, src_flags
= 0;
2057 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2058 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2059 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
2060 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2061 BlockDriverInfo bdi
;
2062 BlockDriverState
*out_bs
;
2063 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2064 QemuOptsList
*create_opts
= NULL
;
2065 QDict
*open_opts
= NULL
;
2066 char *options
= NULL
;
2067 Error
*local_err
= NULL
;
2068 bool writethrough
, src_writethrough
, image_opts
= false,
2069 skip_create
= false, progress
= false, tgt_image_opts
= false;
2070 int64_t ret
= -EINVAL
;
2071 bool force_share
= false;
2072 bool explict_min_sparse
= false;
2074 ImgConvertState s
= (ImgConvertState
) {
2075 /* Need at least 4k of zeros for sparse detection */
2077 .copy_range
= false,
2078 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2079 .wr_in_order
= true,
2080 .num_coroutines
= 8,
2084 static const struct option long_options
[] = {
2085 {"help", no_argument
, 0, 'h'},
2086 {"object", required_argument
, 0, OPTION_OBJECT
},
2087 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2088 {"force-share", no_argument
, 0, 'U'},
2089 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2090 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2091 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2094 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2095 long_options
, NULL
);
2101 missing_argument(argv
[optind
- 1]);
2104 unrecognized_option(argv
[optind
- 1]);
2116 out_baseimg
= optarg
;
2119 s
.copy_range
= true;
2122 s
.compressed
= true;
2125 if (!is_valid_option_list(optarg
)) {
2126 error_report("Invalid option list: %s", optarg
);
2130 options
= g_strdup(optarg
);
2132 char *old_options
= options
;
2133 options
= g_strdup_printf("%s,%s", options
, optarg
);
2134 g_free(old_options
);
2138 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2139 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2142 error_report("Failed in parsing snapshot param '%s'",
2147 snapshot_name
= optarg
;
2154 sval
= cvtnum(optarg
);
2155 if (sval
< 0 || !QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2156 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2157 error_report("Invalid buffer size for sparse output specified. "
2158 "Valid sizes are multiples of %llu up to %llu. Select "
2159 "0 to disable sparse detection (fully allocates output).",
2160 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2164 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2165 explict_min_sparse
= true;
2184 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2185 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2186 error_report("Invalid number of coroutines. Allowed number of"
2187 " coroutines is between 1 and %d", MAX_COROUTINES
);
2192 s
.wr_in_order
= false;
2197 case OPTION_OBJECT
: {
2198 QemuOpts
*object_opts
;
2199 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2206 case OPTION_IMAGE_OPTS
:
2209 case OPTION_SALVAGE
:
2212 case OPTION_TARGET_IMAGE_OPTS
:
2213 tgt_image_opts
= true;
2215 case OPTION_TARGET_IS_ZERO
:
2217 * The user asserting that the target is blank has the
2218 * same effect as the target driver supporting zero
2221 s
.has_zero_init
= true;
2226 if (!out_fmt
&& !tgt_image_opts
) {
2230 if (qemu_opts_foreach(&qemu_object_opts
,
2231 user_creatable_add_opts_foreach
,
2232 qemu_img_object_print_help
, &error_fatal
)) {
2236 if (s
.compressed
&& s
.copy_range
) {
2237 error_report("Cannot enable copy offloading when -c is used");
2241 if (explict_min_sparse
&& s
.copy_range
) {
2242 error_report("Cannot enable copy offloading when -S is used");
2246 if (s
.copy_range
&& s
.salvage
) {
2247 error_report("Cannot use copy offloading in salvaging mode");
2251 if (tgt_image_opts
&& !skip_create
) {
2252 error_report("--target-image-opts requires use of -n flag");
2256 if (skip_create
&& options
) {
2257 warn_report("-o has no effect when skipping image creation");
2258 warn_report("This will become an error in future QEMU versions.");
2261 if (s
.has_zero_init
&& !skip_create
) {
2262 error_report("--target-is-zero requires use of -n flag");
2266 s
.src_num
= argc
- optind
- 1;
2267 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2269 if (options
&& has_help_option(options
)) {
2271 ret
= print_block_option_help(out_filename
, out_fmt
);
2274 error_report("Option help requires a format be specified");
2279 if (s
.src_num
< 1) {
2280 error_report("Must specify image file name");
2285 /* ret is still -EINVAL until here */
2286 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2288 error_report("Invalid source cache option: %s", src_cache
);
2292 /* Initialize before goto out */
2296 qemu_progress_init(progress
, 1.0);
2297 qemu_progress_print(0, 100);
2299 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2300 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2302 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2303 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2304 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2310 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2311 if (s
.src_sectors
[bs_i
] < 0) {
2312 error_report("Could not get size of %s: %s",
2313 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2317 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2321 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2322 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2323 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2325 } else if (snapshot_name
!= NULL
) {
2326 if (s
.src_num
> 1) {
2327 error_report("No support for concatenating multiple snapshot");
2332 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2336 error_reportf_err(local_err
, "Failed to load snapshot: ");
2342 /* Find driver and parse its options */
2343 drv
= bdrv_find_format(out_fmt
);
2345 error_report("Unknown file format '%s'", out_fmt
);
2350 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2352 error_report_err(local_err
);
2357 if (!drv
->create_opts
) {
2358 error_report("Format driver '%s' does not support image creation",
2364 if (!proto_drv
->create_opts
) {
2365 error_report("Protocol driver '%s' does not support image creation",
2366 proto_drv
->format_name
);
2371 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2372 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2374 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2376 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2378 error_report_err(local_err
);
2384 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2386 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2392 /* Get backing file name if -o backing_file was used */
2393 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2394 if (out_baseimg_param
) {
2395 out_baseimg
= out_baseimg_param
;
2397 s
.target_has_backing
= (bool) out_baseimg
;
2399 if (s
.has_zero_init
&& s
.target_has_backing
) {
2400 error_report("Cannot use --target-is-zero when the destination "
2401 "image has a backing file");
2405 if (s
.src_num
> 1 && out_baseimg
) {
2406 error_report("Having a backing file for the target makes no sense when "
2407 "concatenating multiple input images");
2412 /* Check if compression is supported */
2415 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2416 const char *encryptfmt
=
2417 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2418 const char *preallocation
=
2419 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2421 if (drv
&& !block_driver_can_compress(drv
)) {
2422 error_report("Compression not supported for this file format");
2427 if (encryption
|| encryptfmt
) {
2428 error_report("Compression and encryption not supported at "
2435 && strcmp(preallocation
, "off"))
2437 error_report("Compression and preallocation not supported at "
2445 * The later open call will need any decryption secrets, and
2446 * bdrv_create() will purge "opts", so extract them now before
2450 open_opts
= qdict_new();
2451 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2455 /* Create the new image */
2456 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2458 error_reportf_err(local_err
, "%s: error while converting %s: ",
2459 out_filename
, out_fmt
);
2464 s
.target_is_new
= !skip_create
;
2466 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2467 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2469 error_report("Invalid cache option: %s", cache
);
2474 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2475 flags
, writethrough
, s
.quiet
, false);
2477 /* TODO ultimately we should allow --target-image-opts
2478 * to be used even when -n is not given.
2479 * That has to wait for bdrv_create to be improved
2480 * to allow filenames in option syntax
2482 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2483 flags
, writethrough
, s
.quiet
, false);
2484 open_opts
= NULL
; /* blk_new_open will have freed it */
2490 out_bs
= blk_bs(s
.target
);
2492 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2493 error_report("Compression not supported for this file format");
2498 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2499 * or discard_alignment of the out_bs is greater. Limit to
2500 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2501 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2503 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2504 out_bs
->bl
.pdiscard_alignment
>>
2505 BDRV_SECTOR_BITS
)));
2507 /* try to align the write requests to the destination to avoid unnecessary
2509 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2510 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2512 assert(is_power_of_2(s
.alignment
));
2515 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2516 if (output_sectors
< 0) {
2517 error_report("unable to get output image length: %s",
2518 strerror(-output_sectors
));
2521 } else if (output_sectors
< s
.total_sectors
) {
2522 error_report("output file is smaller than input file");
2528 if (s
.target_has_backing
&& s
.target_is_new
) {
2529 /* Errors are treated as "backing length unknown" (which means
2530 * s.target_backing_sectors has to be negative, which it will
2531 * be automatically). The backing file length is used only
2532 * for optimizations, so such a case is not fatal. */
2533 s
.target_backing_sectors
= bdrv_nb_sectors(out_bs
->backing
->bs
);
2535 s
.target_backing_sectors
= -1;
2538 ret
= bdrv_get_info(out_bs
, &bdi
);
2541 error_report("could not get block driver info");
2545 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2546 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2547 s
.unallocated_blocks_are_zero
= bdi
.unallocated_blocks_are_zero
;
2550 ret
= convert_do_copy(&s
);
2553 qemu_progress_print(100, 0);
2555 qemu_progress_end();
2556 qemu_opts_del(opts
);
2557 qemu_opts_free(create_opts
);
2558 qemu_opts_del(sn_opts
);
2559 qobject_unref(open_opts
);
2560 blk_unref(s
.target
);
2562 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2563 blk_unref(s
.src
[bs_i
]);
2567 g_free(s
.src_sectors
);
2575 static void dump_snapshots(BlockDriverState
*bs
)
2577 QEMUSnapshotInfo
*sn_tab
, *sn
;
2580 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2583 printf("Snapshot list:\n");
2584 bdrv_snapshot_dump(NULL
);
2586 for(i
= 0; i
< nb_sns
; i
++) {
2588 bdrv_snapshot_dump(sn
);
2594 static void dump_json_image_info_list(ImageInfoList
*list
)
2598 Visitor
*v
= qobject_output_visitor_new(&obj
);
2600 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2601 visit_complete(v
, &obj
);
2602 str
= qobject_to_json_pretty(obj
);
2603 assert(str
!= NULL
);
2604 printf("%s\n", qstring_get_str(str
));
2610 static void dump_json_image_info(ImageInfo
*info
)
2614 Visitor
*v
= qobject_output_visitor_new(&obj
);
2616 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2617 visit_complete(v
, &obj
);
2618 str
= qobject_to_json_pretty(obj
);
2619 assert(str
!= NULL
);
2620 printf("%s\n", qstring_get_str(str
));
2626 static void dump_human_image_info_list(ImageInfoList
*list
)
2628 ImageInfoList
*elem
;
2631 for (elem
= list
; elem
; elem
= elem
->next
) {
2637 bdrv_image_info_dump(elem
->value
);
2641 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2643 return strcmp(a
, b
) == 0;
2647 * Open an image file chain and return an ImageInfoList
2649 * @filename: topmost image filename
2650 * @fmt: topmost image format (may be NULL to autodetect)
2651 * @chain: true - enumerate entire backing file chain
2652 * false - only topmost image file
2654 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2655 * image file. If there was an error a message will have been printed to
2658 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2659 const char *filename
,
2661 bool chain
, bool force_share
)
2663 ImageInfoList
*head
= NULL
;
2664 ImageInfoList
**last
= &head
;
2665 GHashTable
*filenames
;
2668 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2672 BlockDriverState
*bs
;
2674 ImageInfoList
*elem
;
2676 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2677 error_report("Backing file '%s' creates an infinite loop.",
2681 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2683 blk
= img_open(image_opts
, filename
, fmt
,
2684 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2691 bdrv_query_image_info(bs
, &info
, &err
);
2693 error_report_err(err
);
2698 elem
= g_new0(ImageInfoList
, 1);
2705 /* Clear parameters that only apply to the topmost image */
2706 filename
= fmt
= NULL
;
2710 if (info
->has_full_backing_filename
) {
2711 filename
= info
->full_backing_filename
;
2712 } else if (info
->has_backing_filename
) {
2713 error_report("Could not determine absolute backing filename,"
2714 " but backing filename '%s' present",
2715 info
->backing_filename
);
2718 if (info
->has_backing_filename_format
) {
2719 fmt
= info
->backing_filename_format
;
2723 g_hash_table_destroy(filenames
);
2727 qapi_free_ImageInfoList(head
);
2728 g_hash_table_destroy(filenames
);
2732 static int img_info(int argc
, char **argv
)
2735 OutputFormat output_format
= OFORMAT_HUMAN
;
2737 const char *filename
, *fmt
, *output
;
2738 ImageInfoList
*list
;
2739 bool image_opts
= false;
2740 bool force_share
= false;
2745 int option_index
= 0;
2746 static const struct option long_options
[] = {
2747 {"help", no_argument
, 0, 'h'},
2748 {"format", required_argument
, 0, 'f'},
2749 {"output", required_argument
, 0, OPTION_OUTPUT
},
2750 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2751 {"object", required_argument
, 0, OPTION_OBJECT
},
2752 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2753 {"force-share", no_argument
, 0, 'U'},
2756 c
= getopt_long(argc
, argv
, ":f:hU",
2757 long_options
, &option_index
);
2763 missing_argument(argv
[optind
- 1]);
2766 unrecognized_option(argv
[optind
- 1]);
2780 case OPTION_BACKING_CHAIN
:
2783 case OPTION_OBJECT
: {
2785 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2791 case OPTION_IMAGE_OPTS
:
2796 if (optind
!= argc
- 1) {
2797 error_exit("Expecting one image file name");
2799 filename
= argv
[optind
++];
2801 if (output
&& !strcmp(output
, "json")) {
2802 output_format
= OFORMAT_JSON
;
2803 } else if (output
&& !strcmp(output
, "human")) {
2804 output_format
= OFORMAT_HUMAN
;
2805 } else if (output
) {
2806 error_report("--output must be used with human or json as argument.");
2810 if (qemu_opts_foreach(&qemu_object_opts
,
2811 user_creatable_add_opts_foreach
,
2812 qemu_img_object_print_help
, &error_fatal
)) {
2816 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2822 switch (output_format
) {
2824 dump_human_image_info_list(list
);
2828 dump_json_image_info_list(list
);
2830 dump_json_image_info(list
->value
);
2835 qapi_free_ImageInfoList(list
);
2839 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2842 switch (output_format
) {
2844 if (e
->data
&& !e
->has_offset
) {
2845 error_report("File contains external, encrypted or compressed clusters.");
2848 if (e
->data
&& !e
->zero
) {
2849 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2850 e
->start
, e
->length
,
2851 e
->has_offset
? e
->offset
: 0,
2852 e
->has_filename
? e
->filename
: "");
2854 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2855 * Modify the flags here to allow more coalescing.
2857 if (next
&& (!next
->data
|| next
->zero
)) {
2863 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2864 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2865 (e
->start
== 0 ? "[" : ",\n"),
2866 e
->start
, e
->length
, e
->depth
,
2867 e
->zero
? "true" : "false",
2868 e
->data
? "true" : "false");
2869 if (e
->has_offset
) {
2870 printf(", \"offset\": %"PRId64
"", e
->offset
);
2882 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
2883 int64_t bytes
, MapEntry
*e
)
2887 BlockDriverState
*file
;
2890 char *filename
= NULL
;
2892 /* As an optimization, we could cache the current range of unallocated
2893 * clusters in each file of the chain, and avoid querying the same
2899 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
2904 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2907 bs
= backing_bs(bs
);
2916 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2918 if (file
&& has_offset
) {
2919 bdrv_refresh_filename(file
);
2920 filename
= file
->filename
;
2926 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2927 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2929 .has_offset
= has_offset
,
2931 .has_filename
= filename
,
2932 .filename
= filename
,
2938 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2940 if (curr
->length
== 0) {
2943 if (curr
->zero
!= next
->zero
||
2944 curr
->data
!= next
->data
||
2945 curr
->depth
!= next
->depth
||
2946 curr
->has_filename
!= next
->has_filename
||
2947 curr
->has_offset
!= next
->has_offset
) {
2950 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2953 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2959 static int img_map(int argc
, char **argv
)
2962 OutputFormat output_format
= OFORMAT_HUMAN
;
2964 BlockDriverState
*bs
;
2965 const char *filename
, *fmt
, *output
;
2967 MapEntry curr
= { .length
= 0 }, next
;
2969 bool image_opts
= false;
2970 bool force_share
= false;
2975 int option_index
= 0;
2976 static const struct option long_options
[] = {
2977 {"help", no_argument
, 0, 'h'},
2978 {"format", required_argument
, 0, 'f'},
2979 {"output", required_argument
, 0, OPTION_OUTPUT
},
2980 {"object", required_argument
, 0, OPTION_OBJECT
},
2981 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2982 {"force-share", no_argument
, 0, 'U'},
2985 c
= getopt_long(argc
, argv
, ":f:hU",
2986 long_options
, &option_index
);
2992 missing_argument(argv
[optind
- 1]);
2995 unrecognized_option(argv
[optind
- 1]);
3009 case OPTION_OBJECT
: {
3011 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3017 case OPTION_IMAGE_OPTS
:
3022 if (optind
!= argc
- 1) {
3023 error_exit("Expecting one image file name");
3025 filename
= argv
[optind
];
3027 if (output
&& !strcmp(output
, "json")) {
3028 output_format
= OFORMAT_JSON
;
3029 } else if (output
&& !strcmp(output
, "human")) {
3030 output_format
= OFORMAT_HUMAN
;
3031 } else if (output
) {
3032 error_report("--output must be used with human or json as argument.");
3036 if (qemu_opts_foreach(&qemu_object_opts
,
3037 user_creatable_add_opts_foreach
,
3038 qemu_img_object_print_help
, &error_fatal
)) {
3042 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3048 if (output_format
== OFORMAT_HUMAN
) {
3049 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3052 length
= blk_getlength(blk
);
3053 while (curr
.start
+ curr
.length
< length
) {
3054 int64_t offset
= curr
.start
+ curr
.length
;
3057 /* Probe up to 1 GiB at a time. */
3058 n
= MIN(1 * GiB
, length
- offset
);
3059 ret
= get_block_status(bs
, offset
, n
, &next
);
3062 error_report("Could not read file metadata: %s", strerror(-ret
));
3066 if (entry_mergeable(&curr
, &next
)) {
3067 curr
.length
+= next
.length
;
3071 if (curr
.length
> 0) {
3072 ret
= dump_map_entry(output_format
, &curr
, &next
);
3080 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3087 #define SNAPSHOT_LIST 1
3088 #define SNAPSHOT_CREATE 2
3089 #define SNAPSHOT_APPLY 3
3090 #define SNAPSHOT_DELETE 4
3092 static int img_snapshot(int argc
, char **argv
)
3095 BlockDriverState
*bs
;
3096 QEMUSnapshotInfo sn
;
3097 char *filename
, *snapshot_name
= NULL
;
3098 int c
, ret
= 0, bdrv_oflags
;
3103 bool image_opts
= false;
3104 bool force_share
= false;
3106 bdrv_oflags
= BDRV_O_RDWR
;
3107 /* Parse commandline parameters */
3109 static const struct option long_options
[] = {
3110 {"help", no_argument
, 0, 'h'},
3111 {"object", required_argument
, 0, OPTION_OBJECT
},
3112 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3113 {"force-share", no_argument
, 0, 'U'},
3116 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3117 long_options
, NULL
);
3123 missing_argument(argv
[optind
- 1]);
3126 unrecognized_option(argv
[optind
- 1]);
3133 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3136 action
= SNAPSHOT_LIST
;
3137 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3141 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3144 action
= SNAPSHOT_APPLY
;
3145 snapshot_name
= optarg
;
3149 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3152 action
= SNAPSHOT_CREATE
;
3153 snapshot_name
= optarg
;
3157 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3160 action
= SNAPSHOT_DELETE
;
3161 snapshot_name
= optarg
;
3169 case OPTION_OBJECT
: {
3171 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3177 case OPTION_IMAGE_OPTS
:
3183 if (optind
!= argc
- 1) {
3184 error_exit("Expecting one image file name");
3186 filename
= argv
[optind
++];
3188 if (qemu_opts_foreach(&qemu_object_opts
,
3189 user_creatable_add_opts_foreach
,
3190 qemu_img_object_print_help
, &error_fatal
)) {
3194 /* Open the image */
3195 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3202 /* Perform the requested action */
3208 case SNAPSHOT_CREATE
:
3209 memset(&sn
, 0, sizeof(sn
));
3210 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3212 qemu_gettimeofday(&tv
);
3213 sn
.date_sec
= tv
.tv_sec
;
3214 sn
.date_nsec
= tv
.tv_usec
* 1000;
3216 ret
= bdrv_snapshot_create(bs
, &sn
);
3218 error_report("Could not create snapshot '%s': %d (%s)",
3219 snapshot_name
, ret
, strerror(-ret
));
3223 case SNAPSHOT_APPLY
:
3224 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3226 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3231 case SNAPSHOT_DELETE
:
3232 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3234 error_report("Could not delete snapshot '%s': snapshot not "
3235 "found", snapshot_name
);
3238 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3240 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3256 static int img_rebase(int argc
, char **argv
)
3258 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3259 uint8_t *buf_old
= NULL
;
3260 uint8_t *buf_new
= NULL
;
3261 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3263 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3264 int c
, flags
, src_flags
, ret
;
3265 bool writethrough
, src_writethrough
;
3267 bool force_share
= false;
3270 Error
*local_err
= NULL
;
3271 bool image_opts
= false;
3273 /* Parse commandline parameters */
3275 cache
= BDRV_DEFAULT_CACHE
;
3276 src_cache
= BDRV_DEFAULT_CACHE
;
3280 static const struct option long_options
[] = {
3281 {"help", no_argument
, 0, 'h'},
3282 {"object", required_argument
, 0, OPTION_OBJECT
},
3283 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3284 {"force-share", no_argument
, 0, 'U'},
3287 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3288 long_options
, NULL
);
3294 missing_argument(argv
[optind
- 1]);
3297 unrecognized_option(argv
[optind
- 1]);
3306 out_basefmt
= optarg
;
3309 out_baseimg
= optarg
;
3326 case OPTION_OBJECT
: {
3328 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3334 case OPTION_IMAGE_OPTS
:
3347 if (optind
!= argc
- 1) {
3348 error_exit("Expecting one image file name");
3350 if (!unsafe
&& !out_baseimg
) {
3351 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3353 filename
= argv
[optind
++];
3355 if (qemu_opts_foreach(&qemu_object_opts
,
3356 user_creatable_add_opts_foreach
,
3357 qemu_img_object_print_help
, &error_fatal
)) {
3361 qemu_progress_init(progress
, 2.0);
3362 qemu_progress_print(0, 100);
3364 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3365 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3367 error_report("Invalid cache option: %s", cache
);
3372 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3374 error_report("Invalid source cache option: %s", src_cache
);
3378 /* The source files are opened read-only, don't care about WCE */
3379 assert((src_flags
& BDRV_O_RDWR
) == 0);
3380 (void) src_writethrough
;
3385 * Ignore the old backing file for unsafe rebase in case we want to correct
3386 * the reference to a renamed or moved backing file.
3388 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3396 if (out_basefmt
!= NULL
) {
3397 if (bdrv_find_format(out_basefmt
) == NULL
) {
3398 error_report("Invalid format name: '%s'", out_basefmt
);
3404 /* For safe rebasing we need to compare old and new backing file */
3406 QDict
*options
= NULL
;
3407 BlockDriverState
*base_bs
= backing_bs(bs
);
3410 blk_old_backing
= blk_new(qemu_get_aio_context(),
3411 BLK_PERM_CONSISTENT_READ
,
3413 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3416 error_reportf_err(local_err
,
3417 "Could not reuse old backing file '%s': ",
3422 blk_old_backing
= NULL
;
3425 if (out_baseimg
[0]) {
3426 const char *overlay_filename
;
3427 char *out_real_path
;
3429 options
= qdict_new();
3431 qdict_put_str(options
, "driver", out_basefmt
);
3434 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3437 bdrv_refresh_filename(bs
);
3438 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3441 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3445 qobject_unref(options
);
3446 error_reportf_err(local_err
,
3447 "Could not resolve backing filename: ");
3453 * Find out whether we rebase an image on top of a previous image
3456 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3457 if (prefix_chain_bs
) {
3458 qobject_unref(options
);
3459 g_free(out_real_path
);
3461 blk_new_backing
= blk_new(qemu_get_aio_context(),
3462 BLK_PERM_CONSISTENT_READ
,
3464 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3467 error_reportf_err(local_err
,
3468 "Could not reuse backing file '%s': ",
3473 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3474 options
, src_flags
, &local_err
);
3475 g_free(out_real_path
);
3476 if (!blk_new_backing
) {
3477 error_reportf_err(local_err
,
3478 "Could not open new backing file '%s': ",
3488 * Check each unallocated cluster in the COW file. If it is unallocated,
3489 * accesses go to the backing file. We must therefore compare this cluster
3490 * in the old and new backing file, and if they differ we need to copy it
3491 * from the old backing file into the COW file.
3493 * If qemu-img crashes during this step, no harm is done. The content of
3494 * the image is the same as the original one at any time.
3498 int64_t old_backing_size
= 0;
3499 int64_t new_backing_size
= 0;
3502 float local_progress
= 0;
3504 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3505 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3507 size
= blk_getlength(blk
);
3509 error_report("Could not get size of '%s': %s",
3510 filename
, strerror(-size
));
3514 if (blk_old_backing
) {
3515 old_backing_size
= blk_getlength(blk_old_backing
);
3516 if (old_backing_size
< 0) {
3517 char backing_name
[PATH_MAX
];
3519 bdrv_get_backing_filename(bs
, backing_name
,
3520 sizeof(backing_name
));
3521 error_report("Could not get size of '%s': %s",
3522 backing_name
, strerror(-old_backing_size
));
3527 if (blk_new_backing
) {
3528 new_backing_size
= blk_getlength(blk_new_backing
);
3529 if (new_backing_size
< 0) {
3530 error_report("Could not get size of '%s': %s",
3531 out_baseimg
, strerror(-new_backing_size
));
3538 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3541 for (offset
= 0; offset
< size
; offset
+= n
) {
3542 bool buf_old_is_zero
= false;
3544 /* How many bytes can we handle with the next read? */
3545 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3547 /* If the cluster is allocated, we don't need to take action */
3548 ret
= bdrv_is_allocated(bs
, offset
, n
, &n
);
3550 error_report("error while reading image metadata: %s",
3558 if (prefix_chain_bs
) {
3560 * If cluster wasn't changed since prefix_chain, we don't need
3563 ret
= bdrv_is_allocated_above(backing_bs(bs
), prefix_chain_bs
,
3564 false, offset
, n
, &n
);
3566 error_report("error while reading image metadata: %s",
3576 * Read old and new backing file and take into consideration that
3577 * backing files may be smaller than the COW image.
3579 if (offset
>= old_backing_size
) {
3580 memset(buf_old
, 0, n
);
3581 buf_old_is_zero
= true;
3583 if (offset
+ n
> old_backing_size
) {
3584 n
= old_backing_size
- offset
;
3587 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3589 error_report("error while reading from old backing file");
3594 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3595 memset(buf_new
, 0, n
);
3597 if (offset
+ n
> new_backing_size
) {
3598 n
= new_backing_size
- offset
;
3601 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3603 error_report("error while reading from new backing file");
3608 /* If they differ, we need to write to the COW file */
3609 uint64_t written
= 0;
3611 while (written
< n
) {
3614 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3615 n
- written
, &pnum
))
3617 if (buf_old_is_zero
) {
3618 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3620 ret
= blk_pwrite(blk
, offset
+ written
,
3621 buf_old
+ written
, pnum
, 0);
3624 error_report("Error while writing to COW image: %s",
3632 qemu_progress_print(local_progress
, 100);
3637 * Change the backing file. All clusters that are different from the old
3638 * backing file are overwritten in the COW file now, so the visible content
3639 * doesn't change when we switch the backing file.
3641 if (out_baseimg
&& *out_baseimg
) {
3642 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3644 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3647 if (ret
== -ENOSPC
) {
3648 error_report("Could not change the backing file to '%s': No "
3649 "space left in the file header", out_baseimg
);
3650 } else if (ret
< 0) {
3651 error_report("Could not change the backing file to '%s': %s",
3652 out_baseimg
, strerror(-ret
));
3655 qemu_progress_print(100, 0);
3657 * TODO At this point it is possible to check if any clusters that are
3658 * allocated in the COW file are the same in the backing file. If so, they
3659 * could be dropped from the COW file. Don't do this before switching the
3660 * backing file, in case of a crash this would lead to corruption.
3663 qemu_progress_end();
3666 blk_unref(blk_old_backing
);
3667 blk_unref(blk_new_backing
);
3669 qemu_vfree(buf_old
);
3670 qemu_vfree(buf_new
);
3679 static int img_resize(int argc
, char **argv
)
3682 int c
, ret
, relative
;
3683 const char *filename
, *fmt
, *size
;
3684 int64_t n
, total_size
, current_size
;
3686 BlockBackend
*blk
= NULL
;
3687 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3690 static QemuOptsList resize_options
= {
3691 .name
= "resize_options",
3692 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3695 .name
= BLOCK_OPT_SIZE
,
3696 .type
= QEMU_OPT_SIZE
,
3697 .help
= "Virtual disk size"
3703 bool image_opts
= false;
3704 bool shrink
= false;
3706 /* Remove size from argv manually so that negative numbers are not treated
3707 * as options by getopt. */
3709 error_exit("Not enough arguments");
3713 size
= argv
[--argc
];
3715 /* Parse getopt arguments */
3718 static const struct option long_options
[] = {
3719 {"help", no_argument
, 0, 'h'},
3720 {"object", required_argument
, 0, OPTION_OBJECT
},
3721 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3722 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3723 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3726 c
= getopt_long(argc
, argv
, ":f:hq",
3727 long_options
, NULL
);
3733 missing_argument(argv
[optind
- 1]);
3736 unrecognized_option(argv
[optind
- 1]);
3747 case OPTION_OBJECT
: {
3749 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3755 case OPTION_IMAGE_OPTS
:
3758 case OPTION_PREALLOCATION
:
3759 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3760 PREALLOC_MODE__MAX
, NULL
);
3761 if (prealloc
== PREALLOC_MODE__MAX
) {
3762 error_report("Invalid preallocation mode '%s'", optarg
);
3771 if (optind
!= argc
- 1) {
3772 error_exit("Expecting image file name and size");
3774 filename
= argv
[optind
++];
3776 if (qemu_opts_foreach(&qemu_object_opts
,
3777 user_creatable_add_opts_foreach
,
3778 qemu_img_object_print_help
, &error_fatal
)) {
3782 /* Choose grow, shrink, or absolute resize mode */
3798 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3799 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3801 error_report_err(err
);
3803 qemu_opts_del(param
);
3806 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3807 qemu_opts_del(param
);
3809 blk
= img_open(image_opts
, filename
, fmt
,
3810 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3817 current_size
= blk_getlength(blk
);
3818 if (current_size
< 0) {
3819 error_report("Failed to inquire current image length: %s",
3820 strerror(-current_size
));
3826 total_size
= current_size
+ n
* relative
;
3830 if (total_size
<= 0) {
3831 error_report("New image size must be positive");
3836 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3837 error_report("Preallocation can only be used for growing images");
3842 if (total_size
< current_size
&& !shrink
) {
3843 warn_report("Shrinking an image will delete all data beyond the "
3844 "shrunken image's end. Before performing such an "
3845 "operation, make sure there is no important data there.");
3847 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk
)), "raw") != 0) {
3849 "Use the --shrink option to perform a shrink operation.");
3853 warn_report("Using the --shrink option will suppress this message. "
3854 "Note that future versions of qemu-img may refuse to "
3855 "shrink images without this option.");
3860 * The user expects the image to have the desired size after
3861 * resizing, so pass @exact=true. It is of no use to report
3862 * success when the image has not actually been resized.
3864 ret
= blk_truncate(blk
, total_size
, true, prealloc
, &err
);
3866 qprintf(quiet
, "Image resized.\n");
3868 error_report_err(err
);
3878 static void amend_status_cb(BlockDriverState
*bs
,
3879 int64_t offset
, int64_t total_work_size
,
3882 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3885 static int print_amend_option_help(const char *format
)
3889 /* Find driver and parse its options */
3890 drv
= bdrv_find_format(format
);
3892 error_report("Unknown file format '%s'", format
);
3896 if (!drv
->bdrv_amend_options
) {
3897 error_report("Format driver '%s' does not support option amendment",
3902 /* Every driver supporting amendment must have create_opts */
3903 assert(drv
->create_opts
);
3905 printf("Creation options for '%s':\n", format
);
3906 qemu_opts_print_help(drv
->create_opts
, false);
3907 printf("\nNote that not all of these options may be amendable.\n");
3911 static int img_amend(int argc
, char **argv
)
3915 char *options
= NULL
;
3916 QemuOptsList
*create_opts
= NULL
;
3917 QemuOpts
*opts
= NULL
;
3918 const char *fmt
= NULL
, *filename
, *cache
;
3921 bool quiet
= false, progress
= false;
3922 BlockBackend
*blk
= NULL
;
3923 BlockDriverState
*bs
= NULL
;
3924 bool image_opts
= false;
3926 cache
= BDRV_DEFAULT_CACHE
;
3928 static const struct option long_options
[] = {
3929 {"help", no_argument
, 0, 'h'},
3930 {"object", required_argument
, 0, OPTION_OBJECT
},
3931 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3934 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
3935 long_options
, NULL
);
3942 missing_argument(argv
[optind
- 1]);
3945 unrecognized_option(argv
[optind
- 1]);
3951 if (!is_valid_option_list(optarg
)) {
3952 error_report("Invalid option list: %s", optarg
);
3954 goto out_no_progress
;
3957 options
= g_strdup(optarg
);
3959 char *old_options
= options
;
3960 options
= g_strdup_printf("%s,%s", options
, optarg
);
3961 g_free(old_options
);
3977 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3981 goto out_no_progress
;
3984 case OPTION_IMAGE_OPTS
:
3991 error_exit("Must specify options (-o)");
3994 if (qemu_opts_foreach(&qemu_object_opts
,
3995 user_creatable_add_opts_foreach
,
3996 qemu_img_object_print_help
, &error_fatal
)) {
3998 goto out_no_progress
;
4004 qemu_progress_init(progress
, 1.0);
4006 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
4007 if (fmt
&& has_help_option(options
)) {
4008 /* If a format is explicitly specified (and possibly no filename is
4009 * given), print option help here */
4010 ret
= print_amend_option_help(fmt
);
4014 if (optind
!= argc
- 1) {
4015 error_report("Expecting one image file name");
4020 flags
= BDRV_O_RDWR
;
4021 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
4023 error_report("Invalid cache option: %s", cache
);
4027 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4035 fmt
= bs
->drv
->format_name
;
4037 if (has_help_option(options
)) {
4038 /* If the format was auto-detected, print option help here */
4039 ret
= print_amend_option_help(fmt
);
4043 if (!bs
->drv
->bdrv_amend_options
) {
4044 error_report("Format driver '%s' does not support option amendment",
4050 /* Every driver supporting amendment must have create_opts */
4051 assert(bs
->drv
->create_opts
);
4053 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
4054 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4055 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
4057 error_report_err(err
);
4062 /* In case the driver does not call amend_status_cb() */
4063 qemu_progress_print(0.f
, 0);
4064 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, &err
);
4065 qemu_progress_print(100.f
, 0);
4067 error_report_err(err
);
4072 qemu_progress_end();
4076 qemu_opts_del(opts
);
4077 qemu_opts_free(create_opts
);
4086 typedef struct BenchData
{
4088 uint64_t image_size
;
4095 bool drain_on_flush
;
4104 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4107 error_report("Failed flush request: %s", strerror(-ret
));
4112 static void bench_cb(void *opaque
, int ret
)
4114 BenchData
*b
= opaque
;
4118 error_report("Failed request: %s", strerror(-ret
));
4123 /* Just finished a flush with drained queue: Start next requests */
4124 assert(b
->in_flight
== 0);
4125 b
->in_flush
= false;
4126 } else if (b
->in_flight
> 0) {
4127 int remaining
= b
->n
- b
->in_flight
;
4132 /* Time for flush? Drain queue if requested, then flush */
4133 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4134 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4135 BlockCompletionFunc
*cb
;
4137 if (b
->drain_on_flush
) {
4141 cb
= bench_undrained_flush_cb
;
4144 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4146 error_report("Failed to issue flush request");
4150 if (b
->drain_on_flush
) {
4156 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4157 int64_t offset
= b
->offset
;
4158 /* blk_aio_* might look for completed I/Os and kick bench_cb
4159 * again, so make sure this operation is counted by in_flight
4160 * and b->offset is ready for the next submission.
4163 b
->offset
+= b
->step
;
4164 b
->offset
%= b
->image_size
;
4166 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4168 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4171 error_report("Failed to issue request");
4177 static int img_bench(int argc
, char **argv
)
4180 const char *fmt
= NULL
, *filename
;
4182 bool image_opts
= false;
4183 bool is_write
= false;
4187 size_t bufsize
= 4096;
4190 int flush_interval
= 0;
4191 bool drain_on_flush
= true;
4193 BlockBackend
*blk
= NULL
;
4194 BenchData data
= {};
4196 bool writethrough
= false;
4197 struct timeval t1
, t2
;
4199 bool force_share
= false;
4203 static const struct option long_options
[] = {
4204 {"help", no_argument
, 0, 'h'},
4205 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4206 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4207 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4208 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4209 {"force-share", no_argument
, 0, 'U'},
4212 c
= getopt_long(argc
, argv
, ":hc:d:f:ni:o:qs:S:t:wU", long_options
,
4220 missing_argument(argv
[optind
- 1]);
4223 unrecognized_option(argv
[optind
- 1]);
4232 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4233 error_report("Invalid request count specified");
4243 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4244 error_report("Invalid queue depth specified");
4254 flags
|= BDRV_O_NATIVE_AIO
;
4257 ret
= bdrv_parse_aio(optarg
, &flags
);
4259 error_report("Invalid aio option: %s", optarg
);
4266 offset
= cvtnum(optarg
);
4268 error_report("Invalid offset specified");
4281 sval
= cvtnum(optarg
);
4282 if (sval
< 0 || sval
> INT_MAX
) {
4283 error_report("Invalid buffer size specified");
4294 sval
= cvtnum(optarg
);
4295 if (sval
< 0 || sval
> INT_MAX
) {
4296 error_report("Invalid step size specified");
4304 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4306 error_report("Invalid cache mode");
4312 flags
|= BDRV_O_RDWR
;
4318 case OPTION_PATTERN
:
4322 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4323 error_report("Invalid pattern byte specified");
4329 case OPTION_FLUSH_INTERVAL
:
4333 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4334 error_report("Invalid flush interval specified");
4337 flush_interval
= res
;
4340 case OPTION_NO_DRAIN
:
4341 drain_on_flush
= false;
4343 case OPTION_IMAGE_OPTS
:
4349 if (optind
!= argc
- 1) {
4350 error_exit("Expecting one image file name");
4352 filename
= argv
[argc
- 1];
4354 if (!is_write
&& flush_interval
) {
4355 error_report("--flush-interval is only available in write tests");
4359 if (flush_interval
&& flush_interval
< depth
) {
4360 error_report("Flush interval can't be smaller than depth");
4365 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4372 image_size
= blk_getlength(blk
);
4373 if (image_size
< 0) {
4378 data
= (BenchData
) {
4380 .image_size
= image_size
,
4382 .step
= step
?: bufsize
,
4387 .flush_interval
= flush_interval
,
4388 .drain_on_flush
= drain_on_flush
,
4390 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4391 "(starting at offset %" PRId64
", step size %d)\n",
4392 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4393 data
.offset
, data
.step
);
4394 if (flush_interval
) {
4395 printf("Sending flush every %d requests\n", flush_interval
);
4398 buf_size
= data
.nrreq
* data
.bufsize
;
4399 data
.buf
= blk_blockalign(blk
, buf_size
);
4400 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4402 blk_register_buf(blk
, data
.buf
, buf_size
);
4404 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4405 for (i
= 0; i
< data
.nrreq
; i
++) {
4406 qemu_iovec_init(&data
.qiov
[i
], 1);
4407 qemu_iovec_add(&data
.qiov
[i
],
4408 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4411 gettimeofday(&t1
, NULL
);
4414 while (data
.n
> 0) {
4415 main_loop_wait(false);
4417 gettimeofday(&t2
, NULL
);
4419 printf("Run completed in %3.3f seconds.\n",
4420 (t2
.tv_sec
- t1
.tv_sec
)
4421 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4425 blk_unregister_buf(blk
, data
.buf
);
4427 qemu_vfree(data
.buf
);
4448 int bsz
; /* Block size */
4456 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4460 static int img_dd_bs(const char *arg
,
4461 struct DdIo
*in
, struct DdIo
*out
,
4468 if (res
<= 0 || res
> INT_MAX
) {
4469 error_report("invalid number: '%s'", arg
);
4472 in
->bsz
= out
->bsz
= res
;
4477 static int img_dd_count(const char *arg
,
4478 struct DdIo
*in
, struct DdIo
*out
,
4481 dd
->count
= cvtnum(arg
);
4483 if (dd
->count
< 0) {
4484 error_report("invalid number: '%s'", arg
);
4491 static int img_dd_if(const char *arg
,
4492 struct DdIo
*in
, struct DdIo
*out
,
4495 in
->filename
= g_strdup(arg
);
4500 static int img_dd_of(const char *arg
,
4501 struct DdIo
*in
, struct DdIo
*out
,
4504 out
->filename
= g_strdup(arg
);
4509 static int img_dd_skip(const char *arg
,
4510 struct DdIo
*in
, struct DdIo
*out
,
4513 in
->offset
= cvtnum(arg
);
4515 if (in
->offset
< 0) {
4516 error_report("invalid number: '%s'", arg
);
4523 static int img_dd(int argc
, char **argv
)
4528 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4529 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4530 QemuOpts
*opts
= NULL
;
4531 QemuOptsList
*create_opts
= NULL
;
4532 Error
*local_err
= NULL
;
4533 bool image_opts
= false;
4535 const char *out_fmt
= "raw";
4536 const char *fmt
= NULL
;
4538 int64_t block_count
= 0, out_pos
, in_pos
;
4539 bool force_share
= false;
4540 struct DdInfo dd
= {
4545 .bsz
= 512, /* Block size is by default 512 bytes */
4557 const struct DdOpts options
[] = {
4558 { "bs", img_dd_bs
, C_BS
},
4559 { "count", img_dd_count
, C_COUNT
},
4560 { "if", img_dd_if
, C_IF
},
4561 { "of", img_dd_of
, C_OF
},
4562 { "skip", img_dd_skip
, C_SKIP
},
4565 const struct option long_options
[] = {
4566 { "help", no_argument
, 0, 'h'},
4567 { "object", required_argument
, 0, OPTION_OBJECT
},
4568 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4569 { "force-share", no_argument
, 0, 'U'},
4573 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4585 missing_argument(argv
[optind
- 1]);
4588 unrecognized_option(argv
[optind
- 1]);
4597 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4602 case OPTION_IMAGE_OPTS
:
4608 for (i
= optind
; i
< argc
; i
++) {
4610 arg
= g_strdup(argv
[i
]);
4612 tmp
= strchr(arg
, '=');
4614 error_report("unrecognized operand %s", arg
);
4621 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4622 if (!strcmp(arg
, options
[j
].name
)) {
4626 if (options
[j
].name
== NULL
) {
4627 error_report("unrecognized operand %s", arg
);
4632 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4636 dd
.flags
|= options
[j
].flag
;
4641 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4642 error_report("Must specify both input and output files");
4647 if (qemu_opts_foreach(&qemu_object_opts
,
4648 user_creatable_add_opts_foreach
,
4649 qemu_img_object_print_help
, &error_fatal
)) {
4654 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4662 drv
= bdrv_find_format(out_fmt
);
4664 error_report("Unknown file format");
4668 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4671 error_report_err(local_err
);
4675 if (!drv
->create_opts
) {
4676 error_report("Format driver '%s' does not support image creation",
4681 if (!proto_drv
->create_opts
) {
4682 error_report("Protocol driver '%s' does not support image creation",
4683 proto_drv
->format_name
);
4687 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4688 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4690 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4692 size
= blk_getlength(blk1
);
4694 error_report("Failed to get size for '%s'", in
.filename
);
4699 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4700 dd
.count
* in
.bsz
< size
) {
4701 size
= dd
.count
* in
.bsz
;
4704 /* Overflow means the specified offset is beyond input image's size */
4705 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4706 size
< in
.bsz
* in
.offset
)) {
4707 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4709 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4710 size
- in
.bsz
* in
.offset
, &error_abort
);
4713 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4715 error_reportf_err(local_err
,
4716 "%s: error while creating output image: ",
4722 /* TODO, we can't honour --image-opts for the target,
4723 * since it needs to be given in a format compatible
4724 * with the bdrv_create() call above which does not
4725 * support image-opts style.
4727 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
4728 false, false, false);
4735 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4736 size
< in
.offset
* in
.bsz
)) {
4737 /* We give a warning if the skip option is bigger than the input
4738 * size and create an empty output disk image (i.e. like dd(1)).
4740 error_report("%s: cannot skip to specified offset", in
.filename
);
4743 in_pos
= in
.offset
* in
.bsz
;
4746 in
.buf
= g_new(uint8_t, in
.bsz
);
4748 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4749 int in_ret
, out_ret
;
4751 if (in_pos
+ in
.bsz
> size
) {
4752 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4754 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4757 error_report("error while reading from input image file: %s",
4764 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4767 error_report("error while writing to output image file: %s",
4768 strerror(-out_ret
));
4777 qemu_opts_del(opts
);
4778 qemu_opts_free(create_opts
);
4781 g_free(in
.filename
);
4782 g_free(out
.filename
);
4792 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
4796 Visitor
*v
= qobject_output_visitor_new(&obj
);
4798 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
4799 visit_complete(v
, &obj
);
4800 str
= qobject_to_json_pretty(obj
);
4801 assert(str
!= NULL
);
4802 printf("%s\n", qstring_get_str(str
));
4808 static int img_measure(int argc
, char **argv
)
4810 static const struct option long_options
[] = {
4811 {"help", no_argument
, 0, 'h'},
4812 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4813 {"object", required_argument
, 0, OPTION_OBJECT
},
4814 {"output", required_argument
, 0, OPTION_OUTPUT
},
4815 {"size", required_argument
, 0, OPTION_SIZE
},
4816 {"force-share", no_argument
, 0, 'U'},
4819 OutputFormat output_format
= OFORMAT_HUMAN
;
4820 BlockBackend
*in_blk
= NULL
;
4822 const char *filename
= NULL
;
4823 const char *fmt
= NULL
;
4824 const char *out_fmt
= "raw";
4825 char *options
= NULL
;
4826 char *snapshot_name
= NULL
;
4827 bool force_share
= false;
4828 QemuOpts
*opts
= NULL
;
4829 QemuOpts
*object_opts
= NULL
;
4830 QemuOpts
*sn_opts
= NULL
;
4831 QemuOptsList
*create_opts
= NULL
;
4832 bool image_opts
= false;
4833 uint64_t img_size
= UINT64_MAX
;
4834 BlockMeasureInfo
*info
= NULL
;
4835 Error
*local_err
= NULL
;
4839 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
4840 long_options
, NULL
)) != -1) {
4853 if (!is_valid_option_list(optarg
)) {
4854 error_report("Invalid option list: %s", optarg
);
4858 options
= g_strdup(optarg
);
4860 char *old_options
= options
;
4861 options
= g_strdup_printf("%s,%s", options
, optarg
);
4862 g_free(old_options
);
4866 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
4867 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
4870 error_report("Failed in parsing snapshot param '%s'",
4875 snapshot_name
= optarg
;
4882 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4888 case OPTION_IMAGE_OPTS
:
4892 if (!strcmp(optarg
, "json")) {
4893 output_format
= OFORMAT_JSON
;
4894 } else if (!strcmp(optarg
, "human")) {
4895 output_format
= OFORMAT_HUMAN
;
4897 error_report("--output must be used with human or json "
4906 sval
= cvtnum(optarg
);
4908 if (sval
== -ERANGE
) {
4909 error_report("Image size must be less than 8 EiB!");
4911 error_report("Invalid image size specified! You may use "
4912 "k, M, G, T, P or E suffixes for ");
4913 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4914 "petabytes and exabytes.");
4918 img_size
= (uint64_t)sval
;
4924 if (qemu_opts_foreach(&qemu_object_opts
,
4925 user_creatable_add_opts_foreach
,
4926 qemu_img_object_print_help
, &error_fatal
)) {
4930 if (argc
- optind
> 1) {
4931 error_report("At most one filename argument is allowed.");
4933 } else if (argc
- optind
== 1) {
4934 filename
= argv
[optind
];
4937 if (!filename
&& (image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
4938 error_report("--image-opts, -f, and -l require a filename argument.");
4941 if (filename
&& img_size
!= UINT64_MAX
) {
4942 error_report("--size N cannot be used together with a filename.");
4945 if (!filename
&& img_size
== UINT64_MAX
) {
4946 error_report("Either --size N or one filename must be specified.");
4951 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
4952 false, false, force_share
);
4958 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
4959 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
4960 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
4962 } else if (snapshot_name
!= NULL
) {
4963 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
4964 snapshot_name
, &local_err
);
4967 error_reportf_err(local_err
, "Failed to load snapshot: ");
4972 drv
= bdrv_find_format(out_fmt
);
4974 error_report("Unknown file format '%s'", out_fmt
);
4977 if (!drv
->create_opts
) {
4978 error_report("Format driver '%s' does not support image creation",
4983 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4984 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
4985 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4987 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
4989 error_report_err(local_err
);
4990 error_report("Invalid options for file format '%s'", out_fmt
);
4994 if (img_size
!= UINT64_MAX
) {
4995 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
4998 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
5000 error_report_err(local_err
);
5004 if (output_format
== OFORMAT_HUMAN
) {
5005 printf("required size: %" PRIu64
"\n", info
->required
);
5006 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
5008 dump_json_block_measure_info(info
);
5014 qapi_free_BlockMeasureInfo(info
);
5015 qemu_opts_del(object_opts
);
5016 qemu_opts_del(opts
);
5017 qemu_opts_del(sn_opts
);
5018 qemu_opts_free(create_opts
);
5024 static const img_cmd_t img_cmds
[] = {
5025 #define DEF(option, callback, arg_string) \
5026 { option, callback },
5027 #include "qemu-img-cmds.h"
5032 int main(int argc
, char **argv
)
5034 const img_cmd_t
*cmd
;
5035 const char *cmdname
;
5036 Error
*local_error
= NULL
;
5037 char *trace_file
= NULL
;
5039 static const struct option long_options
[] = {
5040 {"help", no_argument
, 0, 'h'},
5041 {"version", no_argument
, 0, 'V'},
5042 {"trace", required_argument
, NULL
, 'T'},
5047 signal(SIGPIPE
, SIG_IGN
);
5050 error_init(argv
[0]);
5051 module_call_init(MODULE_INIT_TRACE
);
5052 qemu_init_exec_dir(argv
[0]);
5054 if (qemu_init_main_loop(&local_error
)) {
5055 error_report_err(local_error
);
5059 qcrypto_init(&error_fatal
);
5061 module_call_init(MODULE_INIT_QOM
);
5064 error_exit("Not enough arguments");
5067 qemu_add_opts(&qemu_object_opts
);
5068 qemu_add_opts(&qemu_source_opts
);
5069 qemu_add_opts(&qemu_trace_opts
);
5071 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
5074 missing_argument(argv
[optind
- 1]);
5077 unrecognized_option(argv
[optind
- 1]);
5083 printf(QEMU_IMG_VERSION
);
5087 trace_file
= trace_opt_parse(optarg
);
5092 cmdname
= argv
[optind
];
5094 /* reset getopt_long scanning */
5100 qemu_reset_optind();
5102 if (!trace_init_backends()) {
5105 trace_init_file(trace_file
);
5106 qemu_set_log(LOG_TRACE
);
5108 /* find the command */
5109 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5110 if (!strcmp(cmdname
, cmd
->name
)) {
5111 return cmd
->handler(argc
, argv
);
5116 error_exit("Command not found: %s", cmdname
);