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_fixed
!= 0;
651 check
->leaks_fixed
= result
.leaks_fixed
;
652 check
->has_leaks_fixed
= result
.leaks_fixed
!= 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
;
806 bool has_leaks_fixed
, has_corruptions_fixed
;
808 leaks_fixed
= check
->leaks_fixed
;
809 has_leaks_fixed
= check
->has_leaks_fixed
;
810 corruptions_fixed
= check
->corruptions_fixed
;
811 has_corruptions_fixed
= check
->has_corruptions_fixed
;
813 if (output_format
== OFORMAT_HUMAN
) {
815 "The following inconsistencies were found and repaired:\n\n"
816 " %" PRId64
" leaked clusters\n"
817 " %" PRId64
" corruptions\n\n"
818 "Double checking the fixed image now...\n",
820 check
->corruptions_fixed
);
823 qapi_free_ImageCheck(check
);
824 check
= g_new0(ImageCheck
, 1);
825 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
827 check
->leaks_fixed
= leaks_fixed
;
828 check
->has_leaks_fixed
= has_leaks_fixed
;
829 check
->corruptions_fixed
= corruptions_fixed
;
830 check
->has_corruptions_fixed
= has_corruptions_fixed
;
834 switch (output_format
) {
836 dump_human_image_check(check
, quiet
);
839 dump_json_image_check(check
, quiet
);
844 if (ret
|| check
->check_errors
) {
846 error_report("Check failed: %s", strerror(-ret
));
848 error_report("Check failed");
854 if (check
->corruptions
) {
856 } else if (check
->leaks
) {
863 qapi_free_ImageCheck(check
);
868 typedef struct CommonBlockJobCBInfo
{
869 BlockDriverState
*bs
;
871 } CommonBlockJobCBInfo
;
873 static void common_block_job_cb(void *opaque
, int ret
)
875 CommonBlockJobCBInfo
*cbi
= opaque
;
878 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
882 static void run_block_job(BlockJob
*job
, Error
**errp
)
884 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
887 aio_context_acquire(aio_context
);
890 float progress
= 0.0f
;
891 aio_poll(aio_context
, true);
892 if (job
->job
.progress
.total
) {
893 progress
= (float)job
->job
.progress
.current
/
894 job
->job
.progress
.total
* 100.f
;
896 qemu_progress_print(progress
, 0);
897 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
899 if (!job_is_completed(&job
->job
)) {
900 ret
= job_complete_sync(&job
->job
, errp
);
904 job_unref(&job
->job
);
905 aio_context_release(aio_context
);
907 /* publish completion progress only when success */
909 qemu_progress_print(100.f
, 0);
913 static int img_commit(int argc
, char **argv
)
916 const char *filename
, *fmt
, *cache
, *base
;
918 BlockDriverState
*bs
, *base_bs
;
920 bool progress
= false, quiet
= false, drop
= false;
922 Error
*local_err
= NULL
;
923 CommonBlockJobCBInfo cbi
;
924 bool image_opts
= false;
925 AioContext
*aio_context
;
928 cache
= BDRV_DEFAULT_CACHE
;
931 static const struct option long_options
[] = {
932 {"help", no_argument
, 0, 'h'},
933 {"object", required_argument
, 0, OPTION_OBJECT
},
934 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
937 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
944 missing_argument(argv
[optind
- 1]);
947 unrecognized_option(argv
[optind
- 1]);
972 case OPTION_OBJECT
: {
974 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
980 case OPTION_IMAGE_OPTS
:
986 /* Progress is not shown in Quiet mode */
991 if (optind
!= argc
- 1) {
992 error_exit("Expecting one image file name");
994 filename
= argv
[optind
++];
996 if (qemu_opts_foreach(&qemu_object_opts
,
997 user_creatable_add_opts_foreach
,
998 qemu_img_object_print_help
, &error_fatal
)) {
1002 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
1003 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1005 error_report("Invalid cache option: %s", cache
);
1009 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1016 qemu_progress_init(progress
, 1.f
);
1017 qemu_progress_print(0.f
, 100);
1020 base_bs
= bdrv_find_backing_image(bs
, base
);
1022 error_setg(&local_err
,
1023 "Did not find '%s' in the backing chain of '%s'",
1028 /* This is different from QMP, which by default uses the deepest file in
1029 * the backing chain (i.e., the very base); however, the traditional
1030 * behavior of qemu-img commit is using the immediate backing file. */
1031 base_bs
= backing_bs(bs
);
1033 error_setg(&local_err
, "Image does not have a backing file");
1038 cbi
= (CommonBlockJobCBInfo
){
1043 aio_context
= bdrv_get_aio_context(bs
);
1044 aio_context_acquire(aio_context
);
1045 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, 0,
1046 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1047 &cbi
, false, &local_err
);
1048 aio_context_release(aio_context
);
1053 /* When the block job completes, the BlockBackend reference will point to
1054 * the old backing file. In order to avoid that the top image is already
1055 * deleted, so we can still empty it afterwards, increment the reference
1056 * counter here preemptively. */
1061 job
= block_job_get("commit");
1063 run_block_job(job
, &local_err
);
1068 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1069 ret
= bs
->drv
->bdrv_make_empty(bs
);
1071 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1083 qemu_progress_end();
1088 error_report_err(local_err
);
1092 qprintf(quiet
, "Image committed.\n");
1097 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1098 * of the first sector boundary within buf where the sector contains a
1099 * non-zero byte. This function is robust to a buffer that is not
1102 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1105 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1107 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1108 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1112 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1119 * Returns true iff the first sector pointed to by 'buf' contains at least
1122 * 'pnum' is set to the number of sectors (including and immediately following
1123 * the first one) that are known to be in the same allocated/unallocated state.
1124 * The function will try to align the end offset to alignment boundaries so
1125 * that the request will at least end aligned and consequtive requests will
1126 * also start at an aligned offset.
1128 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1129 int64_t sector_num
, int alignment
)
1138 is_zero
= buffer_is_zero(buf
, 512);
1139 for(i
= 1; i
< n
; i
++) {
1141 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1146 tail
= (sector_num
+ i
) & (alignment
- 1);
1148 if (is_zero
&& i
<= tail
) {
1149 /* treat unallocated areas which only consist
1150 * of a small tail as allocated. */
1154 /* align up end offset of allocated areas. */
1155 i
+= alignment
- tail
;
1158 /* align down end offset of zero areas. */
1167 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1168 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1169 * breaking up write requests for only small sparse areas.
1171 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1172 int min
, int64_t sector_num
, int alignment
)
1175 int num_checked
, num_used
;
1181 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1187 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1189 sector_num
+= *pnum
;
1190 num_checked
= num_used
;
1193 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1195 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1197 sector_num
+= *pnum
;
1198 num_checked
+= *pnum
;
1200 num_used
= num_checked
;
1201 } else if (*pnum
>= min
) {
1211 * Compares two buffers sector by sector. Returns 0 if the first
1212 * sector of each buffer matches, non-zero otherwise.
1214 * pnum is set to the sector-aligned size of the buffer prefix that
1215 * has the same matching status as the first sector.
1217 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1218 int64_t bytes
, int64_t *pnum
)
1221 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1225 res
= !!memcmp(buf1
, buf2
, i
);
1227 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1229 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1239 #define IO_BUF_SIZE (2 * MiB)
1242 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1244 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1245 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1246 * failure), and 4 on error (the exit status for read errors), after emitting
1249 * @param blk: BlockBackend for the image
1250 * @param offset: Starting offset to check
1251 * @param bytes: Number of bytes to check
1252 * @param filename: Name of disk file we are checking (logging purpose)
1253 * @param buffer: Allocated buffer for storing read data
1254 * @param quiet: Flag for quiet mode
1256 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1257 int64_t bytes
, const char *filename
,
1258 uint8_t *buffer
, bool quiet
)
1263 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1265 error_report("Error while reading offset %" PRId64
" of %s: %s",
1266 offset
, filename
, strerror(-ret
));
1269 idx
= find_nonzero(buffer
, bytes
);
1271 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1280 * Compares two images. Exit codes:
1282 * 0 - Images are identical
1284 * >1 - Error occurred
1286 static int img_compare(int argc
, char **argv
)
1288 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1289 BlockBackend
*blk1
, *blk2
;
1290 BlockDriverState
*bs1
, *bs2
;
1291 int64_t total_size1
, total_size2
;
1292 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1293 int64_t pnum1
, pnum2
;
1294 int allocated1
, allocated2
;
1295 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1296 bool progress
= false, quiet
= false, strict
= false;
1303 uint64_t progress_base
;
1304 bool image_opts
= false;
1305 bool force_share
= false;
1307 cache
= BDRV_DEFAULT_CACHE
;
1309 static const struct option long_options
[] = {
1310 {"help", no_argument
, 0, 'h'},
1311 {"object", required_argument
, 0, OPTION_OBJECT
},
1312 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1313 {"force-share", no_argument
, 0, 'U'},
1316 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1317 long_options
, NULL
);
1323 missing_argument(argv
[optind
- 1]);
1326 unrecognized_option(argv
[optind
- 1]);
1352 case OPTION_OBJECT
: {
1354 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1361 case OPTION_IMAGE_OPTS
:
1367 /* Progress is not shown in Quiet mode */
1373 if (optind
!= argc
- 2) {
1374 error_exit("Expecting two image file names");
1376 filename1
= argv
[optind
++];
1377 filename2
= argv
[optind
++];
1379 if (qemu_opts_foreach(&qemu_object_opts
,
1380 user_creatable_add_opts_foreach
,
1381 qemu_img_object_print_help
, &error_fatal
)) {
1386 /* Initialize before goto out */
1387 qemu_progress_init(progress
, 2.0);
1390 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1392 error_report("Invalid source cache option: %s", cache
);
1397 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1404 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1413 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1414 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1415 total_size1
= blk_getlength(blk1
);
1416 if (total_size1
< 0) {
1417 error_report("Can't get size of %s: %s",
1418 filename1
, strerror(-total_size1
));
1422 total_size2
= blk_getlength(blk2
);
1423 if (total_size2
< 0) {
1424 error_report("Can't get size of %s: %s",
1425 filename2
, strerror(-total_size2
));
1429 total_size
= MIN(total_size1
, total_size2
);
1430 progress_base
= MAX(total_size1
, total_size2
);
1432 qemu_progress_print(0, 100);
1434 if (strict
&& total_size1
!= total_size2
) {
1436 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1440 while (offset
< total_size
) {
1441 int status1
, status2
;
1443 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1444 total_size1
- offset
, &pnum1
, NULL
,
1448 error_report("Sector allocation test failed for %s", filename1
);
1451 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1453 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1454 total_size2
- offset
, &pnum2
, NULL
,
1458 error_report("Sector allocation test failed for %s", filename2
);
1461 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1463 assert(pnum1
&& pnum2
);
1464 chunk
= MIN(pnum1
, pnum2
);
1467 if (status1
!= status2
) {
1469 qprintf(quiet
, "Strict mode: Offset %" PRId64
1470 " block status mismatch!\n", offset
);
1474 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1476 } else if (allocated1
== allocated2
) {
1480 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1481 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1483 error_report("Error while reading offset %" PRId64
1485 offset
, filename1
, strerror(-ret
));
1489 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1491 error_report("Error while reading offset %" PRId64
1493 offset
, filename2
, strerror(-ret
));
1497 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1498 if (ret
|| pnum
!= chunk
) {
1499 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1500 offset
+ (ret
? 0 : pnum
));
1506 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1508 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1509 filename1
, buf1
, quiet
);
1511 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1512 filename2
, buf1
, quiet
);
1519 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1522 if (total_size1
!= total_size2
) {
1523 BlockBackend
*blk_over
;
1524 const char *filename_over
;
1526 qprintf(quiet
, "Warning: Image size mismatch!\n");
1527 if (total_size1
> total_size2
) {
1529 filename_over
= filename1
;
1532 filename_over
= filename2
;
1535 while (offset
< progress_base
) {
1536 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1537 progress_base
- offset
, &chunk
,
1541 error_report("Sector allocation test failed for %s",
1546 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1547 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1548 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1549 filename_over
, buf1
, quiet
);
1555 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1559 qprintf(quiet
, "Images are identical.\n");
1569 qemu_progress_end();
1574 enum ImgConvertBlockStatus
{
1580 #define MAX_COROUTINES 16
1582 typedef struct ImgConvertState
{
1584 int64_t *src_sectors
;
1586 int64_t total_sectors
;
1587 int64_t allocated_sectors
;
1588 int64_t allocated_done
;
1591 enum ImgConvertBlockStatus status
;
1592 int64_t sector_next_status
;
1593 BlockBackend
*target
;
1596 bool unallocated_blocks_are_zero
;
1598 bool target_has_backing
;
1599 int64_t target_backing_sectors
; /* negative if unknown */
1606 size_t cluster_sectors
;
1608 long num_coroutines
;
1609 int running_coroutines
;
1610 Coroutine
*co
[MAX_COROUTINES
];
1611 int64_t wait_sector_num
[MAX_COROUTINES
];
1616 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1617 int *src_cur
, int64_t *src_cur_offset
)
1620 *src_cur_offset
= 0;
1621 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1622 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1624 assert(*src_cur
< s
->src_num
);
1628 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1630 int64_t src_cur_offset
;
1631 int ret
, n
, src_cur
;
1632 bool post_backing_zero
= false;
1634 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1636 assert(s
->total_sectors
> sector_num
);
1637 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1639 if (s
->target_backing_sectors
>= 0) {
1640 if (sector_num
>= s
->target_backing_sectors
) {
1641 post_backing_zero
= s
->unallocated_blocks_are_zero
;
1642 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1643 /* Split requests around target_backing_sectors (because
1644 * starting from there, zeros are handled differently) */
1645 n
= s
->target_backing_sectors
- sector_num
;
1649 if (s
->sector_next_status
<= sector_num
) {
1650 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1654 count
= n
* BDRV_SECTOR_SIZE
;
1656 if (s
->target_has_backing
) {
1657 ret
= bdrv_block_status(blk_bs(s
->src
[src_cur
]), offset
,
1658 count
, &count
, NULL
, NULL
);
1660 ret
= bdrv_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1661 offset
, count
, &count
, NULL
,
1669 warn_report("error while reading block status at "
1670 "offset %" PRIu64
": %s", offset
,
1673 /* Just try to read the data, then */
1674 ret
= BDRV_BLOCK_DATA
;
1675 count
= BDRV_SECTOR_SIZE
;
1677 /* Retry on a shorter range */
1678 n
= DIV_ROUND_UP(n
, 4);
1681 error_report("error while reading block status at offset "
1682 "%" PRIu64
": %s", offset
, strerror(-ret
));
1688 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1690 if (ret
& BDRV_BLOCK_ZERO
) {
1691 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1692 } else if (ret
& BDRV_BLOCK_DATA
) {
1693 s
->status
= BLK_DATA
;
1695 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1698 s
->sector_next_status
= sector_num
+ n
;
1701 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1702 if (s
->status
== BLK_DATA
) {
1703 n
= MIN(n
, s
->buf_sectors
);
1706 /* We need to write complete clusters for compressed images, so if an
1707 * unallocated area is shorter than that, we must consider the whole
1708 * cluster allocated. */
1709 if (s
->compressed
) {
1710 if (n
< s
->cluster_sectors
) {
1711 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1712 s
->status
= BLK_DATA
;
1714 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1721 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1722 int nb_sectors
, uint8_t *buf
)
1724 uint64_t single_read_until
= 0;
1727 assert(nb_sectors
<= s
->buf_sectors
);
1728 while (nb_sectors
> 0) {
1731 int64_t bs_sectors
, src_cur_offset
;
1734 /* In the case of compression with multiple source files, we can get a
1735 * nb_sectors that spreads into the next part. So we must be able to
1736 * read across multiple BDSes for one convert_read() call. */
1737 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1738 blk
= s
->src
[src_cur
];
1739 bs_sectors
= s
->src_sectors
[src_cur
];
1741 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1743 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1744 if (single_read_until
> offset
) {
1748 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1752 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1756 warn_report("error while reading offset %" PRIu64
1757 ": %s", offset
, strerror(-ret
));
1759 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1768 buf
+= n
* BDRV_SECTOR_SIZE
;
1775 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1776 int nb_sectors
, uint8_t *buf
,
1777 enum ImgConvertBlockStatus status
)
1781 while (nb_sectors
> 0) {
1783 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1786 case BLK_BACKING_FILE
:
1787 /* If we have a backing file, leave clusters unallocated that are
1788 * unallocated in the source image, so that the backing file is
1789 * visible at the respective offset. */
1790 assert(s
->target_has_backing
);
1794 /* If we're told to keep the target fully allocated (-S 0) or there
1795 * is real non-zero data, we must write it. Otherwise we can treat
1796 * it as zero sectors.
1797 * Compressed clusters need to be written as a whole, so in that
1798 * case we can only save the write if the buffer is completely
1800 if (!s
->min_sparse
||
1802 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1803 sector_num
, s
->alignment
)) ||
1805 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1807 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1808 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1817 if (s
->has_zero_init
) {
1818 assert(!s
->target_has_backing
);
1821 ret
= blk_co_pwrite_zeroes(s
->target
,
1822 sector_num
<< BDRV_SECTOR_BITS
,
1823 n
<< BDRV_SECTOR_BITS
,
1824 BDRV_REQ_MAY_UNMAP
);
1833 buf
+= n
* BDRV_SECTOR_SIZE
;
1839 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1844 while (nb_sectors
> 0) {
1847 int64_t bs_sectors
, src_cur_offset
;
1850 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1851 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1852 blk
= s
->src
[src_cur
];
1853 bs_sectors
= s
->src_sectors
[src_cur
];
1855 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1857 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1858 sector_num
<< BDRV_SECTOR_BITS
,
1859 n
<< BDRV_SECTOR_BITS
, 0, 0);
1870 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1872 ImgConvertState
*s
= opaque
;
1873 uint8_t *buf
= NULL
;
1877 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1878 if (s
->co
[i
] == qemu_coroutine_self()) {
1885 s
->running_coroutines
++;
1886 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1891 enum ImgConvertBlockStatus status
;
1894 qemu_co_mutex_lock(&s
->lock
);
1895 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1896 qemu_co_mutex_unlock(&s
->lock
);
1899 n
= convert_iteration_sectors(s
, s
->sector_num
);
1901 qemu_co_mutex_unlock(&s
->lock
);
1905 /* save current sector and allocation status to local variables */
1906 sector_num
= s
->sector_num
;
1908 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1909 n
= MIN(n
, s
->buf_sectors
);
1911 /* increment global sector counter so that other coroutines can
1912 * already continue reading beyond this request */
1914 qemu_co_mutex_unlock(&s
->lock
);
1916 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1917 s
->allocated_done
+= n
;
1918 qemu_progress_print(100.0 * s
->allocated_done
/
1919 s
->allocated_sectors
, 0);
1923 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
1924 if (status
== BLK_DATA
&& !copy_range
) {
1925 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1927 error_report("error while reading sector %" PRId64
1928 ": %s", sector_num
, strerror(-ret
));
1931 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1933 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1936 if (s
->wr_in_order
) {
1937 /* keep writes in order */
1938 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1939 s
->wait_sector_num
[index
] = sector_num
;
1940 qemu_coroutine_yield();
1942 s
->wait_sector_num
[index
] = -1;
1945 if (s
->ret
== -EINPROGRESS
) {
1947 ret
= convert_co_copy_range(s
, sector_num
, n
);
1949 s
->copy_range
= false;
1953 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1956 error_report("error while writing sector %" PRId64
1957 ": %s", sector_num
, strerror(-ret
));
1962 if (s
->wr_in_order
) {
1963 /* reenter the coroutine that might have waited
1964 * for this write to complete */
1965 s
->wr_offs
= sector_num
+ n
;
1966 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1967 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1969 * A -> B -> A cannot occur because A has
1970 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1971 * B will never enter A during this time window.
1973 qemu_coroutine_enter(s
->co
[i
]);
1981 s
->co
[index
] = NULL
;
1982 s
->running_coroutines
--;
1983 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1984 /* the convert job finished successfully */
1989 static int convert_do_copy(ImgConvertState
*s
)
1992 int64_t sector_num
= 0;
1994 /* Check whether we have zero initialisation or can get it efficiently */
1995 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
1996 !s
->target_has_backing
) {
1997 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
2000 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
2001 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
2003 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
| BDRV_REQ_NO_FALLBACK
);
2005 s
->has_zero_init
= true;
2009 /* Allocate buffer for copied data. For compressed images, only one cluster
2010 * can be copied at a time. */
2011 if (s
->compressed
) {
2012 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2013 error_report("invalid cluster size");
2016 s
->buf_sectors
= s
->cluster_sectors
;
2019 while (sector_num
< s
->total_sectors
) {
2020 n
= convert_iteration_sectors(s
, sector_num
);
2024 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2026 s
->allocated_sectors
+= n
;
2032 s
->sector_next_status
= 0;
2033 s
->ret
= -EINPROGRESS
;
2035 qemu_co_mutex_init(&s
->lock
);
2036 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2037 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2038 s
->wait_sector_num
[i
] = -1;
2039 qemu_coroutine_enter(s
->co
[i
]);
2042 while (s
->running_coroutines
) {
2043 main_loop_wait(false);
2046 if (s
->compressed
&& !s
->ret
) {
2047 /* signal EOF to align */
2048 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
2057 #define MAX_BUF_SECTORS 32768
2059 static int img_convert(int argc
, char **argv
)
2061 int c
, bs_i
, flags
, src_flags
= 0;
2062 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2063 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2064 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
2065 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2066 BlockDriverInfo bdi
;
2067 BlockDriverState
*out_bs
;
2068 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2069 QemuOptsList
*create_opts
= NULL
;
2070 QDict
*open_opts
= NULL
;
2071 char *options
= NULL
;
2072 Error
*local_err
= NULL
;
2073 bool writethrough
, src_writethrough
, image_opts
= false,
2074 skip_create
= false, progress
= false, tgt_image_opts
= false;
2075 int64_t ret
= -EINVAL
;
2076 bool force_share
= false;
2077 bool explict_min_sparse
= false;
2079 ImgConvertState s
= (ImgConvertState
) {
2080 /* Need at least 4k of zeros for sparse detection */
2082 .copy_range
= false,
2083 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2084 .wr_in_order
= true,
2085 .num_coroutines
= 8,
2089 static const struct option long_options
[] = {
2090 {"help", no_argument
, 0, 'h'},
2091 {"object", required_argument
, 0, OPTION_OBJECT
},
2092 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2093 {"force-share", no_argument
, 0, 'U'},
2094 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2095 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2096 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2099 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2100 long_options
, NULL
);
2106 missing_argument(argv
[optind
- 1]);
2109 unrecognized_option(argv
[optind
- 1]);
2121 out_baseimg
= optarg
;
2124 s
.copy_range
= true;
2127 s
.compressed
= true;
2130 if (!is_valid_option_list(optarg
)) {
2131 error_report("Invalid option list: %s", optarg
);
2135 options
= g_strdup(optarg
);
2137 char *old_options
= options
;
2138 options
= g_strdup_printf("%s,%s", options
, optarg
);
2139 g_free(old_options
);
2143 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2144 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2147 error_report("Failed in parsing snapshot param '%s'",
2152 snapshot_name
= optarg
;
2159 sval
= cvtnum(optarg
);
2160 if (sval
< 0 || !QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2161 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2162 error_report("Invalid buffer size for sparse output specified. "
2163 "Valid sizes are multiples of %llu up to %llu. Select "
2164 "0 to disable sparse detection (fully allocates output).",
2165 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2169 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2170 explict_min_sparse
= true;
2189 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2190 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2191 error_report("Invalid number of coroutines. Allowed number of"
2192 " coroutines is between 1 and %d", MAX_COROUTINES
);
2197 s
.wr_in_order
= false;
2202 case OPTION_OBJECT
: {
2203 QemuOpts
*object_opts
;
2204 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2211 case OPTION_IMAGE_OPTS
:
2214 case OPTION_SALVAGE
:
2217 case OPTION_TARGET_IMAGE_OPTS
:
2218 tgt_image_opts
= true;
2220 case OPTION_TARGET_IS_ZERO
:
2222 * The user asserting that the target is blank has the
2223 * same effect as the target driver supporting zero
2226 s
.has_zero_init
= true;
2231 if (!out_fmt
&& !tgt_image_opts
) {
2235 if (qemu_opts_foreach(&qemu_object_opts
,
2236 user_creatable_add_opts_foreach
,
2237 qemu_img_object_print_help
, &error_fatal
)) {
2241 if (s
.compressed
&& s
.copy_range
) {
2242 error_report("Cannot enable copy offloading when -c is used");
2246 if (explict_min_sparse
&& s
.copy_range
) {
2247 error_report("Cannot enable copy offloading when -S is used");
2251 if (s
.copy_range
&& s
.salvage
) {
2252 error_report("Cannot use copy offloading in salvaging mode");
2256 if (tgt_image_opts
&& !skip_create
) {
2257 error_report("--target-image-opts requires use of -n flag");
2261 if (skip_create
&& options
) {
2262 warn_report("-o has no effect when skipping image creation");
2263 warn_report("This will become an error in future QEMU versions.");
2266 if (s
.has_zero_init
&& !skip_create
) {
2267 error_report("--target-is-zero requires use of -n flag");
2271 s
.src_num
= argc
- optind
- 1;
2272 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2274 if (options
&& has_help_option(options
)) {
2276 ret
= print_block_option_help(out_filename
, out_fmt
);
2279 error_report("Option help requires a format be specified");
2284 if (s
.src_num
< 1) {
2285 error_report("Must specify image file name");
2290 /* ret is still -EINVAL until here */
2291 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2293 error_report("Invalid source cache option: %s", src_cache
);
2297 /* Initialize before goto out */
2301 qemu_progress_init(progress
, 1.0);
2302 qemu_progress_print(0, 100);
2304 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2305 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2307 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2308 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2309 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2315 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2316 if (s
.src_sectors
[bs_i
] < 0) {
2317 error_report("Could not get size of %s: %s",
2318 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2322 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2326 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2327 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2328 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2330 } else if (snapshot_name
!= NULL
) {
2331 if (s
.src_num
> 1) {
2332 error_report("No support for concatenating multiple snapshot");
2337 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2341 error_reportf_err(local_err
, "Failed to load snapshot: ");
2347 /* Find driver and parse its options */
2348 drv
= bdrv_find_format(out_fmt
);
2350 error_report("Unknown file format '%s'", out_fmt
);
2355 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2357 error_report_err(local_err
);
2362 if (!drv
->create_opts
) {
2363 error_report("Format driver '%s' does not support image creation",
2369 if (!proto_drv
->create_opts
) {
2370 error_report("Protocol driver '%s' does not support image creation",
2371 proto_drv
->format_name
);
2376 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2377 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2379 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2381 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2383 error_report_err(local_err
);
2389 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2391 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2397 /* Get backing file name if -o backing_file was used */
2398 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2399 if (out_baseimg_param
) {
2400 out_baseimg
= out_baseimg_param
;
2402 s
.target_has_backing
= (bool) out_baseimg
;
2404 if (s
.has_zero_init
&& s
.target_has_backing
) {
2405 error_report("Cannot use --target-is-zero when the destination "
2406 "image has a backing file");
2410 if (s
.src_num
> 1 && out_baseimg
) {
2411 error_report("Having a backing file for the target makes no sense when "
2412 "concatenating multiple input images");
2417 /* Check if compression is supported */
2420 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2421 const char *encryptfmt
=
2422 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2423 const char *preallocation
=
2424 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2426 if (drv
&& !block_driver_can_compress(drv
)) {
2427 error_report("Compression not supported for this file format");
2432 if (encryption
|| encryptfmt
) {
2433 error_report("Compression and encryption not supported at "
2440 && strcmp(preallocation
, "off"))
2442 error_report("Compression and preallocation not supported at "
2450 * The later open call will need any decryption secrets, and
2451 * bdrv_create() will purge "opts", so extract them now before
2455 open_opts
= qdict_new();
2456 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2460 /* Create the new image */
2461 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2463 error_reportf_err(local_err
, "%s: error while converting %s: ",
2464 out_filename
, out_fmt
);
2469 s
.target_is_new
= !skip_create
;
2471 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2472 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2474 error_report("Invalid cache option: %s", cache
);
2479 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2480 flags
, writethrough
, s
.quiet
, false);
2482 /* TODO ultimately we should allow --target-image-opts
2483 * to be used even when -n is not given.
2484 * That has to wait for bdrv_create to be improved
2485 * to allow filenames in option syntax
2487 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2488 flags
, writethrough
, s
.quiet
, false);
2489 open_opts
= NULL
; /* blk_new_open will have freed it */
2495 out_bs
= blk_bs(s
.target
);
2497 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2498 error_report("Compression not supported for this file format");
2503 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2504 * or discard_alignment of the out_bs is greater. Limit to
2505 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2506 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2508 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2509 out_bs
->bl
.pdiscard_alignment
>>
2510 BDRV_SECTOR_BITS
)));
2512 /* try to align the write requests to the destination to avoid unnecessary
2514 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2515 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2517 assert(is_power_of_2(s
.alignment
));
2520 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2521 if (output_sectors
< 0) {
2522 error_report("unable to get output image length: %s",
2523 strerror(-output_sectors
));
2526 } else if (output_sectors
< s
.total_sectors
) {
2527 error_report("output file is smaller than input file");
2533 if (s
.target_has_backing
&& s
.target_is_new
) {
2534 /* Errors are treated as "backing length unknown" (which means
2535 * s.target_backing_sectors has to be negative, which it will
2536 * be automatically). The backing file length is used only
2537 * for optimizations, so such a case is not fatal. */
2538 s
.target_backing_sectors
= bdrv_nb_sectors(out_bs
->backing
->bs
);
2540 s
.target_backing_sectors
= -1;
2543 ret
= bdrv_get_info(out_bs
, &bdi
);
2546 error_report("could not get block driver info");
2550 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2551 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2552 s
.unallocated_blocks_are_zero
= bdi
.unallocated_blocks_are_zero
;
2555 ret
= convert_do_copy(&s
);
2558 qemu_progress_print(100, 0);
2560 qemu_progress_end();
2561 qemu_opts_del(opts
);
2562 qemu_opts_free(create_opts
);
2563 qemu_opts_del(sn_opts
);
2564 qobject_unref(open_opts
);
2565 blk_unref(s
.target
);
2567 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2568 blk_unref(s
.src
[bs_i
]);
2572 g_free(s
.src_sectors
);
2580 static void dump_snapshots(BlockDriverState
*bs
)
2582 QEMUSnapshotInfo
*sn_tab
, *sn
;
2585 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2588 printf("Snapshot list:\n");
2589 bdrv_snapshot_dump(NULL
);
2591 for(i
= 0; i
< nb_sns
; i
++) {
2593 bdrv_snapshot_dump(sn
);
2599 static void dump_json_image_info_list(ImageInfoList
*list
)
2603 Visitor
*v
= qobject_output_visitor_new(&obj
);
2605 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2606 visit_complete(v
, &obj
);
2607 str
= qobject_to_json_pretty(obj
);
2608 assert(str
!= NULL
);
2609 printf("%s\n", qstring_get_str(str
));
2615 static void dump_json_image_info(ImageInfo
*info
)
2619 Visitor
*v
= qobject_output_visitor_new(&obj
);
2621 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2622 visit_complete(v
, &obj
);
2623 str
= qobject_to_json_pretty(obj
);
2624 assert(str
!= NULL
);
2625 printf("%s\n", qstring_get_str(str
));
2631 static void dump_human_image_info_list(ImageInfoList
*list
)
2633 ImageInfoList
*elem
;
2636 for (elem
= list
; elem
; elem
= elem
->next
) {
2642 bdrv_image_info_dump(elem
->value
);
2646 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2648 return strcmp(a
, b
) == 0;
2652 * Open an image file chain and return an ImageInfoList
2654 * @filename: topmost image filename
2655 * @fmt: topmost image format (may be NULL to autodetect)
2656 * @chain: true - enumerate entire backing file chain
2657 * false - only topmost image file
2659 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2660 * image file. If there was an error a message will have been printed to
2663 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2664 const char *filename
,
2666 bool chain
, bool force_share
)
2668 ImageInfoList
*head
= NULL
;
2669 ImageInfoList
**last
= &head
;
2670 GHashTable
*filenames
;
2673 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2677 BlockDriverState
*bs
;
2679 ImageInfoList
*elem
;
2681 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2682 error_report("Backing file '%s' creates an infinite loop.",
2686 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2688 blk
= img_open(image_opts
, filename
, fmt
,
2689 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2696 bdrv_query_image_info(bs
, &info
, &err
);
2698 error_report_err(err
);
2703 elem
= g_new0(ImageInfoList
, 1);
2710 /* Clear parameters that only apply to the topmost image */
2711 filename
= fmt
= NULL
;
2715 if (info
->has_full_backing_filename
) {
2716 filename
= info
->full_backing_filename
;
2717 } else if (info
->has_backing_filename
) {
2718 error_report("Could not determine absolute backing filename,"
2719 " but backing filename '%s' present",
2720 info
->backing_filename
);
2723 if (info
->has_backing_filename_format
) {
2724 fmt
= info
->backing_filename_format
;
2728 g_hash_table_destroy(filenames
);
2732 qapi_free_ImageInfoList(head
);
2733 g_hash_table_destroy(filenames
);
2737 static int img_info(int argc
, char **argv
)
2740 OutputFormat output_format
= OFORMAT_HUMAN
;
2742 const char *filename
, *fmt
, *output
;
2743 ImageInfoList
*list
;
2744 bool image_opts
= false;
2745 bool force_share
= false;
2750 int option_index
= 0;
2751 static const struct option long_options
[] = {
2752 {"help", no_argument
, 0, 'h'},
2753 {"format", required_argument
, 0, 'f'},
2754 {"output", required_argument
, 0, OPTION_OUTPUT
},
2755 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2756 {"object", required_argument
, 0, OPTION_OBJECT
},
2757 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2758 {"force-share", no_argument
, 0, 'U'},
2761 c
= getopt_long(argc
, argv
, ":f:hU",
2762 long_options
, &option_index
);
2768 missing_argument(argv
[optind
- 1]);
2771 unrecognized_option(argv
[optind
- 1]);
2785 case OPTION_BACKING_CHAIN
:
2788 case OPTION_OBJECT
: {
2790 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2796 case OPTION_IMAGE_OPTS
:
2801 if (optind
!= argc
- 1) {
2802 error_exit("Expecting one image file name");
2804 filename
= argv
[optind
++];
2806 if (output
&& !strcmp(output
, "json")) {
2807 output_format
= OFORMAT_JSON
;
2808 } else if (output
&& !strcmp(output
, "human")) {
2809 output_format
= OFORMAT_HUMAN
;
2810 } else if (output
) {
2811 error_report("--output must be used with human or json as argument.");
2815 if (qemu_opts_foreach(&qemu_object_opts
,
2816 user_creatable_add_opts_foreach
,
2817 qemu_img_object_print_help
, &error_fatal
)) {
2821 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2827 switch (output_format
) {
2829 dump_human_image_info_list(list
);
2833 dump_json_image_info_list(list
);
2835 dump_json_image_info(list
->value
);
2840 qapi_free_ImageInfoList(list
);
2844 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2847 switch (output_format
) {
2849 if (e
->data
&& !e
->has_offset
) {
2850 error_report("File contains external, encrypted or compressed clusters.");
2853 if (e
->data
&& !e
->zero
) {
2854 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2855 e
->start
, e
->length
,
2856 e
->has_offset
? e
->offset
: 0,
2857 e
->has_filename
? e
->filename
: "");
2859 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2860 * Modify the flags here to allow more coalescing.
2862 if (next
&& (!next
->data
|| next
->zero
)) {
2868 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2869 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2870 (e
->start
== 0 ? "[" : ",\n"),
2871 e
->start
, e
->length
, e
->depth
,
2872 e
->zero
? "true" : "false",
2873 e
->data
? "true" : "false");
2874 if (e
->has_offset
) {
2875 printf(", \"offset\": %"PRId64
"", e
->offset
);
2887 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
2888 int64_t bytes
, MapEntry
*e
)
2892 BlockDriverState
*file
;
2895 char *filename
= NULL
;
2897 /* As an optimization, we could cache the current range of unallocated
2898 * clusters in each file of the chain, and avoid querying the same
2904 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
2909 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2912 bs
= backing_bs(bs
);
2921 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2923 if (file
&& has_offset
) {
2924 bdrv_refresh_filename(file
);
2925 filename
= file
->filename
;
2931 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2932 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2934 .has_offset
= has_offset
,
2936 .has_filename
= filename
,
2937 .filename
= filename
,
2943 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2945 if (curr
->length
== 0) {
2948 if (curr
->zero
!= next
->zero
||
2949 curr
->data
!= next
->data
||
2950 curr
->depth
!= next
->depth
||
2951 curr
->has_filename
!= next
->has_filename
||
2952 curr
->has_offset
!= next
->has_offset
) {
2955 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2958 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2964 static int img_map(int argc
, char **argv
)
2967 OutputFormat output_format
= OFORMAT_HUMAN
;
2969 BlockDriverState
*bs
;
2970 const char *filename
, *fmt
, *output
;
2972 MapEntry curr
= { .length
= 0 }, next
;
2974 bool image_opts
= false;
2975 bool force_share
= false;
2980 int option_index
= 0;
2981 static const struct option long_options
[] = {
2982 {"help", no_argument
, 0, 'h'},
2983 {"format", required_argument
, 0, 'f'},
2984 {"output", required_argument
, 0, OPTION_OUTPUT
},
2985 {"object", required_argument
, 0, OPTION_OBJECT
},
2986 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2987 {"force-share", no_argument
, 0, 'U'},
2990 c
= getopt_long(argc
, argv
, ":f:hU",
2991 long_options
, &option_index
);
2997 missing_argument(argv
[optind
- 1]);
3000 unrecognized_option(argv
[optind
- 1]);
3014 case OPTION_OBJECT
: {
3016 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3022 case OPTION_IMAGE_OPTS
:
3027 if (optind
!= argc
- 1) {
3028 error_exit("Expecting one image file name");
3030 filename
= argv
[optind
];
3032 if (output
&& !strcmp(output
, "json")) {
3033 output_format
= OFORMAT_JSON
;
3034 } else if (output
&& !strcmp(output
, "human")) {
3035 output_format
= OFORMAT_HUMAN
;
3036 } else if (output
) {
3037 error_report("--output must be used with human or json as argument.");
3041 if (qemu_opts_foreach(&qemu_object_opts
,
3042 user_creatable_add_opts_foreach
,
3043 qemu_img_object_print_help
, &error_fatal
)) {
3047 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3053 if (output_format
== OFORMAT_HUMAN
) {
3054 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3057 length
= blk_getlength(blk
);
3058 while (curr
.start
+ curr
.length
< length
) {
3059 int64_t offset
= curr
.start
+ curr
.length
;
3062 /* Probe up to 1 GiB at a time. */
3063 n
= MIN(1 * GiB
, length
- offset
);
3064 ret
= get_block_status(bs
, offset
, n
, &next
);
3067 error_report("Could not read file metadata: %s", strerror(-ret
));
3071 if (entry_mergeable(&curr
, &next
)) {
3072 curr
.length
+= next
.length
;
3076 if (curr
.length
> 0) {
3077 ret
= dump_map_entry(output_format
, &curr
, &next
);
3085 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3092 #define SNAPSHOT_LIST 1
3093 #define SNAPSHOT_CREATE 2
3094 #define SNAPSHOT_APPLY 3
3095 #define SNAPSHOT_DELETE 4
3097 static int img_snapshot(int argc
, char **argv
)
3100 BlockDriverState
*bs
;
3101 QEMUSnapshotInfo sn
;
3102 char *filename
, *snapshot_name
= NULL
;
3103 int c
, ret
= 0, bdrv_oflags
;
3108 bool image_opts
= false;
3109 bool force_share
= false;
3111 bdrv_oflags
= BDRV_O_RDWR
;
3112 /* Parse commandline parameters */
3114 static const struct option long_options
[] = {
3115 {"help", no_argument
, 0, 'h'},
3116 {"object", required_argument
, 0, OPTION_OBJECT
},
3117 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3118 {"force-share", no_argument
, 0, 'U'},
3121 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3122 long_options
, NULL
);
3128 missing_argument(argv
[optind
- 1]);
3131 unrecognized_option(argv
[optind
- 1]);
3138 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3141 action
= SNAPSHOT_LIST
;
3142 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3146 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3149 action
= SNAPSHOT_APPLY
;
3150 snapshot_name
= optarg
;
3154 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3157 action
= SNAPSHOT_CREATE
;
3158 snapshot_name
= optarg
;
3162 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3165 action
= SNAPSHOT_DELETE
;
3166 snapshot_name
= optarg
;
3174 case OPTION_OBJECT
: {
3176 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3182 case OPTION_IMAGE_OPTS
:
3188 if (optind
!= argc
- 1) {
3189 error_exit("Expecting one image file name");
3191 filename
= argv
[optind
++];
3193 if (qemu_opts_foreach(&qemu_object_opts
,
3194 user_creatable_add_opts_foreach
,
3195 qemu_img_object_print_help
, &error_fatal
)) {
3199 /* Open the image */
3200 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3207 /* Perform the requested action */
3213 case SNAPSHOT_CREATE
:
3214 memset(&sn
, 0, sizeof(sn
));
3215 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3217 qemu_gettimeofday(&tv
);
3218 sn
.date_sec
= tv
.tv_sec
;
3219 sn
.date_nsec
= tv
.tv_usec
* 1000;
3221 ret
= bdrv_snapshot_create(bs
, &sn
);
3223 error_report("Could not create snapshot '%s': %d (%s)",
3224 snapshot_name
, ret
, strerror(-ret
));
3228 case SNAPSHOT_APPLY
:
3229 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3231 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3236 case SNAPSHOT_DELETE
:
3237 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3239 error_report("Could not delete snapshot '%s': snapshot not "
3240 "found", snapshot_name
);
3243 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3245 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3261 static int img_rebase(int argc
, char **argv
)
3263 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3264 uint8_t *buf_old
= NULL
;
3265 uint8_t *buf_new
= NULL
;
3266 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3268 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3269 int c
, flags
, src_flags
, ret
;
3270 bool writethrough
, src_writethrough
;
3272 bool force_share
= false;
3275 Error
*local_err
= NULL
;
3276 bool image_opts
= false;
3278 /* Parse commandline parameters */
3280 cache
= BDRV_DEFAULT_CACHE
;
3281 src_cache
= BDRV_DEFAULT_CACHE
;
3285 static const struct option long_options
[] = {
3286 {"help", no_argument
, 0, 'h'},
3287 {"object", required_argument
, 0, OPTION_OBJECT
},
3288 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3289 {"force-share", no_argument
, 0, 'U'},
3292 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3293 long_options
, NULL
);
3299 missing_argument(argv
[optind
- 1]);
3302 unrecognized_option(argv
[optind
- 1]);
3311 out_basefmt
= optarg
;
3314 out_baseimg
= optarg
;
3331 case OPTION_OBJECT
: {
3333 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3339 case OPTION_IMAGE_OPTS
:
3352 if (optind
!= argc
- 1) {
3353 error_exit("Expecting one image file name");
3355 if (!unsafe
&& !out_baseimg
) {
3356 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3358 filename
= argv
[optind
++];
3360 if (qemu_opts_foreach(&qemu_object_opts
,
3361 user_creatable_add_opts_foreach
,
3362 qemu_img_object_print_help
, &error_fatal
)) {
3366 qemu_progress_init(progress
, 2.0);
3367 qemu_progress_print(0, 100);
3369 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3370 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3372 error_report("Invalid cache option: %s", cache
);
3377 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3379 error_report("Invalid source cache option: %s", src_cache
);
3383 /* The source files are opened read-only, don't care about WCE */
3384 assert((src_flags
& BDRV_O_RDWR
) == 0);
3385 (void) src_writethrough
;
3390 * Ignore the old backing file for unsafe rebase in case we want to correct
3391 * the reference to a renamed or moved backing file.
3393 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3401 if (out_basefmt
!= NULL
) {
3402 if (bdrv_find_format(out_basefmt
) == NULL
) {
3403 error_report("Invalid format name: '%s'", out_basefmt
);
3409 /* For safe rebasing we need to compare old and new backing file */
3411 QDict
*options
= NULL
;
3412 BlockDriverState
*base_bs
= backing_bs(bs
);
3415 blk_old_backing
= blk_new(qemu_get_aio_context(),
3416 BLK_PERM_CONSISTENT_READ
,
3418 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3421 error_reportf_err(local_err
,
3422 "Could not reuse old backing file '%s': ",
3427 blk_old_backing
= NULL
;
3430 if (out_baseimg
[0]) {
3431 const char *overlay_filename
;
3432 char *out_real_path
;
3434 options
= qdict_new();
3436 qdict_put_str(options
, "driver", out_basefmt
);
3439 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3442 bdrv_refresh_filename(bs
);
3443 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3446 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3450 qobject_unref(options
);
3451 error_reportf_err(local_err
,
3452 "Could not resolve backing filename: ");
3458 * Find out whether we rebase an image on top of a previous image
3461 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3462 if (prefix_chain_bs
) {
3463 qobject_unref(options
);
3464 g_free(out_real_path
);
3466 blk_new_backing
= blk_new(qemu_get_aio_context(),
3467 BLK_PERM_CONSISTENT_READ
,
3469 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3472 error_reportf_err(local_err
,
3473 "Could not reuse backing file '%s': ",
3478 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3479 options
, src_flags
, &local_err
);
3480 g_free(out_real_path
);
3481 if (!blk_new_backing
) {
3482 error_reportf_err(local_err
,
3483 "Could not open new backing file '%s': ",
3493 * Check each unallocated cluster in the COW file. If it is unallocated,
3494 * accesses go to the backing file. We must therefore compare this cluster
3495 * in the old and new backing file, and if they differ we need to copy it
3496 * from the old backing file into the COW file.
3498 * If qemu-img crashes during this step, no harm is done. The content of
3499 * the image is the same as the original one at any time.
3503 int64_t old_backing_size
= 0;
3504 int64_t new_backing_size
= 0;
3507 float local_progress
= 0;
3509 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3510 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3512 size
= blk_getlength(blk
);
3514 error_report("Could not get size of '%s': %s",
3515 filename
, strerror(-size
));
3519 if (blk_old_backing
) {
3520 old_backing_size
= blk_getlength(blk_old_backing
);
3521 if (old_backing_size
< 0) {
3522 char backing_name
[PATH_MAX
];
3524 bdrv_get_backing_filename(bs
, backing_name
,
3525 sizeof(backing_name
));
3526 error_report("Could not get size of '%s': %s",
3527 backing_name
, strerror(-old_backing_size
));
3532 if (blk_new_backing
) {
3533 new_backing_size
= blk_getlength(blk_new_backing
);
3534 if (new_backing_size
< 0) {
3535 error_report("Could not get size of '%s': %s",
3536 out_baseimg
, strerror(-new_backing_size
));
3543 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3546 for (offset
= 0; offset
< size
; offset
+= n
) {
3547 bool buf_old_is_zero
= false;
3549 /* How many bytes can we handle with the next read? */
3550 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3552 /* If the cluster is allocated, we don't need to take action */
3553 ret
= bdrv_is_allocated(bs
, offset
, n
, &n
);
3555 error_report("error while reading image metadata: %s",
3563 if (prefix_chain_bs
) {
3565 * If cluster wasn't changed since prefix_chain, we don't need
3568 ret
= bdrv_is_allocated_above(backing_bs(bs
), prefix_chain_bs
,
3569 false, offset
, n
, &n
);
3571 error_report("error while reading image metadata: %s",
3581 * Read old and new backing file and take into consideration that
3582 * backing files may be smaller than the COW image.
3584 if (offset
>= old_backing_size
) {
3585 memset(buf_old
, 0, n
);
3586 buf_old_is_zero
= true;
3588 if (offset
+ n
> old_backing_size
) {
3589 n
= old_backing_size
- offset
;
3592 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3594 error_report("error while reading from old backing file");
3599 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3600 memset(buf_new
, 0, n
);
3602 if (offset
+ n
> new_backing_size
) {
3603 n
= new_backing_size
- offset
;
3606 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3608 error_report("error while reading from new backing file");
3613 /* If they differ, we need to write to the COW file */
3614 uint64_t written
= 0;
3616 while (written
< n
) {
3619 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3620 n
- written
, &pnum
))
3622 if (buf_old_is_zero
) {
3623 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3625 ret
= blk_pwrite(blk
, offset
+ written
,
3626 buf_old
+ written
, pnum
, 0);
3629 error_report("Error while writing to COW image: %s",
3637 qemu_progress_print(local_progress
, 100);
3642 * Change the backing file. All clusters that are different from the old
3643 * backing file are overwritten in the COW file now, so the visible content
3644 * doesn't change when we switch the backing file.
3646 if (out_baseimg
&& *out_baseimg
) {
3647 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3649 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3652 if (ret
== -ENOSPC
) {
3653 error_report("Could not change the backing file to '%s': No "
3654 "space left in the file header", out_baseimg
);
3655 } else if (ret
< 0) {
3656 error_report("Could not change the backing file to '%s': %s",
3657 out_baseimg
, strerror(-ret
));
3660 qemu_progress_print(100, 0);
3662 * TODO At this point it is possible to check if any clusters that are
3663 * allocated in the COW file are the same in the backing file. If so, they
3664 * could be dropped from the COW file. Don't do this before switching the
3665 * backing file, in case of a crash this would lead to corruption.
3668 qemu_progress_end();
3671 blk_unref(blk_old_backing
);
3672 blk_unref(blk_new_backing
);
3674 qemu_vfree(buf_old
);
3675 qemu_vfree(buf_new
);
3684 static int img_resize(int argc
, char **argv
)
3687 int c
, ret
, relative
;
3688 const char *filename
, *fmt
, *size
;
3689 int64_t n
, total_size
, current_size
;
3691 BlockBackend
*blk
= NULL
;
3692 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3695 static QemuOptsList resize_options
= {
3696 .name
= "resize_options",
3697 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3700 .name
= BLOCK_OPT_SIZE
,
3701 .type
= QEMU_OPT_SIZE
,
3702 .help
= "Virtual disk size"
3708 bool image_opts
= false;
3709 bool shrink
= false;
3711 /* Remove size from argv manually so that negative numbers are not treated
3712 * as options by getopt. */
3714 error_exit("Not enough arguments");
3718 size
= argv
[--argc
];
3720 /* Parse getopt arguments */
3723 static const struct option long_options
[] = {
3724 {"help", no_argument
, 0, 'h'},
3725 {"object", required_argument
, 0, OPTION_OBJECT
},
3726 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3727 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3728 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3731 c
= getopt_long(argc
, argv
, ":f:hq",
3732 long_options
, NULL
);
3738 missing_argument(argv
[optind
- 1]);
3741 unrecognized_option(argv
[optind
- 1]);
3752 case OPTION_OBJECT
: {
3754 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3760 case OPTION_IMAGE_OPTS
:
3763 case OPTION_PREALLOCATION
:
3764 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3765 PREALLOC_MODE__MAX
, NULL
);
3766 if (prealloc
== PREALLOC_MODE__MAX
) {
3767 error_report("Invalid preallocation mode '%s'", optarg
);
3776 if (optind
!= argc
- 1) {
3777 error_exit("Expecting image file name and size");
3779 filename
= argv
[optind
++];
3781 if (qemu_opts_foreach(&qemu_object_opts
,
3782 user_creatable_add_opts_foreach
,
3783 qemu_img_object_print_help
, &error_fatal
)) {
3787 /* Choose grow, shrink, or absolute resize mode */
3803 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3804 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3806 error_report_err(err
);
3808 qemu_opts_del(param
);
3811 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3812 qemu_opts_del(param
);
3814 blk
= img_open(image_opts
, filename
, fmt
,
3815 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3822 current_size
= blk_getlength(blk
);
3823 if (current_size
< 0) {
3824 error_report("Failed to inquire current image length: %s",
3825 strerror(-current_size
));
3831 total_size
= current_size
+ n
* relative
;
3835 if (total_size
<= 0) {
3836 error_report("New image size must be positive");
3841 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3842 error_report("Preallocation can only be used for growing images");
3847 if (total_size
< current_size
&& !shrink
) {
3848 warn_report("Shrinking an image will delete all data beyond the "
3849 "shrunken image's end. Before performing such an "
3850 "operation, make sure there is no important data there.");
3852 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk
)), "raw") != 0) {
3854 "Use the --shrink option to perform a shrink operation.");
3858 warn_report("Using the --shrink option will suppress this message. "
3859 "Note that future versions of qemu-img may refuse to "
3860 "shrink images without this option.");
3865 * The user expects the image to have the desired size after
3866 * resizing, so pass @exact=true. It is of no use to report
3867 * success when the image has not actually been resized.
3869 ret
= blk_truncate(blk
, total_size
, true, prealloc
, &err
);
3871 qprintf(quiet
, "Image resized.\n");
3873 error_report_err(err
);
3883 static void amend_status_cb(BlockDriverState
*bs
,
3884 int64_t offset
, int64_t total_work_size
,
3887 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3890 static int print_amend_option_help(const char *format
)
3894 /* Find driver and parse its options */
3895 drv
= bdrv_find_format(format
);
3897 error_report("Unknown file format '%s'", format
);
3901 if (!drv
->bdrv_amend_options
) {
3902 error_report("Format driver '%s' does not support option amendment",
3907 /* Every driver supporting amendment must have create_opts */
3908 assert(drv
->create_opts
);
3910 printf("Creation options for '%s':\n", format
);
3911 qemu_opts_print_help(drv
->create_opts
, false);
3912 printf("\nNote that not all of these options may be amendable.\n");
3916 static int img_amend(int argc
, char **argv
)
3920 char *options
= NULL
;
3921 QemuOptsList
*create_opts
= NULL
;
3922 QemuOpts
*opts
= NULL
;
3923 const char *fmt
= NULL
, *filename
, *cache
;
3926 bool quiet
= false, progress
= false;
3927 BlockBackend
*blk
= NULL
;
3928 BlockDriverState
*bs
= NULL
;
3929 bool image_opts
= false;
3931 cache
= BDRV_DEFAULT_CACHE
;
3933 static const struct option long_options
[] = {
3934 {"help", no_argument
, 0, 'h'},
3935 {"object", required_argument
, 0, OPTION_OBJECT
},
3936 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3939 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
3940 long_options
, NULL
);
3947 missing_argument(argv
[optind
- 1]);
3950 unrecognized_option(argv
[optind
- 1]);
3956 if (!is_valid_option_list(optarg
)) {
3957 error_report("Invalid option list: %s", optarg
);
3959 goto out_no_progress
;
3962 options
= g_strdup(optarg
);
3964 char *old_options
= options
;
3965 options
= g_strdup_printf("%s,%s", options
, optarg
);
3966 g_free(old_options
);
3982 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3986 goto out_no_progress
;
3989 case OPTION_IMAGE_OPTS
:
3996 error_exit("Must specify options (-o)");
3999 if (qemu_opts_foreach(&qemu_object_opts
,
4000 user_creatable_add_opts_foreach
,
4001 qemu_img_object_print_help
, &error_fatal
)) {
4003 goto out_no_progress
;
4009 qemu_progress_init(progress
, 1.0);
4011 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
4012 if (fmt
&& has_help_option(options
)) {
4013 /* If a format is explicitly specified (and possibly no filename is
4014 * given), print option help here */
4015 ret
= print_amend_option_help(fmt
);
4019 if (optind
!= argc
- 1) {
4020 error_report("Expecting one image file name");
4025 flags
= BDRV_O_RDWR
;
4026 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
4028 error_report("Invalid cache option: %s", cache
);
4032 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4040 fmt
= bs
->drv
->format_name
;
4042 if (has_help_option(options
)) {
4043 /* If the format was auto-detected, print option help here */
4044 ret
= print_amend_option_help(fmt
);
4048 if (!bs
->drv
->bdrv_amend_options
) {
4049 error_report("Format driver '%s' does not support option amendment",
4055 /* Every driver supporting amendment must have create_opts */
4056 assert(bs
->drv
->create_opts
);
4058 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
4059 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4060 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
4062 error_report_err(err
);
4067 /* In case the driver does not call amend_status_cb() */
4068 qemu_progress_print(0.f
, 0);
4069 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, &err
);
4070 qemu_progress_print(100.f
, 0);
4072 error_report_err(err
);
4077 qemu_progress_end();
4081 qemu_opts_del(opts
);
4082 qemu_opts_free(create_opts
);
4091 typedef struct BenchData
{
4093 uint64_t image_size
;
4100 bool drain_on_flush
;
4109 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4112 error_report("Failed flush request: %s", strerror(-ret
));
4117 static void bench_cb(void *opaque
, int ret
)
4119 BenchData
*b
= opaque
;
4123 error_report("Failed request: %s", strerror(-ret
));
4128 /* Just finished a flush with drained queue: Start next requests */
4129 assert(b
->in_flight
== 0);
4130 b
->in_flush
= false;
4131 } else if (b
->in_flight
> 0) {
4132 int remaining
= b
->n
- b
->in_flight
;
4137 /* Time for flush? Drain queue if requested, then flush */
4138 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4139 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4140 BlockCompletionFunc
*cb
;
4142 if (b
->drain_on_flush
) {
4146 cb
= bench_undrained_flush_cb
;
4149 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4151 error_report("Failed to issue flush request");
4155 if (b
->drain_on_flush
) {
4161 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4162 int64_t offset
= b
->offset
;
4163 /* blk_aio_* might look for completed I/Os and kick bench_cb
4164 * again, so make sure this operation is counted by in_flight
4165 * and b->offset is ready for the next submission.
4168 b
->offset
+= b
->step
;
4169 b
->offset
%= b
->image_size
;
4171 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4173 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4176 error_report("Failed to issue request");
4182 static int img_bench(int argc
, char **argv
)
4185 const char *fmt
= NULL
, *filename
;
4187 bool image_opts
= false;
4188 bool is_write
= false;
4192 size_t bufsize
= 4096;
4195 int flush_interval
= 0;
4196 bool drain_on_flush
= true;
4198 BlockBackend
*blk
= NULL
;
4199 BenchData data
= {};
4201 bool writethrough
= false;
4202 struct timeval t1
, t2
;
4204 bool force_share
= false;
4208 static const struct option long_options
[] = {
4209 {"help", no_argument
, 0, 'h'},
4210 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4211 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4212 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4213 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4214 {"force-share", no_argument
, 0, 'U'},
4217 c
= getopt_long(argc
, argv
, ":hc:d:f:ni:o:qs:S:t:wU", long_options
,
4225 missing_argument(argv
[optind
- 1]);
4228 unrecognized_option(argv
[optind
- 1]);
4237 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4238 error_report("Invalid request count specified");
4248 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4249 error_report("Invalid queue depth specified");
4259 flags
|= BDRV_O_NATIVE_AIO
;
4262 ret
= bdrv_parse_aio(optarg
, &flags
);
4264 error_report("Invalid aio option: %s", optarg
);
4271 offset
= cvtnum(optarg
);
4273 error_report("Invalid offset specified");
4286 sval
= cvtnum(optarg
);
4287 if (sval
< 0 || sval
> INT_MAX
) {
4288 error_report("Invalid buffer size specified");
4299 sval
= cvtnum(optarg
);
4300 if (sval
< 0 || sval
> INT_MAX
) {
4301 error_report("Invalid step size specified");
4309 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4311 error_report("Invalid cache mode");
4317 flags
|= BDRV_O_RDWR
;
4323 case OPTION_PATTERN
:
4327 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4328 error_report("Invalid pattern byte specified");
4334 case OPTION_FLUSH_INTERVAL
:
4338 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4339 error_report("Invalid flush interval specified");
4342 flush_interval
= res
;
4345 case OPTION_NO_DRAIN
:
4346 drain_on_flush
= false;
4348 case OPTION_IMAGE_OPTS
:
4354 if (optind
!= argc
- 1) {
4355 error_exit("Expecting one image file name");
4357 filename
= argv
[argc
- 1];
4359 if (!is_write
&& flush_interval
) {
4360 error_report("--flush-interval is only available in write tests");
4364 if (flush_interval
&& flush_interval
< depth
) {
4365 error_report("Flush interval can't be smaller than depth");
4370 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4377 image_size
= blk_getlength(blk
);
4378 if (image_size
< 0) {
4383 data
= (BenchData
) {
4385 .image_size
= image_size
,
4387 .step
= step
?: bufsize
,
4392 .flush_interval
= flush_interval
,
4393 .drain_on_flush
= drain_on_flush
,
4395 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4396 "(starting at offset %" PRId64
", step size %d)\n",
4397 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4398 data
.offset
, data
.step
);
4399 if (flush_interval
) {
4400 printf("Sending flush every %d requests\n", flush_interval
);
4403 buf_size
= data
.nrreq
* data
.bufsize
;
4404 data
.buf
= blk_blockalign(blk
, buf_size
);
4405 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4407 blk_register_buf(blk
, data
.buf
, buf_size
);
4409 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4410 for (i
= 0; i
< data
.nrreq
; i
++) {
4411 qemu_iovec_init(&data
.qiov
[i
], 1);
4412 qemu_iovec_add(&data
.qiov
[i
],
4413 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4416 gettimeofday(&t1
, NULL
);
4419 while (data
.n
> 0) {
4420 main_loop_wait(false);
4422 gettimeofday(&t2
, NULL
);
4424 printf("Run completed in %3.3f seconds.\n",
4425 (t2
.tv_sec
- t1
.tv_sec
)
4426 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4430 blk_unregister_buf(blk
, data
.buf
);
4432 qemu_vfree(data
.buf
);
4453 int bsz
; /* Block size */
4461 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4465 static int img_dd_bs(const char *arg
,
4466 struct DdIo
*in
, struct DdIo
*out
,
4473 if (res
<= 0 || res
> INT_MAX
) {
4474 error_report("invalid number: '%s'", arg
);
4477 in
->bsz
= out
->bsz
= res
;
4482 static int img_dd_count(const char *arg
,
4483 struct DdIo
*in
, struct DdIo
*out
,
4486 dd
->count
= cvtnum(arg
);
4488 if (dd
->count
< 0) {
4489 error_report("invalid number: '%s'", arg
);
4496 static int img_dd_if(const char *arg
,
4497 struct DdIo
*in
, struct DdIo
*out
,
4500 in
->filename
= g_strdup(arg
);
4505 static int img_dd_of(const char *arg
,
4506 struct DdIo
*in
, struct DdIo
*out
,
4509 out
->filename
= g_strdup(arg
);
4514 static int img_dd_skip(const char *arg
,
4515 struct DdIo
*in
, struct DdIo
*out
,
4518 in
->offset
= cvtnum(arg
);
4520 if (in
->offset
< 0) {
4521 error_report("invalid number: '%s'", arg
);
4528 static int img_dd(int argc
, char **argv
)
4533 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4534 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4535 QemuOpts
*opts
= NULL
;
4536 QemuOptsList
*create_opts
= NULL
;
4537 Error
*local_err
= NULL
;
4538 bool image_opts
= false;
4540 const char *out_fmt
= "raw";
4541 const char *fmt
= NULL
;
4543 int64_t block_count
= 0, out_pos
, in_pos
;
4544 bool force_share
= false;
4545 struct DdInfo dd
= {
4550 .bsz
= 512, /* Block size is by default 512 bytes */
4562 const struct DdOpts options
[] = {
4563 { "bs", img_dd_bs
, C_BS
},
4564 { "count", img_dd_count
, C_COUNT
},
4565 { "if", img_dd_if
, C_IF
},
4566 { "of", img_dd_of
, C_OF
},
4567 { "skip", img_dd_skip
, C_SKIP
},
4570 const struct option long_options
[] = {
4571 { "help", no_argument
, 0, 'h'},
4572 { "object", required_argument
, 0, OPTION_OBJECT
},
4573 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4574 { "force-share", no_argument
, 0, 'U'},
4578 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4590 missing_argument(argv
[optind
- 1]);
4593 unrecognized_option(argv
[optind
- 1]);
4602 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4607 case OPTION_IMAGE_OPTS
:
4613 for (i
= optind
; i
< argc
; i
++) {
4615 arg
= g_strdup(argv
[i
]);
4617 tmp
= strchr(arg
, '=');
4619 error_report("unrecognized operand %s", arg
);
4626 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4627 if (!strcmp(arg
, options
[j
].name
)) {
4631 if (options
[j
].name
== NULL
) {
4632 error_report("unrecognized operand %s", arg
);
4637 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4641 dd
.flags
|= options
[j
].flag
;
4646 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4647 error_report("Must specify both input and output files");
4652 if (qemu_opts_foreach(&qemu_object_opts
,
4653 user_creatable_add_opts_foreach
,
4654 qemu_img_object_print_help
, &error_fatal
)) {
4659 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4667 drv
= bdrv_find_format(out_fmt
);
4669 error_report("Unknown file format");
4673 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4676 error_report_err(local_err
);
4680 if (!drv
->create_opts
) {
4681 error_report("Format driver '%s' does not support image creation",
4686 if (!proto_drv
->create_opts
) {
4687 error_report("Protocol driver '%s' does not support image creation",
4688 proto_drv
->format_name
);
4692 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4693 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4695 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4697 size
= blk_getlength(blk1
);
4699 error_report("Failed to get size for '%s'", in
.filename
);
4704 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4705 dd
.count
* in
.bsz
< size
) {
4706 size
= dd
.count
* in
.bsz
;
4709 /* Overflow means the specified offset is beyond input image's size */
4710 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4711 size
< in
.bsz
* in
.offset
)) {
4712 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4714 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4715 size
- in
.bsz
* in
.offset
, &error_abort
);
4718 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4720 error_reportf_err(local_err
,
4721 "%s: error while creating output image: ",
4727 /* TODO, we can't honour --image-opts for the target,
4728 * since it needs to be given in a format compatible
4729 * with the bdrv_create() call above which does not
4730 * support image-opts style.
4732 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
4733 false, false, false);
4740 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4741 size
< in
.offset
* in
.bsz
)) {
4742 /* We give a warning if the skip option is bigger than the input
4743 * size and create an empty output disk image (i.e. like dd(1)).
4745 error_report("%s: cannot skip to specified offset", in
.filename
);
4748 in_pos
= in
.offset
* in
.bsz
;
4751 in
.buf
= g_new(uint8_t, in
.bsz
);
4753 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4754 int in_ret
, out_ret
;
4756 if (in_pos
+ in
.bsz
> size
) {
4757 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4759 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4762 error_report("error while reading from input image file: %s",
4769 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4772 error_report("error while writing to output image file: %s",
4773 strerror(-out_ret
));
4782 qemu_opts_del(opts
);
4783 qemu_opts_free(create_opts
);
4786 g_free(in
.filename
);
4787 g_free(out
.filename
);
4797 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
4801 Visitor
*v
= qobject_output_visitor_new(&obj
);
4803 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
4804 visit_complete(v
, &obj
);
4805 str
= qobject_to_json_pretty(obj
);
4806 assert(str
!= NULL
);
4807 printf("%s\n", qstring_get_str(str
));
4813 static int img_measure(int argc
, char **argv
)
4815 static const struct option long_options
[] = {
4816 {"help", no_argument
, 0, 'h'},
4817 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4818 {"object", required_argument
, 0, OPTION_OBJECT
},
4819 {"output", required_argument
, 0, OPTION_OUTPUT
},
4820 {"size", required_argument
, 0, OPTION_SIZE
},
4821 {"force-share", no_argument
, 0, 'U'},
4824 OutputFormat output_format
= OFORMAT_HUMAN
;
4825 BlockBackend
*in_blk
= NULL
;
4827 const char *filename
= NULL
;
4828 const char *fmt
= NULL
;
4829 const char *out_fmt
= "raw";
4830 char *options
= NULL
;
4831 char *snapshot_name
= NULL
;
4832 bool force_share
= false;
4833 QemuOpts
*opts
= NULL
;
4834 QemuOpts
*object_opts
= NULL
;
4835 QemuOpts
*sn_opts
= NULL
;
4836 QemuOptsList
*create_opts
= NULL
;
4837 bool image_opts
= false;
4838 uint64_t img_size
= UINT64_MAX
;
4839 BlockMeasureInfo
*info
= NULL
;
4840 Error
*local_err
= NULL
;
4844 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
4845 long_options
, NULL
)) != -1) {
4858 if (!is_valid_option_list(optarg
)) {
4859 error_report("Invalid option list: %s", optarg
);
4863 options
= g_strdup(optarg
);
4865 char *old_options
= options
;
4866 options
= g_strdup_printf("%s,%s", options
, optarg
);
4867 g_free(old_options
);
4871 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
4872 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
4875 error_report("Failed in parsing snapshot param '%s'",
4880 snapshot_name
= optarg
;
4887 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4893 case OPTION_IMAGE_OPTS
:
4897 if (!strcmp(optarg
, "json")) {
4898 output_format
= OFORMAT_JSON
;
4899 } else if (!strcmp(optarg
, "human")) {
4900 output_format
= OFORMAT_HUMAN
;
4902 error_report("--output must be used with human or json "
4911 sval
= cvtnum(optarg
);
4913 if (sval
== -ERANGE
) {
4914 error_report("Image size must be less than 8 EiB!");
4916 error_report("Invalid image size specified! You may use "
4917 "k, M, G, T, P or E suffixes for ");
4918 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4919 "petabytes and exabytes.");
4923 img_size
= (uint64_t)sval
;
4929 if (qemu_opts_foreach(&qemu_object_opts
,
4930 user_creatable_add_opts_foreach
,
4931 qemu_img_object_print_help
, &error_fatal
)) {
4935 if (argc
- optind
> 1) {
4936 error_report("At most one filename argument is allowed.");
4938 } else if (argc
- optind
== 1) {
4939 filename
= argv
[optind
];
4942 if (!filename
&& (image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
4943 error_report("--image-opts, -f, and -l require a filename argument.");
4946 if (filename
&& img_size
!= UINT64_MAX
) {
4947 error_report("--size N cannot be used together with a filename.");
4950 if (!filename
&& img_size
== UINT64_MAX
) {
4951 error_report("Either --size N or one filename must be specified.");
4956 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
4957 false, false, force_share
);
4963 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
4964 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
4965 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
4967 } else if (snapshot_name
!= NULL
) {
4968 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
4969 snapshot_name
, &local_err
);
4972 error_reportf_err(local_err
, "Failed to load snapshot: ");
4977 drv
= bdrv_find_format(out_fmt
);
4979 error_report("Unknown file format '%s'", out_fmt
);
4982 if (!drv
->create_opts
) {
4983 error_report("Format driver '%s' does not support image creation",
4988 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4989 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
4990 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4992 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
4994 error_report_err(local_err
);
4995 error_report("Invalid options for file format '%s'", out_fmt
);
4999 if (img_size
!= UINT64_MAX
) {
5000 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
5003 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
5005 error_report_err(local_err
);
5009 if (output_format
== OFORMAT_HUMAN
) {
5010 printf("required size: %" PRIu64
"\n", info
->required
);
5011 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
5013 dump_json_block_measure_info(info
);
5019 qapi_free_BlockMeasureInfo(info
);
5020 qemu_opts_del(object_opts
);
5021 qemu_opts_del(opts
);
5022 qemu_opts_del(sn_opts
);
5023 qemu_opts_free(create_opts
);
5029 static const img_cmd_t img_cmds
[] = {
5030 #define DEF(option, callback, arg_string) \
5031 { option, callback },
5032 #include "qemu-img-cmds.h"
5037 int main(int argc
, char **argv
)
5039 const img_cmd_t
*cmd
;
5040 const char *cmdname
;
5041 Error
*local_error
= NULL
;
5042 char *trace_file
= NULL
;
5044 static const struct option long_options
[] = {
5045 {"help", no_argument
, 0, 'h'},
5046 {"version", no_argument
, 0, 'V'},
5047 {"trace", required_argument
, NULL
, 'T'},
5052 signal(SIGPIPE
, SIG_IGN
);
5055 error_init(argv
[0]);
5056 module_call_init(MODULE_INIT_TRACE
);
5057 qemu_init_exec_dir(argv
[0]);
5059 if (qemu_init_main_loop(&local_error
)) {
5060 error_report_err(local_error
);
5064 qcrypto_init(&error_fatal
);
5066 module_call_init(MODULE_INIT_QOM
);
5069 error_exit("Not enough arguments");
5072 qemu_add_opts(&qemu_object_opts
);
5073 qemu_add_opts(&qemu_source_opts
);
5074 qemu_add_opts(&qemu_trace_opts
);
5076 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
5079 missing_argument(argv
[optind
- 1]);
5082 unrecognized_option(argv
[optind
- 1]);
5088 printf(QEMU_IMG_VERSION
);
5092 trace_file
= trace_opt_parse(optarg
);
5097 cmdname
= argv
[optind
];
5099 /* reset getopt_long scanning */
5105 qemu_reset_optind();
5107 if (!trace_init_backends()) {
5110 trace_init_file(trace_file
);
5111 qemu_set_log(LOG_TRACE
);
5113 /* find the command */
5114 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5115 if (!strcmp(cmdname
, cmd
->name
)) {
5116 return cmd
->handler(argc
, argv
);
5121 error_exit("Command not found: %s", cmdname
);