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-commands-block-core.h"
32 #include "qapi/qapi-visit-block-core.h"
33 #include "qapi/qobject-output-visitor.h"
34 #include "qapi/qmp/qjson.h"
35 #include "qapi/qmp/qdict.h"
36 #include "qapi/qmp/qstring.h"
37 #include "qemu/cutils.h"
38 #include "qemu/config-file.h"
39 #include "qemu/option.h"
40 #include "qemu/error-report.h"
42 #include "qemu/main-loop.h"
43 #include "qemu/module.h"
44 #include "qemu/sockets.h"
45 #include "qemu/units.h"
46 #include "qom/object_interfaces.h"
47 #include "sysemu/block-backend.h"
48 #include "block/block_int.h"
49 #include "block/blockjob.h"
50 #include "block/qapi.h"
51 #include "crypto/init.h"
52 #include "trace/control.h"
54 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
55 "\n" QEMU_COPYRIGHT "\n"
57 typedef struct img_cmd_t
{
59 int (*handler
)(int argc
, char **argv
);
64 OPTION_BACKING_CHAIN
= 257,
66 OPTION_IMAGE_OPTS
= 259,
68 OPTION_FLUSH_INTERVAL
= 261,
69 OPTION_NO_DRAIN
= 262,
70 OPTION_TARGET_IMAGE_OPTS
= 263,
72 OPTION_PREALLOCATION
= 265,
75 OPTION_TARGET_IS_ZERO
= 268,
86 typedef enum OutputFormat
{
91 /* Default to cache=writeback as data integrity is not important for qemu-img */
92 #define BDRV_DEFAULT_CACHE "writeback"
94 static void format_print(void *opaque
, const char *name
)
99 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
104 error_vreport(fmt
, ap
);
107 error_printf("Try 'qemu-img --help' for more information\n");
111 static void QEMU_NORETURN
missing_argument(const char *option
)
113 error_exit("missing argument for option '%s'", option
);
116 static void QEMU_NORETURN
unrecognized_option(const char *option
)
118 error_exit("unrecognized option '%s'", option
);
121 /* Please keep in synch with docs/tools/qemu-img.rst */
122 static void QEMU_NORETURN
help(void)
124 const char *help_msg
=
126 "usage: qemu-img [standard options] command [command options]\n"
127 "QEMU disk image utility\n"
129 " '-h', '--help' display this help and exit\n"
130 " '-V', '--version' output version information and exit\n"
131 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
132 " specify tracing options\n"
135 #define DEF(option, callback, arg_string) \
137 #include "qemu-img-cmds.h"
140 "Command parameters:\n"
141 " 'filename' is a disk image filename\n"
142 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
143 " manual page for a description of the object properties. The most common\n"
144 " object type is a 'secret', which is used to supply passwords and/or\n"
145 " encryption keys.\n"
146 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
147 " 'cache' is the cache mode used to write the output disk image, the valid\n"
148 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
149 " 'directsync' and 'unsafe' (default for convert)\n"
150 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
151 " options are the same as for the 'cache' option\n"
152 " 'size' is the disk image size in bytes. Optional suffixes\n"
153 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
154 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
155 " supported. 'b' is ignored.\n"
156 " 'output_filename' is the destination disk image filename\n"
157 " 'output_fmt' is the destination format\n"
158 " 'options' is a comma separated list of format specific options in a\n"
159 " name=value format. Use -o ? for an overview of the options supported by the\n"
161 " 'snapshot_param' is param used for internal snapshot, format\n"
162 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
164 " '-c' indicates that target image must be compressed (qcow format only)\n"
165 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
166 " new backing file match exactly. The image doesn't need a working\n"
167 " backing file before rebasing in this case (useful for renaming the\n"
168 " backing file). For image creation, allow creating without attempting\n"
169 " to open the backing file.\n"
170 " '-h' with or without a command shows this help and lists the supported formats\n"
171 " '-p' show progress of command (only certain commands)\n"
172 " '-q' use Quiet mode - do not print any output (except errors)\n"
173 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
174 " contain only zeros for qemu-img to create a sparse image during\n"
175 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
176 " unallocated or zero sectors, and the destination image will always be\n"
178 " '--output' takes the format in which the output must be done (human or json)\n"
179 " '-n' skips the target volume creation (useful if the volume is created\n"
180 " prior to running qemu-img)\n"
182 "Parameters to bitmap subcommand:\n"
183 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
184 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
185 " or '--merge source'\n"
186 " '-g granularity' sets the granularity for '--add' actions\n"
187 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
188 " bitmaps from an alternative file\n"
190 "Parameters to check subcommand:\n"
191 " '-r' tries to repair any inconsistencies that are found during the check.\n"
192 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
193 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
194 " hiding corruption that has already occurred.\n"
196 "Parameters to convert subcommand:\n"
197 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
198 " '-m' specifies how many coroutines work in parallel during the convert\n"
199 " process (defaults to 8)\n"
200 " '-W' allow to write to the target out of order rather than sequential\n"
202 "Parameters to snapshot subcommand:\n"
203 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
204 " '-a' applies a snapshot (revert disk to saved state)\n"
205 " '-c' creates a snapshot\n"
206 " '-d' deletes a snapshot\n"
207 " '-l' lists all snapshots in the given image\n"
209 "Parameters to compare subcommand:\n"
210 " '-f' first image format\n"
211 " '-F' second image format\n"
212 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
214 "Parameters to dd subcommand:\n"
215 " 'bs=BYTES' read and write up to BYTES bytes at a time "
217 " 'count=N' copy only N input blocks\n"
218 " 'if=FILE' read from FILE\n"
219 " 'of=FILE' write to FILE\n"
220 " 'skip=N' skip N bs-sized blocks at the start of input\n";
222 printf("%s\nSupported formats:", help_msg
);
223 bdrv_iterate_format(format_print
, NULL
, false);
224 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
228 static QemuOptsList qemu_object_opts
= {
230 .implied_opt_name
= "qom-type",
231 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
237 static bool qemu_img_object_print_help(const char *type
, QemuOpts
*opts
)
239 if (user_creatable_print_help(type
, opts
)) {
246 * Is @optarg safe for accumulate_options()?
247 * It is when multiple of them can be joined together separated by ','.
248 * To make that work, @optarg must not start with ',' (or else a
249 * separating ',' preceding it gets escaped), and it must not end with
250 * an odd number of ',' (or else a separating ',' following it gets
251 * escaped), or be empty (or else a separating ',' preceding it can
252 * escape a separating ',' following it).
255 static bool is_valid_option_list(const char *optarg
)
257 size_t len
= strlen(optarg
);
260 if (!optarg
[0] || optarg
[0] == ',') {
264 for (i
= len
; i
> 0 && optarg
[i
- 1] == ','; i
--) {
273 static int accumulate_options(char **options
, char *optarg
)
277 if (!is_valid_option_list(optarg
)) {
278 error_report("Invalid option list: %s", optarg
);
283 *options
= g_strdup(optarg
);
285 new_options
= g_strdup_printf("%s,%s", *options
, optarg
);
287 *options
= new_options
;
292 static QemuOptsList qemu_source_opts
= {
294 .implied_opt_name
= "file",
295 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
301 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
307 ret
= vprintf(fmt
, args
);
314 static int print_block_option_help(const char *filename
, const char *fmt
)
316 BlockDriver
*drv
, *proto_drv
;
317 QemuOptsList
*create_opts
= NULL
;
318 Error
*local_err
= NULL
;
320 /* Find driver and parse its options */
321 drv
= bdrv_find_format(fmt
);
323 error_report("Unknown file format '%s'", fmt
);
327 if (!drv
->create_opts
) {
328 error_report("Format driver '%s' does not support image creation", fmt
);
332 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
334 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
336 error_report_err(local_err
);
337 qemu_opts_free(create_opts
);
340 if (!proto_drv
->create_opts
) {
341 error_report("Protocol driver '%s' does not support image creation",
342 proto_drv
->format_name
);
343 qemu_opts_free(create_opts
);
346 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
350 printf("Supported options:\n");
352 printf("Supported %s options:\n", fmt
);
354 qemu_opts_print_help(create_opts
, false);
355 qemu_opts_free(create_opts
);
359 "The protocol level may support further options.\n"
360 "Specify the target filename to include those options.\n");
367 static BlockBackend
*img_open_opts(const char *optstr
,
368 QemuOpts
*opts
, int flags
, bool writethrough
,
369 bool quiet
, bool force_share
)
372 Error
*local_err
= NULL
;
374 options
= qemu_opts_to_qdict(opts
, NULL
);
376 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
377 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
378 error_report("--force-share/-U conflicts with image options");
379 qobject_unref(options
);
382 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
384 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
386 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
389 blk_set_enable_write_cache(blk
, !writethrough
);
394 static BlockBackend
*img_open_file(const char *filename
,
396 const char *fmt
, int flags
,
397 bool writethrough
, bool quiet
,
401 Error
*local_err
= NULL
;
404 options
= qdict_new();
407 qdict_put_str(options
, "driver", fmt
);
411 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
413 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
415 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
418 blk_set_enable_write_cache(blk
, !writethrough
);
424 static int img_add_key_secrets(void *opaque
,
425 const char *name
, const char *value
,
428 QDict
*options
= opaque
;
430 if (g_str_has_suffix(name
, "key-secret")) {
431 qdict_put_str(options
, name
, value
);
438 static BlockBackend
*img_open(bool image_opts
,
439 const char *filename
,
440 const char *fmt
, int flags
, bool writethrough
,
441 bool quiet
, bool force_share
)
447 error_report("--image-opts and --format are mutually exclusive");
450 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
455 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
458 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
465 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
466 const char *base_filename
,
467 const char *base_fmt
)
470 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
472 error_report("Backing file not supported for file format '%s'",
478 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
479 error_report("Backing file format not supported for file "
487 static int64_t cvtnum_full(const char *name
, const char *value
, int64_t min
,
493 err
= qemu_strtosz(value
, NULL
, &res
);
494 if (err
< 0 && err
!= -ERANGE
) {
495 error_report("Invalid %s specified. You may use "
496 "k, M, G, T, P or E suffixes for", name
);
497 error_report("kilobytes, megabytes, gigabytes, terabytes, "
498 "petabytes and exabytes.");
501 if (err
== -ERANGE
|| res
> max
|| res
< min
) {
502 error_report("Invalid %s specified. Must be between %" PRId64
503 " and %" PRId64
".", name
, min
, max
);
509 static int64_t cvtnum(const char *name
, const char *value
)
511 return cvtnum_full(name
, value
, 0, INT64_MAX
);
514 static int img_create(int argc
, char **argv
)
517 uint64_t img_size
= -1;
518 const char *fmt
= "raw";
519 const char *base_fmt
= NULL
;
520 const char *filename
;
521 const char *base_filename
= NULL
;
522 char *options
= NULL
;
523 Error
*local_err
= NULL
;
528 static const struct option long_options
[] = {
529 {"help", no_argument
, 0, 'h'},
530 {"object", required_argument
, 0, OPTION_OBJECT
},
533 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
540 missing_argument(argv
[optind
- 1]);
543 unrecognized_option(argv
[optind
- 1]);
552 base_filename
= optarg
;
558 if (accumulate_options(&options
, optarg
) < 0) {
566 flags
|= BDRV_O_NO_BACKING
;
568 case OPTION_OBJECT
: {
570 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
579 /* Get the filename */
580 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
581 if (options
&& has_help_option(options
)) {
583 return print_block_option_help(filename
, fmt
);
586 if (optind
>= argc
) {
587 error_exit("Expecting image file name");
591 if (qemu_opts_foreach(&qemu_object_opts
,
592 user_creatable_add_opts_foreach
,
593 qemu_img_object_print_help
, &error_fatal
)) {
597 /* Get image size, if specified */
601 sval
= cvtnum("image size", argv
[optind
++]);
605 img_size
= (uint64_t)sval
;
607 if (optind
!= argc
) {
608 error_exit("Unexpected argument: %s", argv
[optind
]);
611 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
612 options
, img_size
, flags
, quiet
, &local_err
);
614 error_reportf_err(local_err
, "%s: ", filename
);
626 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
630 Visitor
*v
= qobject_output_visitor_new(&obj
);
632 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
633 visit_complete(v
, &obj
);
634 str
= qobject_to_json_pretty(obj
);
636 qprintf(quiet
, "%s\n", qstring_get_str(str
));
642 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
644 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
645 qprintf(quiet
, "No errors were found on the image.\n");
647 if (check
->corruptions
) {
648 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
649 "Data may be corrupted, or further writes to the image "
656 "\n%" PRId64
" leaked clusters were found on the image.\n"
657 "This means waste of disk space, but no harm to data.\n",
661 if (check
->check_errors
) {
664 " internal errors have occurred during the check.\n",
665 check
->check_errors
);
669 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
670 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
671 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
672 check
->allocated_clusters
, check
->total_clusters
,
673 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
674 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
675 check
->compressed_clusters
* 100.0 /
676 check
->allocated_clusters
);
679 if (check
->image_end_offset
) {
681 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
685 static int collect_image_check(BlockDriverState
*bs
,
687 const char *filename
,
692 BdrvCheckResult result
;
694 ret
= bdrv_check(bs
, &result
, fix
);
699 check
->filename
= g_strdup(filename
);
700 check
->format
= g_strdup(bdrv_get_format_name(bs
));
701 check
->check_errors
= result
.check_errors
;
702 check
->corruptions
= result
.corruptions
;
703 check
->has_corruptions
= result
.corruptions
!= 0;
704 check
->leaks
= result
.leaks
;
705 check
->has_leaks
= result
.leaks
!= 0;
706 check
->corruptions_fixed
= result
.corruptions_fixed
;
707 check
->has_corruptions_fixed
= result
.corruptions_fixed
!= 0;
708 check
->leaks_fixed
= result
.leaks_fixed
;
709 check
->has_leaks_fixed
= result
.leaks_fixed
!= 0;
710 check
->image_end_offset
= result
.image_end_offset
;
711 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
712 check
->total_clusters
= result
.bfi
.total_clusters
;
713 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
714 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
715 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
716 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
717 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
718 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
719 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
725 * Checks an image for consistency. Exit codes:
727 * 0 - Check completed, image is good
728 * 1 - Check not completed because of internal errors
729 * 2 - Check completed, image is corrupted
730 * 3 - Check completed, image has leaked clusters, but is good otherwise
731 * 63 - Checks are not supported by the image format
733 static int img_check(int argc
, char **argv
)
736 OutputFormat output_format
= OFORMAT_HUMAN
;
737 const char *filename
, *fmt
, *output
, *cache
;
739 BlockDriverState
*bs
;
741 int flags
= BDRV_O_CHECK
;
745 bool image_opts
= false;
746 bool force_share
= false;
750 cache
= BDRV_DEFAULT_CACHE
;
753 int option_index
= 0;
754 static const struct option long_options
[] = {
755 {"help", no_argument
, 0, 'h'},
756 {"format", required_argument
, 0, 'f'},
757 {"repair", required_argument
, 0, 'r'},
758 {"output", required_argument
, 0, OPTION_OUTPUT
},
759 {"object", required_argument
, 0, OPTION_OBJECT
},
760 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
761 {"force-share", no_argument
, 0, 'U'},
764 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
765 long_options
, &option_index
);
771 missing_argument(argv
[optind
- 1]);
774 unrecognized_option(argv
[optind
- 1]);
783 flags
|= BDRV_O_RDWR
;
785 if (!strcmp(optarg
, "leaks")) {
786 fix
= BDRV_FIX_LEAKS
;
787 } else if (!strcmp(optarg
, "all")) {
788 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
790 error_exit("Unknown option value for -r "
791 "(expecting 'leaks' or 'all'): %s", optarg
);
806 case OPTION_OBJECT
: {
808 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
814 case OPTION_IMAGE_OPTS
:
819 if (optind
!= argc
- 1) {
820 error_exit("Expecting one image file name");
822 filename
= argv
[optind
++];
824 if (output
&& !strcmp(output
, "json")) {
825 output_format
= OFORMAT_JSON
;
826 } else if (output
&& !strcmp(output
, "human")) {
827 output_format
= OFORMAT_HUMAN
;
829 error_report("--output must be used with human or json as argument.");
833 if (qemu_opts_foreach(&qemu_object_opts
,
834 user_creatable_add_opts_foreach
,
835 qemu_img_object_print_help
, &error_fatal
)) {
839 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
841 error_report("Invalid source cache option: %s", cache
);
845 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
852 check
= g_new0(ImageCheck
, 1);
853 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
855 if (ret
== -ENOTSUP
) {
856 error_report("This image format does not support checks");
861 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
862 int corruptions_fixed
, leaks_fixed
;
863 bool has_leaks_fixed
, has_corruptions_fixed
;
865 leaks_fixed
= check
->leaks_fixed
;
866 has_leaks_fixed
= check
->has_leaks_fixed
;
867 corruptions_fixed
= check
->corruptions_fixed
;
868 has_corruptions_fixed
= check
->has_corruptions_fixed
;
870 if (output_format
== OFORMAT_HUMAN
) {
872 "The following inconsistencies were found and repaired:\n\n"
873 " %" PRId64
" leaked clusters\n"
874 " %" PRId64
" corruptions\n\n"
875 "Double checking the fixed image now...\n",
877 check
->corruptions_fixed
);
880 qapi_free_ImageCheck(check
);
881 check
= g_new0(ImageCheck
, 1);
882 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
884 check
->leaks_fixed
= leaks_fixed
;
885 check
->has_leaks_fixed
= has_leaks_fixed
;
886 check
->corruptions_fixed
= corruptions_fixed
;
887 check
->has_corruptions_fixed
= has_corruptions_fixed
;
891 switch (output_format
) {
893 dump_human_image_check(check
, quiet
);
896 dump_json_image_check(check
, quiet
);
901 if (ret
|| check
->check_errors
) {
903 error_report("Check failed: %s", strerror(-ret
));
905 error_report("Check failed");
911 if (check
->corruptions
) {
913 } else if (check
->leaks
) {
920 qapi_free_ImageCheck(check
);
925 typedef struct CommonBlockJobCBInfo
{
926 BlockDriverState
*bs
;
928 } CommonBlockJobCBInfo
;
930 static void common_block_job_cb(void *opaque
, int ret
)
932 CommonBlockJobCBInfo
*cbi
= opaque
;
935 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
939 static void run_block_job(BlockJob
*job
, Error
**errp
)
941 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
944 aio_context_acquire(aio_context
);
947 float progress
= 0.0f
;
948 aio_poll(aio_context
, true);
949 if (job
->job
.progress
.total
) {
950 progress
= (float)job
->job
.progress
.current
/
951 job
->job
.progress
.total
* 100.f
;
953 qemu_progress_print(progress
, 0);
954 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
956 if (!job_is_completed(&job
->job
)) {
957 ret
= job_complete_sync(&job
->job
, errp
);
961 job_unref(&job
->job
);
962 aio_context_release(aio_context
);
964 /* publish completion progress only when success */
966 qemu_progress_print(100.f
, 0);
970 static int img_commit(int argc
, char **argv
)
973 const char *filename
, *fmt
, *cache
, *base
;
975 BlockDriverState
*bs
, *base_bs
;
977 bool progress
= false, quiet
= false, drop
= false;
979 Error
*local_err
= NULL
;
980 CommonBlockJobCBInfo cbi
;
981 bool image_opts
= false;
982 AioContext
*aio_context
;
985 cache
= BDRV_DEFAULT_CACHE
;
988 static const struct option long_options
[] = {
989 {"help", no_argument
, 0, 'h'},
990 {"object", required_argument
, 0, OPTION_OBJECT
},
991 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
994 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
1001 missing_argument(argv
[optind
- 1]);
1004 unrecognized_option(argv
[optind
- 1]);
1029 case OPTION_OBJECT
: {
1031 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1037 case OPTION_IMAGE_OPTS
:
1043 /* Progress is not shown in Quiet mode */
1048 if (optind
!= argc
- 1) {
1049 error_exit("Expecting one image file name");
1051 filename
= argv
[optind
++];
1053 if (qemu_opts_foreach(&qemu_object_opts
,
1054 user_creatable_add_opts_foreach
,
1055 qemu_img_object_print_help
, &error_fatal
)) {
1059 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
1060 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1062 error_report("Invalid cache option: %s", cache
);
1066 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1073 qemu_progress_init(progress
, 1.f
);
1074 qemu_progress_print(0.f
, 100);
1077 base_bs
= bdrv_find_backing_image(bs
, base
);
1079 error_setg(&local_err
,
1080 "Did not find '%s' in the backing chain of '%s'",
1085 /* This is different from QMP, which by default uses the deepest file in
1086 * the backing chain (i.e., the very base); however, the traditional
1087 * behavior of qemu-img commit is using the immediate backing file. */
1088 base_bs
= bdrv_backing_chain_next(bs
);
1090 error_setg(&local_err
, "Image does not have a backing file");
1095 cbi
= (CommonBlockJobCBInfo
){
1100 aio_context
= bdrv_get_aio_context(bs
);
1101 aio_context_acquire(aio_context
);
1102 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, 0,
1103 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1104 &cbi
, false, &local_err
);
1105 aio_context_release(aio_context
);
1110 /* When the block job completes, the BlockBackend reference will point to
1111 * the old backing file. In order to avoid that the top image is already
1112 * deleted, so we can still empty it afterwards, increment the reference
1113 * counter here preemptively. */
1118 job
= block_job_get("commit");
1120 run_block_job(job
, &local_err
);
1126 BlockBackend
*old_backing_blk
;
1128 old_backing_blk
= blk_new_with_bs(bs
, BLK_PERM_WRITE
, BLK_PERM_ALL
,
1130 if (!old_backing_blk
) {
1133 ret
= blk_make_empty(old_backing_blk
, &local_err
);
1134 blk_unref(old_backing_blk
);
1135 if (ret
== -ENOTSUP
) {
1136 error_free(local_err
);
1138 } else if (ret
< 0) {
1149 qemu_progress_end();
1154 error_report_err(local_err
);
1158 qprintf(quiet
, "Image committed.\n");
1163 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1164 * of the first sector boundary within buf where the sector contains a
1165 * non-zero byte. This function is robust to a buffer that is not
1168 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1171 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1173 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1174 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1178 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1185 * Returns true iff the first sector pointed to by 'buf' contains at least
1188 * 'pnum' is set to the number of sectors (including and immediately following
1189 * the first one) that are known to be in the same allocated/unallocated state.
1190 * The function will try to align the end offset to alignment boundaries so
1191 * that the request will at least end aligned and consecutive requests will
1192 * also start at an aligned offset.
1194 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1195 int64_t sector_num
, int alignment
)
1204 is_zero
= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
);
1205 for(i
= 1; i
< n
; i
++) {
1206 buf
+= BDRV_SECTOR_SIZE
;
1207 if (is_zero
!= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
)) {
1212 tail
= (sector_num
+ i
) & (alignment
- 1);
1214 if (is_zero
&& i
<= tail
) {
1215 /* treat unallocated areas which only consist
1216 * of a small tail as allocated. */
1220 /* align up end offset of allocated areas. */
1221 i
+= alignment
- tail
;
1224 /* align down end offset of zero areas. */
1233 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1234 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1235 * breaking up write requests for only small sparse areas.
1237 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1238 int min
, int64_t sector_num
, int alignment
)
1241 int num_checked
, num_used
;
1247 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1253 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1255 sector_num
+= *pnum
;
1256 num_checked
= num_used
;
1259 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1261 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1263 sector_num
+= *pnum
;
1264 num_checked
+= *pnum
;
1266 num_used
= num_checked
;
1267 } else if (*pnum
>= min
) {
1277 * Compares two buffers sector by sector. Returns 0 if the first
1278 * sector of each buffer matches, non-zero otherwise.
1280 * pnum is set to the sector-aligned size of the buffer prefix that
1281 * has the same matching status as the first sector.
1283 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1284 int64_t bytes
, int64_t *pnum
)
1287 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1291 res
= !!memcmp(buf1
, buf2
, i
);
1293 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1295 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1305 #define IO_BUF_SIZE (2 * MiB)
1308 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1310 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1311 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1312 * failure), and 4 on error (the exit status for read errors), after emitting
1315 * @param blk: BlockBackend for the image
1316 * @param offset: Starting offset to check
1317 * @param bytes: Number of bytes to check
1318 * @param filename: Name of disk file we are checking (logging purpose)
1319 * @param buffer: Allocated buffer for storing read data
1320 * @param quiet: Flag for quiet mode
1322 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1323 int64_t bytes
, const char *filename
,
1324 uint8_t *buffer
, bool quiet
)
1329 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1331 error_report("Error while reading offset %" PRId64
" of %s: %s",
1332 offset
, filename
, strerror(-ret
));
1335 idx
= find_nonzero(buffer
, bytes
);
1337 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1346 * Compares two images. Exit codes:
1348 * 0 - Images are identical
1350 * >1 - Error occurred
1352 static int img_compare(int argc
, char **argv
)
1354 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1355 BlockBackend
*blk1
, *blk2
;
1356 BlockDriverState
*bs1
, *bs2
;
1357 int64_t total_size1
, total_size2
;
1358 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1359 int64_t pnum1
, pnum2
;
1360 int allocated1
, allocated2
;
1361 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1362 bool progress
= false, quiet
= false, strict
= false;
1369 uint64_t progress_base
;
1370 bool image_opts
= false;
1371 bool force_share
= false;
1373 cache
= BDRV_DEFAULT_CACHE
;
1375 static const struct option long_options
[] = {
1376 {"help", no_argument
, 0, 'h'},
1377 {"object", required_argument
, 0, OPTION_OBJECT
},
1378 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1379 {"force-share", no_argument
, 0, 'U'},
1382 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1383 long_options
, NULL
);
1389 missing_argument(argv
[optind
- 1]);
1392 unrecognized_option(argv
[optind
- 1]);
1418 case OPTION_OBJECT
: {
1420 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1427 case OPTION_IMAGE_OPTS
:
1433 /* Progress is not shown in Quiet mode */
1439 if (optind
!= argc
- 2) {
1440 error_exit("Expecting two image file names");
1442 filename1
= argv
[optind
++];
1443 filename2
= argv
[optind
++];
1445 if (qemu_opts_foreach(&qemu_object_opts
,
1446 user_creatable_add_opts_foreach
,
1447 qemu_img_object_print_help
, &error_fatal
)) {
1452 /* Initialize before goto out */
1453 qemu_progress_init(progress
, 2.0);
1456 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1458 error_report("Invalid source cache option: %s", cache
);
1463 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1470 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1479 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1480 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1481 total_size1
= blk_getlength(blk1
);
1482 if (total_size1
< 0) {
1483 error_report("Can't get size of %s: %s",
1484 filename1
, strerror(-total_size1
));
1488 total_size2
= blk_getlength(blk2
);
1489 if (total_size2
< 0) {
1490 error_report("Can't get size of %s: %s",
1491 filename2
, strerror(-total_size2
));
1495 total_size
= MIN(total_size1
, total_size2
);
1496 progress_base
= MAX(total_size1
, total_size2
);
1498 qemu_progress_print(0, 100);
1500 if (strict
&& total_size1
!= total_size2
) {
1502 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1506 while (offset
< total_size
) {
1507 int status1
, status2
;
1509 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1510 total_size1
- offset
, &pnum1
, NULL
,
1514 error_report("Sector allocation test failed for %s", filename1
);
1517 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1519 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1520 total_size2
- offset
, &pnum2
, NULL
,
1524 error_report("Sector allocation test failed for %s", filename2
);
1527 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1529 assert(pnum1
&& pnum2
);
1530 chunk
= MIN(pnum1
, pnum2
);
1533 if (status1
!= status2
) {
1535 qprintf(quiet
, "Strict mode: Offset %" PRId64
1536 " block status mismatch!\n", offset
);
1540 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1542 } else if (allocated1
== allocated2
) {
1546 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1547 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1549 error_report("Error while reading offset %" PRId64
1551 offset
, filename1
, strerror(-ret
));
1555 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1557 error_report("Error while reading offset %" PRId64
1559 offset
, filename2
, strerror(-ret
));
1563 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1564 if (ret
|| pnum
!= chunk
) {
1565 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1566 offset
+ (ret
? 0 : pnum
));
1572 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1574 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1575 filename1
, buf1
, quiet
);
1577 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1578 filename2
, buf1
, quiet
);
1585 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1588 if (total_size1
!= total_size2
) {
1589 BlockBackend
*blk_over
;
1590 const char *filename_over
;
1592 qprintf(quiet
, "Warning: Image size mismatch!\n");
1593 if (total_size1
> total_size2
) {
1595 filename_over
= filename1
;
1598 filename_over
= filename2
;
1601 while (offset
< progress_base
) {
1602 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1603 progress_base
- offset
, &chunk
,
1607 error_report("Sector allocation test failed for %s",
1612 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1613 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1614 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1615 filename_over
, buf1
, quiet
);
1621 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1625 qprintf(quiet
, "Images are identical.\n");
1635 qemu_progress_end();
1640 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1641 static void do_dirty_bitmap_merge(const char *dst_node
, const char *dst_name
,
1642 const char *src_node
, const char *src_name
,
1645 BlockDirtyBitmapMergeSource
*merge_src
;
1646 BlockDirtyBitmapMergeSourceList
*list
;
1648 merge_src
= g_new0(BlockDirtyBitmapMergeSource
, 1);
1649 merge_src
->type
= QTYPE_QDICT
;
1650 merge_src
->u
.external
.node
= g_strdup(src_node
);
1651 merge_src
->u
.external
.name
= g_strdup(src_name
);
1652 list
= g_new0(BlockDirtyBitmapMergeSourceList
, 1);
1653 list
->value
= merge_src
;
1654 qmp_block_dirty_bitmap_merge(dst_node
, dst_name
, list
, errp
);
1655 qapi_free_BlockDirtyBitmapMergeSourceList(list
);
1658 enum ImgConvertBlockStatus
{
1664 #define MAX_COROUTINES 16
1666 typedef struct ImgConvertState
{
1668 int64_t *src_sectors
;
1671 int64_t total_sectors
;
1672 int64_t allocated_sectors
;
1673 int64_t allocated_done
;
1676 enum ImgConvertBlockStatus status
;
1677 int64_t sector_next_status
;
1678 BlockBackend
*target
;
1682 bool target_has_backing
;
1683 int64_t target_backing_sectors
; /* negative if unknown */
1690 size_t cluster_sectors
;
1692 long num_coroutines
;
1693 int running_coroutines
;
1694 Coroutine
*co
[MAX_COROUTINES
];
1695 int64_t wait_sector_num
[MAX_COROUTINES
];
1700 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1701 int *src_cur
, int64_t *src_cur_offset
)
1704 *src_cur_offset
= 0;
1705 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1706 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1708 assert(*src_cur
< s
->src_num
);
1712 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1714 int64_t src_cur_offset
;
1715 int ret
, n
, src_cur
;
1716 bool post_backing_zero
= false;
1718 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1720 assert(s
->total_sectors
> sector_num
);
1721 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1723 if (s
->target_backing_sectors
>= 0) {
1724 if (sector_num
>= s
->target_backing_sectors
) {
1725 post_backing_zero
= true;
1726 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1727 /* Split requests around target_backing_sectors (because
1728 * starting from there, zeros are handled differently) */
1729 n
= s
->target_backing_sectors
- sector_num
;
1733 if (s
->sector_next_status
<= sector_num
) {
1734 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1737 BlockDriverState
*src_bs
= blk_bs(s
->src
[src_cur
]);
1738 BlockDriverState
*base
;
1740 if (s
->target_has_backing
) {
1741 base
= bdrv_cow_bs(bdrv_skip_filters(src_bs
));
1747 count
= n
* BDRV_SECTOR_SIZE
;
1749 ret
= bdrv_block_status_above(src_bs
, base
, offset
, count
, &count
,
1756 warn_report("error while reading block status at "
1757 "offset %" PRIu64
": %s", offset
,
1760 /* Just try to read the data, then */
1761 ret
= BDRV_BLOCK_DATA
;
1762 count
= BDRV_SECTOR_SIZE
;
1764 /* Retry on a shorter range */
1765 n
= DIV_ROUND_UP(n
, 4);
1768 error_report("error while reading block status at offset "
1769 "%" PRIu64
": %s", offset
, strerror(-ret
));
1775 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1778 * Avoid that s->sector_next_status becomes unaligned to the source
1779 * request alignment and/or cluster size to avoid unnecessary read
1782 tail
= (sector_num
- src_cur_offset
+ n
) % s
->src_alignment
[src_cur
];
1787 if (ret
& BDRV_BLOCK_ZERO
) {
1788 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1789 } else if (ret
& BDRV_BLOCK_DATA
) {
1790 s
->status
= BLK_DATA
;
1792 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1795 s
->sector_next_status
= sector_num
+ n
;
1798 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1799 if (s
->status
== BLK_DATA
) {
1800 n
= MIN(n
, s
->buf_sectors
);
1803 /* We need to write complete clusters for compressed images, so if an
1804 * unallocated area is shorter than that, we must consider the whole
1805 * cluster allocated. */
1806 if (s
->compressed
) {
1807 if (n
< s
->cluster_sectors
) {
1808 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1809 s
->status
= BLK_DATA
;
1811 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1818 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1819 int nb_sectors
, uint8_t *buf
)
1821 uint64_t single_read_until
= 0;
1824 assert(nb_sectors
<= s
->buf_sectors
);
1825 while (nb_sectors
> 0) {
1828 int64_t bs_sectors
, src_cur_offset
;
1831 /* In the case of compression with multiple source files, we can get a
1832 * nb_sectors that spreads into the next part. So we must be able to
1833 * read across multiple BDSes for one convert_read() call. */
1834 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1835 blk
= s
->src
[src_cur
];
1836 bs_sectors
= s
->src_sectors
[src_cur
];
1838 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1840 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1841 if (single_read_until
> offset
) {
1845 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1849 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1853 warn_report("error while reading offset %" PRIu64
1854 ": %s", offset
, strerror(-ret
));
1856 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1865 buf
+= n
* BDRV_SECTOR_SIZE
;
1872 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1873 int nb_sectors
, uint8_t *buf
,
1874 enum ImgConvertBlockStatus status
)
1878 while (nb_sectors
> 0) {
1880 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1883 case BLK_BACKING_FILE
:
1884 /* If we have a backing file, leave clusters unallocated that are
1885 * unallocated in the source image, so that the backing file is
1886 * visible at the respective offset. */
1887 assert(s
->target_has_backing
);
1891 /* If we're told to keep the target fully allocated (-S 0) or there
1892 * is real non-zero data, we must write it. Otherwise we can treat
1893 * it as zero sectors.
1894 * Compressed clusters need to be written as a whole, so in that
1895 * case we can only save the write if the buffer is completely
1897 if (!s
->min_sparse
||
1899 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1900 sector_num
, s
->alignment
)) ||
1902 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1904 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1905 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1914 if (s
->has_zero_init
) {
1915 assert(!s
->target_has_backing
);
1918 ret
= blk_co_pwrite_zeroes(s
->target
,
1919 sector_num
<< BDRV_SECTOR_BITS
,
1920 n
<< BDRV_SECTOR_BITS
,
1921 BDRV_REQ_MAY_UNMAP
);
1930 buf
+= n
* BDRV_SECTOR_SIZE
;
1936 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1941 while (nb_sectors
> 0) {
1944 int64_t bs_sectors
, src_cur_offset
;
1947 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1948 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1949 blk
= s
->src
[src_cur
];
1950 bs_sectors
= s
->src_sectors
[src_cur
];
1952 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1954 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1955 sector_num
<< BDRV_SECTOR_BITS
,
1956 n
<< BDRV_SECTOR_BITS
, 0, 0);
1967 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1969 ImgConvertState
*s
= opaque
;
1970 uint8_t *buf
= NULL
;
1974 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1975 if (s
->co
[i
] == qemu_coroutine_self()) {
1982 s
->running_coroutines
++;
1983 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1988 enum ImgConvertBlockStatus status
;
1991 qemu_co_mutex_lock(&s
->lock
);
1992 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1993 qemu_co_mutex_unlock(&s
->lock
);
1996 n
= convert_iteration_sectors(s
, s
->sector_num
);
1998 qemu_co_mutex_unlock(&s
->lock
);
2002 /* save current sector and allocation status to local variables */
2003 sector_num
= s
->sector_num
;
2005 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
2006 n
= MIN(n
, s
->buf_sectors
);
2008 /* increment global sector counter so that other coroutines can
2009 * already continue reading beyond this request */
2011 qemu_co_mutex_unlock(&s
->lock
);
2013 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
2014 s
->allocated_done
+= n
;
2015 qemu_progress_print(100.0 * s
->allocated_done
/
2016 s
->allocated_sectors
, 0);
2020 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
2021 if (status
== BLK_DATA
&& !copy_range
) {
2022 ret
= convert_co_read(s
, sector_num
, n
, buf
);
2024 error_report("error while reading at byte %lld: %s",
2025 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2028 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
2030 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
2033 if (s
->wr_in_order
) {
2034 /* keep writes in order */
2035 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
2036 s
->wait_sector_num
[index
] = sector_num
;
2037 qemu_coroutine_yield();
2039 s
->wait_sector_num
[index
] = -1;
2042 if (s
->ret
== -EINPROGRESS
) {
2044 ret
= convert_co_copy_range(s
, sector_num
, n
);
2046 s
->copy_range
= false;
2050 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
2053 error_report("error while writing at byte %lld: %s",
2054 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2059 if (s
->wr_in_order
) {
2060 /* reenter the coroutine that might have waited
2061 * for this write to complete */
2062 s
->wr_offs
= sector_num
+ n
;
2063 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2064 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
2066 * A -> B -> A cannot occur because A has
2067 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2068 * B will never enter A during this time window.
2070 qemu_coroutine_enter(s
->co
[i
]);
2078 s
->co
[index
] = NULL
;
2079 s
->running_coroutines
--;
2080 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
2081 /* the convert job finished successfully */
2086 static int convert_do_copy(ImgConvertState
*s
)
2089 int64_t sector_num
= 0;
2091 /* Check whether we have zero initialisation or can get it efficiently */
2092 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
2093 !s
->target_has_backing
) {
2094 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
2097 /* Allocate buffer for copied data. For compressed images, only one cluster
2098 * can be copied at a time. */
2099 if (s
->compressed
) {
2100 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2101 error_report("invalid cluster size");
2104 s
->buf_sectors
= s
->cluster_sectors
;
2107 while (sector_num
< s
->total_sectors
) {
2108 n
= convert_iteration_sectors(s
, sector_num
);
2112 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2114 s
->allocated_sectors
+= n
;
2120 s
->sector_next_status
= 0;
2121 s
->ret
= -EINPROGRESS
;
2123 qemu_co_mutex_init(&s
->lock
);
2124 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2125 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2126 s
->wait_sector_num
[i
] = -1;
2127 qemu_coroutine_enter(s
->co
[i
]);
2130 while (s
->running_coroutines
) {
2131 main_loop_wait(false);
2134 if (s
->compressed
&& !s
->ret
) {
2135 /* signal EOF to align */
2136 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
2145 static int convert_copy_bitmaps(BlockDriverState
*src
, BlockDriverState
*dst
)
2147 BdrvDirtyBitmap
*bm
;
2150 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2153 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2156 name
= bdrv_dirty_bitmap_name(bm
);
2157 qmp_block_dirty_bitmap_add(dst
->node_name
, name
,
2158 true, bdrv_dirty_bitmap_granularity(bm
),
2160 true, !bdrv_dirty_bitmap_enabled(bm
),
2163 error_reportf_err(err
, "Failed to create bitmap %s: ", name
);
2167 do_dirty_bitmap_merge(dst
->node_name
, name
, src
->node_name
, name
,
2170 error_reportf_err(err
, "Failed to populate bitmap %s: ", name
);
2178 #define MAX_BUF_SECTORS 32768
2180 static int img_convert(int argc
, char **argv
)
2182 int c
, bs_i
, flags
, src_flags
= 0;
2183 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2184 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2185 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
2186 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2187 BlockDriverInfo bdi
;
2188 BlockDriverState
*out_bs
;
2189 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2190 QemuOptsList
*create_opts
= NULL
;
2191 QDict
*open_opts
= NULL
;
2192 char *options
= NULL
;
2193 Error
*local_err
= NULL
;
2194 bool writethrough
, src_writethrough
, image_opts
= false,
2195 skip_create
= false, progress
= false, tgt_image_opts
= false;
2196 int64_t ret
= -EINVAL
;
2197 bool force_share
= false;
2198 bool explict_min_sparse
= false;
2199 bool bitmaps
= false;
2201 ImgConvertState s
= (ImgConvertState
) {
2202 /* Need at least 4k of zeros for sparse detection */
2204 .copy_range
= false,
2205 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2206 .wr_in_order
= true,
2207 .num_coroutines
= 8,
2211 static const struct option long_options
[] = {
2212 {"help", no_argument
, 0, 'h'},
2213 {"object", required_argument
, 0, OPTION_OBJECT
},
2214 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2215 {"force-share", no_argument
, 0, 'U'},
2216 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2217 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2218 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2219 {"bitmaps", no_argument
, 0, OPTION_BITMAPS
},
2222 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2223 long_options
, NULL
);
2229 missing_argument(argv
[optind
- 1]);
2232 unrecognized_option(argv
[optind
- 1]);
2244 out_baseimg
= optarg
;
2247 s
.copy_range
= true;
2250 s
.compressed
= true;
2253 if (accumulate_options(&options
, optarg
) < 0) {
2258 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2259 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2262 error_report("Failed in parsing snapshot param '%s'",
2267 snapshot_name
= optarg
;
2274 sval
= cvtnum("buffer size for sparse output", optarg
);
2277 } else if (!QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2278 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2279 error_report("Invalid buffer size for sparse output specified. "
2280 "Valid sizes are multiples of %llu up to %llu. Select "
2281 "0 to disable sparse detection (fully allocates output).",
2282 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2286 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2287 explict_min_sparse
= true;
2306 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2307 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2308 error_report("Invalid number of coroutines. Allowed number of"
2309 " coroutines is between 1 and %d", MAX_COROUTINES
);
2314 s
.wr_in_order
= false;
2319 case OPTION_OBJECT
: {
2320 QemuOpts
*object_opts
;
2321 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2328 case OPTION_IMAGE_OPTS
:
2331 case OPTION_SALVAGE
:
2334 case OPTION_TARGET_IMAGE_OPTS
:
2335 tgt_image_opts
= true;
2337 case OPTION_TARGET_IS_ZERO
:
2339 * The user asserting that the target is blank has the
2340 * same effect as the target driver supporting zero
2343 s
.has_zero_init
= true;
2345 case OPTION_BITMAPS
:
2351 if (!out_fmt
&& !tgt_image_opts
) {
2355 if (qemu_opts_foreach(&qemu_object_opts
,
2356 user_creatable_add_opts_foreach
,
2357 qemu_img_object_print_help
, &error_fatal
)) {
2361 if (s
.compressed
&& s
.copy_range
) {
2362 error_report("Cannot enable copy offloading when -c is used");
2366 if (explict_min_sparse
&& s
.copy_range
) {
2367 error_report("Cannot enable copy offloading when -S is used");
2371 if (s
.copy_range
&& s
.salvage
) {
2372 error_report("Cannot use copy offloading in salvaging mode");
2376 if (tgt_image_opts
&& !skip_create
) {
2377 error_report("--target-image-opts requires use of -n flag");
2381 if (skip_create
&& options
) {
2382 error_report("-o has no effect when skipping image creation");
2386 if (s
.has_zero_init
&& !skip_create
) {
2387 error_report("--target-is-zero requires use of -n flag");
2391 s
.src_num
= argc
- optind
- 1;
2392 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2394 if (options
&& has_help_option(options
)) {
2396 ret
= print_block_option_help(out_filename
, out_fmt
);
2399 error_report("Option help requires a format be specified");
2404 if (s
.src_num
< 1) {
2405 error_report("Must specify image file name");
2409 /* ret is still -EINVAL until here */
2410 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2412 error_report("Invalid source cache option: %s", src_cache
);
2416 /* Initialize before goto out */
2420 qemu_progress_init(progress
, 1.0);
2421 qemu_progress_print(0, 100);
2423 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2424 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2425 s
.src_alignment
= g_new(int, s
.src_num
);
2427 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2428 BlockDriverState
*src_bs
;
2429 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2430 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2436 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2437 if (s
.src_sectors
[bs_i
] < 0) {
2438 error_report("Could not get size of %s: %s",
2439 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2443 src_bs
= blk_bs(s
.src
[bs_i
]);
2444 s
.src_alignment
[bs_i
] = DIV_ROUND_UP(src_bs
->bl
.request_alignment
,
2446 if (!bdrv_get_info(src_bs
, &bdi
)) {
2447 s
.src_alignment
[bs_i
] = MAX(s
.src_alignment
[bs_i
],
2448 bdi
.cluster_size
/ BDRV_SECTOR_SIZE
);
2450 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2454 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2455 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2456 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2458 } else if (snapshot_name
!= NULL
) {
2459 if (s
.src_num
> 1) {
2460 error_report("No support for concatenating multiple snapshot");
2465 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2469 error_reportf_err(local_err
, "Failed to load snapshot: ");
2475 /* Find driver and parse its options */
2476 drv
= bdrv_find_format(out_fmt
);
2478 error_report("Unknown file format '%s'", out_fmt
);
2483 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2485 error_report_err(local_err
);
2490 if (!drv
->create_opts
) {
2491 error_report("Format driver '%s' does not support image creation",
2497 if (!proto_drv
->create_opts
) {
2498 error_report("Protocol driver '%s' does not support image creation",
2499 proto_drv
->format_name
);
2504 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2505 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2507 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2509 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
2510 error_report_err(local_err
);
2516 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
2517 s
.total_sectors
* BDRV_SECTOR_SIZE
, &error_abort
);
2518 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2524 /* Get backing file name if -o backing_file was used */
2525 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2526 if (out_baseimg_param
) {
2527 out_baseimg
= out_baseimg_param
;
2529 s
.target_has_backing
= (bool) out_baseimg
;
2531 if (s
.has_zero_init
&& s
.target_has_backing
) {
2532 error_report("Cannot use --target-is-zero when the destination "
2533 "image has a backing file");
2537 if (s
.src_num
> 1 && out_baseimg
) {
2538 error_report("Having a backing file for the target makes no sense when "
2539 "concatenating multiple input images");
2544 if (out_baseimg_param
) {
2545 if (!qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
)) {
2546 warn_report("Deprecated use of backing file without explicit "
2551 /* Check if compression is supported */
2554 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2555 const char *encryptfmt
=
2556 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2557 const char *preallocation
=
2558 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2560 if (drv
&& !block_driver_can_compress(drv
)) {
2561 error_report("Compression not supported for this file format");
2566 if (encryption
|| encryptfmt
) {
2567 error_report("Compression and encryption not supported at "
2574 && strcmp(preallocation
, "off"))
2576 error_report("Compression and preallocation not supported at "
2583 /* Determine if bitmaps need copying */
2585 if (s
.src_num
> 1) {
2586 error_report("Copying bitmaps only possible with single source");
2590 if (!bdrv_supports_persistent_dirty_bitmap(blk_bs(s
.src
[0]))) {
2591 error_report("Source lacks bitmap support");
2598 * The later open call will need any decryption secrets, and
2599 * bdrv_create() will purge "opts", so extract them now before
2603 open_opts
= qdict_new();
2604 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2606 /* Create the new image */
2607 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2609 error_reportf_err(local_err
, "%s: error while converting %s: ",
2610 out_filename
, out_fmt
);
2615 s
.target_is_new
= !skip_create
;
2617 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2618 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2620 error_report("Invalid cache option: %s", cache
);
2625 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2626 flags
, writethrough
, s
.quiet
, false);
2628 /* TODO ultimately we should allow --target-image-opts
2629 * to be used even when -n is not given.
2630 * That has to wait for bdrv_create to be improved
2631 * to allow filenames in option syntax
2633 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2634 flags
, writethrough
, s
.quiet
, false);
2635 open_opts
= NULL
; /* blk_new_open will have freed it */
2641 out_bs
= blk_bs(s
.target
);
2643 if (bitmaps
&& !bdrv_supports_persistent_dirty_bitmap(out_bs
)) {
2644 error_report("Format driver '%s' does not support bitmaps",
2645 out_bs
->drv
->format_name
);
2650 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2651 error_report("Compression not supported for this file format");
2656 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2657 * or discard_alignment of the out_bs is greater. Limit to
2658 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2659 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2661 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2662 out_bs
->bl
.pdiscard_alignment
>>
2663 BDRV_SECTOR_BITS
)));
2665 /* try to align the write requests to the destination to avoid unnecessary
2667 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2668 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2670 assert(is_power_of_2(s
.alignment
));
2673 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2674 if (output_sectors
< 0) {
2675 error_report("unable to get output image length: %s",
2676 strerror(-output_sectors
));
2679 } else if (output_sectors
< s
.total_sectors
) {
2680 error_report("output file is smaller than input file");
2686 if (s
.target_has_backing
&& s
.target_is_new
) {
2687 /* Errors are treated as "backing length unknown" (which means
2688 * s.target_backing_sectors has to be negative, which it will
2689 * be automatically). The backing file length is used only
2690 * for optimizations, so such a case is not fatal. */
2691 s
.target_backing_sectors
=
2692 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs
));
2694 s
.target_backing_sectors
= -1;
2697 ret
= bdrv_get_info(out_bs
, &bdi
);
2700 error_report("could not get block driver info");
2704 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2705 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2708 ret
= convert_do_copy(&s
);
2710 /* Now copy the bitmaps */
2711 if (bitmaps
&& ret
== 0) {
2712 ret
= convert_copy_bitmaps(blk_bs(s
.src
[0]), out_bs
);
2717 qemu_progress_print(100, 0);
2719 qemu_progress_end();
2720 qemu_opts_del(opts
);
2721 qemu_opts_free(create_opts
);
2722 qemu_opts_del(sn_opts
);
2723 qobject_unref(open_opts
);
2724 blk_unref(s
.target
);
2726 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2727 blk_unref(s
.src
[bs_i
]);
2731 g_free(s
.src_sectors
);
2732 g_free(s
.src_alignment
);
2740 static void dump_snapshots(BlockDriverState
*bs
)
2742 QEMUSnapshotInfo
*sn_tab
, *sn
;
2745 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2748 printf("Snapshot list:\n");
2749 bdrv_snapshot_dump(NULL
);
2751 for(i
= 0; i
< nb_sns
; i
++) {
2753 bdrv_snapshot_dump(sn
);
2759 static void dump_json_image_info_list(ImageInfoList
*list
)
2763 Visitor
*v
= qobject_output_visitor_new(&obj
);
2765 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2766 visit_complete(v
, &obj
);
2767 str
= qobject_to_json_pretty(obj
);
2768 assert(str
!= NULL
);
2769 printf("%s\n", qstring_get_str(str
));
2775 static void dump_json_image_info(ImageInfo
*info
)
2779 Visitor
*v
= qobject_output_visitor_new(&obj
);
2781 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2782 visit_complete(v
, &obj
);
2783 str
= qobject_to_json_pretty(obj
);
2784 assert(str
!= NULL
);
2785 printf("%s\n", qstring_get_str(str
));
2791 static void dump_human_image_info_list(ImageInfoList
*list
)
2793 ImageInfoList
*elem
;
2796 for (elem
= list
; elem
; elem
= elem
->next
) {
2802 bdrv_image_info_dump(elem
->value
);
2806 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2808 return strcmp(a
, b
) == 0;
2812 * Open an image file chain and return an ImageInfoList
2814 * @filename: topmost image filename
2815 * @fmt: topmost image format (may be NULL to autodetect)
2816 * @chain: true - enumerate entire backing file chain
2817 * false - only topmost image file
2819 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2820 * image file. If there was an error a message will have been printed to
2823 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2824 const char *filename
,
2826 bool chain
, bool force_share
)
2828 ImageInfoList
*head
= NULL
;
2829 ImageInfoList
**last
= &head
;
2830 GHashTable
*filenames
;
2833 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2837 BlockDriverState
*bs
;
2839 ImageInfoList
*elem
;
2841 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2842 error_report("Backing file '%s' creates an infinite loop.",
2846 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2848 blk
= img_open(image_opts
, filename
, fmt
,
2849 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2856 bdrv_query_image_info(bs
, &info
, &err
);
2858 error_report_err(err
);
2863 elem
= g_new0(ImageInfoList
, 1);
2870 /* Clear parameters that only apply to the topmost image */
2871 filename
= fmt
= NULL
;
2875 if (info
->has_full_backing_filename
) {
2876 filename
= info
->full_backing_filename
;
2877 } else if (info
->has_backing_filename
) {
2878 error_report("Could not determine absolute backing filename,"
2879 " but backing filename '%s' present",
2880 info
->backing_filename
);
2883 if (info
->has_backing_filename_format
) {
2884 fmt
= info
->backing_filename_format
;
2888 g_hash_table_destroy(filenames
);
2892 qapi_free_ImageInfoList(head
);
2893 g_hash_table_destroy(filenames
);
2897 static int img_info(int argc
, char **argv
)
2900 OutputFormat output_format
= OFORMAT_HUMAN
;
2902 const char *filename
, *fmt
, *output
;
2903 ImageInfoList
*list
;
2904 bool image_opts
= false;
2905 bool force_share
= false;
2910 int option_index
= 0;
2911 static const struct option long_options
[] = {
2912 {"help", no_argument
, 0, 'h'},
2913 {"format", required_argument
, 0, 'f'},
2914 {"output", required_argument
, 0, OPTION_OUTPUT
},
2915 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2916 {"object", required_argument
, 0, OPTION_OBJECT
},
2917 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2918 {"force-share", no_argument
, 0, 'U'},
2921 c
= getopt_long(argc
, argv
, ":f:hU",
2922 long_options
, &option_index
);
2928 missing_argument(argv
[optind
- 1]);
2931 unrecognized_option(argv
[optind
- 1]);
2945 case OPTION_BACKING_CHAIN
:
2948 case OPTION_OBJECT
: {
2950 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2956 case OPTION_IMAGE_OPTS
:
2961 if (optind
!= argc
- 1) {
2962 error_exit("Expecting one image file name");
2964 filename
= argv
[optind
++];
2966 if (output
&& !strcmp(output
, "json")) {
2967 output_format
= OFORMAT_JSON
;
2968 } else if (output
&& !strcmp(output
, "human")) {
2969 output_format
= OFORMAT_HUMAN
;
2970 } else if (output
) {
2971 error_report("--output must be used with human or json as argument.");
2975 if (qemu_opts_foreach(&qemu_object_opts
,
2976 user_creatable_add_opts_foreach
,
2977 qemu_img_object_print_help
, &error_fatal
)) {
2981 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2987 switch (output_format
) {
2989 dump_human_image_info_list(list
);
2993 dump_json_image_info_list(list
);
2995 dump_json_image_info(list
->value
);
3000 qapi_free_ImageInfoList(list
);
3004 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
3007 switch (output_format
) {
3009 if (e
->data
&& !e
->has_offset
) {
3010 error_report("File contains external, encrypted or compressed clusters.");
3013 if (e
->data
&& !e
->zero
) {
3014 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
3015 e
->start
, e
->length
,
3016 e
->has_offset
? e
->offset
: 0,
3017 e
->has_filename
? e
->filename
: "");
3019 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3020 * Modify the flags here to allow more coalescing.
3022 if (next
&& (!next
->data
|| next
->zero
)) {
3028 printf("{ \"start\": %"PRId64
", \"length\": %"PRId64
","
3029 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
3030 e
->start
, e
->length
, e
->depth
,
3031 e
->zero
? "true" : "false",
3032 e
->data
? "true" : "false");
3033 if (e
->has_offset
) {
3034 printf(", \"offset\": %"PRId64
"", e
->offset
);
3046 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
3047 int64_t bytes
, MapEntry
*e
)
3051 BlockDriverState
*file
;
3054 char *filename
= NULL
;
3056 /* As an optimization, we could cache the current range of unallocated
3057 * clusters in each file of the chain, and avoid querying the same
3063 bs
= bdrv_skip_filters(bs
);
3064 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
3069 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
3072 bs
= bdrv_cow_bs(bs
);
3081 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
3083 if (file
&& has_offset
) {
3084 bdrv_refresh_filename(file
);
3085 filename
= file
->filename
;
3091 .data
= !!(ret
& BDRV_BLOCK_DATA
),
3092 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
3094 .has_offset
= has_offset
,
3096 .has_filename
= filename
,
3097 .filename
= filename
,
3103 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
3105 if (curr
->length
== 0) {
3108 if (curr
->zero
!= next
->zero
||
3109 curr
->data
!= next
->data
||
3110 curr
->depth
!= next
->depth
||
3111 curr
->has_filename
!= next
->has_filename
||
3112 curr
->has_offset
!= next
->has_offset
) {
3115 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
3118 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
3124 static int img_map(int argc
, char **argv
)
3127 OutputFormat output_format
= OFORMAT_HUMAN
;
3129 BlockDriverState
*bs
;
3130 const char *filename
, *fmt
, *output
;
3132 MapEntry curr
= { .length
= 0 }, next
;
3134 bool image_opts
= false;
3135 bool force_share
= false;
3136 int64_t start_offset
= 0;
3137 int64_t max_length
= -1;
3142 int option_index
= 0;
3143 static const struct option long_options
[] = {
3144 {"help", no_argument
, 0, 'h'},
3145 {"format", required_argument
, 0, 'f'},
3146 {"output", required_argument
, 0, OPTION_OUTPUT
},
3147 {"object", required_argument
, 0, OPTION_OBJECT
},
3148 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3149 {"force-share", no_argument
, 0, 'U'},
3150 {"start-offset", required_argument
, 0, 's'},
3151 {"max-length", required_argument
, 0, 'l'},
3154 c
= getopt_long(argc
, argv
, ":f:s:l:hU",
3155 long_options
, &option_index
);
3161 missing_argument(argv
[optind
- 1]);
3164 unrecognized_option(argv
[optind
- 1]);
3179 start_offset
= cvtnum("start offset", optarg
);
3180 if (start_offset
< 0) {
3185 max_length
= cvtnum("max length", optarg
);
3186 if (max_length
< 0) {
3190 case OPTION_OBJECT
: {
3192 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3198 case OPTION_IMAGE_OPTS
:
3203 if (optind
!= argc
- 1) {
3204 error_exit("Expecting one image file name");
3206 filename
= argv
[optind
];
3208 if (output
&& !strcmp(output
, "json")) {
3209 output_format
= OFORMAT_JSON
;
3210 } else if (output
&& !strcmp(output
, "human")) {
3211 output_format
= OFORMAT_HUMAN
;
3212 } else if (output
) {
3213 error_report("--output must be used with human or json as argument.");
3217 if (qemu_opts_foreach(&qemu_object_opts
,
3218 user_creatable_add_opts_foreach
,
3219 qemu_img_object_print_help
, &error_fatal
)) {
3223 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3229 if (output_format
== OFORMAT_HUMAN
) {
3230 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3231 } else if (output_format
== OFORMAT_JSON
) {
3235 length
= blk_getlength(blk
);
3237 error_report("Failed to get size for '%s'", filename
);
3240 if (max_length
!= -1) {
3241 length
= MIN(start_offset
+ max_length
, length
);
3244 curr
.start
= start_offset
;
3245 while (curr
.start
+ curr
.length
< length
) {
3246 int64_t offset
= curr
.start
+ curr
.length
;
3247 int64_t n
= length
- offset
;
3249 ret
= get_block_status(bs
, offset
, n
, &next
);
3251 error_report("Could not read file metadata: %s", strerror(-ret
));
3255 if (entry_mergeable(&curr
, &next
)) {
3256 curr
.length
+= next
.length
;
3260 if (curr
.length
> 0) {
3261 ret
= dump_map_entry(output_format
, &curr
, &next
);
3269 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3270 if (output_format
== OFORMAT_JSON
) {
3279 #define SNAPSHOT_LIST 1
3280 #define SNAPSHOT_CREATE 2
3281 #define SNAPSHOT_APPLY 3
3282 #define SNAPSHOT_DELETE 4
3284 static int img_snapshot(int argc
, char **argv
)
3287 BlockDriverState
*bs
;
3288 QEMUSnapshotInfo sn
;
3289 char *filename
, *snapshot_name
= NULL
;
3290 int c
, ret
= 0, bdrv_oflags
;
3295 bool image_opts
= false;
3296 bool force_share
= false;
3298 bdrv_oflags
= BDRV_O_RDWR
;
3299 /* Parse commandline parameters */
3301 static const struct option long_options
[] = {
3302 {"help", no_argument
, 0, 'h'},
3303 {"object", required_argument
, 0, OPTION_OBJECT
},
3304 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3305 {"force-share", no_argument
, 0, 'U'},
3308 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3309 long_options
, NULL
);
3315 missing_argument(argv
[optind
- 1]);
3318 unrecognized_option(argv
[optind
- 1]);
3325 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3328 action
= SNAPSHOT_LIST
;
3329 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3333 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3336 action
= SNAPSHOT_APPLY
;
3337 snapshot_name
= optarg
;
3341 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3344 action
= SNAPSHOT_CREATE
;
3345 snapshot_name
= optarg
;
3349 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3352 action
= SNAPSHOT_DELETE
;
3353 snapshot_name
= optarg
;
3361 case OPTION_OBJECT
: {
3363 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3369 case OPTION_IMAGE_OPTS
:
3375 if (optind
!= argc
- 1) {
3376 error_exit("Expecting one image file name");
3378 filename
= argv
[optind
++];
3380 if (qemu_opts_foreach(&qemu_object_opts
,
3381 user_creatable_add_opts_foreach
,
3382 qemu_img_object_print_help
, &error_fatal
)) {
3386 /* Open the image */
3387 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3394 /* Perform the requested action */
3400 case SNAPSHOT_CREATE
:
3401 memset(&sn
, 0, sizeof(sn
));
3402 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3404 qemu_gettimeofday(&tv
);
3405 sn
.date_sec
= tv
.tv_sec
;
3406 sn
.date_nsec
= tv
.tv_usec
* 1000;
3408 ret
= bdrv_snapshot_create(bs
, &sn
);
3410 error_report("Could not create snapshot '%s': %d (%s)",
3411 snapshot_name
, ret
, strerror(-ret
));
3415 case SNAPSHOT_APPLY
:
3416 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3418 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3423 case SNAPSHOT_DELETE
:
3424 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3426 error_report("Could not delete snapshot '%s': snapshot not "
3427 "found", snapshot_name
);
3430 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3432 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3448 static int img_rebase(int argc
, char **argv
)
3450 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3451 uint8_t *buf_old
= NULL
;
3452 uint8_t *buf_new
= NULL
;
3453 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3454 BlockDriverState
*unfiltered_bs
;
3456 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3457 int c
, flags
, src_flags
, ret
;
3458 bool writethrough
, src_writethrough
;
3460 bool force_share
= false;
3463 Error
*local_err
= NULL
;
3464 bool image_opts
= false;
3466 /* Parse commandline parameters */
3468 cache
= BDRV_DEFAULT_CACHE
;
3469 src_cache
= BDRV_DEFAULT_CACHE
;
3473 static const struct option long_options
[] = {
3474 {"help", no_argument
, 0, 'h'},
3475 {"object", required_argument
, 0, OPTION_OBJECT
},
3476 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3477 {"force-share", no_argument
, 0, 'U'},
3480 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3481 long_options
, NULL
);
3487 missing_argument(argv
[optind
- 1]);
3490 unrecognized_option(argv
[optind
- 1]);
3499 out_basefmt
= optarg
;
3502 out_baseimg
= optarg
;
3519 case OPTION_OBJECT
: {
3521 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3527 case OPTION_IMAGE_OPTS
:
3540 if (optind
!= argc
- 1) {
3541 error_exit("Expecting one image file name");
3543 if (!unsafe
&& !out_baseimg
) {
3544 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3546 filename
= argv
[optind
++];
3548 if (qemu_opts_foreach(&qemu_object_opts
,
3549 user_creatable_add_opts_foreach
,
3550 qemu_img_object_print_help
, &error_fatal
)) {
3554 qemu_progress_init(progress
, 2.0);
3555 qemu_progress_print(0, 100);
3557 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3558 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3560 error_report("Invalid cache option: %s", cache
);
3565 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3567 error_report("Invalid source cache option: %s", src_cache
);
3571 /* The source files are opened read-only, don't care about WCE */
3572 assert((src_flags
& BDRV_O_RDWR
) == 0);
3573 (void) src_writethrough
;
3578 * Ignore the old backing file for unsafe rebase in case we want to correct
3579 * the reference to a renamed or moved backing file.
3581 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3589 unfiltered_bs
= bdrv_skip_filters(bs
);
3591 if (out_basefmt
!= NULL
) {
3592 if (bdrv_find_format(out_basefmt
) == NULL
) {
3593 error_report("Invalid format name: '%s'", out_basefmt
);
3599 /* For safe rebasing we need to compare old and new backing file */
3601 QDict
*options
= NULL
;
3602 BlockDriverState
*base_bs
= bdrv_cow_bs(unfiltered_bs
);
3605 blk_old_backing
= blk_new(qemu_get_aio_context(),
3606 BLK_PERM_CONSISTENT_READ
,
3608 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3611 error_reportf_err(local_err
,
3612 "Could not reuse old backing file '%s': ",
3617 blk_old_backing
= NULL
;
3620 if (out_baseimg
[0]) {
3621 const char *overlay_filename
;
3622 char *out_real_path
;
3624 options
= qdict_new();
3626 qdict_put_str(options
, "driver", out_basefmt
);
3629 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3632 bdrv_refresh_filename(bs
);
3633 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3636 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3640 qobject_unref(options
);
3641 error_reportf_err(local_err
,
3642 "Could not resolve backing filename: ");
3648 * Find out whether we rebase an image on top of a previous image
3651 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3652 if (prefix_chain_bs
) {
3653 qobject_unref(options
);
3654 g_free(out_real_path
);
3656 blk_new_backing
= blk_new(qemu_get_aio_context(),
3657 BLK_PERM_CONSISTENT_READ
,
3659 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3662 error_reportf_err(local_err
,
3663 "Could not reuse backing file '%s': ",
3668 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3669 options
, src_flags
, &local_err
);
3670 g_free(out_real_path
);
3671 if (!blk_new_backing
) {
3672 error_reportf_err(local_err
,
3673 "Could not open new backing file '%s': ",
3683 * Check each unallocated cluster in the COW file. If it is unallocated,
3684 * accesses go to the backing file. We must therefore compare this cluster
3685 * in the old and new backing file, and if they differ we need to copy it
3686 * from the old backing file into the COW file.
3688 * If qemu-img crashes during this step, no harm is done. The content of
3689 * the image is the same as the original one at any time.
3693 int64_t old_backing_size
= 0;
3694 int64_t new_backing_size
= 0;
3697 float local_progress
= 0;
3699 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3700 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3702 size
= blk_getlength(blk
);
3704 error_report("Could not get size of '%s': %s",
3705 filename
, strerror(-size
));
3709 if (blk_old_backing
) {
3710 old_backing_size
= blk_getlength(blk_old_backing
);
3711 if (old_backing_size
< 0) {
3712 char backing_name
[PATH_MAX
];
3714 bdrv_get_backing_filename(bs
, backing_name
,
3715 sizeof(backing_name
));
3716 error_report("Could not get size of '%s': %s",
3717 backing_name
, strerror(-old_backing_size
));
3722 if (blk_new_backing
) {
3723 new_backing_size
= blk_getlength(blk_new_backing
);
3724 if (new_backing_size
< 0) {
3725 error_report("Could not get size of '%s': %s",
3726 out_baseimg
, strerror(-new_backing_size
));
3733 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3736 for (offset
= 0; offset
< size
; offset
+= n
) {
3737 bool buf_old_is_zero
= false;
3739 /* How many bytes can we handle with the next read? */
3740 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3742 /* If the cluster is allocated, we don't need to take action */
3743 ret
= bdrv_is_allocated(unfiltered_bs
, offset
, n
, &n
);
3745 error_report("error while reading image metadata: %s",
3753 if (prefix_chain_bs
) {
3755 * If cluster wasn't changed since prefix_chain, we don't need
3758 ret
= bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs
),
3759 prefix_chain_bs
, false,
3762 error_report("error while reading image metadata: %s",
3772 * Read old and new backing file and take into consideration that
3773 * backing files may be smaller than the COW image.
3775 if (offset
>= old_backing_size
) {
3776 memset(buf_old
, 0, n
);
3777 buf_old_is_zero
= true;
3779 if (offset
+ n
> old_backing_size
) {
3780 n
= old_backing_size
- offset
;
3783 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3785 error_report("error while reading from old backing file");
3790 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3791 memset(buf_new
, 0, n
);
3793 if (offset
+ n
> new_backing_size
) {
3794 n
= new_backing_size
- offset
;
3797 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3799 error_report("error while reading from new backing file");
3804 /* If they differ, we need to write to the COW file */
3805 uint64_t written
= 0;
3807 while (written
< n
) {
3810 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3811 n
- written
, &pnum
))
3813 if (buf_old_is_zero
) {
3814 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3816 ret
= blk_pwrite(blk
, offset
+ written
,
3817 buf_old
+ written
, pnum
, 0);
3820 error_report("Error while writing to COW image: %s",
3828 qemu_progress_print(local_progress
, 100);
3833 * Change the backing file. All clusters that are different from the old
3834 * backing file are overwritten in the COW file now, so the visible content
3835 * doesn't change when we switch the backing file.
3837 if (out_baseimg
&& *out_baseimg
) {
3838 ret
= bdrv_change_backing_file(unfiltered_bs
, out_baseimg
, out_basefmt
,
3841 ret
= bdrv_change_backing_file(unfiltered_bs
, NULL
, NULL
, false);
3844 if (ret
== -ENOSPC
) {
3845 error_report("Could not change the backing file to '%s': No "
3846 "space left in the file header", out_baseimg
);
3847 } else if (ret
< 0) {
3848 error_report("Could not change the backing file to '%s': %s",
3849 out_baseimg
, strerror(-ret
));
3852 qemu_progress_print(100, 0);
3854 * TODO At this point it is possible to check if any clusters that are
3855 * allocated in the COW file are the same in the backing file. If so, they
3856 * could be dropped from the COW file. Don't do this before switching the
3857 * backing file, in case of a crash this would lead to corruption.
3860 qemu_progress_end();
3863 blk_unref(blk_old_backing
);
3864 blk_unref(blk_new_backing
);
3866 qemu_vfree(buf_old
);
3867 qemu_vfree(buf_new
);
3876 static int img_resize(int argc
, char **argv
)
3879 int c
, ret
, relative
;
3880 const char *filename
, *fmt
, *size
;
3881 int64_t n
, total_size
, current_size
;
3883 BlockBackend
*blk
= NULL
;
3884 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3887 static QemuOptsList resize_options
= {
3888 .name
= "resize_options",
3889 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3892 .name
= BLOCK_OPT_SIZE
,
3893 .type
= QEMU_OPT_SIZE
,
3894 .help
= "Virtual disk size"
3900 bool image_opts
= false;
3901 bool shrink
= false;
3903 /* Remove size from argv manually so that negative numbers are not treated
3904 * as options by getopt. */
3906 error_exit("Not enough arguments");
3910 size
= argv
[--argc
];
3912 /* Parse getopt arguments */
3915 static const struct option long_options
[] = {
3916 {"help", no_argument
, 0, 'h'},
3917 {"object", required_argument
, 0, OPTION_OBJECT
},
3918 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3919 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3920 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3923 c
= getopt_long(argc
, argv
, ":f:hq",
3924 long_options
, NULL
);
3930 missing_argument(argv
[optind
- 1]);
3933 unrecognized_option(argv
[optind
- 1]);
3944 case OPTION_OBJECT
: {
3946 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3952 case OPTION_IMAGE_OPTS
:
3955 case OPTION_PREALLOCATION
:
3956 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3957 PREALLOC_MODE__MAX
, NULL
);
3958 if (prealloc
== PREALLOC_MODE__MAX
) {
3959 error_report("Invalid preallocation mode '%s'", optarg
);
3968 if (optind
!= argc
- 1) {
3969 error_exit("Expecting image file name and size");
3971 filename
= argv
[optind
++];
3973 if (qemu_opts_foreach(&qemu_object_opts
,
3974 user_creatable_add_opts_foreach
,
3975 qemu_img_object_print_help
, &error_fatal
)) {
3979 /* Choose grow, shrink, or absolute resize mode */
3995 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3996 if (!qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
)) {
3997 error_report_err(err
);
3999 qemu_opts_del(param
);
4002 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
4003 qemu_opts_del(param
);
4005 blk
= img_open(image_opts
, filename
, fmt
,
4006 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
4013 current_size
= blk_getlength(blk
);
4014 if (current_size
< 0) {
4015 error_report("Failed to inquire current image length: %s",
4016 strerror(-current_size
));
4022 total_size
= current_size
+ n
* relative
;
4026 if (total_size
<= 0) {
4027 error_report("New image size must be positive");
4032 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
4033 error_report("Preallocation can only be used for growing images");
4038 if (total_size
< current_size
&& !shrink
) {
4039 error_report("Use the --shrink option to perform a shrink operation.");
4040 warn_report("Shrinking an image will delete all data beyond the "
4041 "shrunken image's end. Before performing such an "
4042 "operation, make sure there is no important data there.");
4048 * The user expects the image to have the desired size after
4049 * resizing, so pass @exact=true. It is of no use to report
4050 * success when the image has not actually been resized.
4052 ret
= blk_truncate(blk
, total_size
, true, prealloc
, 0, &err
);
4054 qprintf(quiet
, "Image resized.\n");
4056 error_report_err(err
);
4066 static void amend_status_cb(BlockDriverState
*bs
,
4067 int64_t offset
, int64_t total_work_size
,
4070 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
4073 static int print_amend_option_help(const char *format
)
4077 /* Find driver and parse its options */
4078 drv
= bdrv_find_format(format
);
4080 error_report("Unknown file format '%s'", format
);
4084 if (!drv
->bdrv_amend_options
) {
4085 error_report("Format driver '%s' does not support option amendment",
4090 /* Every driver supporting amendment must have amend_opts */
4091 assert(drv
->amend_opts
);
4093 printf("Amend options for '%s':\n", format
);
4094 qemu_opts_print_help(drv
->amend_opts
, false);
4098 static int img_amend(int argc
, char **argv
)
4102 char *options
= NULL
;
4103 QemuOptsList
*amend_opts
= NULL
;
4104 QemuOpts
*opts
= NULL
;
4105 const char *fmt
= NULL
, *filename
, *cache
;
4108 bool quiet
= false, progress
= false;
4109 BlockBackend
*blk
= NULL
;
4110 BlockDriverState
*bs
= NULL
;
4111 bool image_opts
= false;
4114 cache
= BDRV_DEFAULT_CACHE
;
4116 static const struct option long_options
[] = {
4117 {"help", no_argument
, 0, 'h'},
4118 {"object", required_argument
, 0, OPTION_OBJECT
},
4119 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4120 {"force", no_argument
, 0, OPTION_FORCE
},
4123 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
4124 long_options
, NULL
);
4131 missing_argument(argv
[optind
- 1]);
4134 unrecognized_option(argv
[optind
- 1]);
4140 if (accumulate_options(&options
, optarg
) < 0) {
4142 goto out_no_progress
;
4158 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4162 goto out_no_progress
;
4165 case OPTION_IMAGE_OPTS
:
4175 error_exit("Must specify options (-o)");
4178 if (qemu_opts_foreach(&qemu_object_opts
,
4179 user_creatable_add_opts_foreach
,
4180 qemu_img_object_print_help
, &error_fatal
)) {
4182 goto out_no_progress
;
4188 qemu_progress_init(progress
, 1.0);
4190 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
4191 if (fmt
&& has_help_option(options
)) {
4192 /* If a format is explicitly specified (and possibly no filename is
4193 * given), print option help here */
4194 ret
= print_amend_option_help(fmt
);
4198 if (optind
!= argc
- 1) {
4199 error_report("Expecting one image file name");
4204 flags
= BDRV_O_RDWR
;
4205 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
4207 error_report("Invalid cache option: %s", cache
);
4211 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4219 fmt
= bs
->drv
->format_name
;
4221 if (has_help_option(options
)) {
4222 /* If the format was auto-detected, print option help here */
4223 ret
= print_amend_option_help(fmt
);
4227 if (!bs
->drv
->bdrv_amend_options
) {
4228 error_report("Format driver '%s' does not support option amendment",
4234 /* Every driver supporting amendment must have amend_opts */
4235 assert(bs
->drv
->amend_opts
);
4237 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->amend_opts
);
4238 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4239 if (!qemu_opts_do_parse(opts
, options
, NULL
, &err
)) {
4240 /* Try to parse options using the create options */
4241 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->create_opts
);
4242 qemu_opts_del(opts
);
4243 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4244 if (qemu_opts_do_parse(opts
, options
, NULL
, NULL
)) {
4245 error_append_hint(&err
,
4246 "This option is only supported for image creation\n");
4249 error_report_err(err
);
4254 /* In case the driver does not call amend_status_cb() */
4255 qemu_progress_print(0.f
, 0);
4256 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, force
, &err
);
4257 qemu_progress_print(100.f
, 0);
4259 error_report_err(err
);
4264 qemu_progress_end();
4268 qemu_opts_del(opts
);
4269 qemu_opts_free(amend_opts
);
4278 typedef struct BenchData
{
4280 uint64_t image_size
;
4287 bool drain_on_flush
;
4296 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4299 error_report("Failed flush request: %s", strerror(-ret
));
4304 static void bench_cb(void *opaque
, int ret
)
4306 BenchData
*b
= opaque
;
4310 error_report("Failed request: %s", strerror(-ret
));
4315 /* Just finished a flush with drained queue: Start next requests */
4316 assert(b
->in_flight
== 0);
4317 b
->in_flush
= false;
4318 } else if (b
->in_flight
> 0) {
4319 int remaining
= b
->n
- b
->in_flight
;
4324 /* Time for flush? Drain queue if requested, then flush */
4325 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4326 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4327 BlockCompletionFunc
*cb
;
4329 if (b
->drain_on_flush
) {
4333 cb
= bench_undrained_flush_cb
;
4336 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4338 error_report("Failed to issue flush request");
4342 if (b
->drain_on_flush
) {
4348 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4349 int64_t offset
= b
->offset
;
4350 /* blk_aio_* might look for completed I/Os and kick bench_cb
4351 * again, so make sure this operation is counted by in_flight
4352 * and b->offset is ready for the next submission.
4355 b
->offset
+= b
->step
;
4356 b
->offset
%= b
->image_size
;
4358 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4360 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4363 error_report("Failed to issue request");
4369 static int img_bench(int argc
, char **argv
)
4372 const char *fmt
= NULL
, *filename
;
4374 bool image_opts
= false;
4375 bool is_write
= false;
4379 size_t bufsize
= 4096;
4382 int flush_interval
= 0;
4383 bool drain_on_flush
= true;
4385 BlockBackend
*blk
= NULL
;
4386 BenchData data
= {};
4388 bool writethrough
= false;
4389 struct timeval t1
, t2
;
4391 bool force_share
= false;
4395 static const struct option long_options
[] = {
4396 {"help", no_argument
, 0, 'h'},
4397 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4398 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4399 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4400 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4401 {"force-share", no_argument
, 0, 'U'},
4404 c
= getopt_long(argc
, argv
, ":hc:d:f:ni:o:qs:S:t:wU", long_options
,
4412 missing_argument(argv
[optind
- 1]);
4415 unrecognized_option(argv
[optind
- 1]);
4424 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4425 error_report("Invalid request count specified");
4435 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4436 error_report("Invalid queue depth specified");
4446 flags
|= BDRV_O_NATIVE_AIO
;
4449 ret
= bdrv_parse_aio(optarg
, &flags
);
4451 error_report("Invalid aio option: %s", optarg
);
4458 offset
= cvtnum("offset", optarg
);
4472 sval
= cvtnum_full("buffer size", optarg
, 0, INT_MAX
);
4484 sval
= cvtnum_full("step_size", optarg
, 0, INT_MAX
);
4493 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4495 error_report("Invalid cache mode");
4501 flags
|= BDRV_O_RDWR
;
4507 case OPTION_PATTERN
:
4511 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4512 error_report("Invalid pattern byte specified");
4518 case OPTION_FLUSH_INTERVAL
:
4522 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4523 error_report("Invalid flush interval specified");
4526 flush_interval
= res
;
4529 case OPTION_NO_DRAIN
:
4530 drain_on_flush
= false;
4532 case OPTION_IMAGE_OPTS
:
4538 if (optind
!= argc
- 1) {
4539 error_exit("Expecting one image file name");
4541 filename
= argv
[argc
- 1];
4543 if (!is_write
&& flush_interval
) {
4544 error_report("--flush-interval is only available in write tests");
4548 if (flush_interval
&& flush_interval
< depth
) {
4549 error_report("Flush interval can't be smaller than depth");
4554 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4561 image_size
= blk_getlength(blk
);
4562 if (image_size
< 0) {
4567 data
= (BenchData
) {
4569 .image_size
= image_size
,
4571 .step
= step
?: bufsize
,
4576 .flush_interval
= flush_interval
,
4577 .drain_on_flush
= drain_on_flush
,
4579 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4580 "(starting at offset %" PRId64
", step size %d)\n",
4581 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4582 data
.offset
, data
.step
);
4583 if (flush_interval
) {
4584 printf("Sending flush every %d requests\n", flush_interval
);
4587 buf_size
= data
.nrreq
* data
.bufsize
;
4588 data
.buf
= blk_blockalign(blk
, buf_size
);
4589 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4591 blk_register_buf(blk
, data
.buf
, buf_size
);
4593 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4594 for (i
= 0; i
< data
.nrreq
; i
++) {
4595 qemu_iovec_init(&data
.qiov
[i
], 1);
4596 qemu_iovec_add(&data
.qiov
[i
],
4597 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4600 gettimeofday(&t1
, NULL
);
4603 while (data
.n
> 0) {
4604 main_loop_wait(false);
4606 gettimeofday(&t2
, NULL
);
4608 printf("Run completed in %3.3f seconds.\n",
4609 (t2
.tv_sec
- t1
.tv_sec
)
4610 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4614 blk_unregister_buf(blk
, data
.buf
);
4616 qemu_vfree(data
.buf
);
4633 typedef struct ImgBitmapAction
{
4634 enum ImgBitmapAct act
;
4635 const char *src
; /* only used for merge */
4636 QSIMPLEQ_ENTRY(ImgBitmapAction
) next
;
4639 static int img_bitmap(int argc
, char **argv
)
4643 QemuOpts
*opts
= NULL
;
4644 const char *fmt
= NULL
, *src_fmt
= NULL
, *src_filename
= NULL
;
4645 const char *filename
, *bitmap
;
4646 BlockBackend
*blk
= NULL
, *src
= NULL
;
4647 BlockDriverState
*bs
= NULL
, *src_bs
= NULL
;
4648 bool image_opts
= false;
4649 int64_t granularity
= 0;
4650 bool add
= false, merge
= false;
4651 QSIMPLEQ_HEAD(, ImgBitmapAction
) actions
;
4652 ImgBitmapAction
*act
, *act_next
;
4655 QSIMPLEQ_INIT(&actions
);
4658 static const struct option long_options
[] = {
4659 {"help", no_argument
, 0, 'h'},
4660 {"object", required_argument
, 0, OPTION_OBJECT
},
4661 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4662 {"add", no_argument
, 0, OPTION_ADD
},
4663 {"remove", no_argument
, 0, OPTION_REMOVE
},
4664 {"clear", no_argument
, 0, OPTION_CLEAR
},
4665 {"enable", no_argument
, 0, OPTION_ENABLE
},
4666 {"disable", no_argument
, 0, OPTION_DISABLE
},
4667 {"merge", required_argument
, 0, OPTION_MERGE
},
4668 {"granularity", required_argument
, 0, 'g'},
4669 {"source-file", required_argument
, 0, 'b'},
4670 {"source-format", required_argument
, 0, 'F'},
4673 c
= getopt_long(argc
, argv
, ":b:f:F:g:h", long_options
, NULL
);
4680 missing_argument(argv
[optind
- 1]);
4683 unrecognized_option(argv
[optind
- 1]);
4689 src_filename
= optarg
;
4698 granularity
= cvtnum("granularity", optarg
);
4699 if (granularity
< 0) {
4704 act
= g_new0(ImgBitmapAction
, 1);
4705 act
->act
= BITMAP_ADD
;
4706 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4710 act
= g_new0(ImgBitmapAction
, 1);
4711 act
->act
= BITMAP_REMOVE
;
4712 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4715 act
= g_new0(ImgBitmapAction
, 1);
4716 act
->act
= BITMAP_CLEAR
;
4717 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4720 act
= g_new0(ImgBitmapAction
, 1);
4721 act
->act
= BITMAP_ENABLE
;
4722 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4724 case OPTION_DISABLE
:
4725 act
= g_new0(ImgBitmapAction
, 1);
4726 act
->act
= BITMAP_DISABLE
;
4727 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4730 act
= g_new0(ImgBitmapAction
, 1);
4731 act
->act
= BITMAP_MERGE
;
4733 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4737 opts
= qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true);
4742 case OPTION_IMAGE_OPTS
:
4748 if (qemu_opts_foreach(&qemu_object_opts
,
4749 user_creatable_add_opts_foreach
,
4750 qemu_img_object_print_help
, &error_fatal
)) {
4754 if (QSIMPLEQ_EMPTY(&actions
)) {
4755 error_report("Need at least one of --add, --remove, --clear, "
4756 "--enable, --disable, or --merge");
4760 if (granularity
&& !add
) {
4761 error_report("granularity only supported with --add");
4764 if (src_fmt
&& !src_filename
) {
4765 error_report("-F only supported with -b");
4768 if (src_filename
&& !merge
) {
4769 error_report("Merge bitmap source file only supported with "
4774 if (optind
!= argc
- 2) {
4775 error_report("Expecting filename and bitmap name");
4779 filename
= argv
[optind
];
4780 bitmap
= argv
[optind
+ 1];
4782 blk
= img_open(image_opts
, filename
, fmt
, BDRV_O_RDWR
, false, false,
4789 src
= img_open(false, src_filename
, src_fmt
, 0, false, false, false);
4793 src_bs
= blk_bs(src
);
4798 QSIMPLEQ_FOREACH_SAFE(act
, &actions
, next
, act_next
) {
4801 qmp_block_dirty_bitmap_add(bs
->node_name
, bitmap
,
4802 !!granularity
, granularity
, true, true,
4803 false, false, &err
);
4807 qmp_block_dirty_bitmap_remove(bs
->node_name
, bitmap
, &err
);
4811 qmp_block_dirty_bitmap_clear(bs
->node_name
, bitmap
, &err
);
4815 qmp_block_dirty_bitmap_enable(bs
->node_name
, bitmap
, &err
);
4818 case BITMAP_DISABLE
:
4819 qmp_block_dirty_bitmap_disable(bs
->node_name
, bitmap
, &err
);
4823 do_dirty_bitmap_merge(bs
->node_name
, bitmap
, src_bs
->node_name
,
4828 g_assert_not_reached();
4832 error_reportf_err(err
, "Operation %s on bitmap %s failed: ",
4844 qemu_opts_del(opts
);
4860 int bsz
; /* Block size */
4868 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4872 static int img_dd_bs(const char *arg
,
4873 struct DdIo
*in
, struct DdIo
*out
,
4878 res
= cvtnum_full("bs", arg
, 1, INT_MAX
);
4883 in
->bsz
= out
->bsz
= res
;
4888 static int img_dd_count(const char *arg
,
4889 struct DdIo
*in
, struct DdIo
*out
,
4892 dd
->count
= cvtnum("count", arg
);
4894 if (dd
->count
< 0) {
4901 static int img_dd_if(const char *arg
,
4902 struct DdIo
*in
, struct DdIo
*out
,
4905 in
->filename
= g_strdup(arg
);
4910 static int img_dd_of(const char *arg
,
4911 struct DdIo
*in
, struct DdIo
*out
,
4914 out
->filename
= g_strdup(arg
);
4919 static int img_dd_skip(const char *arg
,
4920 struct DdIo
*in
, struct DdIo
*out
,
4923 in
->offset
= cvtnum("skip", arg
);
4925 if (in
->offset
< 0) {
4932 static int img_dd(int argc
, char **argv
)
4937 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4938 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4939 QemuOpts
*opts
= NULL
;
4940 QemuOptsList
*create_opts
= NULL
;
4941 Error
*local_err
= NULL
;
4942 bool image_opts
= false;
4944 const char *out_fmt
= "raw";
4945 const char *fmt
= NULL
;
4947 int64_t block_count
= 0, out_pos
, in_pos
;
4948 bool force_share
= false;
4949 struct DdInfo dd
= {
4954 .bsz
= 512, /* Block size is by default 512 bytes */
4966 const struct DdOpts options
[] = {
4967 { "bs", img_dd_bs
, C_BS
},
4968 { "count", img_dd_count
, C_COUNT
},
4969 { "if", img_dd_if
, C_IF
},
4970 { "of", img_dd_of
, C_OF
},
4971 { "skip", img_dd_skip
, C_SKIP
},
4974 const struct option long_options
[] = {
4975 { "help", no_argument
, 0, 'h'},
4976 { "object", required_argument
, 0, OPTION_OBJECT
},
4977 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4978 { "force-share", no_argument
, 0, 'U'},
4982 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4994 missing_argument(argv
[optind
- 1]);
4997 unrecognized_option(argv
[optind
- 1]);
5006 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
5011 case OPTION_IMAGE_OPTS
:
5017 for (i
= optind
; i
< argc
; i
++) {
5019 arg
= g_strdup(argv
[i
]);
5021 tmp
= strchr(arg
, '=');
5023 error_report("unrecognized operand %s", arg
);
5030 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
5031 if (!strcmp(arg
, options
[j
].name
)) {
5035 if (options
[j
].name
== NULL
) {
5036 error_report("unrecognized operand %s", arg
);
5041 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
5045 dd
.flags
|= options
[j
].flag
;
5050 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
5051 error_report("Must specify both input and output files");
5056 if (qemu_opts_foreach(&qemu_object_opts
,
5057 user_creatable_add_opts_foreach
,
5058 qemu_img_object_print_help
, &error_fatal
)) {
5063 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
5071 drv
= bdrv_find_format(out_fmt
);
5073 error_report("Unknown file format");
5077 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
5080 error_report_err(local_err
);
5084 if (!drv
->create_opts
) {
5085 error_report("Format driver '%s' does not support image creation",
5090 if (!proto_drv
->create_opts
) {
5091 error_report("Protocol driver '%s' does not support image creation",
5092 proto_drv
->format_name
);
5096 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5097 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
5099 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5101 size
= blk_getlength(blk1
);
5103 error_report("Failed to get size for '%s'", in
.filename
);
5108 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
5109 dd
.count
* in
.bsz
< size
) {
5110 size
= dd
.count
* in
.bsz
;
5113 /* Overflow means the specified offset is beyond input image's size */
5114 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5115 size
< in
.bsz
* in
.offset
)) {
5116 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
5118 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
5119 size
- in
.bsz
* in
.offset
, &error_abort
);
5122 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
5124 error_reportf_err(local_err
,
5125 "%s: error while creating output image: ",
5131 /* TODO, we can't honour --image-opts for the target,
5132 * since it needs to be given in a format compatible
5133 * with the bdrv_create() call above which does not
5134 * support image-opts style.
5136 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
5137 false, false, false);
5144 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5145 size
< in
.offset
* in
.bsz
)) {
5146 /* We give a warning if the skip option is bigger than the input
5147 * size and create an empty output disk image (i.e. like dd(1)).
5149 error_report("%s: cannot skip to specified offset", in
.filename
);
5152 in_pos
= in
.offset
* in
.bsz
;
5155 in
.buf
= g_new(uint8_t, in
.bsz
);
5157 for (out_pos
= 0; in_pos
< size
; block_count
++) {
5158 int in_ret
, out_ret
;
5160 if (in_pos
+ in
.bsz
> size
) {
5161 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
5163 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
5166 error_report("error while reading from input image file: %s",
5173 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
5176 error_report("error while writing to output image file: %s",
5177 strerror(-out_ret
));
5186 qemu_opts_del(opts
);
5187 qemu_opts_free(create_opts
);
5190 g_free(in
.filename
);
5191 g_free(out
.filename
);
5201 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
5205 Visitor
*v
= qobject_output_visitor_new(&obj
);
5207 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
5208 visit_complete(v
, &obj
);
5209 str
= qobject_to_json_pretty(obj
);
5210 assert(str
!= NULL
);
5211 printf("%s\n", qstring_get_str(str
));
5217 static int img_measure(int argc
, char **argv
)
5219 static const struct option long_options
[] = {
5220 {"help", no_argument
, 0, 'h'},
5221 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
5222 {"object", required_argument
, 0, OPTION_OBJECT
},
5223 {"output", required_argument
, 0, OPTION_OUTPUT
},
5224 {"size", required_argument
, 0, OPTION_SIZE
},
5225 {"force-share", no_argument
, 0, 'U'},
5228 OutputFormat output_format
= OFORMAT_HUMAN
;
5229 BlockBackend
*in_blk
= NULL
;
5231 const char *filename
= NULL
;
5232 const char *fmt
= NULL
;
5233 const char *out_fmt
= "raw";
5234 char *options
= NULL
;
5235 char *snapshot_name
= NULL
;
5236 bool force_share
= false;
5237 QemuOpts
*opts
= NULL
;
5238 QemuOpts
*object_opts
= NULL
;
5239 QemuOpts
*sn_opts
= NULL
;
5240 QemuOptsList
*create_opts
= NULL
;
5241 bool image_opts
= false;
5242 uint64_t img_size
= UINT64_MAX
;
5243 BlockMeasureInfo
*info
= NULL
;
5244 Error
*local_err
= NULL
;
5248 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
5249 long_options
, NULL
)) != -1) {
5262 if (accumulate_options(&options
, optarg
) < 0) {
5267 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
5268 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
5271 error_report("Failed in parsing snapshot param '%s'",
5276 snapshot_name
= optarg
;
5283 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
5289 case OPTION_IMAGE_OPTS
:
5293 if (!strcmp(optarg
, "json")) {
5294 output_format
= OFORMAT_JSON
;
5295 } else if (!strcmp(optarg
, "human")) {
5296 output_format
= OFORMAT_HUMAN
;
5298 error_report("--output must be used with human or json "
5307 sval
= cvtnum("image size", optarg
);
5311 img_size
= (uint64_t)sval
;
5317 if (qemu_opts_foreach(&qemu_object_opts
,
5318 user_creatable_add_opts_foreach
,
5319 qemu_img_object_print_help
, &error_fatal
)) {
5323 if (argc
- optind
> 1) {
5324 error_report("At most one filename argument is allowed.");
5326 } else if (argc
- optind
== 1) {
5327 filename
= argv
[optind
];
5330 if (!filename
&& (image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
5331 error_report("--image-opts, -f, and -l require a filename argument.");
5334 if (filename
&& img_size
!= UINT64_MAX
) {
5335 error_report("--size N cannot be used together with a filename.");
5338 if (!filename
&& img_size
== UINT64_MAX
) {
5339 error_report("Either --size N or one filename must be specified.");
5344 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
5345 false, false, force_share
);
5351 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
5352 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
5353 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
5355 } else if (snapshot_name
!= NULL
) {
5356 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
5357 snapshot_name
, &local_err
);
5360 error_reportf_err(local_err
, "Failed to load snapshot: ");
5365 drv
= bdrv_find_format(out_fmt
);
5367 error_report("Unknown file format '%s'", out_fmt
);
5370 if (!drv
->create_opts
) {
5371 error_report("Format driver '%s' does not support image creation",
5376 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5377 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
5378 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5380 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
5381 error_report_err(local_err
);
5382 error_report("Invalid options for file format '%s'", out_fmt
);
5386 if (img_size
!= UINT64_MAX
) {
5387 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
5390 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
5392 error_report_err(local_err
);
5396 if (output_format
== OFORMAT_HUMAN
) {
5397 printf("required size: %" PRIu64
"\n", info
->required
);
5398 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
5399 if (info
->has_bitmaps
) {
5400 printf("bitmaps size: %" PRIu64
"\n", info
->bitmaps
);
5403 dump_json_block_measure_info(info
);
5409 qapi_free_BlockMeasureInfo(info
);
5410 qemu_opts_del(object_opts
);
5411 qemu_opts_del(opts
);
5412 qemu_opts_del(sn_opts
);
5413 qemu_opts_free(create_opts
);
5419 static const img_cmd_t img_cmds
[] = {
5420 #define DEF(option, callback, arg_string) \
5421 { option, callback },
5422 #include "qemu-img-cmds.h"
5427 int main(int argc
, char **argv
)
5429 const img_cmd_t
*cmd
;
5430 const char *cmdname
;
5431 Error
*local_error
= NULL
;
5432 char *trace_file
= NULL
;
5434 static const struct option long_options
[] = {
5435 {"help", no_argument
, 0, 'h'},
5436 {"version", no_argument
, 0, 'V'},
5437 {"trace", required_argument
, NULL
, 'T'},
5442 signal(SIGPIPE
, SIG_IGN
);
5446 error_init(argv
[0]);
5447 module_call_init(MODULE_INIT_TRACE
);
5448 qemu_init_exec_dir(argv
[0]);
5450 if (qemu_init_main_loop(&local_error
)) {
5451 error_report_err(local_error
);
5455 qcrypto_init(&error_fatal
);
5457 module_call_init(MODULE_INIT_QOM
);
5460 error_exit("Not enough arguments");
5463 qemu_add_opts(&qemu_object_opts
);
5464 qemu_add_opts(&qemu_source_opts
);
5465 qemu_add_opts(&qemu_trace_opts
);
5467 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
5470 missing_argument(argv
[optind
- 1]);
5473 unrecognized_option(argv
[optind
- 1]);
5479 printf(QEMU_IMG_VERSION
);
5483 trace_file
= trace_opt_parse(optarg
);
5488 cmdname
= argv
[optind
];
5490 /* reset getopt_long scanning */
5496 qemu_reset_optind();
5498 if (!trace_init_backends()) {
5501 trace_init_file(trace_file
);
5502 qemu_set_log(LOG_TRACE
);
5504 /* find the command */
5505 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5506 if (!strcmp(cmdname
, cmd
->name
)) {
5507 return cmd
->handler(argc
, argv
);
5512 error_exit("Command not found: %s", cmdname
);