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_full(const char *name
, const char *value
, int64_t min
,
479 err
= qemu_strtosz(value
, NULL
, &res
);
480 if (err
< 0 && err
!= -ERANGE
) {
481 error_report("Invalid %s specified. You may use "
482 "k, M, G, T, P or E suffixes for", name
);
483 error_report("kilobytes, megabytes, gigabytes, terabytes, "
484 "petabytes and exabytes.");
487 if (err
== -ERANGE
|| res
> max
|| res
< min
) {
488 error_report("Invalid %s specified. Must be between %" PRId64
489 " and %" PRId64
".", name
, min
, max
);
495 static int64_t cvtnum(const char *name
, const char *value
)
497 return cvtnum_full(name
, value
, 0, INT64_MAX
);
500 static int img_create(int argc
, char **argv
)
503 uint64_t img_size
= -1;
504 const char *fmt
= "raw";
505 const char *base_fmt
= NULL
;
506 const char *filename
;
507 const char *base_filename
= NULL
;
508 char *options
= NULL
;
509 Error
*local_err
= NULL
;
514 static const struct option long_options
[] = {
515 {"help", no_argument
, 0, 'h'},
516 {"object", required_argument
, 0, OPTION_OBJECT
},
519 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
526 missing_argument(argv
[optind
- 1]);
529 unrecognized_option(argv
[optind
- 1]);
538 base_filename
= optarg
;
544 if (accumulate_options(&options
, optarg
) < 0) {
552 flags
|= BDRV_O_NO_BACKING
;
554 case OPTION_OBJECT
: {
556 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
565 /* Get the filename */
566 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
567 if (options
&& has_help_option(options
)) {
569 return print_block_option_help(filename
, fmt
);
572 if (optind
>= argc
) {
573 error_exit("Expecting image file name");
577 if (qemu_opts_foreach(&qemu_object_opts
,
578 user_creatable_add_opts_foreach
,
579 qemu_img_object_print_help
, &error_fatal
)) {
583 /* Get image size, if specified */
587 sval
= cvtnum("image size", argv
[optind
++]);
591 img_size
= (uint64_t)sval
;
593 if (optind
!= argc
) {
594 error_exit("Unexpected argument: %s", argv
[optind
]);
597 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
598 options
, img_size
, flags
, quiet
, &local_err
);
600 error_reportf_err(local_err
, "%s: ", filename
);
612 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
616 Visitor
*v
= qobject_output_visitor_new(&obj
);
618 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
619 visit_complete(v
, &obj
);
620 str
= qobject_to_json_pretty(obj
);
622 qprintf(quiet
, "%s\n", qstring_get_str(str
));
628 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
630 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
631 qprintf(quiet
, "No errors were found on the image.\n");
633 if (check
->corruptions
) {
634 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
635 "Data may be corrupted, or further writes to the image "
642 "\n%" PRId64
" leaked clusters were found on the image.\n"
643 "This means waste of disk space, but no harm to data.\n",
647 if (check
->check_errors
) {
650 " internal errors have occurred during the check.\n",
651 check
->check_errors
);
655 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
656 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
657 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
658 check
->allocated_clusters
, check
->total_clusters
,
659 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
660 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
661 check
->compressed_clusters
* 100.0 /
662 check
->allocated_clusters
);
665 if (check
->image_end_offset
) {
667 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
671 static int collect_image_check(BlockDriverState
*bs
,
673 const char *filename
,
678 BdrvCheckResult result
;
680 ret
= bdrv_check(bs
, &result
, fix
);
685 check
->filename
= g_strdup(filename
);
686 check
->format
= g_strdup(bdrv_get_format_name(bs
));
687 check
->check_errors
= result
.check_errors
;
688 check
->corruptions
= result
.corruptions
;
689 check
->has_corruptions
= result
.corruptions
!= 0;
690 check
->leaks
= result
.leaks
;
691 check
->has_leaks
= result
.leaks
!= 0;
692 check
->corruptions_fixed
= result
.corruptions_fixed
;
693 check
->has_corruptions_fixed
= result
.corruptions_fixed
!= 0;
694 check
->leaks_fixed
= result
.leaks_fixed
;
695 check
->has_leaks_fixed
= result
.leaks_fixed
!= 0;
696 check
->image_end_offset
= result
.image_end_offset
;
697 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
698 check
->total_clusters
= result
.bfi
.total_clusters
;
699 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
700 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
701 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
702 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
703 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
704 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
705 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
711 * Checks an image for consistency. Exit codes:
713 * 0 - Check completed, image is good
714 * 1 - Check not completed because of internal errors
715 * 2 - Check completed, image is corrupted
716 * 3 - Check completed, image has leaked clusters, but is good otherwise
717 * 63 - Checks are not supported by the image format
719 static int img_check(int argc
, char **argv
)
722 OutputFormat output_format
= OFORMAT_HUMAN
;
723 const char *filename
, *fmt
, *output
, *cache
;
725 BlockDriverState
*bs
;
727 int flags
= BDRV_O_CHECK
;
731 bool image_opts
= false;
732 bool force_share
= false;
736 cache
= BDRV_DEFAULT_CACHE
;
739 int option_index
= 0;
740 static const struct option long_options
[] = {
741 {"help", no_argument
, 0, 'h'},
742 {"format", required_argument
, 0, 'f'},
743 {"repair", required_argument
, 0, 'r'},
744 {"output", required_argument
, 0, OPTION_OUTPUT
},
745 {"object", required_argument
, 0, OPTION_OBJECT
},
746 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
747 {"force-share", no_argument
, 0, 'U'},
750 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
751 long_options
, &option_index
);
757 missing_argument(argv
[optind
- 1]);
760 unrecognized_option(argv
[optind
- 1]);
769 flags
|= BDRV_O_RDWR
;
771 if (!strcmp(optarg
, "leaks")) {
772 fix
= BDRV_FIX_LEAKS
;
773 } else if (!strcmp(optarg
, "all")) {
774 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
776 error_exit("Unknown option value for -r "
777 "(expecting 'leaks' or 'all'): %s", optarg
);
792 case OPTION_OBJECT
: {
794 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
800 case OPTION_IMAGE_OPTS
:
805 if (optind
!= argc
- 1) {
806 error_exit("Expecting one image file name");
808 filename
= argv
[optind
++];
810 if (output
&& !strcmp(output
, "json")) {
811 output_format
= OFORMAT_JSON
;
812 } else if (output
&& !strcmp(output
, "human")) {
813 output_format
= OFORMAT_HUMAN
;
815 error_report("--output must be used with human or json as argument.");
819 if (qemu_opts_foreach(&qemu_object_opts
,
820 user_creatable_add_opts_foreach
,
821 qemu_img_object_print_help
, &error_fatal
)) {
825 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
827 error_report("Invalid source cache option: %s", cache
);
831 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
838 check
= g_new0(ImageCheck
, 1);
839 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
841 if (ret
== -ENOTSUP
) {
842 error_report("This image format does not support checks");
847 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
848 int corruptions_fixed
, leaks_fixed
;
849 bool has_leaks_fixed
, has_corruptions_fixed
;
851 leaks_fixed
= check
->leaks_fixed
;
852 has_leaks_fixed
= check
->has_leaks_fixed
;
853 corruptions_fixed
= check
->corruptions_fixed
;
854 has_corruptions_fixed
= check
->has_corruptions_fixed
;
856 if (output_format
== OFORMAT_HUMAN
) {
858 "The following inconsistencies were found and repaired:\n\n"
859 " %" PRId64
" leaked clusters\n"
860 " %" PRId64
" corruptions\n\n"
861 "Double checking the fixed image now...\n",
863 check
->corruptions_fixed
);
866 qapi_free_ImageCheck(check
);
867 check
= g_new0(ImageCheck
, 1);
868 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
870 check
->leaks_fixed
= leaks_fixed
;
871 check
->has_leaks_fixed
= has_leaks_fixed
;
872 check
->corruptions_fixed
= corruptions_fixed
;
873 check
->has_corruptions_fixed
= has_corruptions_fixed
;
877 switch (output_format
) {
879 dump_human_image_check(check
, quiet
);
882 dump_json_image_check(check
, quiet
);
887 if (ret
|| check
->check_errors
) {
889 error_report("Check failed: %s", strerror(-ret
));
891 error_report("Check failed");
897 if (check
->corruptions
) {
899 } else if (check
->leaks
) {
906 qapi_free_ImageCheck(check
);
911 typedef struct CommonBlockJobCBInfo
{
912 BlockDriverState
*bs
;
914 } CommonBlockJobCBInfo
;
916 static void common_block_job_cb(void *opaque
, int ret
)
918 CommonBlockJobCBInfo
*cbi
= opaque
;
921 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
925 static void run_block_job(BlockJob
*job
, Error
**errp
)
927 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
930 aio_context_acquire(aio_context
);
933 float progress
= 0.0f
;
934 aio_poll(aio_context
, true);
935 if (job
->job
.progress
.total
) {
936 progress
= (float)job
->job
.progress
.current
/
937 job
->job
.progress
.total
* 100.f
;
939 qemu_progress_print(progress
, 0);
940 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
942 if (!job_is_completed(&job
->job
)) {
943 ret
= job_complete_sync(&job
->job
, errp
);
947 job_unref(&job
->job
);
948 aio_context_release(aio_context
);
950 /* publish completion progress only when success */
952 qemu_progress_print(100.f
, 0);
956 static int img_commit(int argc
, char **argv
)
959 const char *filename
, *fmt
, *cache
, *base
;
961 BlockDriverState
*bs
, *base_bs
;
963 bool progress
= false, quiet
= false, drop
= false;
965 Error
*local_err
= NULL
;
966 CommonBlockJobCBInfo cbi
;
967 bool image_opts
= false;
968 AioContext
*aio_context
;
971 cache
= BDRV_DEFAULT_CACHE
;
974 static const struct option long_options
[] = {
975 {"help", no_argument
, 0, 'h'},
976 {"object", required_argument
, 0, OPTION_OBJECT
},
977 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
980 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
987 missing_argument(argv
[optind
- 1]);
990 unrecognized_option(argv
[optind
- 1]);
1015 case OPTION_OBJECT
: {
1017 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1023 case OPTION_IMAGE_OPTS
:
1029 /* Progress is not shown in Quiet mode */
1034 if (optind
!= argc
- 1) {
1035 error_exit("Expecting one image file name");
1037 filename
= argv
[optind
++];
1039 if (qemu_opts_foreach(&qemu_object_opts
,
1040 user_creatable_add_opts_foreach
,
1041 qemu_img_object_print_help
, &error_fatal
)) {
1045 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
1046 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1048 error_report("Invalid cache option: %s", cache
);
1052 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1059 qemu_progress_init(progress
, 1.f
);
1060 qemu_progress_print(0.f
, 100);
1063 base_bs
= bdrv_find_backing_image(bs
, base
);
1065 error_setg(&local_err
,
1066 "Did not find '%s' in the backing chain of '%s'",
1071 /* This is different from QMP, which by default uses the deepest file in
1072 * the backing chain (i.e., the very base); however, the traditional
1073 * behavior of qemu-img commit is using the immediate backing file. */
1074 base_bs
= backing_bs(bs
);
1076 error_setg(&local_err
, "Image does not have a backing file");
1081 cbi
= (CommonBlockJobCBInfo
){
1086 aio_context
= bdrv_get_aio_context(bs
);
1087 aio_context_acquire(aio_context
);
1088 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, 0,
1089 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1090 &cbi
, false, &local_err
);
1091 aio_context_release(aio_context
);
1096 /* When the block job completes, the BlockBackend reference will point to
1097 * the old backing file. In order to avoid that the top image is already
1098 * deleted, so we can still empty it afterwards, increment the reference
1099 * counter here preemptively. */
1104 job
= block_job_get("commit");
1106 run_block_job(job
, &local_err
);
1112 BlockBackend
*old_backing_blk
;
1114 old_backing_blk
= blk_new_with_bs(bs
, BLK_PERM_WRITE
, BLK_PERM_ALL
,
1116 if (!old_backing_blk
) {
1119 ret
= blk_make_empty(old_backing_blk
, &local_err
);
1120 blk_unref(old_backing_blk
);
1121 if (ret
== -ENOTSUP
) {
1122 error_free(local_err
);
1124 } else if (ret
< 0) {
1135 qemu_progress_end();
1140 error_report_err(local_err
);
1144 qprintf(quiet
, "Image committed.\n");
1149 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1150 * of the first sector boundary within buf where the sector contains a
1151 * non-zero byte. This function is robust to a buffer that is not
1154 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1157 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1159 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1160 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1164 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1171 * Returns true iff the first sector pointed to by 'buf' contains at least
1174 * 'pnum' is set to the number of sectors (including and immediately following
1175 * the first one) that are known to be in the same allocated/unallocated state.
1176 * The function will try to align the end offset to alignment boundaries so
1177 * that the request will at least end aligned and consequtive requests will
1178 * also start at an aligned offset.
1180 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1181 int64_t sector_num
, int alignment
)
1190 is_zero
= buffer_is_zero(buf
, 512);
1191 for(i
= 1; i
< n
; i
++) {
1193 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1198 tail
= (sector_num
+ i
) & (alignment
- 1);
1200 if (is_zero
&& i
<= tail
) {
1201 /* treat unallocated areas which only consist
1202 * of a small tail as allocated. */
1206 /* align up end offset of allocated areas. */
1207 i
+= alignment
- tail
;
1210 /* align down end offset of zero areas. */
1219 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1220 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1221 * breaking up write requests for only small sparse areas.
1223 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1224 int min
, int64_t sector_num
, int alignment
)
1227 int num_checked
, num_used
;
1233 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1239 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1241 sector_num
+= *pnum
;
1242 num_checked
= num_used
;
1245 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1247 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1249 sector_num
+= *pnum
;
1250 num_checked
+= *pnum
;
1252 num_used
= num_checked
;
1253 } else if (*pnum
>= min
) {
1263 * Compares two buffers sector by sector. Returns 0 if the first
1264 * sector of each buffer matches, non-zero otherwise.
1266 * pnum is set to the sector-aligned size of the buffer prefix that
1267 * has the same matching status as the first sector.
1269 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1270 int64_t bytes
, int64_t *pnum
)
1273 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1277 res
= !!memcmp(buf1
, buf2
, i
);
1279 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1281 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1291 #define IO_BUF_SIZE (2 * MiB)
1294 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1296 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1297 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1298 * failure), and 4 on error (the exit status for read errors), after emitting
1301 * @param blk: BlockBackend for the image
1302 * @param offset: Starting offset to check
1303 * @param bytes: Number of bytes to check
1304 * @param filename: Name of disk file we are checking (logging purpose)
1305 * @param buffer: Allocated buffer for storing read data
1306 * @param quiet: Flag for quiet mode
1308 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1309 int64_t bytes
, const char *filename
,
1310 uint8_t *buffer
, bool quiet
)
1315 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1317 error_report("Error while reading offset %" PRId64
" of %s: %s",
1318 offset
, filename
, strerror(-ret
));
1321 idx
= find_nonzero(buffer
, bytes
);
1323 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1332 * Compares two images. Exit codes:
1334 * 0 - Images are identical
1336 * >1 - Error occurred
1338 static int img_compare(int argc
, char **argv
)
1340 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1341 BlockBackend
*blk1
, *blk2
;
1342 BlockDriverState
*bs1
, *bs2
;
1343 int64_t total_size1
, total_size2
;
1344 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1345 int64_t pnum1
, pnum2
;
1346 int allocated1
, allocated2
;
1347 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1348 bool progress
= false, quiet
= false, strict
= false;
1355 uint64_t progress_base
;
1356 bool image_opts
= false;
1357 bool force_share
= false;
1359 cache
= BDRV_DEFAULT_CACHE
;
1361 static const struct option long_options
[] = {
1362 {"help", no_argument
, 0, 'h'},
1363 {"object", required_argument
, 0, OPTION_OBJECT
},
1364 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1365 {"force-share", no_argument
, 0, 'U'},
1368 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1369 long_options
, NULL
);
1375 missing_argument(argv
[optind
- 1]);
1378 unrecognized_option(argv
[optind
- 1]);
1404 case OPTION_OBJECT
: {
1406 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1413 case OPTION_IMAGE_OPTS
:
1419 /* Progress is not shown in Quiet mode */
1425 if (optind
!= argc
- 2) {
1426 error_exit("Expecting two image file names");
1428 filename1
= argv
[optind
++];
1429 filename2
= argv
[optind
++];
1431 if (qemu_opts_foreach(&qemu_object_opts
,
1432 user_creatable_add_opts_foreach
,
1433 qemu_img_object_print_help
, &error_fatal
)) {
1438 /* Initialize before goto out */
1439 qemu_progress_init(progress
, 2.0);
1442 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1444 error_report("Invalid source cache option: %s", cache
);
1449 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1456 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1465 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1466 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1467 total_size1
= blk_getlength(blk1
);
1468 if (total_size1
< 0) {
1469 error_report("Can't get size of %s: %s",
1470 filename1
, strerror(-total_size1
));
1474 total_size2
= blk_getlength(blk2
);
1475 if (total_size2
< 0) {
1476 error_report("Can't get size of %s: %s",
1477 filename2
, strerror(-total_size2
));
1481 total_size
= MIN(total_size1
, total_size2
);
1482 progress_base
= MAX(total_size1
, total_size2
);
1484 qemu_progress_print(0, 100);
1486 if (strict
&& total_size1
!= total_size2
) {
1488 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1492 while (offset
< total_size
) {
1493 int status1
, status2
;
1495 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1496 total_size1
- offset
, &pnum1
, NULL
,
1500 error_report("Sector allocation test failed for %s", filename1
);
1503 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1505 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1506 total_size2
- offset
, &pnum2
, NULL
,
1510 error_report("Sector allocation test failed for %s", filename2
);
1513 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1515 assert(pnum1
&& pnum2
);
1516 chunk
= MIN(pnum1
, pnum2
);
1519 if (status1
!= status2
) {
1521 qprintf(quiet
, "Strict mode: Offset %" PRId64
1522 " block status mismatch!\n", offset
);
1526 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1528 } else if (allocated1
== allocated2
) {
1532 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1533 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1535 error_report("Error while reading offset %" PRId64
1537 offset
, filename1
, strerror(-ret
));
1541 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1543 error_report("Error while reading offset %" PRId64
1545 offset
, filename2
, strerror(-ret
));
1549 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1550 if (ret
|| pnum
!= chunk
) {
1551 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1552 offset
+ (ret
? 0 : pnum
));
1558 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1560 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1561 filename1
, buf1
, quiet
);
1563 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1564 filename2
, buf1
, quiet
);
1571 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1574 if (total_size1
!= total_size2
) {
1575 BlockBackend
*blk_over
;
1576 const char *filename_over
;
1578 qprintf(quiet
, "Warning: Image size mismatch!\n");
1579 if (total_size1
> total_size2
) {
1581 filename_over
= filename1
;
1584 filename_over
= filename2
;
1587 while (offset
< progress_base
) {
1588 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1589 progress_base
- offset
, &chunk
,
1593 error_report("Sector allocation test failed for %s",
1598 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1599 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1600 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1601 filename_over
, buf1
, quiet
);
1607 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1611 qprintf(quiet
, "Images are identical.\n");
1621 qemu_progress_end();
1626 enum ImgConvertBlockStatus
{
1632 #define MAX_COROUTINES 16
1634 typedef struct ImgConvertState
{
1636 int64_t *src_sectors
;
1638 int64_t total_sectors
;
1639 int64_t allocated_sectors
;
1640 int64_t allocated_done
;
1643 enum ImgConvertBlockStatus status
;
1644 int64_t sector_next_status
;
1645 BlockBackend
*target
;
1648 bool unallocated_blocks_are_zero
;
1650 bool target_has_backing
;
1651 int64_t target_backing_sectors
; /* negative if unknown */
1658 size_t cluster_sectors
;
1660 long num_coroutines
;
1661 int running_coroutines
;
1662 Coroutine
*co
[MAX_COROUTINES
];
1663 int64_t wait_sector_num
[MAX_COROUTINES
];
1668 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1669 int *src_cur
, int64_t *src_cur_offset
)
1672 *src_cur_offset
= 0;
1673 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1674 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1676 assert(*src_cur
< s
->src_num
);
1680 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1682 int64_t src_cur_offset
;
1683 int ret
, n
, src_cur
;
1684 bool post_backing_zero
= false;
1686 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1688 assert(s
->total_sectors
> sector_num
);
1689 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1691 if (s
->target_backing_sectors
>= 0) {
1692 if (sector_num
>= s
->target_backing_sectors
) {
1693 post_backing_zero
= s
->unallocated_blocks_are_zero
;
1694 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1695 /* Split requests around target_backing_sectors (because
1696 * starting from there, zeros are handled differently) */
1697 n
= s
->target_backing_sectors
- sector_num
;
1701 if (s
->sector_next_status
<= sector_num
) {
1702 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1706 count
= n
* BDRV_SECTOR_SIZE
;
1708 if (s
->target_has_backing
) {
1709 ret
= bdrv_block_status(blk_bs(s
->src
[src_cur
]), offset
,
1710 count
, &count
, NULL
, NULL
);
1712 ret
= bdrv_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1713 offset
, count
, &count
, NULL
,
1721 warn_report("error while reading block status at "
1722 "offset %" PRIu64
": %s", offset
,
1725 /* Just try to read the data, then */
1726 ret
= BDRV_BLOCK_DATA
;
1727 count
= BDRV_SECTOR_SIZE
;
1729 /* Retry on a shorter range */
1730 n
= DIV_ROUND_UP(n
, 4);
1733 error_report("error while reading block status at offset "
1734 "%" PRIu64
": %s", offset
, strerror(-ret
));
1740 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1742 if (ret
& BDRV_BLOCK_ZERO
) {
1743 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1744 } else if (ret
& BDRV_BLOCK_DATA
) {
1745 s
->status
= BLK_DATA
;
1747 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1750 s
->sector_next_status
= sector_num
+ n
;
1753 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1754 if (s
->status
== BLK_DATA
) {
1755 n
= MIN(n
, s
->buf_sectors
);
1758 /* We need to write complete clusters for compressed images, so if an
1759 * unallocated area is shorter than that, we must consider the whole
1760 * cluster allocated. */
1761 if (s
->compressed
) {
1762 if (n
< s
->cluster_sectors
) {
1763 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1764 s
->status
= BLK_DATA
;
1766 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1773 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1774 int nb_sectors
, uint8_t *buf
)
1776 uint64_t single_read_until
= 0;
1779 assert(nb_sectors
<= s
->buf_sectors
);
1780 while (nb_sectors
> 0) {
1783 int64_t bs_sectors
, src_cur_offset
;
1786 /* In the case of compression with multiple source files, we can get a
1787 * nb_sectors that spreads into the next part. So we must be able to
1788 * read across multiple BDSes for one convert_read() call. */
1789 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1790 blk
= s
->src
[src_cur
];
1791 bs_sectors
= s
->src_sectors
[src_cur
];
1793 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1795 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1796 if (single_read_until
> offset
) {
1800 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1804 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1808 warn_report("error while reading offset %" PRIu64
1809 ": %s", offset
, strerror(-ret
));
1811 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1820 buf
+= n
* BDRV_SECTOR_SIZE
;
1827 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1828 int nb_sectors
, uint8_t *buf
,
1829 enum ImgConvertBlockStatus status
)
1833 while (nb_sectors
> 0) {
1835 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1838 case BLK_BACKING_FILE
:
1839 /* If we have a backing file, leave clusters unallocated that are
1840 * unallocated in the source image, so that the backing file is
1841 * visible at the respective offset. */
1842 assert(s
->target_has_backing
);
1846 /* If we're told to keep the target fully allocated (-S 0) or there
1847 * is real non-zero data, we must write it. Otherwise we can treat
1848 * it as zero sectors.
1849 * Compressed clusters need to be written as a whole, so in that
1850 * case we can only save the write if the buffer is completely
1852 if (!s
->min_sparse
||
1854 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1855 sector_num
, s
->alignment
)) ||
1857 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1859 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1860 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1869 if (s
->has_zero_init
) {
1870 assert(!s
->target_has_backing
);
1873 ret
= blk_co_pwrite_zeroes(s
->target
,
1874 sector_num
<< BDRV_SECTOR_BITS
,
1875 n
<< BDRV_SECTOR_BITS
,
1876 BDRV_REQ_MAY_UNMAP
);
1885 buf
+= n
* BDRV_SECTOR_SIZE
;
1891 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1896 while (nb_sectors
> 0) {
1899 int64_t bs_sectors
, src_cur_offset
;
1902 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1903 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1904 blk
= s
->src
[src_cur
];
1905 bs_sectors
= s
->src_sectors
[src_cur
];
1907 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1909 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1910 sector_num
<< BDRV_SECTOR_BITS
,
1911 n
<< BDRV_SECTOR_BITS
, 0, 0);
1922 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1924 ImgConvertState
*s
= opaque
;
1925 uint8_t *buf
= NULL
;
1929 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1930 if (s
->co
[i
] == qemu_coroutine_self()) {
1937 s
->running_coroutines
++;
1938 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1943 enum ImgConvertBlockStatus status
;
1946 qemu_co_mutex_lock(&s
->lock
);
1947 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1948 qemu_co_mutex_unlock(&s
->lock
);
1951 n
= convert_iteration_sectors(s
, s
->sector_num
);
1953 qemu_co_mutex_unlock(&s
->lock
);
1957 /* save current sector and allocation status to local variables */
1958 sector_num
= s
->sector_num
;
1960 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1961 n
= MIN(n
, s
->buf_sectors
);
1963 /* increment global sector counter so that other coroutines can
1964 * already continue reading beyond this request */
1966 qemu_co_mutex_unlock(&s
->lock
);
1968 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1969 s
->allocated_done
+= n
;
1970 qemu_progress_print(100.0 * s
->allocated_done
/
1971 s
->allocated_sectors
, 0);
1975 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
1976 if (status
== BLK_DATA
&& !copy_range
) {
1977 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1979 error_report("error while reading at byte %lld: %s",
1980 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
1983 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1985 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1988 if (s
->wr_in_order
) {
1989 /* keep writes in order */
1990 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1991 s
->wait_sector_num
[index
] = sector_num
;
1992 qemu_coroutine_yield();
1994 s
->wait_sector_num
[index
] = -1;
1997 if (s
->ret
== -EINPROGRESS
) {
1999 ret
= convert_co_copy_range(s
, sector_num
, n
);
2001 s
->copy_range
= false;
2005 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
2008 error_report("error while writing at byte %lld: %s",
2009 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2014 if (s
->wr_in_order
) {
2015 /* reenter the coroutine that might have waited
2016 * for this write to complete */
2017 s
->wr_offs
= sector_num
+ n
;
2018 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2019 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
2021 * A -> B -> A cannot occur because A has
2022 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2023 * B will never enter A during this time window.
2025 qemu_coroutine_enter(s
->co
[i
]);
2033 s
->co
[index
] = NULL
;
2034 s
->running_coroutines
--;
2035 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
2036 /* the convert job finished successfully */
2041 static int convert_do_copy(ImgConvertState
*s
)
2044 int64_t sector_num
= 0;
2046 /* Check whether we have zero initialisation or can get it efficiently */
2047 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
2048 !s
->target_has_backing
) {
2049 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
2052 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
2053 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
2055 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
| BDRV_REQ_NO_FALLBACK
);
2057 s
->has_zero_init
= true;
2061 /* Allocate buffer for copied data. For compressed images, only one cluster
2062 * can be copied at a time. */
2063 if (s
->compressed
) {
2064 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2065 error_report("invalid cluster size");
2068 s
->buf_sectors
= s
->cluster_sectors
;
2071 while (sector_num
< s
->total_sectors
) {
2072 n
= convert_iteration_sectors(s
, sector_num
);
2076 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2078 s
->allocated_sectors
+= n
;
2084 s
->sector_next_status
= 0;
2085 s
->ret
= -EINPROGRESS
;
2087 qemu_co_mutex_init(&s
->lock
);
2088 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2089 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2090 s
->wait_sector_num
[i
] = -1;
2091 qemu_coroutine_enter(s
->co
[i
]);
2094 while (s
->running_coroutines
) {
2095 main_loop_wait(false);
2098 if (s
->compressed
&& !s
->ret
) {
2099 /* signal EOF to align */
2100 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
2109 #define MAX_BUF_SECTORS 32768
2111 static int img_convert(int argc
, char **argv
)
2113 int c
, bs_i
, flags
, src_flags
= 0;
2114 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2115 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2116 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
2117 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2118 BlockDriverInfo bdi
;
2119 BlockDriverState
*out_bs
;
2120 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2121 QemuOptsList
*create_opts
= NULL
;
2122 QDict
*open_opts
= NULL
;
2123 char *options
= NULL
;
2124 Error
*local_err
= NULL
;
2125 bool writethrough
, src_writethrough
, image_opts
= false,
2126 skip_create
= false, progress
= false, tgt_image_opts
= false;
2127 int64_t ret
= -EINVAL
;
2128 bool force_share
= false;
2129 bool explict_min_sparse
= false;
2131 ImgConvertState s
= (ImgConvertState
) {
2132 /* Need at least 4k of zeros for sparse detection */
2134 .copy_range
= false,
2135 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2136 .wr_in_order
= true,
2137 .num_coroutines
= 8,
2141 static const struct option long_options
[] = {
2142 {"help", no_argument
, 0, 'h'},
2143 {"object", required_argument
, 0, OPTION_OBJECT
},
2144 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2145 {"force-share", no_argument
, 0, 'U'},
2146 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2147 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2148 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2151 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2152 long_options
, NULL
);
2158 missing_argument(argv
[optind
- 1]);
2161 unrecognized_option(argv
[optind
- 1]);
2173 out_baseimg
= optarg
;
2176 s
.copy_range
= true;
2179 s
.compressed
= true;
2182 if (accumulate_options(&options
, optarg
) < 0) {
2187 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2188 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2191 error_report("Failed in parsing snapshot param '%s'",
2196 snapshot_name
= optarg
;
2203 sval
= cvtnum("buffer size for sparse output", optarg
);
2206 } else if (!QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2207 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2208 error_report("Invalid buffer size for sparse output specified. "
2209 "Valid sizes are multiples of %llu up to %llu. Select "
2210 "0 to disable sparse detection (fully allocates output).",
2211 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2215 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2216 explict_min_sparse
= true;
2235 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2236 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2237 error_report("Invalid number of coroutines. Allowed number of"
2238 " coroutines is between 1 and %d", MAX_COROUTINES
);
2243 s
.wr_in_order
= false;
2248 case OPTION_OBJECT
: {
2249 QemuOpts
*object_opts
;
2250 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2257 case OPTION_IMAGE_OPTS
:
2260 case OPTION_SALVAGE
:
2263 case OPTION_TARGET_IMAGE_OPTS
:
2264 tgt_image_opts
= true;
2266 case OPTION_TARGET_IS_ZERO
:
2268 * The user asserting that the target is blank has the
2269 * same effect as the target driver supporting zero
2272 s
.has_zero_init
= true;
2277 if (!out_fmt
&& !tgt_image_opts
) {
2281 if (qemu_opts_foreach(&qemu_object_opts
,
2282 user_creatable_add_opts_foreach
,
2283 qemu_img_object_print_help
, &error_fatal
)) {
2287 if (s
.compressed
&& s
.copy_range
) {
2288 error_report("Cannot enable copy offloading when -c is used");
2292 if (explict_min_sparse
&& s
.copy_range
) {
2293 error_report("Cannot enable copy offloading when -S is used");
2297 if (s
.copy_range
&& s
.salvage
) {
2298 error_report("Cannot use copy offloading in salvaging mode");
2302 if (tgt_image_opts
&& !skip_create
) {
2303 error_report("--target-image-opts requires use of -n flag");
2307 if (skip_create
&& options
) {
2308 warn_report("-o has no effect when skipping image creation");
2309 warn_report("This will become an error in future QEMU versions.");
2312 if (s
.has_zero_init
&& !skip_create
) {
2313 error_report("--target-is-zero requires use of -n flag");
2317 s
.src_num
= argc
- optind
- 1;
2318 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2320 if (options
&& has_help_option(options
)) {
2322 ret
= print_block_option_help(out_filename
, out_fmt
);
2325 error_report("Option help requires a format be specified");
2330 if (s
.src_num
< 1) {
2331 error_report("Must specify image file name");
2336 /* ret is still -EINVAL until here */
2337 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2339 error_report("Invalid source cache option: %s", src_cache
);
2343 /* Initialize before goto out */
2347 qemu_progress_init(progress
, 1.0);
2348 qemu_progress_print(0, 100);
2350 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2351 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2353 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2354 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2355 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2361 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2362 if (s
.src_sectors
[bs_i
] < 0) {
2363 error_report("Could not get size of %s: %s",
2364 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2368 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2372 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2373 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2374 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2376 } else if (snapshot_name
!= NULL
) {
2377 if (s
.src_num
> 1) {
2378 error_report("No support for concatenating multiple snapshot");
2383 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2387 error_reportf_err(local_err
, "Failed to load snapshot: ");
2393 /* Find driver and parse its options */
2394 drv
= bdrv_find_format(out_fmt
);
2396 error_report("Unknown file format '%s'", out_fmt
);
2401 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2403 error_report_err(local_err
);
2408 if (!drv
->create_opts
) {
2409 error_report("Format driver '%s' does not support image creation",
2415 if (!proto_drv
->create_opts
) {
2416 error_report("Protocol driver '%s' does not support image creation",
2417 proto_drv
->format_name
);
2422 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2423 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2425 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2427 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2429 error_report_err(local_err
);
2435 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2437 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2443 /* Get backing file name if -o backing_file was used */
2444 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2445 if (out_baseimg_param
) {
2446 out_baseimg
= out_baseimg_param
;
2448 s
.target_has_backing
= (bool) out_baseimg
;
2450 if (s
.has_zero_init
&& s
.target_has_backing
) {
2451 error_report("Cannot use --target-is-zero when the destination "
2452 "image has a backing file");
2456 if (s
.src_num
> 1 && out_baseimg
) {
2457 error_report("Having a backing file for the target makes no sense when "
2458 "concatenating multiple input images");
2463 /* Check if compression is supported */
2466 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2467 const char *encryptfmt
=
2468 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2469 const char *preallocation
=
2470 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2472 if (drv
&& !block_driver_can_compress(drv
)) {
2473 error_report("Compression not supported for this file format");
2478 if (encryption
|| encryptfmt
) {
2479 error_report("Compression and encryption not supported at "
2486 && strcmp(preallocation
, "off"))
2488 error_report("Compression and preallocation not supported at "
2496 * The later open call will need any decryption secrets, and
2497 * bdrv_create() will purge "opts", so extract them now before
2501 open_opts
= qdict_new();
2502 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2506 /* Create the new image */
2507 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2509 error_reportf_err(local_err
, "%s: error while converting %s: ",
2510 out_filename
, out_fmt
);
2515 s
.target_is_new
= !skip_create
;
2517 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2518 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2520 error_report("Invalid cache option: %s", cache
);
2525 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2526 flags
, writethrough
, s
.quiet
, false);
2528 /* TODO ultimately we should allow --target-image-opts
2529 * to be used even when -n is not given.
2530 * That has to wait for bdrv_create to be improved
2531 * to allow filenames in option syntax
2533 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2534 flags
, writethrough
, s
.quiet
, false);
2535 open_opts
= NULL
; /* blk_new_open will have freed it */
2541 out_bs
= blk_bs(s
.target
);
2543 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2544 error_report("Compression not supported for this file format");
2549 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2550 * or discard_alignment of the out_bs is greater. Limit to
2551 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2552 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2554 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2555 out_bs
->bl
.pdiscard_alignment
>>
2556 BDRV_SECTOR_BITS
)));
2558 /* try to align the write requests to the destination to avoid unnecessary
2560 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2561 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2563 assert(is_power_of_2(s
.alignment
));
2566 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2567 if (output_sectors
< 0) {
2568 error_report("unable to get output image length: %s",
2569 strerror(-output_sectors
));
2572 } else if (output_sectors
< s
.total_sectors
) {
2573 error_report("output file is smaller than input file");
2579 if (s
.target_has_backing
&& s
.target_is_new
) {
2580 /* Errors are treated as "backing length unknown" (which means
2581 * s.target_backing_sectors has to be negative, which it will
2582 * be automatically). The backing file length is used only
2583 * for optimizations, so such a case is not fatal. */
2584 s
.target_backing_sectors
= bdrv_nb_sectors(out_bs
->backing
->bs
);
2586 s
.target_backing_sectors
= -1;
2589 ret
= bdrv_get_info(out_bs
, &bdi
);
2592 error_report("could not get block driver info");
2596 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2597 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2598 s
.unallocated_blocks_are_zero
= bdi
.unallocated_blocks_are_zero
;
2601 ret
= convert_do_copy(&s
);
2604 qemu_progress_print(100, 0);
2606 qemu_progress_end();
2607 qemu_opts_del(opts
);
2608 qemu_opts_free(create_opts
);
2609 qemu_opts_del(sn_opts
);
2610 qobject_unref(open_opts
);
2611 blk_unref(s
.target
);
2613 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2614 blk_unref(s
.src
[bs_i
]);
2618 g_free(s
.src_sectors
);
2626 static void dump_snapshots(BlockDriverState
*bs
)
2628 QEMUSnapshotInfo
*sn_tab
, *sn
;
2631 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2634 printf("Snapshot list:\n");
2635 bdrv_snapshot_dump(NULL
);
2637 for(i
= 0; i
< nb_sns
; i
++) {
2639 bdrv_snapshot_dump(sn
);
2645 static void dump_json_image_info_list(ImageInfoList
*list
)
2649 Visitor
*v
= qobject_output_visitor_new(&obj
);
2651 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2652 visit_complete(v
, &obj
);
2653 str
= qobject_to_json_pretty(obj
);
2654 assert(str
!= NULL
);
2655 printf("%s\n", qstring_get_str(str
));
2661 static void dump_json_image_info(ImageInfo
*info
)
2665 Visitor
*v
= qobject_output_visitor_new(&obj
);
2667 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2668 visit_complete(v
, &obj
);
2669 str
= qobject_to_json_pretty(obj
);
2670 assert(str
!= NULL
);
2671 printf("%s\n", qstring_get_str(str
));
2677 static void dump_human_image_info_list(ImageInfoList
*list
)
2679 ImageInfoList
*elem
;
2682 for (elem
= list
; elem
; elem
= elem
->next
) {
2688 bdrv_image_info_dump(elem
->value
);
2692 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2694 return strcmp(a
, b
) == 0;
2698 * Open an image file chain and return an ImageInfoList
2700 * @filename: topmost image filename
2701 * @fmt: topmost image format (may be NULL to autodetect)
2702 * @chain: true - enumerate entire backing file chain
2703 * false - only topmost image file
2705 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2706 * image file. If there was an error a message will have been printed to
2709 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2710 const char *filename
,
2712 bool chain
, bool force_share
)
2714 ImageInfoList
*head
= NULL
;
2715 ImageInfoList
**last
= &head
;
2716 GHashTable
*filenames
;
2719 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2723 BlockDriverState
*bs
;
2725 ImageInfoList
*elem
;
2727 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2728 error_report("Backing file '%s' creates an infinite loop.",
2732 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2734 blk
= img_open(image_opts
, filename
, fmt
,
2735 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2742 bdrv_query_image_info(bs
, &info
, &err
);
2744 error_report_err(err
);
2749 elem
= g_new0(ImageInfoList
, 1);
2756 /* Clear parameters that only apply to the topmost image */
2757 filename
= fmt
= NULL
;
2761 if (info
->has_full_backing_filename
) {
2762 filename
= info
->full_backing_filename
;
2763 } else if (info
->has_backing_filename
) {
2764 error_report("Could not determine absolute backing filename,"
2765 " but backing filename '%s' present",
2766 info
->backing_filename
);
2769 if (info
->has_backing_filename_format
) {
2770 fmt
= info
->backing_filename_format
;
2774 g_hash_table_destroy(filenames
);
2778 qapi_free_ImageInfoList(head
);
2779 g_hash_table_destroy(filenames
);
2783 static int img_info(int argc
, char **argv
)
2786 OutputFormat output_format
= OFORMAT_HUMAN
;
2788 const char *filename
, *fmt
, *output
;
2789 ImageInfoList
*list
;
2790 bool image_opts
= false;
2791 bool force_share
= false;
2796 int option_index
= 0;
2797 static const struct option long_options
[] = {
2798 {"help", no_argument
, 0, 'h'},
2799 {"format", required_argument
, 0, 'f'},
2800 {"output", required_argument
, 0, OPTION_OUTPUT
},
2801 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2802 {"object", required_argument
, 0, OPTION_OBJECT
},
2803 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2804 {"force-share", no_argument
, 0, 'U'},
2807 c
= getopt_long(argc
, argv
, ":f:hU",
2808 long_options
, &option_index
);
2814 missing_argument(argv
[optind
- 1]);
2817 unrecognized_option(argv
[optind
- 1]);
2831 case OPTION_BACKING_CHAIN
:
2834 case OPTION_OBJECT
: {
2836 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2842 case OPTION_IMAGE_OPTS
:
2847 if (optind
!= argc
- 1) {
2848 error_exit("Expecting one image file name");
2850 filename
= argv
[optind
++];
2852 if (output
&& !strcmp(output
, "json")) {
2853 output_format
= OFORMAT_JSON
;
2854 } else if (output
&& !strcmp(output
, "human")) {
2855 output_format
= OFORMAT_HUMAN
;
2856 } else if (output
) {
2857 error_report("--output must be used with human or json as argument.");
2861 if (qemu_opts_foreach(&qemu_object_opts
,
2862 user_creatable_add_opts_foreach
,
2863 qemu_img_object_print_help
, &error_fatal
)) {
2867 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2873 switch (output_format
) {
2875 dump_human_image_info_list(list
);
2879 dump_json_image_info_list(list
);
2881 dump_json_image_info(list
->value
);
2886 qapi_free_ImageInfoList(list
);
2890 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2893 switch (output_format
) {
2895 if (e
->data
&& !e
->has_offset
) {
2896 error_report("File contains external, encrypted or compressed clusters.");
2899 if (e
->data
&& !e
->zero
) {
2900 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2901 e
->start
, e
->length
,
2902 e
->has_offset
? e
->offset
: 0,
2903 e
->has_filename
? e
->filename
: "");
2905 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2906 * Modify the flags here to allow more coalescing.
2908 if (next
&& (!next
->data
|| next
->zero
)) {
2914 printf("{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2915 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2916 e
->start
, e
->length
, e
->depth
,
2917 e
->zero
? "true" : "false",
2918 e
->data
? "true" : "false");
2919 if (e
->has_offset
) {
2920 printf(", \"offset\": %"PRId64
"", e
->offset
);
2932 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
2933 int64_t bytes
, MapEntry
*e
)
2937 BlockDriverState
*file
;
2940 char *filename
= NULL
;
2942 /* As an optimization, we could cache the current range of unallocated
2943 * clusters in each file of the chain, and avoid querying the same
2949 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
2954 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2957 bs
= backing_bs(bs
);
2966 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2968 if (file
&& has_offset
) {
2969 bdrv_refresh_filename(file
);
2970 filename
= file
->filename
;
2976 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2977 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2979 .has_offset
= has_offset
,
2981 .has_filename
= filename
,
2982 .filename
= filename
,
2988 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2990 if (curr
->length
== 0) {
2993 if (curr
->zero
!= next
->zero
||
2994 curr
->data
!= next
->data
||
2995 curr
->depth
!= next
->depth
||
2996 curr
->has_filename
!= next
->has_filename
||
2997 curr
->has_offset
!= next
->has_offset
) {
3000 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
3003 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
3009 static int img_map(int argc
, char **argv
)
3012 OutputFormat output_format
= OFORMAT_HUMAN
;
3014 BlockDriverState
*bs
;
3015 const char *filename
, *fmt
, *output
;
3017 MapEntry curr
= { .length
= 0 }, next
;
3019 bool image_opts
= false;
3020 bool force_share
= false;
3021 int64_t start_offset
= 0;
3022 int64_t max_length
= -1;
3027 int option_index
= 0;
3028 static const struct option long_options
[] = {
3029 {"help", no_argument
, 0, 'h'},
3030 {"format", required_argument
, 0, 'f'},
3031 {"output", required_argument
, 0, OPTION_OUTPUT
},
3032 {"object", required_argument
, 0, OPTION_OBJECT
},
3033 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3034 {"force-share", no_argument
, 0, 'U'},
3035 {"start-offset", required_argument
, 0, 's'},
3036 {"max-length", required_argument
, 0, 'l'},
3039 c
= getopt_long(argc
, argv
, ":f:s:l:hU",
3040 long_options
, &option_index
);
3046 missing_argument(argv
[optind
- 1]);
3049 unrecognized_option(argv
[optind
- 1]);
3064 start_offset
= cvtnum("start offset", optarg
);
3065 if (start_offset
< 0) {
3070 max_length
= cvtnum("max length", optarg
);
3071 if (max_length
< 0) {
3075 case OPTION_OBJECT
: {
3077 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3083 case OPTION_IMAGE_OPTS
:
3088 if (optind
!= argc
- 1) {
3089 error_exit("Expecting one image file name");
3091 filename
= argv
[optind
];
3093 if (output
&& !strcmp(output
, "json")) {
3094 output_format
= OFORMAT_JSON
;
3095 } else if (output
&& !strcmp(output
, "human")) {
3096 output_format
= OFORMAT_HUMAN
;
3097 } else if (output
) {
3098 error_report("--output must be used with human or json as argument.");
3102 if (qemu_opts_foreach(&qemu_object_opts
,
3103 user_creatable_add_opts_foreach
,
3104 qemu_img_object_print_help
, &error_fatal
)) {
3108 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3114 if (output_format
== OFORMAT_HUMAN
) {
3115 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3116 } else if (output_format
== OFORMAT_JSON
) {
3120 length
= blk_getlength(blk
);
3122 error_report("Failed to get size for '%s'", filename
);
3125 if (max_length
!= -1) {
3126 length
= MIN(start_offset
+ max_length
, length
);
3129 curr
.start
= start_offset
;
3130 while (curr
.start
+ curr
.length
< length
) {
3131 int64_t offset
= curr
.start
+ curr
.length
;
3134 /* Probe up to 1 GiB at a time. */
3135 n
= MIN(1 * GiB
, length
- offset
);
3136 ret
= get_block_status(bs
, offset
, n
, &next
);
3139 error_report("Could not read file metadata: %s", strerror(-ret
));
3143 if (entry_mergeable(&curr
, &next
)) {
3144 curr
.length
+= next
.length
;
3148 if (curr
.length
> 0) {
3149 ret
= dump_map_entry(output_format
, &curr
, &next
);
3157 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3158 if (output_format
== OFORMAT_JSON
) {
3167 #define SNAPSHOT_LIST 1
3168 #define SNAPSHOT_CREATE 2
3169 #define SNAPSHOT_APPLY 3
3170 #define SNAPSHOT_DELETE 4
3172 static int img_snapshot(int argc
, char **argv
)
3175 BlockDriverState
*bs
;
3176 QEMUSnapshotInfo sn
;
3177 char *filename
, *snapshot_name
= NULL
;
3178 int c
, ret
= 0, bdrv_oflags
;
3183 bool image_opts
= false;
3184 bool force_share
= false;
3186 bdrv_oflags
= BDRV_O_RDWR
;
3187 /* Parse commandline parameters */
3189 static const struct option long_options
[] = {
3190 {"help", no_argument
, 0, 'h'},
3191 {"object", required_argument
, 0, OPTION_OBJECT
},
3192 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3193 {"force-share", no_argument
, 0, 'U'},
3196 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3197 long_options
, NULL
);
3203 missing_argument(argv
[optind
- 1]);
3206 unrecognized_option(argv
[optind
- 1]);
3213 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3216 action
= SNAPSHOT_LIST
;
3217 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3221 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3224 action
= SNAPSHOT_APPLY
;
3225 snapshot_name
= optarg
;
3229 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3232 action
= SNAPSHOT_CREATE
;
3233 snapshot_name
= optarg
;
3237 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3240 action
= SNAPSHOT_DELETE
;
3241 snapshot_name
= optarg
;
3249 case OPTION_OBJECT
: {
3251 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3257 case OPTION_IMAGE_OPTS
:
3263 if (optind
!= argc
- 1) {
3264 error_exit("Expecting one image file name");
3266 filename
= argv
[optind
++];
3268 if (qemu_opts_foreach(&qemu_object_opts
,
3269 user_creatable_add_opts_foreach
,
3270 qemu_img_object_print_help
, &error_fatal
)) {
3274 /* Open the image */
3275 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3282 /* Perform the requested action */
3288 case SNAPSHOT_CREATE
:
3289 memset(&sn
, 0, sizeof(sn
));
3290 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3292 qemu_gettimeofday(&tv
);
3293 sn
.date_sec
= tv
.tv_sec
;
3294 sn
.date_nsec
= tv
.tv_usec
* 1000;
3296 ret
= bdrv_snapshot_create(bs
, &sn
);
3298 error_report("Could not create snapshot '%s': %d (%s)",
3299 snapshot_name
, ret
, strerror(-ret
));
3303 case SNAPSHOT_APPLY
:
3304 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3306 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3311 case SNAPSHOT_DELETE
:
3312 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3314 error_report("Could not delete snapshot '%s': snapshot not "
3315 "found", snapshot_name
);
3318 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3320 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3336 static int img_rebase(int argc
, char **argv
)
3338 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3339 uint8_t *buf_old
= NULL
;
3340 uint8_t *buf_new
= NULL
;
3341 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3343 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3344 int c
, flags
, src_flags
, ret
;
3345 bool writethrough
, src_writethrough
;
3347 bool force_share
= false;
3350 Error
*local_err
= NULL
;
3351 bool image_opts
= false;
3353 /* Parse commandline parameters */
3355 cache
= BDRV_DEFAULT_CACHE
;
3356 src_cache
= BDRV_DEFAULT_CACHE
;
3360 static const struct option long_options
[] = {
3361 {"help", no_argument
, 0, 'h'},
3362 {"object", required_argument
, 0, OPTION_OBJECT
},
3363 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3364 {"force-share", no_argument
, 0, 'U'},
3367 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3368 long_options
, NULL
);
3374 missing_argument(argv
[optind
- 1]);
3377 unrecognized_option(argv
[optind
- 1]);
3386 out_basefmt
= optarg
;
3389 out_baseimg
= optarg
;
3406 case OPTION_OBJECT
: {
3408 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3414 case OPTION_IMAGE_OPTS
:
3427 if (optind
!= argc
- 1) {
3428 error_exit("Expecting one image file name");
3430 if (!unsafe
&& !out_baseimg
) {
3431 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3433 filename
= argv
[optind
++];
3435 if (qemu_opts_foreach(&qemu_object_opts
,
3436 user_creatable_add_opts_foreach
,
3437 qemu_img_object_print_help
, &error_fatal
)) {
3441 qemu_progress_init(progress
, 2.0);
3442 qemu_progress_print(0, 100);
3444 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3445 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3447 error_report("Invalid cache option: %s", cache
);
3452 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3454 error_report("Invalid source cache option: %s", src_cache
);
3458 /* The source files are opened read-only, don't care about WCE */
3459 assert((src_flags
& BDRV_O_RDWR
) == 0);
3460 (void) src_writethrough
;
3465 * Ignore the old backing file for unsafe rebase in case we want to correct
3466 * the reference to a renamed or moved backing file.
3468 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3476 if (out_basefmt
!= NULL
) {
3477 if (bdrv_find_format(out_basefmt
) == NULL
) {
3478 error_report("Invalid format name: '%s'", out_basefmt
);
3484 /* For safe rebasing we need to compare old and new backing file */
3486 QDict
*options
= NULL
;
3487 BlockDriverState
*base_bs
= backing_bs(bs
);
3490 blk_old_backing
= blk_new(qemu_get_aio_context(),
3491 BLK_PERM_CONSISTENT_READ
,
3493 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3496 error_reportf_err(local_err
,
3497 "Could not reuse old backing file '%s': ",
3502 blk_old_backing
= NULL
;
3505 if (out_baseimg
[0]) {
3506 const char *overlay_filename
;
3507 char *out_real_path
;
3509 options
= qdict_new();
3511 qdict_put_str(options
, "driver", out_basefmt
);
3514 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3517 bdrv_refresh_filename(bs
);
3518 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3521 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3525 qobject_unref(options
);
3526 error_reportf_err(local_err
,
3527 "Could not resolve backing filename: ");
3533 * Find out whether we rebase an image on top of a previous image
3536 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3537 if (prefix_chain_bs
) {
3538 qobject_unref(options
);
3539 g_free(out_real_path
);
3541 blk_new_backing
= blk_new(qemu_get_aio_context(),
3542 BLK_PERM_CONSISTENT_READ
,
3544 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3547 error_reportf_err(local_err
,
3548 "Could not reuse backing file '%s': ",
3553 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3554 options
, src_flags
, &local_err
);
3555 g_free(out_real_path
);
3556 if (!blk_new_backing
) {
3557 error_reportf_err(local_err
,
3558 "Could not open new backing file '%s': ",
3568 * Check each unallocated cluster in the COW file. If it is unallocated,
3569 * accesses go to the backing file. We must therefore compare this cluster
3570 * in the old and new backing file, and if they differ we need to copy it
3571 * from the old backing file into the COW file.
3573 * If qemu-img crashes during this step, no harm is done. The content of
3574 * the image is the same as the original one at any time.
3578 int64_t old_backing_size
= 0;
3579 int64_t new_backing_size
= 0;
3582 float local_progress
= 0;
3584 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3585 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3587 size
= blk_getlength(blk
);
3589 error_report("Could not get size of '%s': %s",
3590 filename
, strerror(-size
));
3594 if (blk_old_backing
) {
3595 old_backing_size
= blk_getlength(blk_old_backing
);
3596 if (old_backing_size
< 0) {
3597 char backing_name
[PATH_MAX
];
3599 bdrv_get_backing_filename(bs
, backing_name
,
3600 sizeof(backing_name
));
3601 error_report("Could not get size of '%s': %s",
3602 backing_name
, strerror(-old_backing_size
));
3607 if (blk_new_backing
) {
3608 new_backing_size
= blk_getlength(blk_new_backing
);
3609 if (new_backing_size
< 0) {
3610 error_report("Could not get size of '%s': %s",
3611 out_baseimg
, strerror(-new_backing_size
));
3618 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3621 for (offset
= 0; offset
< size
; offset
+= n
) {
3622 bool buf_old_is_zero
= false;
3624 /* How many bytes can we handle with the next read? */
3625 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3627 /* If the cluster is allocated, we don't need to take action */
3628 ret
= bdrv_is_allocated(bs
, offset
, n
, &n
);
3630 error_report("error while reading image metadata: %s",
3638 if (prefix_chain_bs
) {
3640 * If cluster wasn't changed since prefix_chain, we don't need
3643 ret
= bdrv_is_allocated_above(backing_bs(bs
), prefix_chain_bs
,
3644 false, offset
, n
, &n
);
3646 error_report("error while reading image metadata: %s",
3656 * Read old and new backing file and take into consideration that
3657 * backing files may be smaller than the COW image.
3659 if (offset
>= old_backing_size
) {
3660 memset(buf_old
, 0, n
);
3661 buf_old_is_zero
= true;
3663 if (offset
+ n
> old_backing_size
) {
3664 n
= old_backing_size
- offset
;
3667 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3669 error_report("error while reading from old backing file");
3674 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3675 memset(buf_new
, 0, n
);
3677 if (offset
+ n
> new_backing_size
) {
3678 n
= new_backing_size
- offset
;
3681 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3683 error_report("error while reading from new backing file");
3688 /* If they differ, we need to write to the COW file */
3689 uint64_t written
= 0;
3691 while (written
< n
) {
3694 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3695 n
- written
, &pnum
))
3697 if (buf_old_is_zero
) {
3698 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3700 ret
= blk_pwrite(blk
, offset
+ written
,
3701 buf_old
+ written
, pnum
, 0);
3704 error_report("Error while writing to COW image: %s",
3712 qemu_progress_print(local_progress
, 100);
3717 * Change the backing file. All clusters that are different from the old
3718 * backing file are overwritten in the COW file now, so the visible content
3719 * doesn't change when we switch the backing file.
3721 if (out_baseimg
&& *out_baseimg
) {
3722 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3724 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3727 if (ret
== -ENOSPC
) {
3728 error_report("Could not change the backing file to '%s': No "
3729 "space left in the file header", out_baseimg
);
3730 } else if (ret
< 0) {
3731 error_report("Could not change the backing file to '%s': %s",
3732 out_baseimg
, strerror(-ret
));
3735 qemu_progress_print(100, 0);
3737 * TODO At this point it is possible to check if any clusters that are
3738 * allocated in the COW file are the same in the backing file. If so, they
3739 * could be dropped from the COW file. Don't do this before switching the
3740 * backing file, in case of a crash this would lead to corruption.
3743 qemu_progress_end();
3746 blk_unref(blk_old_backing
);
3747 blk_unref(blk_new_backing
);
3749 qemu_vfree(buf_old
);
3750 qemu_vfree(buf_new
);
3759 static int img_resize(int argc
, char **argv
)
3762 int c
, ret
, relative
;
3763 const char *filename
, *fmt
, *size
;
3764 int64_t n
, total_size
, current_size
;
3766 BlockBackend
*blk
= NULL
;
3767 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3770 static QemuOptsList resize_options
= {
3771 .name
= "resize_options",
3772 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3775 .name
= BLOCK_OPT_SIZE
,
3776 .type
= QEMU_OPT_SIZE
,
3777 .help
= "Virtual disk size"
3783 bool image_opts
= false;
3784 bool shrink
= false;
3786 /* Remove size from argv manually so that negative numbers are not treated
3787 * as options by getopt. */
3789 error_exit("Not enough arguments");
3793 size
= argv
[--argc
];
3795 /* Parse getopt arguments */
3798 static const struct option long_options
[] = {
3799 {"help", no_argument
, 0, 'h'},
3800 {"object", required_argument
, 0, OPTION_OBJECT
},
3801 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3802 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3803 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3806 c
= getopt_long(argc
, argv
, ":f:hq",
3807 long_options
, NULL
);
3813 missing_argument(argv
[optind
- 1]);
3816 unrecognized_option(argv
[optind
- 1]);
3827 case OPTION_OBJECT
: {
3829 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3835 case OPTION_IMAGE_OPTS
:
3838 case OPTION_PREALLOCATION
:
3839 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3840 PREALLOC_MODE__MAX
, NULL
);
3841 if (prealloc
== PREALLOC_MODE__MAX
) {
3842 error_report("Invalid preallocation mode '%s'", optarg
);
3851 if (optind
!= argc
- 1) {
3852 error_exit("Expecting image file name and size");
3854 filename
= argv
[optind
++];
3856 if (qemu_opts_foreach(&qemu_object_opts
,
3857 user_creatable_add_opts_foreach
,
3858 qemu_img_object_print_help
, &error_fatal
)) {
3862 /* Choose grow, shrink, or absolute resize mode */
3878 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3879 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3881 error_report_err(err
);
3883 qemu_opts_del(param
);
3886 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3887 qemu_opts_del(param
);
3889 blk
= img_open(image_opts
, filename
, fmt
,
3890 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3897 current_size
= blk_getlength(blk
);
3898 if (current_size
< 0) {
3899 error_report("Failed to inquire current image length: %s",
3900 strerror(-current_size
));
3906 total_size
= current_size
+ n
* relative
;
3910 if (total_size
<= 0) {
3911 error_report("New image size must be positive");
3916 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3917 error_report("Preallocation can only be used for growing images");
3922 if (total_size
< current_size
&& !shrink
) {
3923 warn_report("Shrinking an image will delete all data beyond the "
3924 "shrunken image's end. Before performing such an "
3925 "operation, make sure there is no important data there.");
3927 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk
)), "raw") != 0) {
3929 "Use the --shrink option to perform a shrink operation.");
3933 warn_report("Using the --shrink option will suppress this message. "
3934 "Note that future versions of qemu-img may refuse to "
3935 "shrink images without this option.");
3940 * The user expects the image to have the desired size after
3941 * resizing, so pass @exact=true. It is of no use to report
3942 * success when the image has not actually been resized.
3944 ret
= blk_truncate(blk
, total_size
, true, prealloc
, 0, &err
);
3946 qprintf(quiet
, "Image resized.\n");
3948 error_report_err(err
);
3958 static void amend_status_cb(BlockDriverState
*bs
,
3959 int64_t offset
, int64_t total_work_size
,
3962 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3965 static int print_amend_option_help(const char *format
)
3969 /* Find driver and parse its options */
3970 drv
= bdrv_find_format(format
);
3972 error_report("Unknown file format '%s'", format
);
3976 if (!drv
->bdrv_amend_options
) {
3977 error_report("Format driver '%s' does not support option amendment",
3982 /* Every driver supporting amendment must have create_opts */
3983 assert(drv
->create_opts
);
3985 printf("Creation options for '%s':\n", format
);
3986 qemu_opts_print_help(drv
->create_opts
, false);
3987 printf("\nNote that not all of these options may be amendable.\n");
3991 static int img_amend(int argc
, char **argv
)
3995 char *options
= NULL
;
3996 QemuOptsList
*create_opts
= NULL
;
3997 QemuOpts
*opts
= NULL
;
3998 const char *fmt
= NULL
, *filename
, *cache
;
4001 bool quiet
= false, progress
= false;
4002 BlockBackend
*blk
= NULL
;
4003 BlockDriverState
*bs
= NULL
;
4004 bool image_opts
= false;
4006 cache
= BDRV_DEFAULT_CACHE
;
4008 static const struct option long_options
[] = {
4009 {"help", no_argument
, 0, 'h'},
4010 {"object", required_argument
, 0, OPTION_OBJECT
},
4011 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4014 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
4015 long_options
, NULL
);
4022 missing_argument(argv
[optind
- 1]);
4025 unrecognized_option(argv
[optind
- 1]);
4031 if (accumulate_options(&options
, optarg
) < 0) {
4033 goto out_no_progress
;
4049 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4053 goto out_no_progress
;
4056 case OPTION_IMAGE_OPTS
:
4063 error_exit("Must specify options (-o)");
4066 if (qemu_opts_foreach(&qemu_object_opts
,
4067 user_creatable_add_opts_foreach
,
4068 qemu_img_object_print_help
, &error_fatal
)) {
4070 goto out_no_progress
;
4076 qemu_progress_init(progress
, 1.0);
4078 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
4079 if (fmt
&& has_help_option(options
)) {
4080 /* If a format is explicitly specified (and possibly no filename is
4081 * given), print option help here */
4082 ret
= print_amend_option_help(fmt
);
4086 if (optind
!= argc
- 1) {
4087 error_report("Expecting one image file name");
4092 flags
= BDRV_O_RDWR
;
4093 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
4095 error_report("Invalid cache option: %s", cache
);
4099 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4107 fmt
= bs
->drv
->format_name
;
4109 if (has_help_option(options
)) {
4110 /* If the format was auto-detected, print option help here */
4111 ret
= print_amend_option_help(fmt
);
4115 if (!bs
->drv
->bdrv_amend_options
) {
4116 error_report("Format driver '%s' does not support option amendment",
4122 /* Every driver supporting amendment must have create_opts */
4123 assert(bs
->drv
->create_opts
);
4125 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
4126 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4127 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
4129 error_report_err(err
);
4134 /* In case the driver does not call amend_status_cb() */
4135 qemu_progress_print(0.f
, 0);
4136 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, &err
);
4137 qemu_progress_print(100.f
, 0);
4139 error_report_err(err
);
4144 qemu_progress_end();
4148 qemu_opts_del(opts
);
4149 qemu_opts_free(create_opts
);
4158 typedef struct BenchData
{
4160 uint64_t image_size
;
4167 bool drain_on_flush
;
4176 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4179 error_report("Failed flush request: %s", strerror(-ret
));
4184 static void bench_cb(void *opaque
, int ret
)
4186 BenchData
*b
= opaque
;
4190 error_report("Failed request: %s", strerror(-ret
));
4195 /* Just finished a flush with drained queue: Start next requests */
4196 assert(b
->in_flight
== 0);
4197 b
->in_flush
= false;
4198 } else if (b
->in_flight
> 0) {
4199 int remaining
= b
->n
- b
->in_flight
;
4204 /* Time for flush? Drain queue if requested, then flush */
4205 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4206 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4207 BlockCompletionFunc
*cb
;
4209 if (b
->drain_on_flush
) {
4213 cb
= bench_undrained_flush_cb
;
4216 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4218 error_report("Failed to issue flush request");
4222 if (b
->drain_on_flush
) {
4228 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4229 int64_t offset
= b
->offset
;
4230 /* blk_aio_* might look for completed I/Os and kick bench_cb
4231 * again, so make sure this operation is counted by in_flight
4232 * and b->offset is ready for the next submission.
4235 b
->offset
+= b
->step
;
4236 b
->offset
%= b
->image_size
;
4238 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4240 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4243 error_report("Failed to issue request");
4249 static int img_bench(int argc
, char **argv
)
4252 const char *fmt
= NULL
, *filename
;
4254 bool image_opts
= false;
4255 bool is_write
= false;
4259 size_t bufsize
= 4096;
4262 int flush_interval
= 0;
4263 bool drain_on_flush
= true;
4265 BlockBackend
*blk
= NULL
;
4266 BenchData data
= {};
4268 bool writethrough
= false;
4269 struct timeval t1
, t2
;
4271 bool force_share
= false;
4275 static const struct option long_options
[] = {
4276 {"help", no_argument
, 0, 'h'},
4277 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4278 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4279 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4280 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4281 {"force-share", no_argument
, 0, 'U'},
4284 c
= getopt_long(argc
, argv
, ":hc:d:f:ni:o:qs:S:t:wU", long_options
,
4292 missing_argument(argv
[optind
- 1]);
4295 unrecognized_option(argv
[optind
- 1]);
4304 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4305 error_report("Invalid request count specified");
4315 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4316 error_report("Invalid queue depth specified");
4326 flags
|= BDRV_O_NATIVE_AIO
;
4329 ret
= bdrv_parse_aio(optarg
, &flags
);
4331 error_report("Invalid aio option: %s", optarg
);
4338 offset
= cvtnum("offset", optarg
);
4352 sval
= cvtnum_full("buffer size", optarg
, 0, INT_MAX
);
4364 sval
= cvtnum_full("step_size", optarg
, 0, INT_MAX
);
4373 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4375 error_report("Invalid cache mode");
4381 flags
|= BDRV_O_RDWR
;
4387 case OPTION_PATTERN
:
4391 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4392 error_report("Invalid pattern byte specified");
4398 case OPTION_FLUSH_INTERVAL
:
4402 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4403 error_report("Invalid flush interval specified");
4406 flush_interval
= res
;
4409 case OPTION_NO_DRAIN
:
4410 drain_on_flush
= false;
4412 case OPTION_IMAGE_OPTS
:
4418 if (optind
!= argc
- 1) {
4419 error_exit("Expecting one image file name");
4421 filename
= argv
[argc
- 1];
4423 if (!is_write
&& flush_interval
) {
4424 error_report("--flush-interval is only available in write tests");
4428 if (flush_interval
&& flush_interval
< depth
) {
4429 error_report("Flush interval can't be smaller than depth");
4434 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4441 image_size
= blk_getlength(blk
);
4442 if (image_size
< 0) {
4447 data
= (BenchData
) {
4449 .image_size
= image_size
,
4451 .step
= step
?: bufsize
,
4456 .flush_interval
= flush_interval
,
4457 .drain_on_flush
= drain_on_flush
,
4459 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4460 "(starting at offset %" PRId64
", step size %d)\n",
4461 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4462 data
.offset
, data
.step
);
4463 if (flush_interval
) {
4464 printf("Sending flush every %d requests\n", flush_interval
);
4467 buf_size
= data
.nrreq
* data
.bufsize
;
4468 data
.buf
= blk_blockalign(blk
, buf_size
);
4469 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4471 blk_register_buf(blk
, data
.buf
, buf_size
);
4473 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4474 for (i
= 0; i
< data
.nrreq
; i
++) {
4475 qemu_iovec_init(&data
.qiov
[i
], 1);
4476 qemu_iovec_add(&data
.qiov
[i
],
4477 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4480 gettimeofday(&t1
, NULL
);
4483 while (data
.n
> 0) {
4484 main_loop_wait(false);
4486 gettimeofday(&t2
, NULL
);
4488 printf("Run completed in %3.3f seconds.\n",
4489 (t2
.tv_sec
- t1
.tv_sec
)
4490 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4494 blk_unregister_buf(blk
, data
.buf
);
4496 qemu_vfree(data
.buf
);
4517 int bsz
; /* Block size */
4525 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4529 static int img_dd_bs(const char *arg
,
4530 struct DdIo
*in
, struct DdIo
*out
,
4535 res
= cvtnum_full("bs", arg
, 1, INT_MAX
);
4540 in
->bsz
= out
->bsz
= res
;
4545 static int img_dd_count(const char *arg
,
4546 struct DdIo
*in
, struct DdIo
*out
,
4549 dd
->count
= cvtnum("count", arg
);
4551 if (dd
->count
< 0) {
4558 static int img_dd_if(const char *arg
,
4559 struct DdIo
*in
, struct DdIo
*out
,
4562 in
->filename
= g_strdup(arg
);
4567 static int img_dd_of(const char *arg
,
4568 struct DdIo
*in
, struct DdIo
*out
,
4571 out
->filename
= g_strdup(arg
);
4576 static int img_dd_skip(const char *arg
,
4577 struct DdIo
*in
, struct DdIo
*out
,
4580 in
->offset
= cvtnum("skip", arg
);
4582 if (in
->offset
< 0) {
4589 static int img_dd(int argc
, char **argv
)
4594 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4595 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4596 QemuOpts
*opts
= NULL
;
4597 QemuOptsList
*create_opts
= NULL
;
4598 Error
*local_err
= NULL
;
4599 bool image_opts
= false;
4601 const char *out_fmt
= "raw";
4602 const char *fmt
= NULL
;
4604 int64_t block_count
= 0, out_pos
, in_pos
;
4605 bool force_share
= false;
4606 struct DdInfo dd
= {
4611 .bsz
= 512, /* Block size is by default 512 bytes */
4623 const struct DdOpts options
[] = {
4624 { "bs", img_dd_bs
, C_BS
},
4625 { "count", img_dd_count
, C_COUNT
},
4626 { "if", img_dd_if
, C_IF
},
4627 { "of", img_dd_of
, C_OF
},
4628 { "skip", img_dd_skip
, C_SKIP
},
4631 const struct option long_options
[] = {
4632 { "help", no_argument
, 0, 'h'},
4633 { "object", required_argument
, 0, OPTION_OBJECT
},
4634 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4635 { "force-share", no_argument
, 0, 'U'},
4639 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4651 missing_argument(argv
[optind
- 1]);
4654 unrecognized_option(argv
[optind
- 1]);
4663 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4668 case OPTION_IMAGE_OPTS
:
4674 for (i
= optind
; i
< argc
; i
++) {
4676 arg
= g_strdup(argv
[i
]);
4678 tmp
= strchr(arg
, '=');
4680 error_report("unrecognized operand %s", arg
);
4687 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4688 if (!strcmp(arg
, options
[j
].name
)) {
4692 if (options
[j
].name
== NULL
) {
4693 error_report("unrecognized operand %s", arg
);
4698 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4702 dd
.flags
|= options
[j
].flag
;
4707 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4708 error_report("Must specify both input and output files");
4713 if (qemu_opts_foreach(&qemu_object_opts
,
4714 user_creatable_add_opts_foreach
,
4715 qemu_img_object_print_help
, &error_fatal
)) {
4720 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4728 drv
= bdrv_find_format(out_fmt
);
4730 error_report("Unknown file format");
4734 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4737 error_report_err(local_err
);
4741 if (!drv
->create_opts
) {
4742 error_report("Format driver '%s' does not support image creation",
4747 if (!proto_drv
->create_opts
) {
4748 error_report("Protocol driver '%s' does not support image creation",
4749 proto_drv
->format_name
);
4753 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4754 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4756 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4758 size
= blk_getlength(blk1
);
4760 error_report("Failed to get size for '%s'", in
.filename
);
4765 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4766 dd
.count
* in
.bsz
< size
) {
4767 size
= dd
.count
* in
.bsz
;
4770 /* Overflow means the specified offset is beyond input image's size */
4771 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4772 size
< in
.bsz
* in
.offset
)) {
4773 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4775 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4776 size
- in
.bsz
* in
.offset
, &error_abort
);
4779 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4781 error_reportf_err(local_err
,
4782 "%s: error while creating output image: ",
4788 /* TODO, we can't honour --image-opts for the target,
4789 * since it needs to be given in a format compatible
4790 * with the bdrv_create() call above which does not
4791 * support image-opts style.
4793 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
4794 false, false, false);
4801 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4802 size
< in
.offset
* in
.bsz
)) {
4803 /* We give a warning if the skip option is bigger than the input
4804 * size and create an empty output disk image (i.e. like dd(1)).
4806 error_report("%s: cannot skip to specified offset", in
.filename
);
4809 in_pos
= in
.offset
* in
.bsz
;
4812 in
.buf
= g_new(uint8_t, in
.bsz
);
4814 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4815 int in_ret
, out_ret
;
4817 if (in_pos
+ in
.bsz
> size
) {
4818 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4820 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4823 error_report("error while reading from input image file: %s",
4830 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4833 error_report("error while writing to output image file: %s",
4834 strerror(-out_ret
));
4843 qemu_opts_del(opts
);
4844 qemu_opts_free(create_opts
);
4847 g_free(in
.filename
);
4848 g_free(out
.filename
);
4858 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
4862 Visitor
*v
= qobject_output_visitor_new(&obj
);
4864 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
4865 visit_complete(v
, &obj
);
4866 str
= qobject_to_json_pretty(obj
);
4867 assert(str
!= NULL
);
4868 printf("%s\n", qstring_get_str(str
));
4874 static int img_measure(int argc
, char **argv
)
4876 static const struct option long_options
[] = {
4877 {"help", no_argument
, 0, 'h'},
4878 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4879 {"object", required_argument
, 0, OPTION_OBJECT
},
4880 {"output", required_argument
, 0, OPTION_OUTPUT
},
4881 {"size", required_argument
, 0, OPTION_SIZE
},
4882 {"force-share", no_argument
, 0, 'U'},
4885 OutputFormat output_format
= OFORMAT_HUMAN
;
4886 BlockBackend
*in_blk
= NULL
;
4888 const char *filename
= NULL
;
4889 const char *fmt
= NULL
;
4890 const char *out_fmt
= "raw";
4891 char *options
= NULL
;
4892 char *snapshot_name
= NULL
;
4893 bool force_share
= false;
4894 QemuOpts
*opts
= NULL
;
4895 QemuOpts
*object_opts
= NULL
;
4896 QemuOpts
*sn_opts
= NULL
;
4897 QemuOptsList
*create_opts
= NULL
;
4898 bool image_opts
= false;
4899 uint64_t img_size
= UINT64_MAX
;
4900 BlockMeasureInfo
*info
= NULL
;
4901 Error
*local_err
= NULL
;
4905 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
4906 long_options
, NULL
)) != -1) {
4919 if (accumulate_options(&options
, optarg
) < 0) {
4924 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
4925 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
4928 error_report("Failed in parsing snapshot param '%s'",
4933 snapshot_name
= optarg
;
4940 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4946 case OPTION_IMAGE_OPTS
:
4950 if (!strcmp(optarg
, "json")) {
4951 output_format
= OFORMAT_JSON
;
4952 } else if (!strcmp(optarg
, "human")) {
4953 output_format
= OFORMAT_HUMAN
;
4955 error_report("--output must be used with human or json "
4964 sval
= cvtnum("image size", optarg
);
4968 img_size
= (uint64_t)sval
;
4974 if (qemu_opts_foreach(&qemu_object_opts
,
4975 user_creatable_add_opts_foreach
,
4976 qemu_img_object_print_help
, &error_fatal
)) {
4980 if (argc
- optind
> 1) {
4981 error_report("At most one filename argument is allowed.");
4983 } else if (argc
- optind
== 1) {
4984 filename
= argv
[optind
];
4987 if (!filename
&& (image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
4988 error_report("--image-opts, -f, and -l require a filename argument.");
4991 if (filename
&& img_size
!= UINT64_MAX
) {
4992 error_report("--size N cannot be used together with a filename.");
4995 if (!filename
&& img_size
== UINT64_MAX
) {
4996 error_report("Either --size N or one filename must be specified.");
5001 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
5002 false, false, force_share
);
5008 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
5009 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
5010 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
5012 } else if (snapshot_name
!= NULL
) {
5013 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
5014 snapshot_name
, &local_err
);
5017 error_reportf_err(local_err
, "Failed to load snapshot: ");
5022 drv
= bdrv_find_format(out_fmt
);
5024 error_report("Unknown file format '%s'", out_fmt
);
5027 if (!drv
->create_opts
) {
5028 error_report("Format driver '%s' does not support image creation",
5033 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5034 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
5035 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5037 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
5039 error_report_err(local_err
);
5040 error_report("Invalid options for file format '%s'", out_fmt
);
5044 if (img_size
!= UINT64_MAX
) {
5045 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
5048 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
5050 error_report_err(local_err
);
5054 if (output_format
== OFORMAT_HUMAN
) {
5055 printf("required size: %" PRIu64
"\n", info
->required
);
5056 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
5058 dump_json_block_measure_info(info
);
5064 qapi_free_BlockMeasureInfo(info
);
5065 qemu_opts_del(object_opts
);
5066 qemu_opts_del(opts
);
5067 qemu_opts_del(sn_opts
);
5068 qemu_opts_free(create_opts
);
5074 static const img_cmd_t img_cmds
[] = {
5075 #define DEF(option, callback, arg_string) \
5076 { option, callback },
5077 #include "qemu-img-cmds.h"
5082 int main(int argc
, char **argv
)
5084 const img_cmd_t
*cmd
;
5085 const char *cmdname
;
5086 Error
*local_error
= NULL
;
5087 char *trace_file
= NULL
;
5089 static const struct option long_options
[] = {
5090 {"help", no_argument
, 0, 'h'},
5091 {"version", no_argument
, 0, 'V'},
5092 {"trace", required_argument
, NULL
, 'T'},
5097 signal(SIGPIPE
, SIG_IGN
);
5100 error_init(argv
[0]);
5101 module_call_init(MODULE_INIT_TRACE
);
5102 qemu_init_exec_dir(argv
[0]);
5104 if (qemu_init_main_loop(&local_error
)) {
5105 error_report_err(local_error
);
5109 qcrypto_init(&error_fatal
);
5111 module_call_init(MODULE_INIT_QOM
);
5114 error_exit("Not enough arguments");
5117 qemu_add_opts(&qemu_object_opts
);
5118 qemu_add_opts(&qemu_source_opts
);
5119 qemu_add_opts(&qemu_trace_opts
);
5121 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
5124 missing_argument(argv
[optind
- 1]);
5127 unrecognized_option(argv
[optind
- 1]);
5133 printf(QEMU_IMG_VERSION
);
5137 trace_file
= trace_opt_parse(optarg
);
5142 cmdname
= argv
[optind
];
5144 /* reset getopt_long scanning */
5150 qemu_reset_optind();
5152 if (!trace_init_backends()) {
5155 trace_init_file(trace_file
);
5156 qemu_set_log(LOG_TRACE
);
5158 /* find the command */
5159 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5160 if (!strcmp(cmdname
, cmd
->name
)) {
5161 return cmd
->handler(argc
, argv
);
5166 error_exit("Command not found: %s", cmdname
);