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
)) {
227 * Is @optarg safe for accumulate_options()?
228 * It is when multiple of them can be joined together separated by ','.
229 * To make that work, @optarg must not start with ',' (or else a
230 * separating ',' preceding it gets escaped), and it must not end with
231 * an odd number of ',' (or else a separating ',' following it gets
232 * escaped), or be empty (or else a separating ',' preceding it can
233 * escape a separating ',' following it).
236 static bool is_valid_option_list(const char *optarg
)
238 size_t len
= strlen(optarg
);
241 if (!optarg
[0] || optarg
[0] == ',') {
245 for (i
= len
; i
> 0 && optarg
[i
- 1] == ','; i
--) {
254 static int accumulate_options(char **options
, char *optarg
)
258 if (!is_valid_option_list(optarg
)) {
259 error_report("Invalid option list: %s", optarg
);
264 *options
= g_strdup(optarg
);
266 new_options
= g_strdup_printf("%s,%s", *options
, optarg
);
268 *options
= new_options
;
273 static QemuOptsList qemu_source_opts
= {
275 .implied_opt_name
= "file",
276 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
282 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
288 ret
= vprintf(fmt
, args
);
295 static int print_block_option_help(const char *filename
, const char *fmt
)
297 BlockDriver
*drv
, *proto_drv
;
298 QemuOptsList
*create_opts
= NULL
;
299 Error
*local_err
= NULL
;
301 /* Find driver and parse its options */
302 drv
= bdrv_find_format(fmt
);
304 error_report("Unknown file format '%s'", fmt
);
308 if (!drv
->create_opts
) {
309 error_report("Format driver '%s' does not support image creation", fmt
);
313 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
315 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
317 error_report_err(local_err
);
318 qemu_opts_free(create_opts
);
321 if (!proto_drv
->create_opts
) {
322 error_report("Protocol driver '%s' does not support image creation",
323 proto_drv
->format_name
);
324 qemu_opts_free(create_opts
);
327 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
331 printf("Supported options:\n");
333 printf("Supported %s options:\n", fmt
);
335 qemu_opts_print_help(create_opts
, false);
336 qemu_opts_free(create_opts
);
340 "The protocol level may support further options.\n"
341 "Specify the target filename to include those options.\n");
348 static BlockBackend
*img_open_opts(const char *optstr
,
349 QemuOpts
*opts
, int flags
, bool writethrough
,
350 bool quiet
, bool force_share
)
353 Error
*local_err
= NULL
;
355 options
= qemu_opts_to_qdict(opts
, NULL
);
357 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
358 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
359 error_report("--force-share/-U conflicts with image options");
360 qobject_unref(options
);
363 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
365 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
367 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
370 blk_set_enable_write_cache(blk
, !writethrough
);
375 static BlockBackend
*img_open_file(const char *filename
,
377 const char *fmt
, int flags
,
378 bool writethrough
, bool quiet
,
382 Error
*local_err
= NULL
;
385 options
= qdict_new();
388 qdict_put_str(options
, "driver", fmt
);
392 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
394 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
396 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
399 blk_set_enable_write_cache(blk
, !writethrough
);
405 static int img_add_key_secrets(void *opaque
,
406 const char *name
, const char *value
,
409 QDict
*options
= opaque
;
411 if (g_str_has_suffix(name
, "key-secret")) {
412 qdict_put_str(options
, name
, value
);
419 static BlockBackend
*img_open(bool image_opts
,
420 const char *filename
,
421 const char *fmt
, int flags
, bool writethrough
,
422 bool quiet
, bool force_share
)
428 error_report("--image-opts and --format are mutually exclusive");
431 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
436 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
439 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
446 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
447 const char *base_filename
,
448 const char *base_fmt
)
453 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
455 error_report("Backing file not supported for file format '%s'",
462 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
464 error_report("Backing file format not supported for file "
473 static int64_t cvtnum(const char *s
)
478 err
= qemu_strtosz(s
, NULL
, &value
);
482 if (value
> INT64_MAX
) {
488 static int img_create(int argc
, char **argv
)
491 uint64_t img_size
= -1;
492 const char *fmt
= "raw";
493 const char *base_fmt
= NULL
;
494 const char *filename
;
495 const char *base_filename
= NULL
;
496 char *options
= NULL
;
497 Error
*local_err
= NULL
;
502 static const struct option long_options
[] = {
503 {"help", no_argument
, 0, 'h'},
504 {"object", required_argument
, 0, OPTION_OBJECT
},
507 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
514 missing_argument(argv
[optind
- 1]);
517 unrecognized_option(argv
[optind
- 1]);
526 base_filename
= optarg
;
532 if (accumulate_options(&options
, optarg
) < 0) {
540 flags
|= BDRV_O_NO_BACKING
;
542 case OPTION_OBJECT
: {
544 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
553 /* Get the filename */
554 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
555 if (options
&& has_help_option(options
)) {
557 return print_block_option_help(filename
, fmt
);
560 if (optind
>= argc
) {
561 error_exit("Expecting image file name");
565 if (qemu_opts_foreach(&qemu_object_opts
,
566 user_creatable_add_opts_foreach
,
567 qemu_img_object_print_help
, &error_fatal
)) {
571 /* Get image size, if specified */
575 sval
= cvtnum(argv
[optind
++]);
577 if (sval
== -ERANGE
) {
578 error_report("Image size must be less than 8 EiB!");
580 error_report("Invalid image size specified! You may use k, M, "
581 "G, T, P or E suffixes for ");
582 error_report("kilobytes, megabytes, gigabytes, terabytes, "
583 "petabytes and exabytes.");
587 img_size
= (uint64_t)sval
;
589 if (optind
!= argc
) {
590 error_exit("Unexpected argument: %s", argv
[optind
]);
593 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
594 options
, img_size
, flags
, quiet
, &local_err
);
596 error_reportf_err(local_err
, "%s: ", filename
);
608 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
612 Visitor
*v
= qobject_output_visitor_new(&obj
);
614 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
615 visit_complete(v
, &obj
);
616 str
= qobject_to_json_pretty(obj
);
618 qprintf(quiet
, "%s\n", qstring_get_str(str
));
624 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
626 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
627 qprintf(quiet
, "No errors were found on the image.\n");
629 if (check
->corruptions
) {
630 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
631 "Data may be corrupted, or further writes to the image "
638 "\n%" PRId64
" leaked clusters were found on the image.\n"
639 "This means waste of disk space, but no harm to data.\n",
643 if (check
->check_errors
) {
646 " internal errors have occurred during the check.\n",
647 check
->check_errors
);
651 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
652 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
653 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
654 check
->allocated_clusters
, check
->total_clusters
,
655 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
656 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
657 check
->compressed_clusters
* 100.0 /
658 check
->allocated_clusters
);
661 if (check
->image_end_offset
) {
663 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
667 static int collect_image_check(BlockDriverState
*bs
,
669 const char *filename
,
674 BdrvCheckResult result
;
676 ret
= bdrv_check(bs
, &result
, fix
);
681 check
->filename
= g_strdup(filename
);
682 check
->format
= g_strdup(bdrv_get_format_name(bs
));
683 check
->check_errors
= result
.check_errors
;
684 check
->corruptions
= result
.corruptions
;
685 check
->has_corruptions
= result
.corruptions
!= 0;
686 check
->leaks
= result
.leaks
;
687 check
->has_leaks
= result
.leaks
!= 0;
688 check
->corruptions_fixed
= result
.corruptions_fixed
;
689 check
->has_corruptions_fixed
= result
.corruptions_fixed
!= 0;
690 check
->leaks_fixed
= result
.leaks_fixed
;
691 check
->has_leaks_fixed
= result
.leaks_fixed
!= 0;
692 check
->image_end_offset
= result
.image_end_offset
;
693 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
694 check
->total_clusters
= result
.bfi
.total_clusters
;
695 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
696 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
697 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
698 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
699 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
700 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
701 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
707 * Checks an image for consistency. Exit codes:
709 * 0 - Check completed, image is good
710 * 1 - Check not completed because of internal errors
711 * 2 - Check completed, image is corrupted
712 * 3 - Check completed, image has leaked clusters, but is good otherwise
713 * 63 - Checks are not supported by the image format
715 static int img_check(int argc
, char **argv
)
718 OutputFormat output_format
= OFORMAT_HUMAN
;
719 const char *filename
, *fmt
, *output
, *cache
;
721 BlockDriverState
*bs
;
723 int flags
= BDRV_O_CHECK
;
727 bool image_opts
= false;
728 bool force_share
= false;
732 cache
= BDRV_DEFAULT_CACHE
;
735 int option_index
= 0;
736 static const struct option long_options
[] = {
737 {"help", no_argument
, 0, 'h'},
738 {"format", required_argument
, 0, 'f'},
739 {"repair", required_argument
, 0, 'r'},
740 {"output", required_argument
, 0, OPTION_OUTPUT
},
741 {"object", required_argument
, 0, OPTION_OBJECT
},
742 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
743 {"force-share", no_argument
, 0, 'U'},
746 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
747 long_options
, &option_index
);
753 missing_argument(argv
[optind
- 1]);
756 unrecognized_option(argv
[optind
- 1]);
765 flags
|= BDRV_O_RDWR
;
767 if (!strcmp(optarg
, "leaks")) {
768 fix
= BDRV_FIX_LEAKS
;
769 } else if (!strcmp(optarg
, "all")) {
770 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
772 error_exit("Unknown option value for -r "
773 "(expecting 'leaks' or 'all'): %s", optarg
);
788 case OPTION_OBJECT
: {
790 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
796 case OPTION_IMAGE_OPTS
:
801 if (optind
!= argc
- 1) {
802 error_exit("Expecting one image file name");
804 filename
= argv
[optind
++];
806 if (output
&& !strcmp(output
, "json")) {
807 output_format
= OFORMAT_JSON
;
808 } else if (output
&& !strcmp(output
, "human")) {
809 output_format
= OFORMAT_HUMAN
;
811 error_report("--output must be used with human or json as argument.");
815 if (qemu_opts_foreach(&qemu_object_opts
,
816 user_creatable_add_opts_foreach
,
817 qemu_img_object_print_help
, &error_fatal
)) {
821 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
823 error_report("Invalid source cache option: %s", cache
);
827 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
834 check
= g_new0(ImageCheck
, 1);
835 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
837 if (ret
== -ENOTSUP
) {
838 error_report("This image format does not support checks");
843 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
844 int corruptions_fixed
, leaks_fixed
;
845 bool has_leaks_fixed
, has_corruptions_fixed
;
847 leaks_fixed
= check
->leaks_fixed
;
848 has_leaks_fixed
= check
->has_leaks_fixed
;
849 corruptions_fixed
= check
->corruptions_fixed
;
850 has_corruptions_fixed
= check
->has_corruptions_fixed
;
852 if (output_format
== OFORMAT_HUMAN
) {
854 "The following inconsistencies were found and repaired:\n\n"
855 " %" PRId64
" leaked clusters\n"
856 " %" PRId64
" corruptions\n\n"
857 "Double checking the fixed image now...\n",
859 check
->corruptions_fixed
);
862 qapi_free_ImageCheck(check
);
863 check
= g_new0(ImageCheck
, 1);
864 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
866 check
->leaks_fixed
= leaks_fixed
;
867 check
->has_leaks_fixed
= has_leaks_fixed
;
868 check
->corruptions_fixed
= corruptions_fixed
;
869 check
->has_corruptions_fixed
= has_corruptions_fixed
;
873 switch (output_format
) {
875 dump_human_image_check(check
, quiet
);
878 dump_json_image_check(check
, quiet
);
883 if (ret
|| check
->check_errors
) {
885 error_report("Check failed: %s", strerror(-ret
));
887 error_report("Check failed");
893 if (check
->corruptions
) {
895 } else if (check
->leaks
) {
902 qapi_free_ImageCheck(check
);
907 typedef struct CommonBlockJobCBInfo
{
908 BlockDriverState
*bs
;
910 } CommonBlockJobCBInfo
;
912 static void common_block_job_cb(void *opaque
, int ret
)
914 CommonBlockJobCBInfo
*cbi
= opaque
;
917 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
921 static void run_block_job(BlockJob
*job
, Error
**errp
)
923 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
926 aio_context_acquire(aio_context
);
929 float progress
= 0.0f
;
930 aio_poll(aio_context
, true);
931 if (job
->job
.progress
.total
) {
932 progress
= (float)job
->job
.progress
.current
/
933 job
->job
.progress
.total
* 100.f
;
935 qemu_progress_print(progress
, 0);
936 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
938 if (!job_is_completed(&job
->job
)) {
939 ret
= job_complete_sync(&job
->job
, errp
);
943 job_unref(&job
->job
);
944 aio_context_release(aio_context
);
946 /* publish completion progress only when success */
948 qemu_progress_print(100.f
, 0);
952 static int img_commit(int argc
, char **argv
)
955 const char *filename
, *fmt
, *cache
, *base
;
957 BlockDriverState
*bs
, *base_bs
;
959 bool progress
= false, quiet
= false, drop
= false;
961 Error
*local_err
= NULL
;
962 CommonBlockJobCBInfo cbi
;
963 bool image_opts
= false;
964 AioContext
*aio_context
;
967 cache
= BDRV_DEFAULT_CACHE
;
970 static const struct option long_options
[] = {
971 {"help", no_argument
, 0, 'h'},
972 {"object", required_argument
, 0, OPTION_OBJECT
},
973 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
976 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
983 missing_argument(argv
[optind
- 1]);
986 unrecognized_option(argv
[optind
- 1]);
1011 case OPTION_OBJECT
: {
1013 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1019 case OPTION_IMAGE_OPTS
:
1025 /* Progress is not shown in Quiet mode */
1030 if (optind
!= argc
- 1) {
1031 error_exit("Expecting one image file name");
1033 filename
= argv
[optind
++];
1035 if (qemu_opts_foreach(&qemu_object_opts
,
1036 user_creatable_add_opts_foreach
,
1037 qemu_img_object_print_help
, &error_fatal
)) {
1041 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
1042 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1044 error_report("Invalid cache option: %s", cache
);
1048 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1055 qemu_progress_init(progress
, 1.f
);
1056 qemu_progress_print(0.f
, 100);
1059 base_bs
= bdrv_find_backing_image(bs
, base
);
1061 error_setg(&local_err
,
1062 "Did not find '%s' in the backing chain of '%s'",
1067 /* This is different from QMP, which by default uses the deepest file in
1068 * the backing chain (i.e., the very base); however, the traditional
1069 * behavior of qemu-img commit is using the immediate backing file. */
1070 base_bs
= backing_bs(bs
);
1072 error_setg(&local_err
, "Image does not have a backing file");
1077 cbi
= (CommonBlockJobCBInfo
){
1082 aio_context
= bdrv_get_aio_context(bs
);
1083 aio_context_acquire(aio_context
);
1084 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, 0,
1085 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1086 &cbi
, false, &local_err
);
1087 aio_context_release(aio_context
);
1092 /* When the block job completes, the BlockBackend reference will point to
1093 * the old backing file. In order to avoid that the top image is already
1094 * deleted, so we can still empty it afterwards, increment the reference
1095 * counter here preemptively. */
1100 job
= block_job_get("commit");
1102 run_block_job(job
, &local_err
);
1107 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1108 ret
= bs
->drv
->bdrv_make_empty(bs
);
1110 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1122 qemu_progress_end();
1127 error_report_err(local_err
);
1131 qprintf(quiet
, "Image committed.\n");
1136 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1137 * of the first sector boundary within buf where the sector contains a
1138 * non-zero byte. This function is robust to a buffer that is not
1141 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1144 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1146 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1147 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1151 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1158 * Returns true iff the first sector pointed to by 'buf' contains at least
1161 * 'pnum' is set to the number of sectors (including and immediately following
1162 * the first one) that are known to be in the same allocated/unallocated state.
1163 * The function will try to align the end offset to alignment boundaries so
1164 * that the request will at least end aligned and consequtive requests will
1165 * also start at an aligned offset.
1167 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1168 int64_t sector_num
, int alignment
)
1177 is_zero
= buffer_is_zero(buf
, 512);
1178 for(i
= 1; i
< n
; i
++) {
1180 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1185 tail
= (sector_num
+ i
) & (alignment
- 1);
1187 if (is_zero
&& i
<= tail
) {
1188 /* treat unallocated areas which only consist
1189 * of a small tail as allocated. */
1193 /* align up end offset of allocated areas. */
1194 i
+= alignment
- tail
;
1197 /* align down end offset of zero areas. */
1206 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1207 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1208 * breaking up write requests for only small sparse areas.
1210 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1211 int min
, int64_t sector_num
, int alignment
)
1214 int num_checked
, num_used
;
1220 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1226 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1228 sector_num
+= *pnum
;
1229 num_checked
= num_used
;
1232 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1234 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1236 sector_num
+= *pnum
;
1237 num_checked
+= *pnum
;
1239 num_used
= num_checked
;
1240 } else if (*pnum
>= min
) {
1250 * Compares two buffers sector by sector. Returns 0 if the first
1251 * sector of each buffer matches, non-zero otherwise.
1253 * pnum is set to the sector-aligned size of the buffer prefix that
1254 * has the same matching status as the first sector.
1256 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1257 int64_t bytes
, int64_t *pnum
)
1260 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1264 res
= !!memcmp(buf1
, buf2
, i
);
1266 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1268 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1278 #define IO_BUF_SIZE (2 * MiB)
1281 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1283 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1284 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1285 * failure), and 4 on error (the exit status for read errors), after emitting
1288 * @param blk: BlockBackend for the image
1289 * @param offset: Starting offset to check
1290 * @param bytes: Number of bytes to check
1291 * @param filename: Name of disk file we are checking (logging purpose)
1292 * @param buffer: Allocated buffer for storing read data
1293 * @param quiet: Flag for quiet mode
1295 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1296 int64_t bytes
, const char *filename
,
1297 uint8_t *buffer
, bool quiet
)
1302 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1304 error_report("Error while reading offset %" PRId64
" of %s: %s",
1305 offset
, filename
, strerror(-ret
));
1308 idx
= find_nonzero(buffer
, bytes
);
1310 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1319 * Compares two images. Exit codes:
1321 * 0 - Images are identical
1323 * >1 - Error occurred
1325 static int img_compare(int argc
, char **argv
)
1327 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1328 BlockBackend
*blk1
, *blk2
;
1329 BlockDriverState
*bs1
, *bs2
;
1330 int64_t total_size1
, total_size2
;
1331 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1332 int64_t pnum1
, pnum2
;
1333 int allocated1
, allocated2
;
1334 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1335 bool progress
= false, quiet
= false, strict
= false;
1342 uint64_t progress_base
;
1343 bool image_opts
= false;
1344 bool force_share
= false;
1346 cache
= BDRV_DEFAULT_CACHE
;
1348 static const struct option long_options
[] = {
1349 {"help", no_argument
, 0, 'h'},
1350 {"object", required_argument
, 0, OPTION_OBJECT
},
1351 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1352 {"force-share", no_argument
, 0, 'U'},
1355 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1356 long_options
, NULL
);
1362 missing_argument(argv
[optind
- 1]);
1365 unrecognized_option(argv
[optind
- 1]);
1391 case OPTION_OBJECT
: {
1393 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1400 case OPTION_IMAGE_OPTS
:
1406 /* Progress is not shown in Quiet mode */
1412 if (optind
!= argc
- 2) {
1413 error_exit("Expecting two image file names");
1415 filename1
= argv
[optind
++];
1416 filename2
= argv
[optind
++];
1418 if (qemu_opts_foreach(&qemu_object_opts
,
1419 user_creatable_add_opts_foreach
,
1420 qemu_img_object_print_help
, &error_fatal
)) {
1425 /* Initialize before goto out */
1426 qemu_progress_init(progress
, 2.0);
1429 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1431 error_report("Invalid source cache option: %s", cache
);
1436 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1443 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1452 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1453 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1454 total_size1
= blk_getlength(blk1
);
1455 if (total_size1
< 0) {
1456 error_report("Can't get size of %s: %s",
1457 filename1
, strerror(-total_size1
));
1461 total_size2
= blk_getlength(blk2
);
1462 if (total_size2
< 0) {
1463 error_report("Can't get size of %s: %s",
1464 filename2
, strerror(-total_size2
));
1468 total_size
= MIN(total_size1
, total_size2
);
1469 progress_base
= MAX(total_size1
, total_size2
);
1471 qemu_progress_print(0, 100);
1473 if (strict
&& total_size1
!= total_size2
) {
1475 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1479 while (offset
< total_size
) {
1480 int status1
, status2
;
1482 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1483 total_size1
- offset
, &pnum1
, NULL
,
1487 error_report("Sector allocation test failed for %s", filename1
);
1490 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1492 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1493 total_size2
- offset
, &pnum2
, NULL
,
1497 error_report("Sector allocation test failed for %s", filename2
);
1500 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1502 assert(pnum1
&& pnum2
);
1503 chunk
= MIN(pnum1
, pnum2
);
1506 if (status1
!= status2
) {
1508 qprintf(quiet
, "Strict mode: Offset %" PRId64
1509 " block status mismatch!\n", offset
);
1513 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1515 } else if (allocated1
== allocated2
) {
1519 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1520 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1522 error_report("Error while reading offset %" PRId64
1524 offset
, filename1
, strerror(-ret
));
1528 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1530 error_report("Error while reading offset %" PRId64
1532 offset
, filename2
, strerror(-ret
));
1536 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1537 if (ret
|| pnum
!= chunk
) {
1538 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1539 offset
+ (ret
? 0 : pnum
));
1545 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1547 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1548 filename1
, buf1
, quiet
);
1550 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1551 filename2
, buf1
, quiet
);
1558 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1561 if (total_size1
!= total_size2
) {
1562 BlockBackend
*blk_over
;
1563 const char *filename_over
;
1565 qprintf(quiet
, "Warning: Image size mismatch!\n");
1566 if (total_size1
> total_size2
) {
1568 filename_over
= filename1
;
1571 filename_over
= filename2
;
1574 while (offset
< progress_base
) {
1575 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1576 progress_base
- offset
, &chunk
,
1580 error_report("Sector allocation test failed for %s",
1585 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1586 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1587 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1588 filename_over
, buf1
, quiet
);
1594 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1598 qprintf(quiet
, "Images are identical.\n");
1608 qemu_progress_end();
1613 enum ImgConvertBlockStatus
{
1619 #define MAX_COROUTINES 16
1621 typedef struct ImgConvertState
{
1623 int64_t *src_sectors
;
1625 int64_t total_sectors
;
1626 int64_t allocated_sectors
;
1627 int64_t allocated_done
;
1630 enum ImgConvertBlockStatus status
;
1631 int64_t sector_next_status
;
1632 BlockBackend
*target
;
1635 bool unallocated_blocks_are_zero
;
1637 bool target_has_backing
;
1638 int64_t target_backing_sectors
; /* negative if unknown */
1645 size_t cluster_sectors
;
1647 long num_coroutines
;
1648 int running_coroutines
;
1649 Coroutine
*co
[MAX_COROUTINES
];
1650 int64_t wait_sector_num
[MAX_COROUTINES
];
1655 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1656 int *src_cur
, int64_t *src_cur_offset
)
1659 *src_cur_offset
= 0;
1660 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1661 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1663 assert(*src_cur
< s
->src_num
);
1667 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1669 int64_t src_cur_offset
;
1670 int ret
, n
, src_cur
;
1671 bool post_backing_zero
= false;
1673 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1675 assert(s
->total_sectors
> sector_num
);
1676 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1678 if (s
->target_backing_sectors
>= 0) {
1679 if (sector_num
>= s
->target_backing_sectors
) {
1680 post_backing_zero
= s
->unallocated_blocks_are_zero
;
1681 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1682 /* Split requests around target_backing_sectors (because
1683 * starting from there, zeros are handled differently) */
1684 n
= s
->target_backing_sectors
- sector_num
;
1688 if (s
->sector_next_status
<= sector_num
) {
1689 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1693 count
= n
* BDRV_SECTOR_SIZE
;
1695 if (s
->target_has_backing
) {
1696 ret
= bdrv_block_status(blk_bs(s
->src
[src_cur
]), offset
,
1697 count
, &count
, NULL
, NULL
);
1699 ret
= bdrv_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1700 offset
, count
, &count
, NULL
,
1708 warn_report("error while reading block status at "
1709 "offset %" PRIu64
": %s", offset
,
1712 /* Just try to read the data, then */
1713 ret
= BDRV_BLOCK_DATA
;
1714 count
= BDRV_SECTOR_SIZE
;
1716 /* Retry on a shorter range */
1717 n
= DIV_ROUND_UP(n
, 4);
1720 error_report("error while reading block status at offset "
1721 "%" PRIu64
": %s", offset
, strerror(-ret
));
1727 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1729 if (ret
& BDRV_BLOCK_ZERO
) {
1730 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1731 } else if (ret
& BDRV_BLOCK_DATA
) {
1732 s
->status
= BLK_DATA
;
1734 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1737 s
->sector_next_status
= sector_num
+ n
;
1740 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1741 if (s
->status
== BLK_DATA
) {
1742 n
= MIN(n
, s
->buf_sectors
);
1745 /* We need to write complete clusters for compressed images, so if an
1746 * unallocated area is shorter than that, we must consider the whole
1747 * cluster allocated. */
1748 if (s
->compressed
) {
1749 if (n
< s
->cluster_sectors
) {
1750 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1751 s
->status
= BLK_DATA
;
1753 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1760 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1761 int nb_sectors
, uint8_t *buf
)
1763 uint64_t single_read_until
= 0;
1766 assert(nb_sectors
<= s
->buf_sectors
);
1767 while (nb_sectors
> 0) {
1770 int64_t bs_sectors
, src_cur_offset
;
1773 /* In the case of compression with multiple source files, we can get a
1774 * nb_sectors that spreads into the next part. So we must be able to
1775 * read across multiple BDSes for one convert_read() call. */
1776 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1777 blk
= s
->src
[src_cur
];
1778 bs_sectors
= s
->src_sectors
[src_cur
];
1780 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1782 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1783 if (single_read_until
> offset
) {
1787 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1791 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1795 warn_report("error while reading offset %" PRIu64
1796 ": %s", offset
, strerror(-ret
));
1798 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1807 buf
+= n
* BDRV_SECTOR_SIZE
;
1814 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1815 int nb_sectors
, uint8_t *buf
,
1816 enum ImgConvertBlockStatus status
)
1820 while (nb_sectors
> 0) {
1822 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1825 case BLK_BACKING_FILE
:
1826 /* If we have a backing file, leave clusters unallocated that are
1827 * unallocated in the source image, so that the backing file is
1828 * visible at the respective offset. */
1829 assert(s
->target_has_backing
);
1833 /* If we're told to keep the target fully allocated (-S 0) or there
1834 * is real non-zero data, we must write it. Otherwise we can treat
1835 * it as zero sectors.
1836 * Compressed clusters need to be written as a whole, so in that
1837 * case we can only save the write if the buffer is completely
1839 if (!s
->min_sparse
||
1841 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1842 sector_num
, s
->alignment
)) ||
1844 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1846 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1847 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1856 if (s
->has_zero_init
) {
1857 assert(!s
->target_has_backing
);
1860 ret
= blk_co_pwrite_zeroes(s
->target
,
1861 sector_num
<< BDRV_SECTOR_BITS
,
1862 n
<< BDRV_SECTOR_BITS
,
1863 BDRV_REQ_MAY_UNMAP
);
1872 buf
+= n
* BDRV_SECTOR_SIZE
;
1878 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1883 while (nb_sectors
> 0) {
1886 int64_t bs_sectors
, src_cur_offset
;
1889 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1890 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1891 blk
= s
->src
[src_cur
];
1892 bs_sectors
= s
->src_sectors
[src_cur
];
1894 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1896 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1897 sector_num
<< BDRV_SECTOR_BITS
,
1898 n
<< BDRV_SECTOR_BITS
, 0, 0);
1909 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1911 ImgConvertState
*s
= opaque
;
1912 uint8_t *buf
= NULL
;
1916 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1917 if (s
->co
[i
] == qemu_coroutine_self()) {
1924 s
->running_coroutines
++;
1925 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1930 enum ImgConvertBlockStatus status
;
1933 qemu_co_mutex_lock(&s
->lock
);
1934 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1935 qemu_co_mutex_unlock(&s
->lock
);
1938 n
= convert_iteration_sectors(s
, s
->sector_num
);
1940 qemu_co_mutex_unlock(&s
->lock
);
1944 /* save current sector and allocation status to local variables */
1945 sector_num
= s
->sector_num
;
1947 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1948 n
= MIN(n
, s
->buf_sectors
);
1950 /* increment global sector counter so that other coroutines can
1951 * already continue reading beyond this request */
1953 qemu_co_mutex_unlock(&s
->lock
);
1955 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1956 s
->allocated_done
+= n
;
1957 qemu_progress_print(100.0 * s
->allocated_done
/
1958 s
->allocated_sectors
, 0);
1962 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
1963 if (status
== BLK_DATA
&& !copy_range
) {
1964 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1966 error_report("error while reading at byte %lld: %s",
1967 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
1970 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1972 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1975 if (s
->wr_in_order
) {
1976 /* keep writes in order */
1977 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1978 s
->wait_sector_num
[index
] = sector_num
;
1979 qemu_coroutine_yield();
1981 s
->wait_sector_num
[index
] = -1;
1984 if (s
->ret
== -EINPROGRESS
) {
1986 ret
= convert_co_copy_range(s
, sector_num
, n
);
1988 s
->copy_range
= false;
1992 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1995 error_report("error while writing at byte %lld: %s",
1996 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2001 if (s
->wr_in_order
) {
2002 /* reenter the coroutine that might have waited
2003 * for this write to complete */
2004 s
->wr_offs
= sector_num
+ n
;
2005 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2006 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
2008 * A -> B -> A cannot occur because A has
2009 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2010 * B will never enter A during this time window.
2012 qemu_coroutine_enter(s
->co
[i
]);
2020 s
->co
[index
] = NULL
;
2021 s
->running_coroutines
--;
2022 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
2023 /* the convert job finished successfully */
2028 static int convert_do_copy(ImgConvertState
*s
)
2031 int64_t sector_num
= 0;
2033 /* Check whether we have zero initialisation or can get it efficiently */
2034 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
2035 !s
->target_has_backing
) {
2036 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
2039 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
2040 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
2042 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
| BDRV_REQ_NO_FALLBACK
);
2044 s
->has_zero_init
= true;
2048 /* Allocate buffer for copied data. For compressed images, only one cluster
2049 * can be copied at a time. */
2050 if (s
->compressed
) {
2051 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2052 error_report("invalid cluster size");
2055 s
->buf_sectors
= s
->cluster_sectors
;
2058 while (sector_num
< s
->total_sectors
) {
2059 n
= convert_iteration_sectors(s
, sector_num
);
2063 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2065 s
->allocated_sectors
+= n
;
2071 s
->sector_next_status
= 0;
2072 s
->ret
= -EINPROGRESS
;
2074 qemu_co_mutex_init(&s
->lock
);
2075 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2076 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2077 s
->wait_sector_num
[i
] = -1;
2078 qemu_coroutine_enter(s
->co
[i
]);
2081 while (s
->running_coroutines
) {
2082 main_loop_wait(false);
2085 if (s
->compressed
&& !s
->ret
) {
2086 /* signal EOF to align */
2087 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
2096 #define MAX_BUF_SECTORS 32768
2098 static int img_convert(int argc
, char **argv
)
2100 int c
, bs_i
, flags
, src_flags
= 0;
2101 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2102 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2103 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
2104 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2105 BlockDriverInfo bdi
;
2106 BlockDriverState
*out_bs
;
2107 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2108 QemuOptsList
*create_opts
= NULL
;
2109 QDict
*open_opts
= NULL
;
2110 char *options
= NULL
;
2111 Error
*local_err
= NULL
;
2112 bool writethrough
, src_writethrough
, image_opts
= false,
2113 skip_create
= false, progress
= false, tgt_image_opts
= false;
2114 int64_t ret
= -EINVAL
;
2115 bool force_share
= false;
2116 bool explict_min_sparse
= false;
2118 ImgConvertState s
= (ImgConvertState
) {
2119 /* Need at least 4k of zeros for sparse detection */
2121 .copy_range
= false,
2122 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2123 .wr_in_order
= true,
2124 .num_coroutines
= 8,
2128 static const struct option long_options
[] = {
2129 {"help", no_argument
, 0, 'h'},
2130 {"object", required_argument
, 0, OPTION_OBJECT
},
2131 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2132 {"force-share", no_argument
, 0, 'U'},
2133 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2134 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2135 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2138 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2139 long_options
, NULL
);
2145 missing_argument(argv
[optind
- 1]);
2148 unrecognized_option(argv
[optind
- 1]);
2160 out_baseimg
= optarg
;
2163 s
.copy_range
= true;
2166 s
.compressed
= true;
2169 if (accumulate_options(&options
, optarg
) < 0) {
2174 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2175 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2178 error_report("Failed in parsing snapshot param '%s'",
2183 snapshot_name
= optarg
;
2190 sval
= cvtnum(optarg
);
2191 if (sval
< 0 || !QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2192 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2193 error_report("Invalid buffer size for sparse output specified. "
2194 "Valid sizes are multiples of %llu up to %llu. Select "
2195 "0 to disable sparse detection (fully allocates output).",
2196 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2200 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2201 explict_min_sparse
= true;
2220 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2221 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2222 error_report("Invalid number of coroutines. Allowed number of"
2223 " coroutines is between 1 and %d", MAX_COROUTINES
);
2228 s
.wr_in_order
= false;
2233 case OPTION_OBJECT
: {
2234 QemuOpts
*object_opts
;
2235 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2242 case OPTION_IMAGE_OPTS
:
2245 case OPTION_SALVAGE
:
2248 case OPTION_TARGET_IMAGE_OPTS
:
2249 tgt_image_opts
= true;
2251 case OPTION_TARGET_IS_ZERO
:
2253 * The user asserting that the target is blank has the
2254 * same effect as the target driver supporting zero
2257 s
.has_zero_init
= true;
2262 if (!out_fmt
&& !tgt_image_opts
) {
2266 if (qemu_opts_foreach(&qemu_object_opts
,
2267 user_creatable_add_opts_foreach
,
2268 qemu_img_object_print_help
, &error_fatal
)) {
2272 if (s
.compressed
&& s
.copy_range
) {
2273 error_report("Cannot enable copy offloading when -c is used");
2277 if (explict_min_sparse
&& s
.copy_range
) {
2278 error_report("Cannot enable copy offloading when -S is used");
2282 if (s
.copy_range
&& s
.salvage
) {
2283 error_report("Cannot use copy offloading in salvaging mode");
2287 if (tgt_image_opts
&& !skip_create
) {
2288 error_report("--target-image-opts requires use of -n flag");
2292 if (skip_create
&& options
) {
2293 warn_report("-o has no effect when skipping image creation");
2294 warn_report("This will become an error in future QEMU versions.");
2297 if (s
.has_zero_init
&& !skip_create
) {
2298 error_report("--target-is-zero requires use of -n flag");
2302 s
.src_num
= argc
- optind
- 1;
2303 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2305 if (options
&& has_help_option(options
)) {
2307 ret
= print_block_option_help(out_filename
, out_fmt
);
2310 error_report("Option help requires a format be specified");
2315 if (s
.src_num
< 1) {
2316 error_report("Must specify image file name");
2321 /* ret is still -EINVAL until here */
2322 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2324 error_report("Invalid source cache option: %s", src_cache
);
2328 /* Initialize before goto out */
2332 qemu_progress_init(progress
, 1.0);
2333 qemu_progress_print(0, 100);
2335 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2336 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2338 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2339 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2340 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2346 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2347 if (s
.src_sectors
[bs_i
] < 0) {
2348 error_report("Could not get size of %s: %s",
2349 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2353 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2357 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2358 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2359 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2361 } else if (snapshot_name
!= NULL
) {
2362 if (s
.src_num
> 1) {
2363 error_report("No support for concatenating multiple snapshot");
2368 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2372 error_reportf_err(local_err
, "Failed to load snapshot: ");
2378 /* Find driver and parse its options */
2379 drv
= bdrv_find_format(out_fmt
);
2381 error_report("Unknown file format '%s'", out_fmt
);
2386 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2388 error_report_err(local_err
);
2393 if (!drv
->create_opts
) {
2394 error_report("Format driver '%s' does not support image creation",
2400 if (!proto_drv
->create_opts
) {
2401 error_report("Protocol driver '%s' does not support image creation",
2402 proto_drv
->format_name
);
2407 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2408 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2410 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2412 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2414 error_report_err(local_err
);
2420 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2422 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2428 /* Get backing file name if -o backing_file was used */
2429 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2430 if (out_baseimg_param
) {
2431 out_baseimg
= out_baseimg_param
;
2433 s
.target_has_backing
= (bool) out_baseimg
;
2435 if (s
.has_zero_init
&& s
.target_has_backing
) {
2436 error_report("Cannot use --target-is-zero when the destination "
2437 "image has a backing file");
2441 if (s
.src_num
> 1 && out_baseimg
) {
2442 error_report("Having a backing file for the target makes no sense when "
2443 "concatenating multiple input images");
2448 /* Check if compression is supported */
2451 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2452 const char *encryptfmt
=
2453 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2454 const char *preallocation
=
2455 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2457 if (drv
&& !block_driver_can_compress(drv
)) {
2458 error_report("Compression not supported for this file format");
2463 if (encryption
|| encryptfmt
) {
2464 error_report("Compression and encryption not supported at "
2471 && strcmp(preallocation
, "off"))
2473 error_report("Compression and preallocation not supported at "
2481 * The later open call will need any decryption secrets, and
2482 * bdrv_create() will purge "opts", so extract them now before
2486 open_opts
= qdict_new();
2487 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2491 /* Create the new image */
2492 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2494 error_reportf_err(local_err
, "%s: error while converting %s: ",
2495 out_filename
, out_fmt
);
2500 s
.target_is_new
= !skip_create
;
2502 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2503 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2505 error_report("Invalid cache option: %s", cache
);
2510 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2511 flags
, writethrough
, s
.quiet
, false);
2513 /* TODO ultimately we should allow --target-image-opts
2514 * to be used even when -n is not given.
2515 * That has to wait for bdrv_create to be improved
2516 * to allow filenames in option syntax
2518 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2519 flags
, writethrough
, s
.quiet
, false);
2520 open_opts
= NULL
; /* blk_new_open will have freed it */
2526 out_bs
= blk_bs(s
.target
);
2528 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2529 error_report("Compression not supported for this file format");
2534 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2535 * or discard_alignment of the out_bs is greater. Limit to
2536 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2537 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2539 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2540 out_bs
->bl
.pdiscard_alignment
>>
2541 BDRV_SECTOR_BITS
)));
2543 /* try to align the write requests to the destination to avoid unnecessary
2545 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2546 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2548 assert(is_power_of_2(s
.alignment
));
2551 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2552 if (output_sectors
< 0) {
2553 error_report("unable to get output image length: %s",
2554 strerror(-output_sectors
));
2557 } else if (output_sectors
< s
.total_sectors
) {
2558 error_report("output file is smaller than input file");
2564 if (s
.target_has_backing
&& s
.target_is_new
) {
2565 /* Errors are treated as "backing length unknown" (which means
2566 * s.target_backing_sectors has to be negative, which it will
2567 * be automatically). The backing file length is used only
2568 * for optimizations, so such a case is not fatal. */
2569 s
.target_backing_sectors
= bdrv_nb_sectors(out_bs
->backing
->bs
);
2571 s
.target_backing_sectors
= -1;
2574 ret
= bdrv_get_info(out_bs
, &bdi
);
2577 error_report("could not get block driver info");
2581 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2582 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2583 s
.unallocated_blocks_are_zero
= bdi
.unallocated_blocks_are_zero
;
2586 ret
= convert_do_copy(&s
);
2589 qemu_progress_print(100, 0);
2591 qemu_progress_end();
2592 qemu_opts_del(opts
);
2593 qemu_opts_free(create_opts
);
2594 qemu_opts_del(sn_opts
);
2595 qobject_unref(open_opts
);
2596 blk_unref(s
.target
);
2598 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2599 blk_unref(s
.src
[bs_i
]);
2603 g_free(s
.src_sectors
);
2611 static void dump_snapshots(BlockDriverState
*bs
)
2613 QEMUSnapshotInfo
*sn_tab
, *sn
;
2616 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2619 printf("Snapshot list:\n");
2620 bdrv_snapshot_dump(NULL
);
2622 for(i
= 0; i
< nb_sns
; i
++) {
2624 bdrv_snapshot_dump(sn
);
2630 static void dump_json_image_info_list(ImageInfoList
*list
)
2634 Visitor
*v
= qobject_output_visitor_new(&obj
);
2636 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2637 visit_complete(v
, &obj
);
2638 str
= qobject_to_json_pretty(obj
);
2639 assert(str
!= NULL
);
2640 printf("%s\n", qstring_get_str(str
));
2646 static void dump_json_image_info(ImageInfo
*info
)
2650 Visitor
*v
= qobject_output_visitor_new(&obj
);
2652 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2653 visit_complete(v
, &obj
);
2654 str
= qobject_to_json_pretty(obj
);
2655 assert(str
!= NULL
);
2656 printf("%s\n", qstring_get_str(str
));
2662 static void dump_human_image_info_list(ImageInfoList
*list
)
2664 ImageInfoList
*elem
;
2667 for (elem
= list
; elem
; elem
= elem
->next
) {
2673 bdrv_image_info_dump(elem
->value
);
2677 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2679 return strcmp(a
, b
) == 0;
2683 * Open an image file chain and return an ImageInfoList
2685 * @filename: topmost image filename
2686 * @fmt: topmost image format (may be NULL to autodetect)
2687 * @chain: true - enumerate entire backing file chain
2688 * false - only topmost image file
2690 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2691 * image file. If there was an error a message will have been printed to
2694 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2695 const char *filename
,
2697 bool chain
, bool force_share
)
2699 ImageInfoList
*head
= NULL
;
2700 ImageInfoList
**last
= &head
;
2701 GHashTable
*filenames
;
2704 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2708 BlockDriverState
*bs
;
2710 ImageInfoList
*elem
;
2712 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2713 error_report("Backing file '%s' creates an infinite loop.",
2717 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2719 blk
= img_open(image_opts
, filename
, fmt
,
2720 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2727 bdrv_query_image_info(bs
, &info
, &err
);
2729 error_report_err(err
);
2734 elem
= g_new0(ImageInfoList
, 1);
2741 /* Clear parameters that only apply to the topmost image */
2742 filename
= fmt
= NULL
;
2746 if (info
->has_full_backing_filename
) {
2747 filename
= info
->full_backing_filename
;
2748 } else if (info
->has_backing_filename
) {
2749 error_report("Could not determine absolute backing filename,"
2750 " but backing filename '%s' present",
2751 info
->backing_filename
);
2754 if (info
->has_backing_filename_format
) {
2755 fmt
= info
->backing_filename_format
;
2759 g_hash_table_destroy(filenames
);
2763 qapi_free_ImageInfoList(head
);
2764 g_hash_table_destroy(filenames
);
2768 static int img_info(int argc
, char **argv
)
2771 OutputFormat output_format
= OFORMAT_HUMAN
;
2773 const char *filename
, *fmt
, *output
;
2774 ImageInfoList
*list
;
2775 bool image_opts
= false;
2776 bool force_share
= false;
2781 int option_index
= 0;
2782 static const struct option long_options
[] = {
2783 {"help", no_argument
, 0, 'h'},
2784 {"format", required_argument
, 0, 'f'},
2785 {"output", required_argument
, 0, OPTION_OUTPUT
},
2786 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2787 {"object", required_argument
, 0, OPTION_OBJECT
},
2788 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2789 {"force-share", no_argument
, 0, 'U'},
2792 c
= getopt_long(argc
, argv
, ":f:hU",
2793 long_options
, &option_index
);
2799 missing_argument(argv
[optind
- 1]);
2802 unrecognized_option(argv
[optind
- 1]);
2816 case OPTION_BACKING_CHAIN
:
2819 case OPTION_OBJECT
: {
2821 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2827 case OPTION_IMAGE_OPTS
:
2832 if (optind
!= argc
- 1) {
2833 error_exit("Expecting one image file name");
2835 filename
= argv
[optind
++];
2837 if (output
&& !strcmp(output
, "json")) {
2838 output_format
= OFORMAT_JSON
;
2839 } else if (output
&& !strcmp(output
, "human")) {
2840 output_format
= OFORMAT_HUMAN
;
2841 } else if (output
) {
2842 error_report("--output must be used with human or json as argument.");
2846 if (qemu_opts_foreach(&qemu_object_opts
,
2847 user_creatable_add_opts_foreach
,
2848 qemu_img_object_print_help
, &error_fatal
)) {
2852 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2858 switch (output_format
) {
2860 dump_human_image_info_list(list
);
2864 dump_json_image_info_list(list
);
2866 dump_json_image_info(list
->value
);
2871 qapi_free_ImageInfoList(list
);
2875 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2878 switch (output_format
) {
2880 if (e
->data
&& !e
->has_offset
) {
2881 error_report("File contains external, encrypted or compressed clusters.");
2884 if (e
->data
&& !e
->zero
) {
2885 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2886 e
->start
, e
->length
,
2887 e
->has_offset
? e
->offset
: 0,
2888 e
->has_filename
? e
->filename
: "");
2890 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2891 * Modify the flags here to allow more coalescing.
2893 if (next
&& (!next
->data
|| next
->zero
)) {
2899 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2900 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2901 (e
->start
== 0 ? "[" : ",\n"),
2902 e
->start
, e
->length
, e
->depth
,
2903 e
->zero
? "true" : "false",
2904 e
->data
? "true" : "false");
2905 if (e
->has_offset
) {
2906 printf(", \"offset\": %"PRId64
"", e
->offset
);
2918 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
2919 int64_t bytes
, MapEntry
*e
)
2923 BlockDriverState
*file
;
2926 char *filename
= NULL
;
2928 /* As an optimization, we could cache the current range of unallocated
2929 * clusters in each file of the chain, and avoid querying the same
2935 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
2940 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2943 bs
= backing_bs(bs
);
2952 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2954 if (file
&& has_offset
) {
2955 bdrv_refresh_filename(file
);
2956 filename
= file
->filename
;
2962 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2963 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2965 .has_offset
= has_offset
,
2967 .has_filename
= filename
,
2968 .filename
= filename
,
2974 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2976 if (curr
->length
== 0) {
2979 if (curr
->zero
!= next
->zero
||
2980 curr
->data
!= next
->data
||
2981 curr
->depth
!= next
->depth
||
2982 curr
->has_filename
!= next
->has_filename
||
2983 curr
->has_offset
!= next
->has_offset
) {
2986 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2989 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2995 static int img_map(int argc
, char **argv
)
2998 OutputFormat output_format
= OFORMAT_HUMAN
;
3000 BlockDriverState
*bs
;
3001 const char *filename
, *fmt
, *output
;
3003 MapEntry curr
= { .length
= 0 }, next
;
3005 bool image_opts
= false;
3006 bool force_share
= false;
3011 int option_index
= 0;
3012 static const struct option long_options
[] = {
3013 {"help", no_argument
, 0, 'h'},
3014 {"format", required_argument
, 0, 'f'},
3015 {"output", required_argument
, 0, OPTION_OUTPUT
},
3016 {"object", required_argument
, 0, OPTION_OBJECT
},
3017 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3018 {"force-share", no_argument
, 0, 'U'},
3021 c
= getopt_long(argc
, argv
, ":f:hU",
3022 long_options
, &option_index
);
3028 missing_argument(argv
[optind
- 1]);
3031 unrecognized_option(argv
[optind
- 1]);
3045 case OPTION_OBJECT
: {
3047 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3053 case OPTION_IMAGE_OPTS
:
3058 if (optind
!= argc
- 1) {
3059 error_exit("Expecting one image file name");
3061 filename
= argv
[optind
];
3063 if (output
&& !strcmp(output
, "json")) {
3064 output_format
= OFORMAT_JSON
;
3065 } else if (output
&& !strcmp(output
, "human")) {
3066 output_format
= OFORMAT_HUMAN
;
3067 } else if (output
) {
3068 error_report("--output must be used with human or json as argument.");
3072 if (qemu_opts_foreach(&qemu_object_opts
,
3073 user_creatable_add_opts_foreach
,
3074 qemu_img_object_print_help
, &error_fatal
)) {
3078 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3084 if (output_format
== OFORMAT_HUMAN
) {
3085 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3088 length
= blk_getlength(blk
);
3089 while (curr
.start
+ curr
.length
< length
) {
3090 int64_t offset
= curr
.start
+ curr
.length
;
3093 /* Probe up to 1 GiB at a time. */
3094 n
= MIN(1 * GiB
, length
- offset
);
3095 ret
= get_block_status(bs
, offset
, n
, &next
);
3098 error_report("Could not read file metadata: %s", strerror(-ret
));
3102 if (entry_mergeable(&curr
, &next
)) {
3103 curr
.length
+= next
.length
;
3107 if (curr
.length
> 0) {
3108 ret
= dump_map_entry(output_format
, &curr
, &next
);
3116 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3123 #define SNAPSHOT_LIST 1
3124 #define SNAPSHOT_CREATE 2
3125 #define SNAPSHOT_APPLY 3
3126 #define SNAPSHOT_DELETE 4
3128 static int img_snapshot(int argc
, char **argv
)
3131 BlockDriverState
*bs
;
3132 QEMUSnapshotInfo sn
;
3133 char *filename
, *snapshot_name
= NULL
;
3134 int c
, ret
= 0, bdrv_oflags
;
3139 bool image_opts
= false;
3140 bool force_share
= false;
3142 bdrv_oflags
= BDRV_O_RDWR
;
3143 /* Parse commandline parameters */
3145 static const struct option long_options
[] = {
3146 {"help", no_argument
, 0, 'h'},
3147 {"object", required_argument
, 0, OPTION_OBJECT
},
3148 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3149 {"force-share", no_argument
, 0, 'U'},
3152 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3153 long_options
, NULL
);
3159 missing_argument(argv
[optind
- 1]);
3162 unrecognized_option(argv
[optind
- 1]);
3169 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3172 action
= SNAPSHOT_LIST
;
3173 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3177 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3180 action
= SNAPSHOT_APPLY
;
3181 snapshot_name
= optarg
;
3185 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3188 action
= SNAPSHOT_CREATE
;
3189 snapshot_name
= optarg
;
3193 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3196 action
= SNAPSHOT_DELETE
;
3197 snapshot_name
= optarg
;
3205 case OPTION_OBJECT
: {
3207 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3213 case OPTION_IMAGE_OPTS
:
3219 if (optind
!= argc
- 1) {
3220 error_exit("Expecting one image file name");
3222 filename
= argv
[optind
++];
3224 if (qemu_opts_foreach(&qemu_object_opts
,
3225 user_creatable_add_opts_foreach
,
3226 qemu_img_object_print_help
, &error_fatal
)) {
3230 /* Open the image */
3231 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3238 /* Perform the requested action */
3244 case SNAPSHOT_CREATE
:
3245 memset(&sn
, 0, sizeof(sn
));
3246 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3248 qemu_gettimeofday(&tv
);
3249 sn
.date_sec
= tv
.tv_sec
;
3250 sn
.date_nsec
= tv
.tv_usec
* 1000;
3252 ret
= bdrv_snapshot_create(bs
, &sn
);
3254 error_report("Could not create snapshot '%s': %d (%s)",
3255 snapshot_name
, ret
, strerror(-ret
));
3259 case SNAPSHOT_APPLY
:
3260 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3262 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3267 case SNAPSHOT_DELETE
:
3268 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3270 error_report("Could not delete snapshot '%s': snapshot not "
3271 "found", snapshot_name
);
3274 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3276 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3292 static int img_rebase(int argc
, char **argv
)
3294 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3295 uint8_t *buf_old
= NULL
;
3296 uint8_t *buf_new
= NULL
;
3297 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3299 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3300 int c
, flags
, src_flags
, ret
;
3301 bool writethrough
, src_writethrough
;
3303 bool force_share
= false;
3306 Error
*local_err
= NULL
;
3307 bool image_opts
= false;
3309 /* Parse commandline parameters */
3311 cache
= BDRV_DEFAULT_CACHE
;
3312 src_cache
= BDRV_DEFAULT_CACHE
;
3316 static const struct option long_options
[] = {
3317 {"help", no_argument
, 0, 'h'},
3318 {"object", required_argument
, 0, OPTION_OBJECT
},
3319 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3320 {"force-share", no_argument
, 0, 'U'},
3323 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3324 long_options
, NULL
);
3330 missing_argument(argv
[optind
- 1]);
3333 unrecognized_option(argv
[optind
- 1]);
3342 out_basefmt
= optarg
;
3345 out_baseimg
= optarg
;
3362 case OPTION_OBJECT
: {
3364 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3370 case OPTION_IMAGE_OPTS
:
3383 if (optind
!= argc
- 1) {
3384 error_exit("Expecting one image file name");
3386 if (!unsafe
&& !out_baseimg
) {
3387 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3389 filename
= argv
[optind
++];
3391 if (qemu_opts_foreach(&qemu_object_opts
,
3392 user_creatable_add_opts_foreach
,
3393 qemu_img_object_print_help
, &error_fatal
)) {
3397 qemu_progress_init(progress
, 2.0);
3398 qemu_progress_print(0, 100);
3400 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3401 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3403 error_report("Invalid cache option: %s", cache
);
3408 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3410 error_report("Invalid source cache option: %s", src_cache
);
3414 /* The source files are opened read-only, don't care about WCE */
3415 assert((src_flags
& BDRV_O_RDWR
) == 0);
3416 (void) src_writethrough
;
3421 * Ignore the old backing file for unsafe rebase in case we want to correct
3422 * the reference to a renamed or moved backing file.
3424 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3432 if (out_basefmt
!= NULL
) {
3433 if (bdrv_find_format(out_basefmt
) == NULL
) {
3434 error_report("Invalid format name: '%s'", out_basefmt
);
3440 /* For safe rebasing we need to compare old and new backing file */
3442 QDict
*options
= NULL
;
3443 BlockDriverState
*base_bs
= backing_bs(bs
);
3446 blk_old_backing
= blk_new(qemu_get_aio_context(),
3447 BLK_PERM_CONSISTENT_READ
,
3449 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3452 error_reportf_err(local_err
,
3453 "Could not reuse old backing file '%s': ",
3458 blk_old_backing
= NULL
;
3461 if (out_baseimg
[0]) {
3462 const char *overlay_filename
;
3463 char *out_real_path
;
3465 options
= qdict_new();
3467 qdict_put_str(options
, "driver", out_basefmt
);
3470 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3473 bdrv_refresh_filename(bs
);
3474 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3477 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3481 qobject_unref(options
);
3482 error_reportf_err(local_err
,
3483 "Could not resolve backing filename: ");
3489 * Find out whether we rebase an image on top of a previous image
3492 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3493 if (prefix_chain_bs
) {
3494 qobject_unref(options
);
3495 g_free(out_real_path
);
3497 blk_new_backing
= blk_new(qemu_get_aio_context(),
3498 BLK_PERM_CONSISTENT_READ
,
3500 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3503 error_reportf_err(local_err
,
3504 "Could not reuse backing file '%s': ",
3509 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3510 options
, src_flags
, &local_err
);
3511 g_free(out_real_path
);
3512 if (!blk_new_backing
) {
3513 error_reportf_err(local_err
,
3514 "Could not open new backing file '%s': ",
3524 * Check each unallocated cluster in the COW file. If it is unallocated,
3525 * accesses go to the backing file. We must therefore compare this cluster
3526 * in the old and new backing file, and if they differ we need to copy it
3527 * from the old backing file into the COW file.
3529 * If qemu-img crashes during this step, no harm is done. The content of
3530 * the image is the same as the original one at any time.
3534 int64_t old_backing_size
= 0;
3535 int64_t new_backing_size
= 0;
3538 float local_progress
= 0;
3540 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3541 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3543 size
= blk_getlength(blk
);
3545 error_report("Could not get size of '%s': %s",
3546 filename
, strerror(-size
));
3550 if (blk_old_backing
) {
3551 old_backing_size
= blk_getlength(blk_old_backing
);
3552 if (old_backing_size
< 0) {
3553 char backing_name
[PATH_MAX
];
3555 bdrv_get_backing_filename(bs
, backing_name
,
3556 sizeof(backing_name
));
3557 error_report("Could not get size of '%s': %s",
3558 backing_name
, strerror(-old_backing_size
));
3563 if (blk_new_backing
) {
3564 new_backing_size
= blk_getlength(blk_new_backing
);
3565 if (new_backing_size
< 0) {
3566 error_report("Could not get size of '%s': %s",
3567 out_baseimg
, strerror(-new_backing_size
));
3574 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3577 for (offset
= 0; offset
< size
; offset
+= n
) {
3578 bool buf_old_is_zero
= false;
3580 /* How many bytes can we handle with the next read? */
3581 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3583 /* If the cluster is allocated, we don't need to take action */
3584 ret
= bdrv_is_allocated(bs
, offset
, n
, &n
);
3586 error_report("error while reading image metadata: %s",
3594 if (prefix_chain_bs
) {
3596 * If cluster wasn't changed since prefix_chain, we don't need
3599 ret
= bdrv_is_allocated_above(backing_bs(bs
), prefix_chain_bs
,
3600 false, offset
, n
, &n
);
3602 error_report("error while reading image metadata: %s",
3612 * Read old and new backing file and take into consideration that
3613 * backing files may be smaller than the COW image.
3615 if (offset
>= old_backing_size
) {
3616 memset(buf_old
, 0, n
);
3617 buf_old_is_zero
= true;
3619 if (offset
+ n
> old_backing_size
) {
3620 n
= old_backing_size
- offset
;
3623 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3625 error_report("error while reading from old backing file");
3630 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3631 memset(buf_new
, 0, n
);
3633 if (offset
+ n
> new_backing_size
) {
3634 n
= new_backing_size
- offset
;
3637 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3639 error_report("error while reading from new backing file");
3644 /* If they differ, we need to write to the COW file */
3645 uint64_t written
= 0;
3647 while (written
< n
) {
3650 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3651 n
- written
, &pnum
))
3653 if (buf_old_is_zero
) {
3654 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3656 ret
= blk_pwrite(blk
, offset
+ written
,
3657 buf_old
+ written
, pnum
, 0);
3660 error_report("Error while writing to COW image: %s",
3668 qemu_progress_print(local_progress
, 100);
3673 * Change the backing file. All clusters that are different from the old
3674 * backing file are overwritten in the COW file now, so the visible content
3675 * doesn't change when we switch the backing file.
3677 if (out_baseimg
&& *out_baseimg
) {
3678 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3680 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3683 if (ret
== -ENOSPC
) {
3684 error_report("Could not change the backing file to '%s': No "
3685 "space left in the file header", out_baseimg
);
3686 } else if (ret
< 0) {
3687 error_report("Could not change the backing file to '%s': %s",
3688 out_baseimg
, strerror(-ret
));
3691 qemu_progress_print(100, 0);
3693 * TODO At this point it is possible to check if any clusters that are
3694 * allocated in the COW file are the same in the backing file. If so, they
3695 * could be dropped from the COW file. Don't do this before switching the
3696 * backing file, in case of a crash this would lead to corruption.
3699 qemu_progress_end();
3702 blk_unref(blk_old_backing
);
3703 blk_unref(blk_new_backing
);
3705 qemu_vfree(buf_old
);
3706 qemu_vfree(buf_new
);
3715 static int img_resize(int argc
, char **argv
)
3718 int c
, ret
, relative
;
3719 const char *filename
, *fmt
, *size
;
3720 int64_t n
, total_size
, current_size
;
3722 BlockBackend
*blk
= NULL
;
3723 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3726 static QemuOptsList resize_options
= {
3727 .name
= "resize_options",
3728 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3731 .name
= BLOCK_OPT_SIZE
,
3732 .type
= QEMU_OPT_SIZE
,
3733 .help
= "Virtual disk size"
3739 bool image_opts
= false;
3740 bool shrink
= false;
3742 /* Remove size from argv manually so that negative numbers are not treated
3743 * as options by getopt. */
3745 error_exit("Not enough arguments");
3749 size
= argv
[--argc
];
3751 /* Parse getopt arguments */
3754 static const struct option long_options
[] = {
3755 {"help", no_argument
, 0, 'h'},
3756 {"object", required_argument
, 0, OPTION_OBJECT
},
3757 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3758 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3759 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3762 c
= getopt_long(argc
, argv
, ":f:hq",
3763 long_options
, NULL
);
3769 missing_argument(argv
[optind
- 1]);
3772 unrecognized_option(argv
[optind
- 1]);
3783 case OPTION_OBJECT
: {
3785 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3791 case OPTION_IMAGE_OPTS
:
3794 case OPTION_PREALLOCATION
:
3795 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3796 PREALLOC_MODE__MAX
, NULL
);
3797 if (prealloc
== PREALLOC_MODE__MAX
) {
3798 error_report("Invalid preallocation mode '%s'", optarg
);
3807 if (optind
!= argc
- 1) {
3808 error_exit("Expecting image file name and size");
3810 filename
= argv
[optind
++];
3812 if (qemu_opts_foreach(&qemu_object_opts
,
3813 user_creatable_add_opts_foreach
,
3814 qemu_img_object_print_help
, &error_fatal
)) {
3818 /* Choose grow, shrink, or absolute resize mode */
3834 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3835 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3837 error_report_err(err
);
3839 qemu_opts_del(param
);
3842 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3843 qemu_opts_del(param
);
3845 blk
= img_open(image_opts
, filename
, fmt
,
3846 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3853 current_size
= blk_getlength(blk
);
3854 if (current_size
< 0) {
3855 error_report("Failed to inquire current image length: %s",
3856 strerror(-current_size
));
3862 total_size
= current_size
+ n
* relative
;
3866 if (total_size
<= 0) {
3867 error_report("New image size must be positive");
3872 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3873 error_report("Preallocation can only be used for growing images");
3878 if (total_size
< current_size
&& !shrink
) {
3879 warn_report("Shrinking an image will delete all data beyond the "
3880 "shrunken image's end. Before performing such an "
3881 "operation, make sure there is no important data there.");
3883 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk
)), "raw") != 0) {
3885 "Use the --shrink option to perform a shrink operation.");
3889 warn_report("Using the --shrink option will suppress this message. "
3890 "Note that future versions of qemu-img may refuse to "
3891 "shrink images without this option.");
3896 * The user expects the image to have the desired size after
3897 * resizing, so pass @exact=true. It is of no use to report
3898 * success when the image has not actually been resized.
3900 ret
= blk_truncate(blk
, total_size
, true, prealloc
, 0, &err
);
3902 qprintf(quiet
, "Image resized.\n");
3904 error_report_err(err
);
3914 static void amend_status_cb(BlockDriverState
*bs
,
3915 int64_t offset
, int64_t total_work_size
,
3918 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3921 static int print_amend_option_help(const char *format
)
3925 /* Find driver and parse its options */
3926 drv
= bdrv_find_format(format
);
3928 error_report("Unknown file format '%s'", format
);
3932 if (!drv
->bdrv_amend_options
) {
3933 error_report("Format driver '%s' does not support option amendment",
3938 /* Every driver supporting amendment must have create_opts */
3939 assert(drv
->create_opts
);
3941 printf("Creation options for '%s':\n", format
);
3942 qemu_opts_print_help(drv
->create_opts
, false);
3943 printf("\nNote that not all of these options may be amendable.\n");
3947 static int img_amend(int argc
, char **argv
)
3951 char *options
= NULL
;
3952 QemuOptsList
*create_opts
= NULL
;
3953 QemuOpts
*opts
= NULL
;
3954 const char *fmt
= NULL
, *filename
, *cache
;
3957 bool quiet
= false, progress
= false;
3958 BlockBackend
*blk
= NULL
;
3959 BlockDriverState
*bs
= NULL
;
3960 bool image_opts
= false;
3962 cache
= BDRV_DEFAULT_CACHE
;
3964 static const struct option long_options
[] = {
3965 {"help", no_argument
, 0, 'h'},
3966 {"object", required_argument
, 0, OPTION_OBJECT
},
3967 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3970 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
3971 long_options
, NULL
);
3978 missing_argument(argv
[optind
- 1]);
3981 unrecognized_option(argv
[optind
- 1]);
3987 if (accumulate_options(&options
, optarg
) < 0) {
3989 goto out_no_progress
;
4005 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4009 goto out_no_progress
;
4012 case OPTION_IMAGE_OPTS
:
4019 error_exit("Must specify options (-o)");
4022 if (qemu_opts_foreach(&qemu_object_opts
,
4023 user_creatable_add_opts_foreach
,
4024 qemu_img_object_print_help
, &error_fatal
)) {
4026 goto out_no_progress
;
4032 qemu_progress_init(progress
, 1.0);
4034 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
4035 if (fmt
&& has_help_option(options
)) {
4036 /* If a format is explicitly specified (and possibly no filename is
4037 * given), print option help here */
4038 ret
= print_amend_option_help(fmt
);
4042 if (optind
!= argc
- 1) {
4043 error_report("Expecting one image file name");
4048 flags
= BDRV_O_RDWR
;
4049 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
4051 error_report("Invalid cache option: %s", cache
);
4055 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4063 fmt
= bs
->drv
->format_name
;
4065 if (has_help_option(options
)) {
4066 /* If the format was auto-detected, print option help here */
4067 ret
= print_amend_option_help(fmt
);
4071 if (!bs
->drv
->bdrv_amend_options
) {
4072 error_report("Format driver '%s' does not support option amendment",
4078 /* Every driver supporting amendment must have create_opts */
4079 assert(bs
->drv
->create_opts
);
4081 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
4082 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4083 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
4085 error_report_err(err
);
4090 /* In case the driver does not call amend_status_cb() */
4091 qemu_progress_print(0.f
, 0);
4092 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, &err
);
4093 qemu_progress_print(100.f
, 0);
4095 error_report_err(err
);
4100 qemu_progress_end();
4104 qemu_opts_del(opts
);
4105 qemu_opts_free(create_opts
);
4114 typedef struct BenchData
{
4116 uint64_t image_size
;
4123 bool drain_on_flush
;
4132 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4135 error_report("Failed flush request: %s", strerror(-ret
));
4140 static void bench_cb(void *opaque
, int ret
)
4142 BenchData
*b
= opaque
;
4146 error_report("Failed request: %s", strerror(-ret
));
4151 /* Just finished a flush with drained queue: Start next requests */
4152 assert(b
->in_flight
== 0);
4153 b
->in_flush
= false;
4154 } else if (b
->in_flight
> 0) {
4155 int remaining
= b
->n
- b
->in_flight
;
4160 /* Time for flush? Drain queue if requested, then flush */
4161 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4162 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4163 BlockCompletionFunc
*cb
;
4165 if (b
->drain_on_flush
) {
4169 cb
= bench_undrained_flush_cb
;
4172 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4174 error_report("Failed to issue flush request");
4178 if (b
->drain_on_flush
) {
4184 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4185 int64_t offset
= b
->offset
;
4186 /* blk_aio_* might look for completed I/Os and kick bench_cb
4187 * again, so make sure this operation is counted by in_flight
4188 * and b->offset is ready for the next submission.
4191 b
->offset
+= b
->step
;
4192 b
->offset
%= b
->image_size
;
4194 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4196 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4199 error_report("Failed to issue request");
4205 static int img_bench(int argc
, char **argv
)
4208 const char *fmt
= NULL
, *filename
;
4210 bool image_opts
= false;
4211 bool is_write
= false;
4215 size_t bufsize
= 4096;
4218 int flush_interval
= 0;
4219 bool drain_on_flush
= true;
4221 BlockBackend
*blk
= NULL
;
4222 BenchData data
= {};
4224 bool writethrough
= false;
4225 struct timeval t1
, t2
;
4227 bool force_share
= false;
4231 static const struct option long_options
[] = {
4232 {"help", no_argument
, 0, 'h'},
4233 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4234 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4235 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4236 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4237 {"force-share", no_argument
, 0, 'U'},
4240 c
= getopt_long(argc
, argv
, ":hc:d:f:ni:o:qs:S:t:wU", long_options
,
4248 missing_argument(argv
[optind
- 1]);
4251 unrecognized_option(argv
[optind
- 1]);
4260 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4261 error_report("Invalid request count specified");
4271 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4272 error_report("Invalid queue depth specified");
4282 flags
|= BDRV_O_NATIVE_AIO
;
4285 ret
= bdrv_parse_aio(optarg
, &flags
);
4287 error_report("Invalid aio option: %s", optarg
);
4294 offset
= cvtnum(optarg
);
4296 error_report("Invalid offset specified");
4309 sval
= cvtnum(optarg
);
4310 if (sval
< 0 || sval
> INT_MAX
) {
4311 error_report("Invalid buffer size specified");
4322 sval
= cvtnum(optarg
);
4323 if (sval
< 0 || sval
> INT_MAX
) {
4324 error_report("Invalid step size specified");
4332 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4334 error_report("Invalid cache mode");
4340 flags
|= BDRV_O_RDWR
;
4346 case OPTION_PATTERN
:
4350 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4351 error_report("Invalid pattern byte specified");
4357 case OPTION_FLUSH_INTERVAL
:
4361 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4362 error_report("Invalid flush interval specified");
4365 flush_interval
= res
;
4368 case OPTION_NO_DRAIN
:
4369 drain_on_flush
= false;
4371 case OPTION_IMAGE_OPTS
:
4377 if (optind
!= argc
- 1) {
4378 error_exit("Expecting one image file name");
4380 filename
= argv
[argc
- 1];
4382 if (!is_write
&& flush_interval
) {
4383 error_report("--flush-interval is only available in write tests");
4387 if (flush_interval
&& flush_interval
< depth
) {
4388 error_report("Flush interval can't be smaller than depth");
4393 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4400 image_size
= blk_getlength(blk
);
4401 if (image_size
< 0) {
4406 data
= (BenchData
) {
4408 .image_size
= image_size
,
4410 .step
= step
?: bufsize
,
4415 .flush_interval
= flush_interval
,
4416 .drain_on_flush
= drain_on_flush
,
4418 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4419 "(starting at offset %" PRId64
", step size %d)\n",
4420 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4421 data
.offset
, data
.step
);
4422 if (flush_interval
) {
4423 printf("Sending flush every %d requests\n", flush_interval
);
4426 buf_size
= data
.nrreq
* data
.bufsize
;
4427 data
.buf
= blk_blockalign(blk
, buf_size
);
4428 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4430 blk_register_buf(blk
, data
.buf
, buf_size
);
4432 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4433 for (i
= 0; i
< data
.nrreq
; i
++) {
4434 qemu_iovec_init(&data
.qiov
[i
], 1);
4435 qemu_iovec_add(&data
.qiov
[i
],
4436 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4439 gettimeofday(&t1
, NULL
);
4442 while (data
.n
> 0) {
4443 main_loop_wait(false);
4445 gettimeofday(&t2
, NULL
);
4447 printf("Run completed in %3.3f seconds.\n",
4448 (t2
.tv_sec
- t1
.tv_sec
)
4449 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4453 blk_unregister_buf(blk
, data
.buf
);
4455 qemu_vfree(data
.buf
);
4476 int bsz
; /* Block size */
4484 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4488 static int img_dd_bs(const char *arg
,
4489 struct DdIo
*in
, struct DdIo
*out
,
4496 if (res
<= 0 || res
> INT_MAX
) {
4497 error_report("invalid number: '%s'", arg
);
4500 in
->bsz
= out
->bsz
= res
;
4505 static int img_dd_count(const char *arg
,
4506 struct DdIo
*in
, struct DdIo
*out
,
4509 dd
->count
= cvtnum(arg
);
4511 if (dd
->count
< 0) {
4512 error_report("invalid number: '%s'", arg
);
4519 static int img_dd_if(const char *arg
,
4520 struct DdIo
*in
, struct DdIo
*out
,
4523 in
->filename
= g_strdup(arg
);
4528 static int img_dd_of(const char *arg
,
4529 struct DdIo
*in
, struct DdIo
*out
,
4532 out
->filename
= g_strdup(arg
);
4537 static int img_dd_skip(const char *arg
,
4538 struct DdIo
*in
, struct DdIo
*out
,
4541 in
->offset
= cvtnum(arg
);
4543 if (in
->offset
< 0) {
4544 error_report("invalid number: '%s'", arg
);
4551 static int img_dd(int argc
, char **argv
)
4556 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4557 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4558 QemuOpts
*opts
= NULL
;
4559 QemuOptsList
*create_opts
= NULL
;
4560 Error
*local_err
= NULL
;
4561 bool image_opts
= false;
4563 const char *out_fmt
= "raw";
4564 const char *fmt
= NULL
;
4566 int64_t block_count
= 0, out_pos
, in_pos
;
4567 bool force_share
= false;
4568 struct DdInfo dd
= {
4573 .bsz
= 512, /* Block size is by default 512 bytes */
4585 const struct DdOpts options
[] = {
4586 { "bs", img_dd_bs
, C_BS
},
4587 { "count", img_dd_count
, C_COUNT
},
4588 { "if", img_dd_if
, C_IF
},
4589 { "of", img_dd_of
, C_OF
},
4590 { "skip", img_dd_skip
, C_SKIP
},
4593 const struct option long_options
[] = {
4594 { "help", no_argument
, 0, 'h'},
4595 { "object", required_argument
, 0, OPTION_OBJECT
},
4596 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4597 { "force-share", no_argument
, 0, 'U'},
4601 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4613 missing_argument(argv
[optind
- 1]);
4616 unrecognized_option(argv
[optind
- 1]);
4625 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4630 case OPTION_IMAGE_OPTS
:
4636 for (i
= optind
; i
< argc
; i
++) {
4638 arg
= g_strdup(argv
[i
]);
4640 tmp
= strchr(arg
, '=');
4642 error_report("unrecognized operand %s", arg
);
4649 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4650 if (!strcmp(arg
, options
[j
].name
)) {
4654 if (options
[j
].name
== NULL
) {
4655 error_report("unrecognized operand %s", arg
);
4660 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4664 dd
.flags
|= options
[j
].flag
;
4669 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4670 error_report("Must specify both input and output files");
4675 if (qemu_opts_foreach(&qemu_object_opts
,
4676 user_creatable_add_opts_foreach
,
4677 qemu_img_object_print_help
, &error_fatal
)) {
4682 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4690 drv
= bdrv_find_format(out_fmt
);
4692 error_report("Unknown file format");
4696 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4699 error_report_err(local_err
);
4703 if (!drv
->create_opts
) {
4704 error_report("Format driver '%s' does not support image creation",
4709 if (!proto_drv
->create_opts
) {
4710 error_report("Protocol driver '%s' does not support image creation",
4711 proto_drv
->format_name
);
4715 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4716 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4718 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4720 size
= blk_getlength(blk1
);
4722 error_report("Failed to get size for '%s'", in
.filename
);
4727 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4728 dd
.count
* in
.bsz
< size
) {
4729 size
= dd
.count
* in
.bsz
;
4732 /* Overflow means the specified offset is beyond input image's size */
4733 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4734 size
< in
.bsz
* in
.offset
)) {
4735 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4737 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4738 size
- in
.bsz
* in
.offset
, &error_abort
);
4741 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4743 error_reportf_err(local_err
,
4744 "%s: error while creating output image: ",
4750 /* TODO, we can't honour --image-opts for the target,
4751 * since it needs to be given in a format compatible
4752 * with the bdrv_create() call above which does not
4753 * support image-opts style.
4755 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
4756 false, false, false);
4763 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4764 size
< in
.offset
* in
.bsz
)) {
4765 /* We give a warning if the skip option is bigger than the input
4766 * size and create an empty output disk image (i.e. like dd(1)).
4768 error_report("%s: cannot skip to specified offset", in
.filename
);
4771 in_pos
= in
.offset
* in
.bsz
;
4774 in
.buf
= g_new(uint8_t, in
.bsz
);
4776 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4777 int in_ret
, out_ret
;
4779 if (in_pos
+ in
.bsz
> size
) {
4780 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4782 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4785 error_report("error while reading from input image file: %s",
4792 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4795 error_report("error while writing to output image file: %s",
4796 strerror(-out_ret
));
4805 qemu_opts_del(opts
);
4806 qemu_opts_free(create_opts
);
4809 g_free(in
.filename
);
4810 g_free(out
.filename
);
4820 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
4824 Visitor
*v
= qobject_output_visitor_new(&obj
);
4826 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
4827 visit_complete(v
, &obj
);
4828 str
= qobject_to_json_pretty(obj
);
4829 assert(str
!= NULL
);
4830 printf("%s\n", qstring_get_str(str
));
4836 static int img_measure(int argc
, char **argv
)
4838 static const struct option long_options
[] = {
4839 {"help", no_argument
, 0, 'h'},
4840 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4841 {"object", required_argument
, 0, OPTION_OBJECT
},
4842 {"output", required_argument
, 0, OPTION_OUTPUT
},
4843 {"size", required_argument
, 0, OPTION_SIZE
},
4844 {"force-share", no_argument
, 0, 'U'},
4847 OutputFormat output_format
= OFORMAT_HUMAN
;
4848 BlockBackend
*in_blk
= NULL
;
4850 const char *filename
= NULL
;
4851 const char *fmt
= NULL
;
4852 const char *out_fmt
= "raw";
4853 char *options
= NULL
;
4854 char *snapshot_name
= NULL
;
4855 bool force_share
= false;
4856 QemuOpts
*opts
= NULL
;
4857 QemuOpts
*object_opts
= NULL
;
4858 QemuOpts
*sn_opts
= NULL
;
4859 QemuOptsList
*create_opts
= NULL
;
4860 bool image_opts
= false;
4861 uint64_t img_size
= UINT64_MAX
;
4862 BlockMeasureInfo
*info
= NULL
;
4863 Error
*local_err
= NULL
;
4867 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
4868 long_options
, NULL
)) != -1) {
4881 if (accumulate_options(&options
, optarg
) < 0) {
4886 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
4887 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
4890 error_report("Failed in parsing snapshot param '%s'",
4895 snapshot_name
= optarg
;
4902 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4908 case OPTION_IMAGE_OPTS
:
4912 if (!strcmp(optarg
, "json")) {
4913 output_format
= OFORMAT_JSON
;
4914 } else if (!strcmp(optarg
, "human")) {
4915 output_format
= OFORMAT_HUMAN
;
4917 error_report("--output must be used with human or json "
4926 sval
= cvtnum(optarg
);
4928 if (sval
== -ERANGE
) {
4929 error_report("Image size must be less than 8 EiB!");
4931 error_report("Invalid image size specified! You may use "
4932 "k, M, G, T, P or E suffixes for ");
4933 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4934 "petabytes and exabytes.");
4938 img_size
= (uint64_t)sval
;
4944 if (qemu_opts_foreach(&qemu_object_opts
,
4945 user_creatable_add_opts_foreach
,
4946 qemu_img_object_print_help
, &error_fatal
)) {
4950 if (argc
- optind
> 1) {
4951 error_report("At most one filename argument is allowed.");
4953 } else if (argc
- optind
== 1) {
4954 filename
= argv
[optind
];
4957 if (!filename
&& (image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
4958 error_report("--image-opts, -f, and -l require a filename argument.");
4961 if (filename
&& img_size
!= UINT64_MAX
) {
4962 error_report("--size N cannot be used together with a filename.");
4965 if (!filename
&& img_size
== UINT64_MAX
) {
4966 error_report("Either --size N or one filename must be specified.");
4971 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
4972 false, false, force_share
);
4978 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
4979 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
4980 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
4982 } else if (snapshot_name
!= NULL
) {
4983 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
4984 snapshot_name
, &local_err
);
4987 error_reportf_err(local_err
, "Failed to load snapshot: ");
4992 drv
= bdrv_find_format(out_fmt
);
4994 error_report("Unknown file format '%s'", out_fmt
);
4997 if (!drv
->create_opts
) {
4998 error_report("Format driver '%s' does not support image creation",
5003 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5004 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
5005 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5007 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
5009 error_report_err(local_err
);
5010 error_report("Invalid options for file format '%s'", out_fmt
);
5014 if (img_size
!= UINT64_MAX
) {
5015 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
5018 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
5020 error_report_err(local_err
);
5024 if (output_format
== OFORMAT_HUMAN
) {
5025 printf("required size: %" PRIu64
"\n", info
->required
);
5026 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
5028 dump_json_block_measure_info(info
);
5034 qapi_free_BlockMeasureInfo(info
);
5035 qemu_opts_del(object_opts
);
5036 qemu_opts_del(opts
);
5037 qemu_opts_del(sn_opts
);
5038 qemu_opts_free(create_opts
);
5044 static const img_cmd_t img_cmds
[] = {
5045 #define DEF(option, callback, arg_string) \
5046 { option, callback },
5047 #include "qemu-img-cmds.h"
5052 int main(int argc
, char **argv
)
5054 const img_cmd_t
*cmd
;
5055 const char *cmdname
;
5056 Error
*local_error
= NULL
;
5057 char *trace_file
= NULL
;
5059 static const struct option long_options
[] = {
5060 {"help", no_argument
, 0, 'h'},
5061 {"version", no_argument
, 0, 'V'},
5062 {"trace", required_argument
, NULL
, 'T'},
5067 signal(SIGPIPE
, SIG_IGN
);
5070 error_init(argv
[0]);
5071 module_call_init(MODULE_INIT_TRACE
);
5072 qemu_init_exec_dir(argv
[0]);
5074 if (qemu_init_main_loop(&local_error
)) {
5075 error_report_err(local_error
);
5079 qcrypto_init(&error_fatal
);
5081 module_call_init(MODULE_INIT_QOM
);
5084 error_exit("Not enough arguments");
5087 qemu_add_opts(&qemu_object_opts
);
5088 qemu_add_opts(&qemu_source_opts
);
5089 qemu_add_opts(&qemu_trace_opts
);
5091 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
5094 missing_argument(argv
[optind
- 1]);
5097 unrecognized_option(argv
[optind
- 1]);
5103 printf(QEMU_IMG_VERSION
);
5107 trace_file
= trace_opt_parse(optarg
);
5112 cmdname
= argv
[optind
];
5114 /* reset getopt_long scanning */
5120 qemu_reset_optind();
5122 if (!trace_init_backends()) {
5125 trace_init_file(trace_file
);
5126 qemu_set_log(LOG_TRACE
);
5128 /* find the command */
5129 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5130 if (!strcmp(cmdname
, cmd
->name
)) {
5131 return cmd
->handler(argc
, argv
);
5136 error_exit("Command not found: %s", cmdname
);