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"
53 #include "qemu/throttle.h"
54 #include "block/throttle-groups.h"
56 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
57 "\n" QEMU_COPYRIGHT "\n"
59 typedef struct img_cmd_t
{
61 int (*handler
)(int argc
, char **argv
);
66 OPTION_BACKING_CHAIN
= 257,
68 OPTION_IMAGE_OPTS
= 259,
70 OPTION_FLUSH_INTERVAL
= 261,
71 OPTION_NO_DRAIN
= 262,
72 OPTION_TARGET_IMAGE_OPTS
= 263,
74 OPTION_PREALLOCATION
= 265,
77 OPTION_TARGET_IS_ZERO
= 268,
88 typedef enum OutputFormat
{
93 /* Default to cache=writeback as data integrity is not important for qemu-img */
94 #define BDRV_DEFAULT_CACHE "writeback"
96 static void format_print(void *opaque
, const char *name
)
101 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
106 error_vreport(fmt
, ap
);
109 error_printf("Try 'qemu-img --help' for more information\n");
113 static void QEMU_NORETURN
missing_argument(const char *option
)
115 error_exit("missing argument for option '%s'", option
);
118 static void QEMU_NORETURN
unrecognized_option(const char *option
)
120 error_exit("unrecognized option '%s'", option
);
123 /* Please keep in synch with docs/tools/qemu-img.rst */
124 static void QEMU_NORETURN
help(void)
126 const char *help_msg
=
128 "usage: qemu-img [standard options] command [command options]\n"
129 "QEMU disk image utility\n"
131 " '-h', '--help' display this help and exit\n"
132 " '-V', '--version' output version information and exit\n"
133 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
134 " specify tracing options\n"
137 #define DEF(option, callback, arg_string) \
139 #include "qemu-img-cmds.h"
142 "Command parameters:\n"
143 " 'filename' is a disk image filename\n"
144 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
145 " manual page for a description of the object properties. The most common\n"
146 " object type is a 'secret', which is used to supply passwords and/or\n"
147 " encryption keys.\n"
148 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
149 " 'cache' is the cache mode used to write the output disk image, the valid\n"
150 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
151 " 'directsync' and 'unsafe' (default for convert)\n"
152 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
153 " options are the same as for the 'cache' option\n"
154 " 'size' is the disk image size in bytes. Optional suffixes\n"
155 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
156 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
157 " supported. 'b' is ignored.\n"
158 " 'output_filename' is the destination disk image filename\n"
159 " 'output_fmt' is the destination format\n"
160 " 'options' is a comma separated list of format specific options in a\n"
161 " name=value format. Use -o ? for an overview of the options supported by the\n"
163 " 'snapshot_param' is param used for internal snapshot, format\n"
164 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
166 " '-c' indicates that target image must be compressed (qcow format only)\n"
167 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
168 " new backing file match exactly. The image doesn't need a working\n"
169 " backing file before rebasing in this case (useful for renaming the\n"
170 " backing file). For image creation, allow creating without attempting\n"
171 " to open the backing file.\n"
172 " '-h' with or without a command shows this help and lists the supported formats\n"
173 " '-p' show progress of command (only certain commands)\n"
174 " '-q' use Quiet mode - do not print any output (except errors)\n"
175 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
176 " contain only zeros for qemu-img to create a sparse image during\n"
177 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
178 " unallocated or zero sectors, and the destination image will always be\n"
180 " '--output' takes the format in which the output must be done (human or json)\n"
181 " '-n' skips the target volume creation (useful if the volume is created\n"
182 " prior to running qemu-img)\n"
184 "Parameters to bitmap subcommand:\n"
185 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
186 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
187 " or '--merge source'\n"
188 " '-g granularity' sets the granularity for '--add' actions\n"
189 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
190 " bitmaps from an alternative file\n"
192 "Parameters to check subcommand:\n"
193 " '-r' tries to repair any inconsistencies that are found during the check.\n"
194 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
195 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
196 " hiding corruption that has already occurred.\n"
198 "Parameters to convert subcommand:\n"
199 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
200 " '-m' specifies how many coroutines work in parallel during the convert\n"
201 " process (defaults to 8)\n"
202 " '-W' allow to write to the target out of order rather than sequential\n"
204 "Parameters to snapshot subcommand:\n"
205 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
206 " '-a' applies a snapshot (revert disk to saved state)\n"
207 " '-c' creates a snapshot\n"
208 " '-d' deletes a snapshot\n"
209 " '-l' lists all snapshots in the given image\n"
211 "Parameters to compare subcommand:\n"
212 " '-f' first image format\n"
213 " '-F' second image format\n"
214 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
216 "Parameters to dd subcommand:\n"
217 " 'bs=BYTES' read and write up to BYTES bytes at a time "
219 " 'count=N' copy only N input blocks\n"
220 " 'if=FILE' read from FILE\n"
221 " 'of=FILE' write to FILE\n"
222 " 'skip=N' skip N bs-sized blocks at the start of input\n";
224 printf("%s\nSupported formats:", help_msg
);
225 bdrv_iterate_format(format_print
, NULL
, false);
226 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
230 static QemuOptsList qemu_object_opts
= {
232 .implied_opt_name
= "qom-type",
233 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
239 static bool qemu_img_object_print_help(const char *type
, QemuOpts
*opts
)
241 if (user_creatable_print_help(type
, opts
)) {
248 * Is @optarg safe for accumulate_options()?
249 * It is when multiple of them can be joined together separated by ','.
250 * To make that work, @optarg must not start with ',' (or else a
251 * separating ',' preceding it gets escaped), and it must not end with
252 * an odd number of ',' (or else a separating ',' following it gets
253 * escaped), or be empty (or else a separating ',' preceding it can
254 * escape a separating ',' following it).
257 static bool is_valid_option_list(const char *optarg
)
259 size_t len
= strlen(optarg
);
262 if (!optarg
[0] || optarg
[0] == ',') {
266 for (i
= len
; i
> 0 && optarg
[i
- 1] == ','; i
--) {
275 static int accumulate_options(char **options
, char *optarg
)
279 if (!is_valid_option_list(optarg
)) {
280 error_report("Invalid option list: %s", optarg
);
285 *options
= g_strdup(optarg
);
287 new_options
= g_strdup_printf("%s,%s", *options
, optarg
);
289 *options
= new_options
;
294 static QemuOptsList qemu_source_opts
= {
296 .implied_opt_name
= "file",
297 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
303 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
309 ret
= vprintf(fmt
, args
);
316 static int print_block_option_help(const char *filename
, const char *fmt
)
318 BlockDriver
*drv
, *proto_drv
;
319 QemuOptsList
*create_opts
= NULL
;
320 Error
*local_err
= NULL
;
322 /* Find driver and parse its options */
323 drv
= bdrv_find_format(fmt
);
325 error_report("Unknown file format '%s'", fmt
);
329 if (!drv
->create_opts
) {
330 error_report("Format driver '%s' does not support image creation", fmt
);
334 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
336 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
338 error_report_err(local_err
);
339 qemu_opts_free(create_opts
);
342 if (!proto_drv
->create_opts
) {
343 error_report("Protocol driver '%s' does not support image creation",
344 proto_drv
->format_name
);
345 qemu_opts_free(create_opts
);
348 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
352 printf("Supported options:\n");
354 printf("Supported %s options:\n", fmt
);
356 qemu_opts_print_help(create_opts
, false);
357 qemu_opts_free(create_opts
);
361 "The protocol level may support further options.\n"
362 "Specify the target filename to include those options.\n");
369 static BlockBackend
*img_open_opts(const char *optstr
,
370 QemuOpts
*opts
, int flags
, bool writethrough
,
371 bool quiet
, bool force_share
)
374 Error
*local_err
= NULL
;
376 options
= qemu_opts_to_qdict(opts
, NULL
);
378 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
379 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
380 error_report("--force-share/-U conflicts with image options");
381 qobject_unref(options
);
384 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
386 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
388 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
391 blk_set_enable_write_cache(blk
, !writethrough
);
396 static BlockBackend
*img_open_file(const char *filename
,
398 const char *fmt
, int flags
,
399 bool writethrough
, bool quiet
,
403 Error
*local_err
= NULL
;
406 options
= qdict_new();
409 qdict_put_str(options
, "driver", fmt
);
413 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
415 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
417 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
420 blk_set_enable_write_cache(blk
, !writethrough
);
426 static int img_add_key_secrets(void *opaque
,
427 const char *name
, const char *value
,
430 QDict
*options
= opaque
;
432 if (g_str_has_suffix(name
, "key-secret")) {
433 qdict_put_str(options
, name
, value
);
440 static BlockBackend
*img_open(bool image_opts
,
441 const char *filename
,
442 const char *fmt
, int flags
, bool writethrough
,
443 bool quiet
, bool force_share
)
449 error_report("--image-opts and --format are mutually exclusive");
452 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
457 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
460 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
467 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
468 const char *base_filename
,
469 const char *base_fmt
)
472 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
474 error_report("Backing file not supported for file format '%s'",
480 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
481 error_report("Backing file format not supported for file "
489 static int64_t cvtnum_full(const char *name
, const char *value
, int64_t min
,
495 err
= qemu_strtosz(value
, NULL
, &res
);
496 if (err
< 0 && err
!= -ERANGE
) {
497 error_report("Invalid %s specified. You may use "
498 "k, M, G, T, P or E suffixes for", name
);
499 error_report("kilobytes, megabytes, gigabytes, terabytes, "
500 "petabytes and exabytes.");
503 if (err
== -ERANGE
|| res
> max
|| res
< min
) {
504 error_report("Invalid %s specified. Must be between %" PRId64
505 " and %" PRId64
".", name
, min
, max
);
511 static int64_t cvtnum(const char *name
, const char *value
)
513 return cvtnum_full(name
, value
, 0, INT64_MAX
);
516 static int img_create(int argc
, char **argv
)
519 uint64_t img_size
= -1;
520 const char *fmt
= "raw";
521 const char *base_fmt
= NULL
;
522 const char *filename
;
523 const char *base_filename
= NULL
;
524 char *options
= NULL
;
525 Error
*local_err
= NULL
;
530 static const struct option long_options
[] = {
531 {"help", no_argument
, 0, 'h'},
532 {"object", required_argument
, 0, OPTION_OBJECT
},
535 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
542 missing_argument(argv
[optind
- 1]);
545 unrecognized_option(argv
[optind
- 1]);
554 base_filename
= optarg
;
560 if (accumulate_options(&options
, optarg
) < 0) {
568 flags
|= BDRV_O_NO_BACKING
;
570 case OPTION_OBJECT
: {
572 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
581 /* Get the filename */
582 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
583 if (options
&& has_help_option(options
)) {
585 return print_block_option_help(filename
, fmt
);
588 if (optind
>= argc
) {
589 error_exit("Expecting image file name");
593 if (qemu_opts_foreach(&qemu_object_opts
,
594 user_creatable_add_opts_foreach
,
595 qemu_img_object_print_help
, &error_fatal
)) {
599 /* Get image size, if specified */
603 sval
= cvtnum("image size", argv
[optind
++]);
607 img_size
= (uint64_t)sval
;
609 if (optind
!= argc
) {
610 error_exit("Unexpected argument: %s", argv
[optind
]);
613 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
614 options
, img_size
, flags
, quiet
, &local_err
);
616 error_reportf_err(local_err
, "%s: ", filename
);
628 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
632 Visitor
*v
= qobject_output_visitor_new(&obj
);
634 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
635 visit_complete(v
, &obj
);
636 str
= qobject_to_json_pretty(obj
);
638 qprintf(quiet
, "%s\n", qstring_get_str(str
));
644 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
646 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
647 qprintf(quiet
, "No errors were found on the image.\n");
649 if (check
->corruptions
) {
650 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
651 "Data may be corrupted, or further writes to the image "
658 "\n%" PRId64
" leaked clusters were found on the image.\n"
659 "This means waste of disk space, but no harm to data.\n",
663 if (check
->check_errors
) {
666 " internal errors have occurred during the check.\n",
667 check
->check_errors
);
671 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
672 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
673 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
674 check
->allocated_clusters
, check
->total_clusters
,
675 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
676 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
677 check
->compressed_clusters
* 100.0 /
678 check
->allocated_clusters
);
681 if (check
->image_end_offset
) {
683 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
687 static int collect_image_check(BlockDriverState
*bs
,
689 const char *filename
,
694 BdrvCheckResult result
;
696 ret
= bdrv_check(bs
, &result
, fix
);
701 check
->filename
= g_strdup(filename
);
702 check
->format
= g_strdup(bdrv_get_format_name(bs
));
703 check
->check_errors
= result
.check_errors
;
704 check
->corruptions
= result
.corruptions
;
705 check
->has_corruptions
= result
.corruptions
!= 0;
706 check
->leaks
= result
.leaks
;
707 check
->has_leaks
= result
.leaks
!= 0;
708 check
->corruptions_fixed
= result
.corruptions_fixed
;
709 check
->has_corruptions_fixed
= result
.corruptions_fixed
!= 0;
710 check
->leaks_fixed
= result
.leaks_fixed
;
711 check
->has_leaks_fixed
= result
.leaks_fixed
!= 0;
712 check
->image_end_offset
= result
.image_end_offset
;
713 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
714 check
->total_clusters
= result
.bfi
.total_clusters
;
715 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
716 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
717 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
718 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
719 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
720 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
721 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
727 * Checks an image for consistency. Exit codes:
729 * 0 - Check completed, image is good
730 * 1 - Check not completed because of internal errors
731 * 2 - Check completed, image is corrupted
732 * 3 - Check completed, image has leaked clusters, but is good otherwise
733 * 63 - Checks are not supported by the image format
735 static int img_check(int argc
, char **argv
)
738 OutputFormat output_format
= OFORMAT_HUMAN
;
739 const char *filename
, *fmt
, *output
, *cache
;
741 BlockDriverState
*bs
;
743 int flags
= BDRV_O_CHECK
;
747 bool image_opts
= false;
748 bool force_share
= false;
752 cache
= BDRV_DEFAULT_CACHE
;
755 int option_index
= 0;
756 static const struct option long_options
[] = {
757 {"help", no_argument
, 0, 'h'},
758 {"format", required_argument
, 0, 'f'},
759 {"repair", required_argument
, 0, 'r'},
760 {"output", required_argument
, 0, OPTION_OUTPUT
},
761 {"object", required_argument
, 0, OPTION_OBJECT
},
762 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
763 {"force-share", no_argument
, 0, 'U'},
766 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
767 long_options
, &option_index
);
773 missing_argument(argv
[optind
- 1]);
776 unrecognized_option(argv
[optind
- 1]);
785 flags
|= BDRV_O_RDWR
;
787 if (!strcmp(optarg
, "leaks")) {
788 fix
= BDRV_FIX_LEAKS
;
789 } else if (!strcmp(optarg
, "all")) {
790 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
792 error_exit("Unknown option value for -r "
793 "(expecting 'leaks' or 'all'): %s", optarg
);
808 case OPTION_OBJECT
: {
810 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
816 case OPTION_IMAGE_OPTS
:
821 if (optind
!= argc
- 1) {
822 error_exit("Expecting one image file name");
824 filename
= argv
[optind
++];
826 if (output
&& !strcmp(output
, "json")) {
827 output_format
= OFORMAT_JSON
;
828 } else if (output
&& !strcmp(output
, "human")) {
829 output_format
= OFORMAT_HUMAN
;
831 error_report("--output must be used with human or json as argument.");
835 if (qemu_opts_foreach(&qemu_object_opts
,
836 user_creatable_add_opts_foreach
,
837 qemu_img_object_print_help
, &error_fatal
)) {
841 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
843 error_report("Invalid source cache option: %s", cache
);
847 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
854 check
= g_new0(ImageCheck
, 1);
855 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
857 if (ret
== -ENOTSUP
) {
858 error_report("This image format does not support checks");
863 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
864 int corruptions_fixed
, leaks_fixed
;
865 bool has_leaks_fixed
, has_corruptions_fixed
;
867 leaks_fixed
= check
->leaks_fixed
;
868 has_leaks_fixed
= check
->has_leaks_fixed
;
869 corruptions_fixed
= check
->corruptions_fixed
;
870 has_corruptions_fixed
= check
->has_corruptions_fixed
;
872 if (output_format
== OFORMAT_HUMAN
) {
874 "The following inconsistencies were found and repaired:\n\n"
875 " %" PRId64
" leaked clusters\n"
876 " %" PRId64
" corruptions\n\n"
877 "Double checking the fixed image now...\n",
879 check
->corruptions_fixed
);
882 qapi_free_ImageCheck(check
);
883 check
= g_new0(ImageCheck
, 1);
884 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
886 check
->leaks_fixed
= leaks_fixed
;
887 check
->has_leaks_fixed
= has_leaks_fixed
;
888 check
->corruptions_fixed
= corruptions_fixed
;
889 check
->has_corruptions_fixed
= has_corruptions_fixed
;
893 switch (output_format
) {
895 dump_human_image_check(check
, quiet
);
898 dump_json_image_check(check
, quiet
);
903 if (ret
|| check
->check_errors
) {
905 error_report("Check failed: %s", strerror(-ret
));
907 error_report("Check failed");
913 if (check
->corruptions
) {
915 } else if (check
->leaks
) {
922 qapi_free_ImageCheck(check
);
927 typedef struct CommonBlockJobCBInfo
{
928 BlockDriverState
*bs
;
930 } CommonBlockJobCBInfo
;
932 static void common_block_job_cb(void *opaque
, int ret
)
934 CommonBlockJobCBInfo
*cbi
= opaque
;
937 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
941 static void run_block_job(BlockJob
*job
, Error
**errp
)
943 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
946 aio_context_acquire(aio_context
);
949 float progress
= 0.0f
;
950 aio_poll(aio_context
, true);
951 if (job
->job
.progress
.total
) {
952 progress
= (float)job
->job
.progress
.current
/
953 job
->job
.progress
.total
* 100.f
;
955 qemu_progress_print(progress
, 0);
956 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
958 if (!job_is_completed(&job
->job
)) {
959 ret
= job_complete_sync(&job
->job
, errp
);
963 job_unref(&job
->job
);
964 aio_context_release(aio_context
);
966 /* publish completion progress only when success */
968 qemu_progress_print(100.f
, 0);
972 static int img_commit(int argc
, char **argv
)
975 const char *filename
, *fmt
, *cache
, *base
;
977 BlockDriverState
*bs
, *base_bs
;
979 bool progress
= false, quiet
= false, drop
= false;
981 Error
*local_err
= NULL
;
982 CommonBlockJobCBInfo cbi
;
983 bool image_opts
= false;
984 AioContext
*aio_context
;
985 int64_t rate_limit
= 0;
988 cache
= BDRV_DEFAULT_CACHE
;
991 static const struct option long_options
[] = {
992 {"help", no_argument
, 0, 'h'},
993 {"object", required_argument
, 0, OPTION_OBJECT
},
994 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
997 c
= getopt_long(argc
, argv
, ":f:ht:b:dpqr:",
1004 missing_argument(argv
[optind
- 1]);
1007 unrecognized_option(argv
[optind
- 1]);
1033 rate_limit
= cvtnum("rate limit", optarg
);
1034 if (rate_limit
< 0) {
1038 case OPTION_OBJECT
: {
1040 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1046 case OPTION_IMAGE_OPTS
:
1052 /* Progress is not shown in Quiet mode */
1057 if (optind
!= argc
- 1) {
1058 error_exit("Expecting one image file name");
1060 filename
= argv
[optind
++];
1062 if (qemu_opts_foreach(&qemu_object_opts
,
1063 user_creatable_add_opts_foreach
,
1064 qemu_img_object_print_help
, &error_fatal
)) {
1068 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
1069 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1071 error_report("Invalid cache option: %s", cache
);
1075 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1082 qemu_progress_init(progress
, 1.f
);
1083 qemu_progress_print(0.f
, 100);
1086 base_bs
= bdrv_find_backing_image(bs
, base
);
1088 error_setg(&local_err
,
1089 "Did not find '%s' in the backing chain of '%s'",
1094 /* This is different from QMP, which by default uses the deepest file in
1095 * the backing chain (i.e., the very base); however, the traditional
1096 * behavior of qemu-img commit is using the immediate backing file. */
1097 base_bs
= bdrv_backing_chain_next(bs
);
1099 error_setg(&local_err
, "Image does not have a backing file");
1104 cbi
= (CommonBlockJobCBInfo
){
1109 aio_context
= bdrv_get_aio_context(bs
);
1110 aio_context_acquire(aio_context
);
1111 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, rate_limit
,
1112 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1113 &cbi
, false, &local_err
);
1114 aio_context_release(aio_context
);
1119 /* When the block job completes, the BlockBackend reference will point to
1120 * the old backing file. In order to avoid that the top image is already
1121 * deleted, so we can still empty it afterwards, increment the reference
1122 * counter here preemptively. */
1127 job
= block_job_get("commit");
1129 run_block_job(job
, &local_err
);
1135 BlockBackend
*old_backing_blk
;
1137 old_backing_blk
= blk_new_with_bs(bs
, BLK_PERM_WRITE
, BLK_PERM_ALL
,
1139 if (!old_backing_blk
) {
1142 ret
= blk_make_empty(old_backing_blk
, &local_err
);
1143 blk_unref(old_backing_blk
);
1144 if (ret
== -ENOTSUP
) {
1145 error_free(local_err
);
1147 } else if (ret
< 0) {
1158 qemu_progress_end();
1163 error_report_err(local_err
);
1167 qprintf(quiet
, "Image committed.\n");
1172 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1173 * of the first sector boundary within buf where the sector contains a
1174 * non-zero byte. This function is robust to a buffer that is not
1177 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1180 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1182 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1183 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1187 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1194 * Returns true iff the first sector pointed to by 'buf' contains at least
1197 * 'pnum' is set to the number of sectors (including and immediately following
1198 * the first one) that are known to be in the same allocated/unallocated state.
1199 * The function will try to align the end offset to alignment boundaries so
1200 * that the request will at least end aligned and consecutive requests will
1201 * also start at an aligned offset.
1203 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1204 int64_t sector_num
, int alignment
)
1213 is_zero
= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
);
1214 for(i
= 1; i
< n
; i
++) {
1215 buf
+= BDRV_SECTOR_SIZE
;
1216 if (is_zero
!= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
)) {
1221 tail
= (sector_num
+ i
) & (alignment
- 1);
1223 if (is_zero
&& i
<= tail
) {
1224 /* treat unallocated areas which only consist
1225 * of a small tail as allocated. */
1229 /* align up end offset of allocated areas. */
1230 i
+= alignment
- tail
;
1233 /* align down end offset of zero areas. */
1242 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1243 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1244 * breaking up write requests for only small sparse areas.
1246 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1247 int min
, int64_t sector_num
, int alignment
)
1250 int num_checked
, num_used
;
1256 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1262 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1264 sector_num
+= *pnum
;
1265 num_checked
= num_used
;
1268 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1270 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1272 sector_num
+= *pnum
;
1273 num_checked
+= *pnum
;
1275 num_used
= num_checked
;
1276 } else if (*pnum
>= min
) {
1286 * Compares two buffers sector by sector. Returns 0 if the first
1287 * sector of each buffer matches, non-zero otherwise.
1289 * pnum is set to the sector-aligned size of the buffer prefix that
1290 * has the same matching status as the first sector.
1292 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1293 int64_t bytes
, int64_t *pnum
)
1296 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1300 res
= !!memcmp(buf1
, buf2
, i
);
1302 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1304 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1314 #define IO_BUF_SIZE (2 * MiB)
1317 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1319 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1320 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1321 * failure), and 4 on error (the exit status for read errors), after emitting
1324 * @param blk: BlockBackend for the image
1325 * @param offset: Starting offset to check
1326 * @param bytes: Number of bytes to check
1327 * @param filename: Name of disk file we are checking (logging purpose)
1328 * @param buffer: Allocated buffer for storing read data
1329 * @param quiet: Flag for quiet mode
1331 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1332 int64_t bytes
, const char *filename
,
1333 uint8_t *buffer
, bool quiet
)
1338 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1340 error_report("Error while reading offset %" PRId64
" of %s: %s",
1341 offset
, filename
, strerror(-ret
));
1344 idx
= find_nonzero(buffer
, bytes
);
1346 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1355 * Compares two images. Exit codes:
1357 * 0 - Images are identical
1359 * >1 - Error occurred
1361 static int img_compare(int argc
, char **argv
)
1363 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1364 BlockBackend
*blk1
, *blk2
;
1365 BlockDriverState
*bs1
, *bs2
;
1366 int64_t total_size1
, total_size2
;
1367 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1368 int64_t pnum1
, pnum2
;
1369 int allocated1
, allocated2
;
1370 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1371 bool progress
= false, quiet
= false, strict
= false;
1378 uint64_t progress_base
;
1379 bool image_opts
= false;
1380 bool force_share
= false;
1382 cache
= BDRV_DEFAULT_CACHE
;
1384 static const struct option long_options
[] = {
1385 {"help", no_argument
, 0, 'h'},
1386 {"object", required_argument
, 0, OPTION_OBJECT
},
1387 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1388 {"force-share", no_argument
, 0, 'U'},
1391 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1392 long_options
, NULL
);
1398 missing_argument(argv
[optind
- 1]);
1401 unrecognized_option(argv
[optind
- 1]);
1427 case OPTION_OBJECT
: {
1429 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1436 case OPTION_IMAGE_OPTS
:
1442 /* Progress is not shown in Quiet mode */
1448 if (optind
!= argc
- 2) {
1449 error_exit("Expecting two image file names");
1451 filename1
= argv
[optind
++];
1452 filename2
= argv
[optind
++];
1454 if (qemu_opts_foreach(&qemu_object_opts
,
1455 user_creatable_add_opts_foreach
,
1456 qemu_img_object_print_help
, &error_fatal
)) {
1461 /* Initialize before goto out */
1462 qemu_progress_init(progress
, 2.0);
1465 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1467 error_report("Invalid source cache option: %s", cache
);
1472 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1479 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1488 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1489 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1490 total_size1
= blk_getlength(blk1
);
1491 if (total_size1
< 0) {
1492 error_report("Can't get size of %s: %s",
1493 filename1
, strerror(-total_size1
));
1497 total_size2
= blk_getlength(blk2
);
1498 if (total_size2
< 0) {
1499 error_report("Can't get size of %s: %s",
1500 filename2
, strerror(-total_size2
));
1504 total_size
= MIN(total_size1
, total_size2
);
1505 progress_base
= MAX(total_size1
, total_size2
);
1507 qemu_progress_print(0, 100);
1509 if (strict
&& total_size1
!= total_size2
) {
1511 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1515 while (offset
< total_size
) {
1516 int status1
, status2
;
1518 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1519 total_size1
- offset
, &pnum1
, NULL
,
1523 error_report("Sector allocation test failed for %s", filename1
);
1526 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1528 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1529 total_size2
- offset
, &pnum2
, NULL
,
1533 error_report("Sector allocation test failed for %s", filename2
);
1536 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1538 assert(pnum1
&& pnum2
);
1539 chunk
= MIN(pnum1
, pnum2
);
1542 if (status1
!= status2
) {
1544 qprintf(quiet
, "Strict mode: Offset %" PRId64
1545 " block status mismatch!\n", offset
);
1549 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1551 } else if (allocated1
== allocated2
) {
1555 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1556 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1558 error_report("Error while reading offset %" PRId64
1560 offset
, filename1
, strerror(-ret
));
1564 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1566 error_report("Error while reading offset %" PRId64
1568 offset
, filename2
, strerror(-ret
));
1572 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1573 if (ret
|| pnum
!= chunk
) {
1574 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1575 offset
+ (ret ?
0 : pnum
));
1581 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1583 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1584 filename1
, buf1
, quiet
);
1586 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1587 filename2
, buf1
, quiet
);
1594 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1597 if (total_size1
!= total_size2
) {
1598 BlockBackend
*blk_over
;
1599 const char *filename_over
;
1601 qprintf(quiet
, "Warning: Image size mismatch!\n");
1602 if (total_size1
> total_size2
) {
1604 filename_over
= filename1
;
1607 filename_over
= filename2
;
1610 while (offset
< progress_base
) {
1611 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1612 progress_base
- offset
, &chunk
,
1616 error_report("Sector allocation test failed for %s",
1621 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1622 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1623 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1624 filename_over
, buf1
, quiet
);
1630 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1634 qprintf(quiet
, "Images are identical.\n");
1644 qemu_progress_end();
1649 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1650 static void do_dirty_bitmap_merge(const char *dst_node
, const char *dst_name
,
1651 const char *src_node
, const char *src_name
,
1654 BlockDirtyBitmapMergeSource
*merge_src
;
1655 BlockDirtyBitmapMergeSourceList
*list
;
1657 merge_src
= g_new0(BlockDirtyBitmapMergeSource
, 1);
1658 merge_src
->type
= QTYPE_QDICT
;
1659 merge_src
->u
.external
.node
= g_strdup(src_node
);
1660 merge_src
->u
.external
.name
= g_strdup(src_name
);
1661 list
= g_new0(BlockDirtyBitmapMergeSourceList
, 1);
1662 list
->value
= merge_src
;
1663 qmp_block_dirty_bitmap_merge(dst_node
, dst_name
, list
, errp
);
1664 qapi_free_BlockDirtyBitmapMergeSourceList(list
);
1667 enum ImgConvertBlockStatus
{
1673 #define MAX_COROUTINES 16
1674 #define CONVERT_THROTTLE_GROUP "img_convert"
1676 typedef struct ImgConvertState
{
1678 int64_t *src_sectors
;
1681 int64_t total_sectors
;
1682 int64_t allocated_sectors
;
1683 int64_t allocated_done
;
1686 enum ImgConvertBlockStatus status
;
1687 int64_t sector_next_status
;
1688 BlockBackend
*target
;
1692 bool target_has_backing
;
1693 int64_t target_backing_sectors
; /* negative if unknown */
1700 size_t cluster_sectors
;
1702 long num_coroutines
;
1703 int running_coroutines
;
1704 Coroutine
*co
[MAX_COROUTINES
];
1705 int64_t wait_sector_num
[MAX_COROUTINES
];
1710 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1711 int *src_cur
, int64_t *src_cur_offset
)
1714 *src_cur_offset
= 0;
1715 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1716 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1718 assert(*src_cur
< s
->src_num
);
1722 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1724 int64_t src_cur_offset
;
1725 int ret
, n
, src_cur
;
1726 bool post_backing_zero
= false;
1728 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1730 assert(s
->total_sectors
> sector_num
);
1731 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1733 if (s
->target_backing_sectors
>= 0) {
1734 if (sector_num
>= s
->target_backing_sectors
) {
1735 post_backing_zero
= true;
1736 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1737 /* Split requests around target_backing_sectors (because
1738 * starting from there, zeros are handled differently) */
1739 n
= s
->target_backing_sectors
- sector_num
;
1743 if (s
->sector_next_status
<= sector_num
) {
1744 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1747 BlockDriverState
*src_bs
= blk_bs(s
->src
[src_cur
]);
1748 BlockDriverState
*base
;
1750 if (s
->target_has_backing
) {
1751 base
= bdrv_cow_bs(bdrv_skip_filters(src_bs
));
1757 count
= n
* BDRV_SECTOR_SIZE
;
1759 ret
= bdrv_block_status_above(src_bs
, base
, offset
, count
, &count
,
1766 warn_report("error while reading block status at "
1767 "offset %" PRIu64
": %s", offset
,
1770 /* Just try to read the data, then */
1771 ret
= BDRV_BLOCK_DATA
;
1772 count
= BDRV_SECTOR_SIZE
;
1774 /* Retry on a shorter range */
1775 n
= DIV_ROUND_UP(n
, 4);
1778 error_report("error while reading block status at offset "
1779 "%" PRIu64
": %s", offset
, strerror(-ret
));
1785 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1788 * Avoid that s->sector_next_status becomes unaligned to the source
1789 * request alignment and/or cluster size to avoid unnecessary read
1792 tail
= (sector_num
- src_cur_offset
+ n
) % s
->src_alignment
[src_cur
];
1797 if (ret
& BDRV_BLOCK_ZERO
) {
1798 s
->status
= post_backing_zero ? BLK_BACKING_FILE
: BLK_ZERO
;
1799 } else if (ret
& BDRV_BLOCK_DATA
) {
1800 s
->status
= BLK_DATA
;
1802 s
->status
= s
->target_has_backing ? BLK_BACKING_FILE
: BLK_DATA
;
1805 s
->sector_next_status
= sector_num
+ n
;
1808 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1809 if (s
->status
== BLK_DATA
) {
1810 n
= MIN(n
, s
->buf_sectors
);
1813 /* We need to write complete clusters for compressed images, so if an
1814 * unallocated area is shorter than that, we must consider the whole
1815 * cluster allocated. */
1816 if (s
->compressed
) {
1817 if (n
< s
->cluster_sectors
) {
1818 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1819 s
->status
= BLK_DATA
;
1821 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1828 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1829 int nb_sectors
, uint8_t *buf
)
1831 uint64_t single_read_until
= 0;
1834 assert(nb_sectors
<= s
->buf_sectors
);
1835 while (nb_sectors
> 0) {
1838 int64_t bs_sectors
, src_cur_offset
;
1841 /* In the case of compression with multiple source files, we can get a
1842 * nb_sectors that spreads into the next part. So we must be able to
1843 * read across multiple BDSes for one convert_read() call. */
1844 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1845 blk
= s
->src
[src_cur
];
1846 bs_sectors
= s
->src_sectors
[src_cur
];
1848 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1850 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1851 if (single_read_until
> offset
) {
1855 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1859 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1863 warn_report("error while reading offset %" PRIu64
1864 ": %s", offset
, strerror(-ret
));
1866 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1875 buf
+= n
* BDRV_SECTOR_SIZE
;
1882 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1883 int nb_sectors
, uint8_t *buf
,
1884 enum ImgConvertBlockStatus status
)
1888 while (nb_sectors
> 0) {
1890 BdrvRequestFlags flags
= s
->compressed ? BDRV_REQ_WRITE_COMPRESSED
: 0;
1893 case BLK_BACKING_FILE
:
1894 /* If we have a backing file, leave clusters unallocated that are
1895 * unallocated in the source image, so that the backing file is
1896 * visible at the respective offset. */
1897 assert(s
->target_has_backing
);
1901 /* If we're told to keep the target fully allocated (-S 0) or there
1902 * is real non-zero data, we must write it. Otherwise we can treat
1903 * it as zero sectors.
1904 * Compressed clusters need to be written as a whole, so in that
1905 * case we can only save the write if the buffer is completely
1907 if (!s
->min_sparse
||
1909 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1910 sector_num
, s
->alignment
)) ||
1912 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1914 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1915 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1924 if (s
->has_zero_init
) {
1925 assert(!s
->target_has_backing
);
1928 ret
= blk_co_pwrite_zeroes(s
->target
,
1929 sector_num
<< BDRV_SECTOR_BITS
,
1930 n
<< BDRV_SECTOR_BITS
,
1931 BDRV_REQ_MAY_UNMAP
);
1940 buf
+= n
* BDRV_SECTOR_SIZE
;
1946 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1951 while (nb_sectors
> 0) {
1954 int64_t bs_sectors
, src_cur_offset
;
1957 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1958 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1959 blk
= s
->src
[src_cur
];
1960 bs_sectors
= s
->src_sectors
[src_cur
];
1962 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1964 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1965 sector_num
<< BDRV_SECTOR_BITS
,
1966 n
<< BDRV_SECTOR_BITS
, 0, 0);
1977 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1979 ImgConvertState
*s
= opaque
;
1980 uint8_t *buf
= NULL
;
1984 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1985 if (s
->co
[i
] == qemu_coroutine_self()) {
1992 s
->running_coroutines
++;
1993 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1998 enum ImgConvertBlockStatus status
;
2001 qemu_co_mutex_lock(&s
->lock
);
2002 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
2003 qemu_co_mutex_unlock(&s
->lock
);
2006 n
= convert_iteration_sectors(s
, s
->sector_num
);
2008 qemu_co_mutex_unlock(&s
->lock
);
2012 /* save current sector and allocation status to local variables */
2013 sector_num
= s
->sector_num
;
2015 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
2016 n
= MIN(n
, s
->buf_sectors
);
2018 /* increment global sector counter so that other coroutines can
2019 * already continue reading beyond this request */
2021 qemu_co_mutex_unlock(&s
->lock
);
2023 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
2024 s
->allocated_done
+= n
;
2025 qemu_progress_print(100.0 * s
->allocated_done
/
2026 s
->allocated_sectors
, 0);
2030 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
2031 if (status
== BLK_DATA
&& !copy_range
) {
2032 ret
= convert_co_read(s
, sector_num
, n
, buf
);
2034 error_report("error while reading at byte %lld: %s",
2035 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2038 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
2040 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
2043 if (s
->wr_in_order
) {
2044 /* keep writes in order */
2045 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
2046 s
->wait_sector_num
[index
] = sector_num
;
2047 qemu_coroutine_yield();
2049 s
->wait_sector_num
[index
] = -1;
2052 if (s
->ret
== -EINPROGRESS
) {
2054 ret
= convert_co_copy_range(s
, sector_num
, n
);
2056 s
->copy_range
= false;
2060 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
2063 error_report("error while writing at byte %lld: %s",
2064 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2069 if (s
->wr_in_order
) {
2070 /* reenter the coroutine that might have waited
2071 * for this write to complete */
2072 s
->wr_offs
= sector_num
+ n
;
2073 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2074 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
2076 * A -> B -> A cannot occur because A has
2077 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2078 * B will never enter A during this time window.
2080 qemu_coroutine_enter(s
->co
[i
]);
2088 s
->co
[index
] = NULL
;
2089 s
->running_coroutines
--;
2090 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
2091 /* the convert job finished successfully */
2096 static int convert_do_copy(ImgConvertState
*s
)
2099 int64_t sector_num
= 0;
2101 /* Check whether we have zero initialisation or can get it efficiently */
2102 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
2103 !s
->target_has_backing
) {
2104 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
2107 /* Allocate buffer for copied data. For compressed images, only one cluster
2108 * can be copied at a time. */
2109 if (s
->compressed
) {
2110 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2111 error_report("invalid cluster size");
2114 s
->buf_sectors
= s
->cluster_sectors
;
2117 while (sector_num
< s
->total_sectors
) {
2118 n
= convert_iteration_sectors(s
, sector_num
);
2122 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2124 s
->allocated_sectors
+= n
;
2130 s
->sector_next_status
= 0;
2131 s
->ret
= -EINPROGRESS
;
2133 qemu_co_mutex_init(&s
->lock
);
2134 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2135 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2136 s
->wait_sector_num
[i
] = -1;
2137 qemu_coroutine_enter(s
->co
[i
]);
2140 while (s
->running_coroutines
) {
2141 main_loop_wait(false);
2144 if (s
->compressed
&& !s
->ret
) {
2145 /* signal EOF to align */
2146 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
2155 static int convert_copy_bitmaps(BlockDriverState
*src
, BlockDriverState
*dst
)
2157 BdrvDirtyBitmap
*bm
;
2160 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2163 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2166 name
= bdrv_dirty_bitmap_name(bm
);
2167 qmp_block_dirty_bitmap_add(dst
->node_name
, name
,
2168 true, bdrv_dirty_bitmap_granularity(bm
),
2170 true, !bdrv_dirty_bitmap_enabled(bm
),
2173 error_reportf_err(err
, "Failed to create bitmap %s: ", name
);
2177 do_dirty_bitmap_merge(dst
->node_name
, name
, src
->node_name
, name
,
2180 error_reportf_err(err
, "Failed to populate bitmap %s: ", name
);
2188 #define MAX_BUF_SECTORS 32768
2190 static void set_rate_limit(BlockBackend
*blk
, int64_t rate_limit
)
2194 throttle_config_init(&cfg
);
2195 cfg
.buckets
[THROTTLE_BPS_WRITE
].avg
= rate_limit
;
2197 blk_io_limits_enable(blk
, CONVERT_THROTTLE_GROUP
);
2198 blk_set_io_limits(blk
, &cfg
);
2201 static int img_convert(int argc
, char **argv
)
2203 int c
, bs_i
, flags
, src_flags
= 0;
2204 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2205 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2206 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
2207 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2208 BlockDriverInfo bdi
;
2209 BlockDriverState
*out_bs
;
2210 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2211 QemuOptsList
*create_opts
= NULL
;
2212 QDict
*open_opts
= NULL
;
2213 char *options
= NULL
;
2214 Error
*local_err
= NULL
;
2215 bool writethrough
, src_writethrough
, image_opts
= false,
2216 skip_create
= false, progress
= false, tgt_image_opts
= false;
2217 int64_t ret
= -EINVAL
;
2218 bool force_share
= false;
2219 bool explict_min_sparse
= false;
2220 bool bitmaps
= false;
2221 int64_t rate_limit
= 0;
2223 ImgConvertState s
= (ImgConvertState
) {
2224 /* Need at least 4k of zeros for sparse detection */
2226 .copy_range
= false,
2227 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2228 .wr_in_order
= true,
2229 .num_coroutines
= 8,
2233 static const struct option long_options
[] = {
2234 {"help", no_argument
, 0, 'h'},
2235 {"object", required_argument
, 0, OPTION_OBJECT
},
2236 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2237 {"force-share", no_argument
, 0, 'U'},
2238 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2239 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2240 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2241 {"bitmaps", no_argument
, 0, OPTION_BITMAPS
},
2244 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WUr:",
2245 long_options
, NULL
);
2251 missing_argument(argv
[optind
- 1]);
2254 unrecognized_option(argv
[optind
- 1]);
2266 out_baseimg
= optarg
;
2269 s
.copy_range
= true;
2272 s
.compressed
= true;
2275 if (accumulate_options(&options
, optarg
) < 0) {
2280 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2281 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2284 error_report("Failed in parsing snapshot param '%s'",
2289 snapshot_name
= optarg
;
2296 sval
= cvtnum("buffer size for sparse output", optarg
);
2299 } else if (!QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2300 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2301 error_report("Invalid buffer size for sparse output specified. "
2302 "Valid sizes are multiples of %llu up to %llu. Select "
2303 "0 to disable sparse detection (fully allocates output).",
2304 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2308 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2309 explict_min_sparse
= true;
2328 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2329 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2330 error_report("Invalid number of coroutines. Allowed number of"
2331 " coroutines is between 1 and %d", MAX_COROUTINES
);
2336 s
.wr_in_order
= false;
2342 rate_limit
= cvtnum("rate limit", optarg
);
2343 if (rate_limit
< 0) {
2347 case OPTION_OBJECT
: {
2348 QemuOpts
*object_opts
;
2349 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2356 case OPTION_IMAGE_OPTS
:
2359 case OPTION_SALVAGE
:
2362 case OPTION_TARGET_IMAGE_OPTS
:
2363 tgt_image_opts
= true;
2365 case OPTION_TARGET_IS_ZERO
:
2367 * The user asserting that the target is blank has the
2368 * same effect as the target driver supporting zero
2371 s
.has_zero_init
= true;
2373 case OPTION_BITMAPS
:
2379 if (!out_fmt
&& !tgt_image_opts
) {
2383 if (qemu_opts_foreach(&qemu_object_opts
,
2384 user_creatable_add_opts_foreach
,
2385 qemu_img_object_print_help
, &error_fatal
)) {
2389 if (s
.compressed
&& s
.copy_range
) {
2390 error_report("Cannot enable copy offloading when -c is used");
2394 if (explict_min_sparse
&& s
.copy_range
) {
2395 error_report("Cannot enable copy offloading when -S is used");
2399 if (s
.copy_range
&& s
.salvage
) {
2400 error_report("Cannot use copy offloading in salvaging mode");
2404 if (tgt_image_opts
&& !skip_create
) {
2405 error_report("--target-image-opts requires use of -n flag");
2409 if (skip_create
&& options
) {
2410 error_report("-o has no effect when skipping image creation");
2414 if (s
.has_zero_init
&& !skip_create
) {
2415 error_report("--target-is-zero requires use of -n flag");
2419 s
.src_num
= argc
- optind
- 1;
2420 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2422 if (options
&& has_help_option(options
)) {
2424 ret
= print_block_option_help(out_filename
, out_fmt
);
2427 error_report("Option help requires a format be specified");
2432 if (s
.src_num
< 1) {
2433 error_report("Must specify image file name");
2437 /* ret is still -EINVAL until here */
2438 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2440 error_report("Invalid source cache option: %s", src_cache
);
2444 /* Initialize before goto out */
2448 qemu_progress_init(progress
, 1.0);
2449 qemu_progress_print(0, 100);
2451 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2452 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2453 s
.src_alignment
= g_new(int, s
.src_num
);
2455 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2456 BlockDriverState
*src_bs
;
2457 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2458 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2464 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2465 if (s
.src_sectors
[bs_i
] < 0) {
2466 error_report("Could not get size of %s: %s",
2467 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2471 src_bs
= blk_bs(s
.src
[bs_i
]);
2472 s
.src_alignment
[bs_i
] = DIV_ROUND_UP(src_bs
->bl
.request_alignment
,
2474 if (!bdrv_get_info(src_bs
, &bdi
)) {
2475 s
.src_alignment
[bs_i
] = MAX(s
.src_alignment
[bs_i
],
2476 bdi
.cluster_size
/ BDRV_SECTOR_SIZE
);
2478 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2482 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2483 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2484 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2486 } else if (snapshot_name
!= NULL
) {
2487 if (s
.src_num
> 1) {
2488 error_report("No support for concatenating multiple snapshot");
2493 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2497 error_reportf_err(local_err
, "Failed to load snapshot: ");
2503 /* Find driver and parse its options */
2504 drv
= bdrv_find_format(out_fmt
);
2506 error_report("Unknown file format '%s'", out_fmt
);
2511 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2513 error_report_err(local_err
);
2518 if (!drv
->create_opts
) {
2519 error_report("Format driver '%s' does not support image creation",
2525 if (!proto_drv
->create_opts
) {
2526 error_report("Protocol driver '%s' does not support image creation",
2527 proto_drv
->format_name
);
2532 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2533 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2535 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2537 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
2538 error_report_err(local_err
);
2544 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
2545 s
.total_sectors
* BDRV_SECTOR_SIZE
, &error_abort
);
2546 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2552 /* Get backing file name if -o backing_file was used */
2553 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2554 if (out_baseimg_param
) {
2555 out_baseimg
= out_baseimg_param
;
2557 s
.target_has_backing
= (bool) out_baseimg
;
2559 if (s
.has_zero_init
&& s
.target_has_backing
) {
2560 error_report("Cannot use --target-is-zero when the destination "
2561 "image has a backing file");
2565 if (s
.src_num
> 1 && out_baseimg
) {
2566 error_report("Having a backing file for the target makes no sense when "
2567 "concatenating multiple input images");
2572 if (out_baseimg_param
) {
2573 if (!qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
)) {
2574 warn_report("Deprecated use of backing file without explicit "
2579 /* Check if compression is supported */
2582 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2583 const char *encryptfmt
=
2584 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2585 const char *preallocation
=
2586 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2588 if (drv
&& !block_driver_can_compress(drv
)) {
2589 error_report("Compression not supported for this file format");
2594 if (encryption
|| encryptfmt
) {
2595 error_report("Compression and encryption not supported at "
2602 && strcmp(preallocation
, "off"))
2604 error_report("Compression and preallocation not supported at "
2611 /* Determine if bitmaps need copying */
2613 if (s
.src_num
> 1) {
2614 error_report("Copying bitmaps only possible with single source");
2618 if (!bdrv_supports_persistent_dirty_bitmap(blk_bs(s
.src
[0]))) {
2619 error_report("Source lacks bitmap support");
2626 * The later open call will need any decryption secrets, and
2627 * bdrv_create() will purge "opts", so extract them now before
2631 open_opts
= qdict_new();
2632 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2634 /* Create the new image */
2635 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2637 error_reportf_err(local_err
, "%s: error while converting %s: ",
2638 out_filename
, out_fmt
);
2643 s
.target_is_new
= !skip_create
;
2645 flags
= s
.min_sparse ?
(BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2646 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2648 error_report("Invalid cache option: %s", cache
);
2653 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2654 flags
, writethrough
, s
.quiet
, false);
2656 /* TODO ultimately we should allow --target-image-opts
2657 * to be used even when -n is not given.
2658 * That has to wait for bdrv_create to be improved
2659 * to allow filenames in option syntax
2661 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2662 flags
, writethrough
, s
.quiet
, false);
2663 open_opts
= NULL
; /* blk_new_open will have freed it */
2669 out_bs
= blk_bs(s
.target
);
2671 if (bitmaps
&& !bdrv_supports_persistent_dirty_bitmap(out_bs
)) {
2672 error_report("Format driver '%s' does not support bitmaps",
2673 out_bs
->drv
->format_name
);
2678 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2679 error_report("Compression not supported for this file format");
2684 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2685 * or discard_alignment of the out_bs is greater. Limit to
2686 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2687 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2689 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2690 out_bs
->bl
.pdiscard_alignment
>>
2691 BDRV_SECTOR_BITS
)));
2693 /* try to align the write requests to the destination to avoid unnecessary
2695 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2696 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2698 assert(is_power_of_2(s
.alignment
));
2701 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2702 if (output_sectors
< 0) {
2703 error_report("unable to get output image length: %s",
2704 strerror(-output_sectors
));
2707 } else if (output_sectors
< s
.total_sectors
) {
2708 error_report("output file is smaller than input file");
2714 if (s
.target_has_backing
&& s
.target_is_new
) {
2715 /* Errors are treated as "backing length unknown" (which means
2716 * s.target_backing_sectors has to be negative, which it will
2717 * be automatically). The backing file length is used only
2718 * for optimizations, so such a case is not fatal. */
2719 s
.target_backing_sectors
=
2720 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs
));
2722 s
.target_backing_sectors
= -1;
2725 ret
= bdrv_get_info(out_bs
, &bdi
);
2728 error_report("could not get block driver info");
2732 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2733 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2737 set_rate_limit(s
.target
, rate_limit
);
2740 ret
= convert_do_copy(&s
);
2742 /* Now copy the bitmaps */
2743 if (bitmaps
&& ret
== 0) {
2744 ret
= convert_copy_bitmaps(blk_bs(s
.src
[0]), out_bs
);
2749 qemu_progress_print(100, 0);
2751 qemu_progress_end();
2752 qemu_opts_del(opts
);
2753 qemu_opts_free(create_opts
);
2754 qobject_unref(open_opts
);
2755 blk_unref(s
.target
);
2757 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2758 blk_unref(s
.src
[bs_i
]);
2762 g_free(s
.src_sectors
);
2763 g_free(s
.src_alignment
);
2765 qemu_opts_del(sn_opts
);
2772 static void dump_snapshots(BlockDriverState
*bs
)
2774 QEMUSnapshotInfo
*sn_tab
, *sn
;
2777 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2780 printf("Snapshot list:\n");
2781 bdrv_snapshot_dump(NULL
);
2783 for(i
= 0; i
< nb_sns
; i
++) {
2785 bdrv_snapshot_dump(sn
);
2791 static void dump_json_image_info_list(ImageInfoList
*list
)
2795 Visitor
*v
= qobject_output_visitor_new(&obj
);
2797 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2798 visit_complete(v
, &obj
);
2799 str
= qobject_to_json_pretty(obj
);
2800 assert(str
!= NULL
);
2801 printf("%s\n", qstring_get_str(str
));
2807 static void dump_json_image_info(ImageInfo
*info
)
2811 Visitor
*v
= qobject_output_visitor_new(&obj
);
2813 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2814 visit_complete(v
, &obj
);
2815 str
= qobject_to_json_pretty(obj
);
2816 assert(str
!= NULL
);
2817 printf("%s\n", qstring_get_str(str
));
2823 static void dump_human_image_info_list(ImageInfoList
*list
)
2825 ImageInfoList
*elem
;
2828 for (elem
= list
; elem
; elem
= elem
->next
) {
2834 bdrv_image_info_dump(elem
->value
);
2838 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2840 return strcmp(a
, b
) == 0;
2844 * Open an image file chain and return an ImageInfoList
2846 * @filename: topmost image filename
2847 * @fmt: topmost image format (may be NULL to autodetect)
2848 * @chain: true - enumerate entire backing file chain
2849 * false - only topmost image file
2851 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2852 * image file. If there was an error a message will have been printed to
2855 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2856 const char *filename
,
2858 bool chain
, bool force_share
)
2860 ImageInfoList
*head
= NULL
;
2861 ImageInfoList
**last
= &head
;
2862 GHashTable
*filenames
;
2865 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2869 BlockDriverState
*bs
;
2871 ImageInfoList
*elem
;
2873 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2874 error_report("Backing file '%s' creates an infinite loop.",
2878 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2880 blk
= img_open(image_opts
, filename
, fmt
,
2881 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2888 bdrv_query_image_info(bs
, &info
, &err
);
2890 error_report_err(err
);
2895 elem
= g_new0(ImageInfoList
, 1);
2902 /* Clear parameters that only apply to the topmost image */
2903 filename
= fmt
= NULL
;
2907 if (info
->has_full_backing_filename
) {
2908 filename
= info
->full_backing_filename
;
2909 } else if (info
->has_backing_filename
) {
2910 error_report("Could not determine absolute backing filename,"
2911 " but backing filename '%s' present",
2912 info
->backing_filename
);
2915 if (info
->has_backing_filename_format
) {
2916 fmt
= info
->backing_filename_format
;
2920 g_hash_table_destroy(filenames
);
2924 qapi_free_ImageInfoList(head
);
2925 g_hash_table_destroy(filenames
);
2929 static int img_info(int argc
, char **argv
)
2932 OutputFormat output_format
= OFORMAT_HUMAN
;
2934 const char *filename
, *fmt
, *output
;
2935 ImageInfoList
*list
;
2936 bool image_opts
= false;
2937 bool force_share
= false;
2942 int option_index
= 0;
2943 static const struct option long_options
[] = {
2944 {"help", no_argument
, 0, 'h'},
2945 {"format", required_argument
, 0, 'f'},
2946 {"output", required_argument
, 0, OPTION_OUTPUT
},
2947 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2948 {"object", required_argument
, 0, OPTION_OBJECT
},
2949 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2950 {"force-share", no_argument
, 0, 'U'},
2953 c
= getopt_long(argc
, argv
, ":f:hU",
2954 long_options
, &option_index
);
2960 missing_argument(argv
[optind
- 1]);
2963 unrecognized_option(argv
[optind
- 1]);
2977 case OPTION_BACKING_CHAIN
:
2980 case OPTION_OBJECT
: {
2982 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2988 case OPTION_IMAGE_OPTS
:
2993 if (optind
!= argc
- 1) {
2994 error_exit("Expecting one image file name");
2996 filename
= argv
[optind
++];
2998 if (output
&& !strcmp(output
, "json")) {
2999 output_format
= OFORMAT_JSON
;
3000 } else if (output
&& !strcmp(output
, "human")) {
3001 output_format
= OFORMAT_HUMAN
;
3002 } else if (output
) {
3003 error_report("--output must be used with human or json as argument.");
3007 if (qemu_opts_foreach(&qemu_object_opts
,
3008 user_creatable_add_opts_foreach
,
3009 qemu_img_object_print_help
, &error_fatal
)) {
3013 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
3019 switch (output_format
) {
3021 dump_human_image_info_list(list
);
3025 dump_json_image_info_list(list
);
3027 dump_json_image_info(list
->value
);
3032 qapi_free_ImageInfoList(list
);
3036 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
3039 switch (output_format
) {
3041 if (e
->data
&& !e
->has_offset
) {
3042 error_report("File contains external, encrypted or compressed clusters.");
3045 if (e
->data
&& !e
->zero
) {
3046 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
3047 e
->start
, e
->length
,
3048 e
->has_offset ? e
->offset
: 0,
3049 e
->has_filename ? e
->filename
: "");
3051 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3052 * Modify the flags here to allow more coalescing.
3054 if (next
&& (!next
->data
|| next
->zero
)) {
3060 printf("{ \"start\": %"PRId64
", \"length\": %"PRId64
","
3061 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
3062 e
->start
, e
->length
, e
->depth
,
3063 e
->zero ?
"true" : "false",
3064 e
->data ?
"true" : "false");
3065 if (e
->has_offset
) {
3066 printf(", \"offset\": %"PRId64
"", e
->offset
);
3078 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
3079 int64_t bytes
, MapEntry
*e
)
3083 BlockDriverState
*file
;
3086 char *filename
= NULL
;
3088 /* As an optimization, we could cache the current range of unallocated
3089 * clusters in each file of the chain, and avoid querying the same
3095 bs
= bdrv_skip_filters(bs
);
3096 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
3101 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
3104 bs
= bdrv_cow_bs(bs
);
3113 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
3115 if (file
&& has_offset
) {
3116 bdrv_refresh_filename(file
);
3117 filename
= file
->filename
;
3123 .data
= !!(ret
& BDRV_BLOCK_DATA
),
3124 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
3126 .has_offset
= has_offset
,
3128 .has_filename
= filename
,
3129 .filename
= filename
,
3135 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
3137 if (curr
->length
== 0) {
3140 if (curr
->zero
!= next
->zero
||
3141 curr
->data
!= next
->data
||
3142 curr
->depth
!= next
->depth
||
3143 curr
->has_filename
!= next
->has_filename
||
3144 curr
->has_offset
!= next
->has_offset
) {
3147 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
3150 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
3156 static int img_map(int argc
, char **argv
)
3159 OutputFormat output_format
= OFORMAT_HUMAN
;
3161 BlockDriverState
*bs
;
3162 const char *filename
, *fmt
, *output
;
3164 MapEntry curr
= { .length
= 0 }, next
;
3166 bool image_opts
= false;
3167 bool force_share
= false;
3168 int64_t start_offset
= 0;
3169 int64_t max_length
= -1;
3174 int option_index
= 0;
3175 static const struct option long_options
[] = {
3176 {"help", no_argument
, 0, 'h'},
3177 {"format", required_argument
, 0, 'f'},
3178 {"output", required_argument
, 0, OPTION_OUTPUT
},
3179 {"object", required_argument
, 0, OPTION_OBJECT
},
3180 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3181 {"force-share", no_argument
, 0, 'U'},
3182 {"start-offset", required_argument
, 0, 's'},
3183 {"max-length", required_argument
, 0, 'l'},
3186 c
= getopt_long(argc
, argv
, ":f:s:l:hU",
3187 long_options
, &option_index
);
3193 missing_argument(argv
[optind
- 1]);
3196 unrecognized_option(argv
[optind
- 1]);
3211 start_offset
= cvtnum("start offset", optarg
);
3212 if (start_offset
< 0) {
3217 max_length
= cvtnum("max length", optarg
);
3218 if (max_length
< 0) {
3222 case OPTION_OBJECT
: {
3224 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3230 case OPTION_IMAGE_OPTS
:
3235 if (optind
!= argc
- 1) {
3236 error_exit("Expecting one image file name");
3238 filename
= argv
[optind
];
3240 if (output
&& !strcmp(output
, "json")) {
3241 output_format
= OFORMAT_JSON
;
3242 } else if (output
&& !strcmp(output
, "human")) {
3243 output_format
= OFORMAT_HUMAN
;
3244 } else if (output
) {
3245 error_report("--output must be used with human or json as argument.");
3249 if (qemu_opts_foreach(&qemu_object_opts
,
3250 user_creatable_add_opts_foreach
,
3251 qemu_img_object_print_help
, &error_fatal
)) {
3255 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3261 if (output_format
== OFORMAT_HUMAN
) {
3262 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3263 } else if (output_format
== OFORMAT_JSON
) {
3267 length
= blk_getlength(blk
);
3269 error_report("Failed to get size for '%s'", filename
);
3272 if (max_length
!= -1) {
3273 length
= MIN(start_offset
+ max_length
, length
);
3276 curr
.start
= start_offset
;
3277 while (curr
.start
+ curr
.length
< length
) {
3278 int64_t offset
= curr
.start
+ curr
.length
;
3279 int64_t n
= length
- offset
;
3281 ret
= get_block_status(bs
, offset
, n
, &next
);
3283 error_report("Could not read file metadata: %s", strerror(-ret
));
3287 if (entry_mergeable(&curr
, &next
)) {
3288 curr
.length
+= next
.length
;
3292 if (curr
.length
> 0) {
3293 ret
= dump_map_entry(output_format
, &curr
, &next
);
3301 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3302 if (output_format
== OFORMAT_JSON
) {
3311 #define SNAPSHOT_LIST 1
3312 #define SNAPSHOT_CREATE 2
3313 #define SNAPSHOT_APPLY 3
3314 #define SNAPSHOT_DELETE 4
3316 static int img_snapshot(int argc
, char **argv
)
3319 BlockDriverState
*bs
;
3320 QEMUSnapshotInfo sn
;
3321 char *filename
, *snapshot_name
= NULL
;
3322 int c
, ret
= 0, bdrv_oflags
;
3327 bool image_opts
= false;
3328 bool force_share
= false;
3330 bdrv_oflags
= BDRV_O_RDWR
;
3331 /* Parse commandline parameters */
3333 static const struct option long_options
[] = {
3334 {"help", no_argument
, 0, 'h'},
3335 {"object", required_argument
, 0, OPTION_OBJECT
},
3336 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3337 {"force-share", no_argument
, 0, 'U'},
3340 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3341 long_options
, NULL
);
3347 missing_argument(argv
[optind
- 1]);
3350 unrecognized_option(argv
[optind
- 1]);
3357 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3360 action
= SNAPSHOT_LIST
;
3361 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3365 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3368 action
= SNAPSHOT_APPLY
;
3369 snapshot_name
= optarg
;
3373 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3376 action
= SNAPSHOT_CREATE
;
3377 snapshot_name
= optarg
;
3381 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3384 action
= SNAPSHOT_DELETE
;
3385 snapshot_name
= optarg
;
3393 case OPTION_OBJECT
: {
3395 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3401 case OPTION_IMAGE_OPTS
:
3407 if (optind
!= argc
- 1) {
3408 error_exit("Expecting one image file name");
3410 filename
= argv
[optind
++];